1 use rustc_errors::ErrorReported;
2 use rustc_hir::def::DefKind;
4 use rustc_middle::ty::{self, Ty};
5 use std::borrow::Borrow;
6 use std::collections::hash_map::Entry;
9 use rustc_data_structures::fx::FxHashMap;
12 use rustc_ast::Mutability;
13 use rustc_hir::def_id::DefId;
14 use rustc_middle::mir::AssertMessage;
15 use rustc_session::Limit;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Align, Size};
18 use rustc_target::spec::abi::Abi;
20 use crate::interpret::{
21 self, compile_time_machine, AllocId, Allocation, Frame, ImmTy, InterpCx, InterpResult, OpTy,
22 PlaceTy, Scalar, StackPopUnwind,
27 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
28 /// "Intercept" a function call to a panic-related function
29 /// because we have something special to do for it.
30 /// If this returns successfully (`Ok`), the function should just be evaluated normally.
31 fn hook_special_const_fn(
33 instance: ty::Instance<'tcx>,
35 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
36 // All `#[rustc_do_not_const_check]` functions should be hooked here.
37 let def_id = instance.def_id();
39 if Some(def_id) == self.tcx.lang_items().const_eval_select() {
40 // redirect to const_eval_select_ct
41 if let Some(const_eval_select) = self.tcx.lang_items().const_eval_select_ct() {
43 ty::Instance::resolve(
45 ty::ParamEnv::reveal_all(),
53 } else if Some(def_id) == self.tcx.lang_items().panic_display()
54 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
57 assert!(args.len() == 1);
59 let mut msg_place = self.deref_operand(&args[0])?;
60 while msg_place.layout.ty.is_ref() {
61 msg_place = self.deref_operand(&msg_place.into())?;
64 let msg = Symbol::intern(self.read_str(&msg_place)?);
65 let span = self.find_closest_untracked_caller_location();
66 let (file, line, col) = self.location_triple_for_span(span);
67 return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
68 } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
69 // For panic_fmt, call const_panic_fmt instead.
70 if let Some(const_panic_fmt) = self.tcx.lang_items().const_panic_fmt() {
72 ty::Instance::resolve(
74 ty::ParamEnv::reveal_all(),
76 self.tcx.intern_substs(&[]),
87 /// Extra machine state for CTFE, and the Machine instance
88 pub struct CompileTimeInterpreter<'mir, 'tcx> {
89 /// For now, the number of terminators that can be evaluated before we throw a resource
92 /// Setting this to `0` disables the limit and allows the interpreter to run forever.
93 pub steps_remaining: usize,
95 /// The virtual call stack.
96 pub(crate) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
99 #[derive(Copy, Clone, Debug)]
100 pub struct MemoryExtra {
101 /// We need to make sure consts never point to anything mutable, even recursively. That is
102 /// relied on for pattern matching on consts with references.
103 /// To achieve this, two pieces have to work together:
104 /// * Interning makes everything outside of statics immutable.
105 /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
106 /// This boolean here controls the second part.
107 pub(super) can_access_statics: bool,
110 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
111 pub(super) fn new(const_eval_limit: Limit) -> Self {
112 CompileTimeInterpreter { steps_remaining: const_eval_limit.0, stack: Vec::new() }
116 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
118 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
122 FxHashMap::contains_key(self, k)
126 fn insert(&mut self, k: K, v: V) -> Option<V> {
127 FxHashMap::insert(self, k, v)
131 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
135 FxHashMap::remove(self, k)
139 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
140 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
144 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
149 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
155 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
156 match self.entry(k) {
157 Entry::Occupied(e) => Ok(e.into_mut()),
158 Entry::Vacant(e) => {
166 crate type CompileTimeEvalContext<'mir, 'tcx> =
167 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
169 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
170 pub enum MemoryKind {
174 impl fmt::Display for MemoryKind {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 MemoryKind::Heap => write!(f, "heap allocation"),
182 impl interpret::MayLeak for MemoryKind {
184 fn may_leak(self) -> bool {
186 MemoryKind::Heap => false,
191 impl interpret::MayLeak for ! {
193 fn may_leak(self) -> bool {
194 // `self` is uninhabited
199 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
200 fn guaranteed_eq(&mut self, a: Scalar, b: Scalar) -> bool {
202 // Comparisons between integers are always known.
203 (Scalar::Int { .. }, Scalar::Int { .. }) => a == b,
204 // Equality with integers can never be known for sure.
205 (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => false,
206 // FIXME: return `true` for when both sides are the same pointer, *except* that
207 // some things (like functions and vtables) do not have stable addresses
208 // so we need to be careful around them (see e.g. #73722).
209 (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
213 fn guaranteed_ne(&mut self, a: Scalar, b: Scalar) -> bool {
215 // Comparisons between integers are always known.
216 (Scalar::Int(_), Scalar::Int(_)) => a != b,
217 // Comparisons of abstract pointers with null pointers are known if the pointer
218 // is in bounds, because if they are in bounds, the pointer can't be null.
219 // Inequality with integers other than null can never be known for sure.
220 (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
221 int.is_null() && !self.memory.ptr_may_be_null(ptr.into())
223 // FIXME: return `true` for at least some comparisons where we can reliably
224 // determine the result of runtime inequality tests at compile-time.
225 // Examples include comparison of addresses in different static items.
226 (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
231 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
232 compile_time_machine!(<'mir, 'tcx>);
234 type MemoryKind = MemoryKind;
236 type MemoryExtra = MemoryExtra;
238 const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
241 ecx: &InterpCx<'mir, 'tcx, Self>,
242 instance: ty::InstanceDef<'tcx>,
243 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
245 ty::InstanceDef::Item(def) => {
246 if ecx.tcx.is_ctfe_mir_available(def.did) {
247 Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
248 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
249 ecx.tcx.sess.delay_span_bug(
250 rustc_span::DUMMY_SP,
251 "This is likely a const item that is missing from its impl",
253 throw_inval!(AlreadyReported(ErrorReported {}));
255 let path = ecx.tcx.def_path_str(def.did);
256 Err(ConstEvalErrKind::NeedsRfc(format!("calling extern function `{}`", path))
260 _ => Ok(ecx.tcx.instance_mir(instance)),
264 fn find_mir_or_eval_fn(
265 ecx: &mut InterpCx<'mir, 'tcx, Self>,
266 instance: ty::Instance<'tcx>,
269 _ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
270 _unwind: StackPopUnwind, // unwinding is not supported in consts
271 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
272 debug!("find_mir_or_eval_fn: {:?}", instance);
274 // Only check non-glue functions
275 if let ty::InstanceDef::Item(def) = instance.def {
276 // Execution might have wandered off into other crates, so we cannot do a stability-
277 // sensitive check here. But we can at least rule out functions that are not const
279 if !ecx.tcx.is_const_fn_raw(def.did) {
280 // allow calling functions marked with #[default_method_body_is_const].
281 if !ecx.tcx.has_attr(def.did, sym::default_method_body_is_const) {
282 // We certainly do *not* want to actually call the fn
283 // though, so be sure we return here.
284 throw_unsup_format!("calling non-const function `{}`", instance)
288 if let Some(new_instance) = ecx.hook_special_const_fn(instance, args)? {
289 // We call another const fn instead.
290 // However, we return the *original* instance to make backtraces work out
291 // (and we hope this does not confuse the FnAbi checks too much).
292 return Ok(Self::find_mir_or_eval_fn(
300 .map(|(body, _instance)| (body, instance)));
303 // This is a const fn. Call it.
304 Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
308 ecx: &mut InterpCx<'mir, 'tcx, Self>,
309 instance: ty::Instance<'tcx>,
311 ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
312 _unwind: StackPopUnwind,
313 ) -> InterpResult<'tcx> {
314 // Shared intrinsics.
315 if ecx.emulate_intrinsic(instance, args, ret)? {
318 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
320 // CTFE-specific intrinsics.
321 let (dest, ret) = match ret {
323 return Err(ConstEvalErrKind::NeedsRfc(format!(
324 "calling intrinsic `{}`",
331 match intrinsic_name {
332 sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
333 let a = ecx.read_immediate(&args[0])?.to_scalar()?;
334 let b = ecx.read_immediate(&args[1])?.to_scalar()?;
335 let cmp = if intrinsic_name == sym::ptr_guaranteed_eq {
336 ecx.guaranteed_eq(a, b)
338 ecx.guaranteed_ne(a, b)
340 ecx.write_scalar(Scalar::from_bool(cmp), dest)?;
342 sym::const_allocate => {
343 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
344 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
346 let align = match Align::from_bytes(align) {
348 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
351 let ptr = ecx.memory.allocate(
352 Size::from_bytes(size as u64),
354 interpret::MemoryKind::Machine(MemoryKind::Heap),
356 ecx.write_pointer(ptr, dest)?;
358 sym::const_deallocate => {
359 let ptr = ecx.read_pointer(&args[0])?;
360 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
361 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
363 let size = Size::from_bytes(size);
364 let align = match Align::from_bytes(align) {
366 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
369 // If an allocation is created in an another const,
370 // we don't deallocate it.
371 let (alloc_id, _, _) = ecx.memory.ptr_get_alloc(ptr)?;
372 let is_allocated_in_another_const = matches!(
373 ecx.tcx.get_global_alloc(alloc_id),
374 Some(interpret::GlobalAlloc::Memory(_))
377 if !is_allocated_in_another_const {
378 ecx.memory.deallocate(
381 interpret::MemoryKind::Machine(MemoryKind::Heap),
386 return Err(ConstEvalErrKind::NeedsRfc(format!(
387 "calling intrinsic `{}`",
394 ecx.go_to_block(ret);
399 ecx: &mut InterpCx<'mir, 'tcx, Self>,
400 msg: &AssertMessage<'tcx>,
401 _unwind: Option<mir::BasicBlock>,
402 ) -> InterpResult<'tcx> {
403 use rustc_middle::mir::AssertKind::*;
404 // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
406 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
407 let err = match msg {
408 BoundsCheck { ref len, ref index } => {
409 let len = eval_to_int(len)?;
410 let index = eval_to_int(index)?;
411 BoundsCheck { len, index }
413 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
414 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
415 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
416 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
417 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
418 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
420 Err(ConstEvalErrKind::AssertFailure(err).into())
423 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
424 Err(ConstEvalErrKind::Abort(msg).into())
428 _ecx: &InterpCx<'mir, 'tcx, Self>,
431 _right: &ImmTy<'tcx>,
432 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
433 Err(ConstEvalErrKind::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
436 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
437 // The step limit has already been hit in a previous call to `before_terminator`.
438 if ecx.machine.steps_remaining == 0 {
442 ecx.machine.steps_remaining -= 1;
443 if ecx.machine.steps_remaining == 0 {
444 throw_exhaust!(StepLimitReached)
452 ecx: &mut InterpCx<'mir, 'tcx, Self>,
453 frame: Frame<'mir, 'tcx>,
454 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
455 // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
456 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
457 throw_exhaust!(StackFrameLimitReached)
465 ecx: &'a InterpCx<'mir, 'tcx, Self>,
466 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
472 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
473 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
474 &mut ecx.machine.stack
477 fn before_access_global(
478 memory_extra: &MemoryExtra,
480 allocation: &Allocation,
481 static_def_id: Option<DefId>,
483 ) -> InterpResult<'tcx> {
485 // Write access. These are never allowed, but we give a targeted error message.
486 if allocation.mutability == Mutability::Not {
487 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
489 Err(ConstEvalErrKind::ModifiedGlobal.into())
492 // Read access. These are usually allowed, with some exceptions.
493 if memory_extra.can_access_statics {
494 // Machine configuration allows us read from anything (e.g., `static` initializer).
496 } else if static_def_id.is_some() {
497 // Machine configuration does not allow us to read statics
498 // (e.g., `const` initializer).
499 // See const_eval::machine::MemoryExtra::can_access_statics for why
500 // this check is so important: if we could read statics, we could read pointers
501 // to mutable allocations *inside* statics. These allocations are not themselves
502 // statics, so pointers to them can get around the check in `validity.rs`.
503 Err(ConstEvalErrKind::ConstAccessesStatic.into())
505 // Immutable global, this read is fine.
506 // But make sure we never accept a read from something mutable, that would be
507 // unsound. The reason is that as the content of this allocation may be different
508 // now and at run-time, so if we permit reading now we might return the wrong value.
509 assert_eq!(allocation.mutability, Mutability::Not);
516 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
517 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
518 // at the bottom of this file.