1 use rustc_hir::def::DefKind;
3 use rustc_middle::ty::{self, Ty, TyCtxt};
4 use std::borrow::Borrow;
5 use std::collections::hash_map::Entry;
8 use rustc_data_structures::fx::FxHashMap;
11 use rustc_ast::Mutability;
12 use rustc_hir::def_id::DefId;
13 use rustc_middle::mir::AssertMessage;
14 use rustc_session::Limit;
15 use rustc_span::symbol::{sym, Symbol};
16 use rustc_target::abi::{Align, Size};
17 use rustc_target::spec::abi::Abi as CallAbi;
19 use crate::interpret::{
20 self, compile_time_machine, AllocId, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
21 OpTy, PlaceTy, Pointer, Scalar, StackPopUnwind,
26 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
27 /// "Intercept" a function call to a panic-related function
28 /// because we have something special to do for it.
29 /// If this returns successfully (`Ok`), the function should just be evaluated normally.
30 fn hook_special_const_fn(
32 instance: ty::Instance<'tcx>,
34 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
35 // All `#[rustc_do_not_const_check]` functions should be hooked here.
36 let def_id = instance.def_id();
38 if Some(def_id) == self.tcx.lang_items().panic_display()
39 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
42 assert!(args.len() == 1);
44 let mut msg_place = self.deref_operand(&args[0])?;
45 while msg_place.layout.ty.is_ref() {
46 msg_place = self.deref_operand(&msg_place.into())?;
49 let msg = Symbol::intern(self.read_str(&msg_place)?);
50 let span = self.find_closest_untracked_caller_location();
51 let (file, line, col) = self.location_triple_for_span(span);
52 return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
53 } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
54 // For panic_fmt, call const_panic_fmt instead.
55 if let Some(const_panic_fmt) = self.tcx.lang_items().const_panic_fmt() {
57 ty::Instance::resolve(
59 ty::ParamEnv::reveal_all(),
61 self.tcx.intern_substs(&[]),
72 /// Extra machine state for CTFE, and the Machine instance
73 pub struct CompileTimeInterpreter<'mir, 'tcx> {
74 /// For now, the number of terminators that can be evaluated before we throw a resource
77 /// Setting this to `0` disables the limit and allows the interpreter to run forever.
78 pub(super) steps_remaining: usize,
80 /// The virtual call stack.
81 pub(super) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
83 /// We need to make sure consts never point to anything mutable, even recursively. That is
84 /// relied on for pattern matching on consts with references.
85 /// To achieve this, two pieces have to work together:
86 /// * Interning makes everything outside of statics immutable.
87 /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
88 /// This boolean here controls the second part.
89 pub(super) can_access_statics: bool,
91 /// Whether to check alignment during evaluation.
92 pub(super) check_alignment: bool,
95 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
97 const_eval_limit: Limit,
98 can_access_statics: bool,
99 check_alignment: bool,
101 CompileTimeInterpreter {
102 steps_remaining: const_eval_limit.0,
110 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
112 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
116 FxHashMap::contains_key(self, k)
120 fn insert(&mut self, k: K, v: V) -> Option<V> {
121 FxHashMap::insert(self, k, v)
125 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
129 FxHashMap::remove(self, k)
133 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
134 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
138 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
143 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
149 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
150 match self.entry(k) {
151 Entry::Occupied(e) => Ok(e.into_mut()),
152 Entry::Vacant(e) => {
160 pub(crate) type CompileTimeEvalContext<'mir, 'tcx> =
161 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
163 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
164 pub enum MemoryKind {
168 impl fmt::Display for MemoryKind {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 MemoryKind::Heap => write!(f, "heap allocation"),
176 impl interpret::MayLeak for MemoryKind {
178 fn may_leak(self) -> bool {
180 MemoryKind::Heap => false,
185 impl interpret::MayLeak for ! {
187 fn may_leak(self) -> bool {
188 // `self` is uninhabited
193 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
194 /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
195 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
197 // Comparisons between integers are always known.
198 (Scalar::Int { .. }, Scalar::Int { .. }) => {
205 // Comparisons of abstract pointers with null pointers are known if the pointer
206 // is in bounds, because if they are in bounds, the pointer can't be null.
207 // Inequality with integers other than null can never be known for sure.
208 (Scalar::Int(int), ptr @ Scalar::Ptr(..))
209 | (ptr @ Scalar::Ptr(..), Scalar::Int(int))
210 if int.is_null() && !self.scalar_may_be_null(ptr)? =>
214 // Equality with integers can never be known for sure.
215 (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => 2,
216 // FIXME: return a `1` for when both sides are the same pointer, *except* that
217 // some things (like functions and vtables) do not have stable addresses
218 // so we need to be careful around them (see e.g. #73722).
219 // FIXME: return `0` for at least some comparisons where we can reliably
220 // determine the result of runtime inequality tests at compile-time.
221 // Examples include comparison of addresses in different static items.
222 (Scalar::Ptr(..), Scalar::Ptr(..)) => 2,
227 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
228 compile_time_machine!(<'mir, 'tcx>);
230 type MemoryKind = MemoryKind;
232 const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
235 fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
236 ecx.machine.check_alignment
240 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
241 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks
245 ecx: &InterpCx<'mir, 'tcx, Self>,
246 instance: ty::InstanceDef<'tcx>,
247 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
249 ty::InstanceDef::Item(def) => {
250 if ecx.tcx.is_ctfe_mir_available(def.did) {
251 Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
252 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
253 let guar = ecx.tcx.sess.delay_span_bug(
254 rustc_span::DUMMY_SP,
255 "This is likely a const item that is missing from its impl",
257 throw_inval!(AlreadyReported(guar));
259 // `find_mir_or_eval_fn` checks that this is a const fn before even calling us,
260 // so this should be unreachable.
261 let path = ecx.tcx.def_path_str(def.did);
262 bug!("trying to call extern function `{path}` at compile-time");
265 _ => Ok(ecx.tcx.instance_mir(instance)),
269 fn find_mir_or_eval_fn(
270 ecx: &mut InterpCx<'mir, 'tcx, Self>,
271 instance: ty::Instance<'tcx>,
274 _dest: &PlaceTy<'tcx>,
275 _ret: Option<mir::BasicBlock>,
276 _unwind: StackPopUnwind, // unwinding is not supported in consts
277 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
278 debug!("find_mir_or_eval_fn: {:?}", instance);
280 // Only check non-glue functions
281 if let ty::InstanceDef::Item(def) = instance.def {
282 // Execution might have wandered off into other crates, so we cannot do a stability-
283 // sensitive check here. But we can at least rule out functions that are not const
285 if !ecx.tcx.is_const_fn_raw(def.did) {
286 // allow calling functions inside a trait marked with #[const_trait].
287 if !ecx.tcx.is_const_default_method(def.did) {
288 // We certainly do *not* want to actually call the fn
289 // though, so be sure we return here.
290 throw_unsup_format!("calling non-const function `{}`", instance)
294 if let Some(new_instance) = ecx.hook_special_const_fn(instance, args)? {
295 // We call another const fn instead.
296 // However, we return the *original* instance to make backtraces work out
297 // (and we hope this does not confuse the FnAbi checks too much).
298 return Ok(Self::find_mir_or_eval_fn(
307 .map(|(body, _instance)| (body, instance)));
310 // This is a const fn. Call it.
311 Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
315 ecx: &mut InterpCx<'mir, 'tcx, Self>,
316 instance: ty::Instance<'tcx>,
318 dest: &PlaceTy<'tcx, Self::Provenance>,
319 target: Option<mir::BasicBlock>,
320 _unwind: StackPopUnwind,
321 ) -> InterpResult<'tcx> {
322 // Shared intrinsics.
323 if ecx.emulate_intrinsic(instance, args, dest, target)? {
326 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
328 // CTFE-specific intrinsics.
329 let Some(ret) = target else {
330 throw_unsup_format!("intrinsic `{intrinsic_name}` is not supported at compile-time");
332 match intrinsic_name {
333 sym::ptr_guaranteed_cmp => {
334 let a = ecx.read_scalar(&args[0])?;
335 let b = ecx.read_scalar(&args[1])?;
336 let cmp = ecx.guaranteed_cmp(a, b)?;
337 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
339 sym::const_allocate => {
340 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
341 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
343 let align = match Align::from_bytes(align) {
345 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
348 let ptr = ecx.allocate_ptr(
349 Size::from_bytes(size as u64),
351 interpret::MemoryKind::Machine(MemoryKind::Heap),
353 ecx.write_pointer(ptr, dest)?;
355 sym::const_deallocate => {
356 let ptr = ecx.read_pointer(&args[0])?;
357 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
358 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
360 let size = Size::from_bytes(size);
361 let align = match Align::from_bytes(align) {
363 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
366 // If an allocation is created in an another const,
367 // we don't deallocate it.
368 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?;
369 let is_allocated_in_another_const = matches!(
370 ecx.tcx.try_get_global_alloc(alloc_id),
371 Some(interpret::GlobalAlloc::Memory(_))
374 if !is_allocated_in_another_const {
378 interpret::MemoryKind::Machine(MemoryKind::Heap),
384 "intrinsic `{intrinsic_name}` is not supported at compile-time"
389 ecx.go_to_block(ret);
394 ecx: &mut InterpCx<'mir, 'tcx, Self>,
395 msg: &AssertMessage<'tcx>,
396 _unwind: Option<mir::BasicBlock>,
397 ) -> InterpResult<'tcx> {
398 use rustc_middle::mir::AssertKind::*;
399 // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
401 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
402 let err = match msg {
403 BoundsCheck { ref len, ref index } => {
404 let len = eval_to_int(len)?;
405 let index = eval_to_int(index)?;
406 BoundsCheck { len, index }
408 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
409 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
410 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
411 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
412 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
413 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
415 Err(ConstEvalErrKind::AssertFailure(err).into())
418 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
419 Err(ConstEvalErrKind::Abort(msg).into())
423 _ecx: &InterpCx<'mir, 'tcx, Self>,
426 _right: &ImmTy<'tcx>,
427 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
428 throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
431 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
432 // The step limit has already been hit in a previous call to `before_terminator`.
433 if ecx.machine.steps_remaining == 0 {
437 ecx.machine.steps_remaining -= 1;
438 if ecx.machine.steps_remaining == 0 {
439 throw_exhaust!(StepLimitReached)
447 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
448 _ptr: Pointer<AllocId>,
449 ) -> InterpResult<'tcx> {
450 // This is only reachable with -Zunleash-the-miri-inside-of-you.
451 throw_unsup_format!("exposing pointers is not possible at compile-time")
456 ecx: &mut InterpCx<'mir, 'tcx, Self>,
457 frame: Frame<'mir, 'tcx>,
458 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
459 // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
460 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
461 throw_exhaust!(StackFrameLimitReached)
469 ecx: &'a InterpCx<'mir, 'tcx, Self>,
470 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
476 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
477 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
478 &mut ecx.machine.stack
481 fn before_access_global(
485 alloc: ConstAllocation<'tcx>,
486 static_def_id: Option<DefId>,
488 ) -> InterpResult<'tcx> {
489 let alloc = alloc.inner();
491 // Write access. These are never allowed, but we give a targeted error message.
492 if alloc.mutability == Mutability::Not {
493 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
495 Err(ConstEvalErrKind::ModifiedGlobal.into())
498 // Read access. These are usually allowed, with some exceptions.
499 if machine.can_access_statics {
500 // Machine configuration allows us read from anything (e.g., `static` initializer).
502 } else if static_def_id.is_some() {
503 // Machine configuration does not allow us to read statics
504 // (e.g., `const` initializer).
505 // See const_eval::machine::MemoryExtra::can_access_statics for why
506 // this check is so important: if we could read statics, we could read pointers
507 // to mutable allocations *inside* statics. These allocations are not themselves
508 // statics, so pointers to them can get around the check in `validity.rs`.
509 Err(ConstEvalErrKind::ConstAccessesStatic.into())
511 // Immutable global, this read is fine.
512 // But make sure we never accept a read from something mutable, that would be
513 // unsound. The reason is that as the content of this allocation may be different
514 // now and at run-time, so if we permit reading now we might return the wrong value.
515 assert_eq!(alloc.mutability, Mutability::Not);
522 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
523 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
524 // at the bottom of this file.