2 use rustc_middle::ty::{self, Ty};
3 use std::borrow::Borrow;
4 use std::collections::hash_map::Entry;
7 use rustc_data_structures::fx::FxHashMap;
10 use rustc_ast::Mutability;
11 use rustc_hir::def_id::DefId;
12 use rustc_middle::mir::AssertMessage;
13 use rustc_session::Limit;
14 use rustc_span::symbol::{sym, Symbol};
15 use rustc_target::abi::{Align, Size};
16 use rustc_target::spec::abi::Abi;
18 use crate::interpret::{
19 self, compile_time_machine, AllocId, Allocation, Frame, ImmTy, InterpCx, InterpResult, OpTy,
20 PlaceTy, Scalar, StackPopUnwind,
25 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
26 /// "Intercept" a function call to a panic-related function
27 /// because we have something special to do for it.
28 /// If this returns successfully (`Ok`), the function should just be evaluated normally.
31 instance: ty::Instance<'tcx>,
33 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
34 // The list of functions we handle here must be in sync with
35 // `is_lang_panic_fn` in `transform/check_consts/mod.rs`.
36 let def_id = instance.def_id();
37 if Some(def_id) == self.tcx.lang_items().panic_fn()
38 || Some(def_id) == self.tcx.lang_items().panic_str()
39 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
42 assert!(args.len() == 1);
44 let msg_place = self.deref_operand(&args[0])?;
45 let msg = Symbol::intern(self.read_str(&msg_place)?);
46 let span = self.find_closest_untracked_caller_location();
47 let (file, line, col) = self.location_triple_for_span(span);
48 return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
49 } else if Some(def_id) == self.tcx.lang_items().panic_fmt()
50 || Some(def_id) == self.tcx.lang_items().begin_panic_fmt()
52 // For panic_fmt, call const_panic_fmt instead.
53 if let Some(const_panic_fmt) = self.tcx.lang_items().const_panic_fmt() {
55 ty::Instance::resolve(
57 ty::ParamEnv::reveal_all(),
59 self.tcx.intern_substs(&[]),
70 /// Extra machine state for CTFE, and the Machine instance
71 pub struct CompileTimeInterpreter<'mir, 'tcx> {
72 /// For now, the number of terminators that can be evaluated before we throw a resource
75 /// Setting this to `0` disables the limit and allows the interpreter to run forever.
76 pub steps_remaining: usize,
78 /// The virtual call stack.
79 pub(crate) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
82 #[derive(Copy, Clone, Debug)]
83 pub struct MemoryExtra {
84 /// We need to make sure consts never point to anything mutable, even recursively. That is
85 /// relied on for pattern matching on consts with references.
86 /// To achieve this, two pieces have to work together:
87 /// * Interning makes everything outside of statics immutable.
88 /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
89 /// This boolean here controls the second part.
90 pub(super) can_access_statics: bool,
93 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
94 pub(super) fn new(const_eval_limit: Limit) -> Self {
95 CompileTimeInterpreter { steps_remaining: const_eval_limit.0, stack: Vec::new() }
99 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
101 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
105 FxHashMap::contains_key(self, k)
109 fn insert(&mut self, k: K, v: V) -> Option<V> {
110 FxHashMap::insert(self, k, v)
114 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
118 FxHashMap::remove(self, k)
122 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
123 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
127 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
132 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
138 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
139 match self.entry(k) {
140 Entry::Occupied(e) => Ok(e.into_mut()),
141 Entry::Vacant(e) => {
149 crate type CompileTimeEvalContext<'mir, 'tcx> =
150 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
152 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
153 pub enum MemoryKind {
157 impl fmt::Display for MemoryKind {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 MemoryKind::Heap => write!(f, "heap allocation"),
165 impl interpret::MayLeak for MemoryKind {
167 fn may_leak(self) -> bool {
169 MemoryKind::Heap => false,
174 impl interpret::MayLeak for ! {
176 fn may_leak(self) -> bool {
177 // `self` is uninhabited
182 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
183 fn guaranteed_eq(&mut self, a: Scalar, b: Scalar) -> bool {
185 // Comparisons between integers are always known.
186 (Scalar::Int { .. }, Scalar::Int { .. }) => a == b,
187 // Equality with integers can never be known for sure.
188 (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => false,
189 // FIXME: return `true` for when both sides are the same pointer, *except* that
190 // some things (like functions and vtables) do not have stable addresses
191 // so we need to be careful around them (see e.g. #73722).
192 (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
196 fn guaranteed_ne(&mut self, a: Scalar, b: Scalar) -> bool {
198 // Comparisons between integers are always known.
199 (Scalar::Int(_), Scalar::Int(_)) => a != b,
200 // Comparisons of abstract pointers with null pointers are known if the pointer
201 // is in bounds, because if they are in bounds, the pointer can't be null.
202 // Inequality with integers other than null can never be known for sure.
203 (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
204 int.is_null() && !self.memory.ptr_may_be_null(ptr.into())
206 // FIXME: return `true` for at least some comparisons where we can reliably
207 // determine the result of runtime inequality tests at compile-time.
208 // Examples include comparison of addresses in different static items.
209 (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
214 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
215 compile_time_machine!(<'mir, 'tcx>);
217 type MemoryKind = MemoryKind;
219 type MemoryExtra = MemoryExtra;
221 const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
224 ecx: &InterpCx<'mir, 'tcx, Self>,
225 instance: ty::InstanceDef<'tcx>,
226 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
228 ty::InstanceDef::Item(def) => {
229 if ecx.tcx.is_ctfe_mir_available(def.did) {
230 Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
232 let path = ecx.tcx.def_path_str(def.did);
233 Err(ConstEvalErrKind::NeedsRfc(format!("calling extern function `{}`", path))
237 _ => Ok(ecx.tcx.instance_mir(instance)),
241 fn find_mir_or_eval_fn(
242 ecx: &mut InterpCx<'mir, 'tcx, Self>,
243 instance: ty::Instance<'tcx>,
246 _ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
247 _unwind: StackPopUnwind, // unwinding is not supported in consts
248 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
249 debug!("find_mir_or_eval_fn: {:?}", instance);
251 // Only check non-glue functions
252 if let ty::InstanceDef::Item(def) = instance.def {
253 // Execution might have wandered off into other crates, so we cannot do a stability-
254 // sensitive check here. But we can at least rule out functions that are not const
256 if !ecx.tcx.is_const_fn_raw(def.did) {
257 // allow calling functions marked with #[default_method_body_is_const].
258 if !ecx.tcx.has_attr(def.did, sym::default_method_body_is_const) {
259 // Some functions we support even if they are non-const -- but avoid testing
260 // that for const fn!
261 if let Some(new_instance) = ecx.hook_panic_fn(instance, args)? {
262 // We call another const fn instead.
263 return Self::find_mir_or_eval_fn(
272 // We certainly do *not* want to actually call the fn
273 // though, so be sure we return here.
274 throw_unsup_format!("calling non-const function `{}`", instance)
279 // This is a const fn. Call it.
280 Ok(Some(ecx.load_mir(instance.def, None)?))
284 ecx: &mut InterpCx<'mir, 'tcx, Self>,
285 instance: ty::Instance<'tcx>,
287 ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
288 _unwind: StackPopUnwind,
289 ) -> InterpResult<'tcx> {
290 // Shared intrinsics.
291 if ecx.emulate_intrinsic(instance, args, ret)? {
294 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
296 // CTFE-specific intrinsics.
297 let (dest, ret) = match ret {
299 return Err(ConstEvalErrKind::NeedsRfc(format!(
300 "calling intrinsic `{}`",
307 match intrinsic_name {
308 sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
309 let a = ecx.read_immediate(&args[0])?.to_scalar()?;
310 let b = ecx.read_immediate(&args[1])?.to_scalar()?;
311 let cmp = if intrinsic_name == sym::ptr_guaranteed_eq {
312 ecx.guaranteed_eq(a, b)
314 ecx.guaranteed_ne(a, b)
316 ecx.write_scalar(Scalar::from_bool(cmp), dest)?;
318 sym::const_allocate => {
319 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
320 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
322 let align = match Align::from_bytes(align) {
324 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
327 let ptr = ecx.memory.allocate(
328 Size::from_bytes(size as u64),
330 interpret::MemoryKind::Machine(MemoryKind::Heap),
332 ecx.write_pointer(ptr, dest)?;
335 return Err(ConstEvalErrKind::NeedsRfc(format!(
336 "calling intrinsic `{}`",
343 ecx.go_to_block(ret);
348 ecx: &mut InterpCx<'mir, 'tcx, Self>,
349 msg: &AssertMessage<'tcx>,
350 _unwind: Option<mir::BasicBlock>,
351 ) -> InterpResult<'tcx> {
352 use rustc_middle::mir::AssertKind::*;
353 // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
355 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
356 let err = match msg {
357 BoundsCheck { ref len, ref index } => {
358 let len = eval_to_int(len)?;
359 let index = eval_to_int(index)?;
360 BoundsCheck { len, index }
362 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
363 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
364 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
365 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
366 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
367 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
369 Err(ConstEvalErrKind::AssertFailure(err).into())
372 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
373 Err(ConstEvalErrKind::Abort(msg).into())
377 _ecx: &InterpCx<'mir, 'tcx, Self>,
380 _right: &ImmTy<'tcx>,
381 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
382 Err(ConstEvalErrKind::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
386 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
387 _dest: &PlaceTy<'tcx>,
388 ) -> InterpResult<'tcx> {
389 Err(ConstEvalErrKind::NeedsRfc("heap allocations via `box` keyword".to_string()).into())
392 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
393 // The step limit has already been hit in a previous call to `before_terminator`.
394 if ecx.machine.steps_remaining == 0 {
398 ecx.machine.steps_remaining -= 1;
399 if ecx.machine.steps_remaining == 0 {
400 throw_exhaust!(StepLimitReached)
408 ecx: &mut InterpCx<'mir, 'tcx, Self>,
409 frame: Frame<'mir, 'tcx>,
410 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
411 // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
412 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
413 throw_exhaust!(StackFrameLimitReached)
421 ecx: &'a InterpCx<'mir, 'tcx, Self>,
422 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
428 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
429 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
430 &mut ecx.machine.stack
433 fn before_access_global(
434 memory_extra: &MemoryExtra,
436 allocation: &Allocation,
437 static_def_id: Option<DefId>,
439 ) -> InterpResult<'tcx> {
441 // Write access. These are never allowed, but we give a targeted error message.
442 if allocation.mutability == Mutability::Not {
443 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
445 Err(ConstEvalErrKind::ModifiedGlobal.into())
448 // Read access. These are usually allowed, with some exceptions.
449 if memory_extra.can_access_statics {
450 // Machine configuration allows us read from anything (e.g., `static` initializer).
452 } else if static_def_id.is_some() {
453 // Machine configuration does not allow us to read statics
454 // (e.g., `const` initializer).
455 // See const_eval::machine::MemoryExtra::can_access_statics for why
456 // this check is so important: if we could read statics, we could read pointers
457 // to mutable allocations *inside* statics. These allocations are not themselves
458 // statics, so pointers to them can get around the check in `validity.rs`.
459 Err(ConstEvalErrKind::ConstAccessesStatic.into())
461 // Immutable global, this read is fine.
462 // But make sure we never accept a read from something mutable, that would be
463 // unsound. The reason is that as the content of this allocation may be different
464 // now and at run-time, so if we permit reading now we might return the wrong value.
465 assert_eq!(allocation.mutability, Mutability::Not);
472 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
473 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
474 // at the bottom of this file.