1//! This module contains everything needed to instantiate an interpreter.
2//! This separation exists to ensure that no fancy miri features like
3//! interpreting common C functions leak into CTFE.
45use std::borrow::{Borrow, Cow};
6use std::fmt::Debug;
7use std::hash::Hash;
89use rustc_abi::{Align, Size};
10use rustc_apfloat::{Float, FloatConvert};
11use rustc_middle::query::TyCtxtAt;
12use rustc_middle::ty::layout::TyAndLayout;
13use rustc_middle::ty::{AtomicOrdering, Ty};
14use rustc_middle::{mir, ty};
15use rustc_span::def_id::DefId;
16use rustc_target::callconv::FnAbi;
1718use super::{
19AllocBytes, AllocId, AllocKind, AllocRange, Allocation, AtomicRmwOp, CTFE_ALLOC_SALT,
20ConstAllocation, CtfeProvenance, EnteredTraceSpan, FnArg, Frame, ImmTy, InterpCx, InterpResult,
21MPlaceTy, MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, Scalar,
22interp_ok, throw_unsup,
23};
2425/// Data returned by [`Machine::after_stack_pop`], and consumed by
26/// [`InterpCx::return_from_current_stack_frame`] to determine what actions should be done when
27/// returning from a stack frame.
28#[derive(#[automatically_derived]
impl ::core::cmp::Eq for ReturnAction {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ReturnAction {
#[inline]
fn eq(&self, other: &ReturnAction) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ReturnAction {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ReturnAction::Normal => "Normal",
ReturnAction::NoJump => "NoJump",
ReturnAction::NoCleanup => "NoCleanup",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReturnAction { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReturnAction {
#[inline]
fn clone(&self) -> ReturnAction { *self }
}Clone)]
29pub enum ReturnAction {
30/// Indicates that no special handling should be
31 /// done - we'll either return normally or unwind
32 /// based on the terminator for the function
33 /// we're leaving.
34Normal,
3536/// Indicates that we should *not* jump to the return/unwind address, as the callback already
37 /// took care of everything.
38NoJump,
3940/// Returned by [`InterpCx::pop_stack_frame_raw`] when no cleanup should be done.
41NoCleanup,
42}
4344/// The currently active retagging mode.
45#[derive(#[automatically_derived]
impl ::core::cmp::Eq for RetagMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for RetagMode {
#[inline]
fn eq(&self, other: &RetagMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for RetagMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RetagMode::Default => "Default",
RetagMode::TwoPhase => "TwoPhase",
RetagMode::FnEntry => "FnEntry",
RetagMode::Raw => "Raw",
RetagMode::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RetagMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RetagMode {
#[inline]
fn clone(&self) -> RetagMode { *self }
}Clone)]
46pub enum RetagMode {
47/// A regular retag.
48Default,
49/// Retag preparing for a two-phase borrow.
50TwoPhase,
51/// The initial retag of arguments when entering a function.
52FnEntry,
53/// Retagging for reference-to-raw-pointer cast.
54Raw,
55/// No retagging.
56None,
57}
5859/// Whether this kind of memory is allowed to leak
60pub trait MayLeak: Copy {
61fn may_leak(self) -> bool;
62}
6364/// The functionality needed by memory to manage its allocations
65pub trait AllocMap<K: Hash + Eq, V> {
66/// Tests if the map contains the given key.
67 /// Deliberately takes `&mut` because that is sufficient, and some implementations
68 /// can be more efficient then (using `RefCell::get_mut`).
69fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool70where
71K: Borrow<Q>;
7273/// Callers should prefer [`AllocMap::contains_key`] when it is possible to call because it may
74 /// be more efficient. This function exists for callers that only have a shared reference
75 /// (which might make it slightly less efficient than `contains_key`, e.g. if
76 /// the data is stored inside a `RefCell`).
77fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool78where
79K: Borrow<Q>;
8081/// Inserts a new entry into the map.
82fn insert(&mut self, k: K, v: V) -> Option<V>;
8384/// Removes an entry from the map.
85fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
86where
87K: Borrow<Q>;
8889/// Returns data based on the keys and values in the map.
90fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
9192/// Returns a reference to entry `k`. If no such entry exists, call
93 /// `vacant` and either forward its error, or add its result to the map
94 /// and return a reference to *that*.
95fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
9697/// Returns a mutable reference to entry `k`. If no such entry exists, call
98 /// `vacant` and either forward its error, or add its result to the map
99 /// and return a reference to *that*.
100fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
101102/// Read-only lookup.
103fn get(&self, k: K) -> Option<&V> {
104self.get_or(k, || Err(())).ok()
105 }
106107/// Mutable lookup.
108fn get_mut(&mut self, k: K) -> Option<&mut V> {
109self.get_mut_or(k, || Err(())).ok()
110 }
111}
112113/// Methods of this trait signifies a point where CTFE evaluation would fail
114/// and some use case dependent behaviour can instead be applied.
115pub trait Machine<'tcx>: Sized {
116/// Additional memory kinds a machine wishes to distinguish from the builtin ones
117type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
118119/// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
120type Provenance: Provenance + Eq + Hash + 'static;
121122/// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
123 /// that is passed to memory access hooks so they can do things with it.
124type ProvenanceExtra: Copy + 'static;
125126/// Machines can define extra (non-instance) things that represent values of function pointers.
127 /// For example, Miri uses this to return a function pointer from `dlsym`
128 /// that can later be called to execute the right thing.
129type ExtraFnVal: Debug + Copy;
130131/// Extra data stored in every call frame.
132type FrameExtra;
133134/// Extra data stored in every allocation.
135type AllocExtra: Debug + Clone + 'tcx;
136137/// Type for the bytes of the allocation.
138type Bytes: AllocBytes + 'static;
139140/// Memory's allocation map
141type MemoryMap: AllocMap<
142AllocId,
143 (
144MemoryKind<Self::MemoryKind>,
145Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>,
146 ),
147 > + Default148 + Clone;
149150/// The memory kind to use for copied global memory (held in `tcx`) --
151 /// or None if such memory should not be mutated and thus any such attempt will cause
152 /// a `ModifiedStatic` error to be raised.
153 /// Statics are copied under two circumstances: When they are mutated, and when
154 /// `adjust_allocation` (see below) returns an owned allocation
155 /// that is added to the memory so that the work is not done twice.
156const GLOBAL_KIND: Option<Self::MemoryKind>;
157158/// Should the machine panic on allocation failures?
159const PANIC_ON_ALLOC_FAIL: bool;
160161/// Determines whether `eval_mir_constant` can never fail because all required consts have
162 /// already been checked before.
163const ALL_CONSTS_ARE_PRECHECKED: bool = true;
164165/// Whether memory accesses should be alignment-checked.
166fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool;
167168/// Gives the machine a chance to detect more misalignment than the built-in checks would catch.
169#[inline(always)]
170fn alignment_check(
171 _ecx: &InterpCx<'tcx, Self>,
172 _alloc_id: AllocId,
173 _alloc_align: Align,
174 _alloc_kind: AllocKind,
175 _offset: Size,
176 _align: Align,
177 ) -> Option<Misalignment> {
178None179 }
180181/// Whether to enforce the validity invariant for a specific layout.
182fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool;
183/// Whether to enforce the validity invariant *recursively*.
184fn enforce_validity_recursively(
185 _ecx: &InterpCx<'tcx, Self>,
186 _layout: TyAndLayout<'tcx>,
187 ) -> bool {
188false
189}
190191/// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
192 /// check for overflow.
193fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
194195/// Entry point for obtaining the MIR of anything that should get evaluated.
196 /// So not just functions and shims, but also const/static initializers, anonymous
197 /// constants, ...
198fn load_mir(
199 ecx: &InterpCx<'tcx, Self>,
200 instance: ty::InstanceKind<'tcx>,
201 ) -> &'tcx mir::Body<'tcx> {
202ecx.tcx.instance_mir(instance)
203 }
204205/// Entry point to all function calls.
206 ///
207 /// Returns either the mir to use for the call, or `None` if execution should
208 /// just proceed (which usually means this hook did all the work that the
209 /// called function should usually have done). In the latter case, it is
210 /// this hook's responsibility to advance the instruction pointer!
211 /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
212 /// nor just jump to `ret`, but instead push their own stack frame.)
213 /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
214 /// was used.
215fn find_mir_or_eval_fn(
216 ecx: &mut InterpCx<'tcx, Self>,
217 instance: ty::Instance<'tcx>,
218 abi: &FnAbi<'tcx, Ty<'tcx>>,
219 args: &[FnArg<'tcx, Self::Provenance>],
220 destination: &PlaceTy<'tcx, Self::Provenance>,
221 target: Option<mir::BasicBlock>,
222 unwind: mir::UnwindAction,
223 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>>;
224225/// Execute `fn_val`. It is the hook's responsibility to advance the instruction
226 /// pointer as appropriate.
227fn call_extra_fn(
228 ecx: &mut InterpCx<'tcx, Self>,
229 fn_val: Self::ExtraFnVal,
230 abi: &FnAbi<'tcx, Ty<'tcx>>,
231 args: &[FnArg<'tcx, Self::Provenance>],
232 destination: &PlaceTy<'tcx, Self::Provenance>,
233 target: Option<mir::BasicBlock>,
234 unwind: mir::UnwindAction,
235 ) -> InterpResult<'tcx>;
236237/// Directly process an intrinsic without pushing a stack frame. It is the hook's
238 /// responsibility to advance the instruction pointer as appropriate.
239 ///
240 /// Returns `None` if the intrinsic was fully handled.
241 /// Otherwise, returns an `Instance` of the function that implements the intrinsic.
242fn call_intrinsic(
243 ecx: &mut InterpCx<'tcx, Self>,
244 instance: ty::Instance<'tcx>,
245 args: &[OpTy<'tcx, Self::Provenance>],
246 destination: &PlaceTy<'tcx, Self::Provenance>,
247 target: Option<mir::BasicBlock>,
248 unwind: mir::UnwindAction,
249 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>;
250251/// Directly process an LLVM intrinsic without pushing a stack frame. It is the hook's
252 /// responsibility to advance the instruction pointer as appropriate.
253fn call_llvm_intrinsic(
254 ecx: &mut InterpCx<'tcx, Self>,
255 instance: ty::Instance<'tcx>,
256 args: &[OpTy<'tcx, Self::Provenance>],
257 destination: &PlaceTy<'tcx, Self::Provenance>,
258 target: Option<mir::BasicBlock>,
259 ) -> InterpResult<'tcx>;
260261/// Check whether the given function may be executed on the current machine, in terms of the
262 /// target features is requires.
263fn check_fn_target_features(
264 _ecx: &InterpCx<'tcx, Self>,
265 _instance: ty::Instance<'tcx>,
266 ) -> InterpResult<'tcx>;
267268/// Called to evaluate `Assert` MIR terminators that trigger a panic.
269fn assert_panic(
270 ecx: &mut InterpCx<'tcx, Self>,
271 msg: &mir::AssertMessage<'tcx>,
272 unwind: mir::UnwindAction,
273 ) -> InterpResult<'tcx>;
274275/// Called to trigger a non-unwinding panic.
276fn panic_nounwind(_ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx>;
277278/// Called when unwinding reached a state where execution should be terminated.
279fn unwind_terminate(
280 ecx: &mut InterpCx<'tcx, Self>,
281 reason: mir::UnwindTerminateReason,
282 ) -> InterpResult<'tcx>;
283284/// Called for all binary operations where the LHS has pointer type.
285fn binary_ptr_op(
286 ecx: &InterpCx<'tcx, Self>,
287 bin_op: mir::BinOp,
288 left: &ImmTy<'tcx, Self::Provenance>,
289 right: &ImmTy<'tcx, Self::Provenance>,
290 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>>;
291292/// Generate the NaN returned by a float operation, given the list of inputs.
293 /// (This is all inputs, not just NaN inputs!)
294fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
295 _ecx: &InterpCx<'tcx, Self>,
296 _inputs: &[F1],
297 ) -> F2 {
298// By default we always return the preferred NaN.
299F2::NAN300 }
301302/// Apply non-determinism to float operations that do not return a precise result.
303fn apply_float_nondet(
304 _ecx: &mut InterpCx<'tcx, Self>,
305 val: ImmTy<'tcx, Self::Provenance>,
306 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
307interp_ok(val)
308 }
309310/// Determines the result of `min`/`max` on floats when the arguments are equal.
311fn equal_float_min_max<F: Float>(_ecx: &InterpCx<'tcx, Self>, a: F, _b: F) -> F {
312// By default, we pick the left argument.
313a314 }
315316/// Determines whether the `fmuladd` intrinsics fuse the multiply-add or use separate operations.
317fn float_fuse_mul_add(ecx: &InterpCx<'tcx, Self>) -> bool;
318319fn atomic_load(
320 ecx: &InterpCx<'tcx, Self>,
321 place: &MPlaceTy<'tcx, Self::Provenance>,
322 ordering: AtomicOrdering,
323 ) -> InterpResult<'tcx, Scalar<Self::Provenance>>;
324325fn atomic_store(
326 ecx: &mut InterpCx<'tcx, Self>,
327 place: &MPlaceTy<'tcx, Self::Provenance>,
328 val: &ImmTy<'tcx, Self::Provenance>,
329 ordering: AtomicOrdering,
330 ) -> InterpResult<'tcx>;
331332/// Returns the old value.
333fn atomic_rmw(
334 ecx: &mut InterpCx<'tcx, Self>,
335 place: &MPlaceTy<'tcx, Self::Provenance>,
336 op: AtomicRmwOp,
337 operand: &ImmTy<'tcx, Self::Provenance>,
338 ordering: AtomicOrdering,
339 ) -> InterpResult<'tcx, Scalar<Self::Provenance>>;
340341/// Returns a pair of the old value and a boolean indicating whether the update happened.
342fn atomic_compare_exchange(
343 ecx: &mut InterpCx<'tcx, Self>,
344 place: &MPlaceTy<'tcx, Self::Provenance>,
345 expected_old: &ImmTy<'tcx, Self::Provenance>,
346 new: &ImmTy<'tcx, Self::Provenance>,
347 can_fail_spuriously: bool,
348 success_ordering: AtomicOrdering,
349 failure_ordering: AtomicOrdering,
350 ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)>;
351352fn atomic_fence(
353 ecx: &InterpCx<'tcx, Self>,
354 ordering: AtomicOrdering,
355 singlethread: bool,
356 ) -> InterpResult<'tcx>;
357358/// Called before a basic block terminator is executed.
359#[inline]
360fn before_terminator(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
361interp_ok(())
362 }
363364/// Determines the result of a `Operand::RuntimeChecks` invocation.
365fn runtime_checks(
366 _ecx: &InterpCx<'tcx, Self>,
367 r: mir::RuntimeChecks,
368 ) -> InterpResult<'tcx, bool>;
369370/// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
371 /// You can use this to detect long or endlessly running programs.
372#[inline]
373fn increment_const_eval_counter(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
374interp_ok(())
375 }
376377/// Called before a global allocation is accessed.
378 /// `def_id` is `Some` if this is the "lazy" allocation of a static.
379#[inline]
380fn before_access_global(
381 _tcx: TyCtxtAt<'tcx>,
382 _machine: &Self,
383 _alloc_id: AllocId,
384 _allocation: ConstAllocation<'tcx>,
385 _static_def_id: Option<DefId>,
386 _is_write: bool,
387 ) -> InterpResult<'tcx> {
388interp_ok(())
389 }
390391/// Return the `AllocId` for the given thread-local static in the current thread.
392fn thread_local_static_pointer(
393 _ecx: &mut InterpCx<'tcx, Self>,
394 def_id: DefId,
395 ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
396do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ThreadLocalStatic(def_id))throw_unsup!(ThreadLocalStatic(def_id))397 }
398399/// Return the `AllocId` for the given `extern static`.
400fn extern_static_pointer(
401 ecx: &InterpCx<'tcx, Self>,
402 def_id: DefId,
403 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
404405/// "Int-to-pointer cast"
406fn ptr_from_addr_cast(
407 ecx: &InterpCx<'tcx, Self>,
408 addr: u64,
409 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
410411/// Marks a pointer as exposed, allowing its provenance
412 /// to be recovered. "Pointer-to-int cast"
413fn expose_provenance(
414 ecx: &InterpCx<'tcx, Self>,
415 provenance: Self::Provenance,
416 ) -> InterpResult<'tcx>;
417418/// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.
419 /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can
420 /// be used to disambiguate situations where a wildcard pointer sits right in between two
421 /// allocations.
422 ///
423 /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`.
424 /// The resulting `AllocId` will just be used for that one step and the forgotten again
425 /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be
426 /// stored in machine state).
427 ///
428 /// When this fails, that means the pointer does not point to a live allocation.
429fn ptr_get_alloc(
430 ecx: &InterpCx<'tcx, Self>,
431 ptr: Pointer<Self::Provenance>,
432 size: i64,
433 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
434435/// Return a "root" pointer for the given allocation: the one that is used for direct
436 /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
437 ///
438 /// Not called on `extern` or thread-local statics (those use the methods above).
439 ///
440 /// `kind` is the kind of the allocation the pointer points to; it can be `None` when
441 /// it's a global and `GLOBAL_KIND` is `None`.
442fn adjust_alloc_root_pointer(
443 ecx: &InterpCx<'tcx, Self>,
444 ptr: Pointer,
445 kind: Option<MemoryKind<Self::MemoryKind>>,
446 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
447448/// Called to adjust global allocations to the Provenance and AllocExtra of this machine.
449 ///
450 /// If `alloc` contains pointers, then they are all pointing to globals.
451 ///
452 /// This should avoid copying if no work has to be done! If this returns an owned
453 /// allocation (because a copy had to be done to adjust things), machine memory will
454 /// cache the result. (This relies on `AllocMap::get_or` being able to add the
455 /// owned allocation to the map even when the map is shared.)
456fn adjust_global_allocation<'b>(
457 ecx: &InterpCx<'tcx, Self>,
458 id: AllocId,
459 alloc: &'b Allocation,
460 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>;
461462/// Initialize the extra state of an allocation local to this machine.
463 ///
464 /// This is guaranteed to be called exactly once on all allocations local to this machine.
465 /// It will not be called automatically for global allocations; `adjust_global_allocation`
466 /// has to do that itself if that is desired.
467fn init_local_allocation(
468 ecx: &InterpCx<'tcx, Self>,
469 id: AllocId,
470 kind: MemoryKind<Self::MemoryKind>,
471 size: Size,
472 align: Align,
473 ) -> InterpResult<'tcx, Self::AllocExtra>;
474475/// Hook for performing extra checks on a memory read access.
476 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
477 /// `range`.
478 ///
479 /// This will *not* be called during validation!
480 ///
481 /// Takes read-only access to the allocation so we can keep all the memory read
482 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
483 /// need to mutate.
484 ///
485 /// This is not invoked for ZST accesses, as no read actually happens.
486#[inline(always)]
487fn before_memory_read(
488 _tcx: TyCtxtAt<'tcx>,
489 _machine: &Self,
490 _alloc_extra: &Self::AllocExtra,
491 _ptr: Pointer<Option<Self::Provenance>>,
492 _prov: (AllocId, Self::ProvenanceExtra),
493 _range: AllocRange,
494 ) -> InterpResult<'tcx> {
495interp_ok(())
496 }
497498/// Hook for performing extra checks on any memory read access,
499 /// that involves an allocation, even ZST reads.
500 ///
501 /// This will *not* be called during validation!
502 ///
503 /// Used to prevent statics from self-initializing by reading from their own memory
504 /// as it is being initialized.
505fn before_alloc_access(
506 _tcx: TyCtxtAt<'tcx>,
507 _machine: &Self,
508 _alloc_id: AllocId,
509 ) -> InterpResult<'tcx> {
510interp_ok(())
511 }
512513/// Hook for performing extra checks on a memory write access.
514 /// This is not invoked for ZST accesses, as no write actually happens.
515 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
516 /// `range`.
517#[inline(always)]
518fn before_memory_write(
519 _tcx: TyCtxtAt<'tcx>,
520 _machine: &mut Self,
521 _alloc_extra: &mut Self::AllocExtra,
522 _ptr: Pointer<Option<Self::Provenance>>,
523 _prov: (AllocId, Self::ProvenanceExtra),
524 _range: AllocRange,
525 ) -> InterpResult<'tcx> {
526interp_ok(())
527 }
528529/// Hook for performing extra operations on a memory deallocation.
530 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
531 /// the allocation.
532#[inline(always)]
533fn before_memory_deallocation(
534 _tcx: TyCtxtAt<'tcx>,
535 _machine: &mut Self,
536 _alloc_extra: &mut Self::AllocExtra,
537 _ptr: Pointer<Option<Self::Provenance>>,
538 _prov: (AllocId, Self::ProvenanceExtra),
539 _size: Size,
540 _align: Align,
541 _kind: MemoryKind<Self::MemoryKind>,
542 ) -> InterpResult<'tcx> {
543interp_ok(())
544 }
545546/// Executes a retagging operation for a single pointer.
547 /// Returns the possibly adjusted pointer. Return `None` if the pointer
548 /// was left unchanged.
549 ///
550 /// `ty` is the full type of the pointer. This is not the same as `val.layout.ty` for boxes
551 /// where `val` is just the inner raw pointer, but `ty` is the entire `Box` type.
552#[inline]
553fn retag_ptr_value(
554 _ecx: &mut InterpCx<'tcx, Self>,
555 _val: &ImmTy<'tcx, Self::Provenance>,
556 _ty: Ty<'tcx>,
557 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, Self::Provenance>>> {
558interp_ok(None)
559 }
560561/// Invoke `f` in a state where calls to `retag_ptr_value` will use the given retag mode.
562#[inline(always)]
563fn with_retag_mode<T>(
564 ecx: &mut InterpCx<'tcx, Self>,
565 _mode: RetagMode,
566 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
567 ) -> InterpResult<'tcx, T> {
568f(ecx)
569 }
570571/// Called on places used for in-place function argument and return value handling.
572 ///
573 /// These places need to be protected to make sure the program cannot tell whether the
574 /// argument/return value was actually copied or passed in-place..
575fn protect_in_place_function_argument(
576 ecx: &mut InterpCx<'tcx, Self>,
577 mplace: &MPlaceTy<'tcx, Self::Provenance>,
578 ) -> InterpResult<'tcx> {
579// Without an aliasing model, all we can do is put `Uninit` into the place.
580 // Conveniently this also ensures that the place actually points to suitable memory.
581ecx.write_uninit(mplace)
582 }
583584/// Called immediately before a new stack frame gets pushed.
585fn init_frame(
586 ecx: &mut InterpCx<'tcx, Self>,
587 frame: Frame<'tcx, Self::Provenance>,
588 ) -> InterpResult<'tcx, Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
589590/// Borrow the current thread's stack.
591fn stack<'a>(
592 ecx: &'a InterpCx<'tcx, Self>,
593 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>];
594595/// Mutably borrow the current thread's stack.
596fn stack_mut<'a>(
597 ecx: &'a mut InterpCx<'tcx, Self>,
598 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
599600/// Called immediately after a stack frame got pushed and its locals got initialized.
601fn after_stack_push(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
602interp_ok(())
603 }
604605/// Called just before the frame is removed from the stack (followed by return value copy and
606 /// local cleanup).
607fn before_stack_pop(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
608interp_ok(())
609 }
610611/// Called immediately after a stack frame got popped, but before jumping back to the caller.
612 /// The `locals` have already been destroyed!
613#[inline(always)]
614fn after_stack_pop(
615 _ecx: &mut InterpCx<'tcx, Self>,
616 _frame: Frame<'tcx, Self::Provenance, Self::FrameExtra>,
617 unwinding: bool,
618 ) -> InterpResult<'tcx, ReturnAction> {
619// By default, we do not support unwinding from panics
620if !!unwinding { ::core::panicking::panic("assertion failed: !unwinding") };assert!(!unwinding);
621interp_ok(ReturnAction::Normal)
622 }
623624/// Called immediately after an "immediate" local variable is read in a given frame
625 /// (i.e., this is called for reads that do not end up accessing addressable memory).
626#[inline(always)]
627fn after_local_read(
628 _ecx: &InterpCx<'tcx, Self>,
629 _frame: &Frame<'tcx, Self::Provenance, Self::FrameExtra>,
630 _local: mir::Local,
631 ) -> InterpResult<'tcx> {
632interp_ok(())
633 }
634635/// Called immediately after an "immediate" local variable is assigned a new value
636 /// (i.e., this is called for writes that do not end up in memory).
637 /// `storage_live` indicates whether this is the initial write upon `StorageLive`.
638#[inline(always)]
639fn after_local_write(
640 _ecx: &mut InterpCx<'tcx, Self>,
641 _local: mir::Local,
642 _storage_live: bool,
643 ) -> InterpResult<'tcx> {
644interp_ok(())
645 }
646647/// Called immediately after actual memory was allocated for a local
648 /// but before the local's stack frame is updated to point to that memory.
649#[inline(always)]
650fn after_local_moved_to_memory(
651 _ecx: &mut InterpCx<'tcx, Self>,
652 _local: mir::Local,
653 _mplace: &MPlaceTy<'tcx, Self::Provenance>,
654 ) -> InterpResult<'tcx> {
655interp_ok(())
656 }
657658/// Returns the salt to be used for a deduplicated global alloation.
659 /// If the allocation is for a function, the instance is provided as well
660 /// (this lets Miri ensure unique addresses for some functions).
661fn get_global_alloc_salt(
662 ecx: &InterpCx<'tcx, Self>,
663 instance: Option<ty::Instance<'tcx>>,
664 ) -> usize;
665666fn cached_union_data_range<'e>(
667 _ecx: &'e mut InterpCx<'tcx, Self>,
668 _ty: Ty<'tcx>,
669 compute_range: impl FnOnce() -> RangeSet,
670 ) -> Cow<'e, RangeSet> {
671// Default to no caching.
672Cow::Owned(compute_range())
673 }
674675/// Compute the value passed to the constructors of the `AllocBytes` type for
676 /// abstract machine allocations.
677fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
678679/// Allows enabling/disabling tracing calls from within `rustc_const_eval` at compile time, by
680 /// delegating the entering of [tracing::Span]s to implementors of the [Machine] trait. The
681 /// default implementation corresponds to tracing being disabled, meaning the tracing calls will
682 /// supposedly be optimized out completely. To enable tracing, override this trait method and
683 /// return `span.entered()`. Also see [crate::enter_trace_span].
684#[must_use]
685 #[inline(always)]
686fn enter_trace_span(_span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan {
687 ()
688 }
689}
690691/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
692/// (CTFE and ConstProp) use the same instance. Here, we share that code.
693pub macro compile_time_machine(<$tcx: lifetime>) {
694type Provenance = CtfeProvenance;
695type ProvenanceExtra = bool; // the "immutable" flag
696697type ExtraFnVal = !;
698699type MemoryKind = $crate::const_eval::MemoryKind;
700type MemoryMap =
701 rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
702const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
703704type AllocExtra = ();
705type FrameExtra = ();
706type Bytes = Box<[u8]>;
707708#[inline(always)]
709fn ignore_optional_overflow_checks(_ecx: &InterpCx<$tcx, Self>) -> bool {
710false
711}
712713#[inline(always)]
714fn unwind_terminate(
715 _ecx: &mut InterpCx<$tcx, Self>,
716 _reason: mir::UnwindTerminateReason,
717 ) -> InterpResult<$tcx> {
718unreachable!("unwinding cannot happen during compile-time evaluation")
719 }
720721#[inline(always)]
722fn check_fn_target_features(
723 _ecx: &InterpCx<$tcx, Self>,
724 _instance: ty::Instance<$tcx>,
725 ) -> InterpResult<$tcx> {
726// For now we don't do any checking here. We can't use `tcx.sess` because that can differ
727 // between crates, and we need to ensure that const-eval always behaves the same.
728interp_ok(())
729 }
730731#[inline(always)]
732fn call_extra_fn(
733 _ecx: &mut InterpCx<$tcx, Self>,
734 fn_val: !,
735 _abi: &FnAbi<$tcx, Ty<$tcx>>,
736 _args: &[FnArg<$tcx>],
737 _destination: &PlaceTy<$tcx, Self::Provenance>,
738 _target: Option<mir::BasicBlock>,
739 _unwind: mir::UnwindAction,
740 ) -> InterpResult<$tcx> {
741match fn_val {}
742 }
743744#[inline(always)]
745fn float_fuse_mul_add(_ecx: &InterpCx<$tcx, Self>) -> bool {
746true
747}
748749#[inline(always)]
750fn atomic_load(
751 ecx: &InterpCx<$tcx, Self>,
752 place: &MPlaceTy<$tcx, Self::Provenance>,
753 _ordering: AtomicOrdering,
754 ) -> InterpResult<$tcx, Scalar<Self::Provenance>> {
755// Compile-time machines are single-threaded so this is like a regular load.
756ecx.read_scalar(place)
757 }
758759#[inline(always)]
760fn atomic_store(
761 ecx: &mut InterpCx<$tcx, Self>,
762 place: &MPlaceTy<$tcx, Self::Provenance>,
763 val: &ImmTy<$tcx, Self::Provenance>,
764 _ordering: AtomicOrdering,
765 ) -> InterpResult<$tcx> {
766// Compile-time machines are single-threaded so this is like a regular store.
767ecx.write_scalar(val.to_scalar(), place)
768 }
769770fn atomic_rmw(
771 ecx: &mut InterpCx<$tcx, Self>,
772 place: &MPlaceTy<$tcx, Self::Provenance>,
773 op: AtomicRmwOp,
774 operand: &ImmTy<$tcx, Self::Provenance>,
775 _ordering: AtomicOrdering,
776 ) -> InterpResult<$tcx, Scalar<Self::Provenance>> {
777// Compile-time machines are single-threaded so we ignore the ordering.
778let old_val = ecx.read_immediate(place)?;
779let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
780 ecx.write_immediate(*new_val, place)?;
781 interp_ok(old_val.to_scalar())
782 }
783784fn atomic_compare_exchange(
785 ecx: &mut InterpCx<$tcx, Self>,
786 place: &MPlaceTy<$tcx, Self::Provenance>,
787 expected_old: &ImmTy<$tcx, Self::Provenance>,
788 new: &ImmTy<$tcx, Self::Provenance>,
789 _can_fail_spuriously: bool,
790 _success_ordering: AtomicOrdering,
791 _failure_ordering: AtomicOrdering,
792 ) -> InterpResult<$tcx, (Scalar<Self::Provenance>, bool)> {
793// Compile-time machines are single-threaded so we ignore the ordering.
794 // They are also deterministic so we do not fail spuriously.
795let actual_old = ecx.read_immediate(place)?;
796let eq = ecx.binary_op(mir::BinOp::Eq, &actual_old, expected_old)?.to_scalar().to_bool()?;
797if eq {
798 ecx.write_immediate(**new, place)?;
799 }
800 interp_ok((actual_old.to_scalar(), eq))
801 }
802803#[inline(always)]
804fn atomic_fence(
805 _ecx: &InterpCx<$tcx, Self>,
806 _ordering: AtomicOrdering,
807 _singlethread: bool,
808 ) -> InterpResult<$tcx> {
809// Compile-time machines are single-threaded so this is a NOP.
810interp_ok(())
811 }
812813#[inline(always)]
814fn adjust_global_allocation<'b>(
815 _ecx: &InterpCx<$tcx, Self>,
816 _id: AllocId,
817 alloc: &'b Allocation,
818 ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
819// Overwrite default implementation: no need to adjust anything.
820interp_ok(Cow::Borrowed(alloc))
821 }
822823fn init_local_allocation(
824 _ecx: &InterpCx<$tcx, Self>,
825 _id: AllocId,
826 _kind: MemoryKind<Self::MemoryKind>,
827 _size: Size,
828 _align: Align,
829 ) -> InterpResult<$tcx, Self::AllocExtra> {
830 interp_ok(())
831 }
832833fn extern_static_pointer(
834 ecx: &InterpCx<$tcx, Self>,
835 def_id: DefId,
836 ) -> InterpResult<$tcx, Pointer> {
837// Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
838interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(), Size::ZERO))
839 }
840841#[inline(always)]
842fn adjust_alloc_root_pointer(
843 _ecx: &InterpCx<$tcx, Self>,
844 ptr: Pointer<CtfeProvenance>,
845 _kind: Option<MemoryKind<Self::MemoryKind>>,
846 ) -> InterpResult<$tcx, Pointer<CtfeProvenance>> {
847 interp_ok(ptr)
848 }
849850#[inline(always)]
851fn ptr_from_addr_cast(
852 _ecx: &InterpCx<$tcx, Self>,
853 addr: u64,
854 ) -> InterpResult<$tcx, Pointer<Option<CtfeProvenance>>> {
855// Allow these casts, but make the pointer not dereferenceable.
856 // (I.e., they behave like transmutation.)
857 // This is correct because no pointers can ever be exposed in compile-time evaluation.
858interp_ok(Pointer::without_provenance(addr))
859 }
860861#[inline(always)]
862fn ptr_get_alloc(
863 _ecx: &InterpCx<$tcx, Self>,
864 ptr: Pointer<CtfeProvenance>,
865 _size: i64,
866 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
867let (prov, offset) = ptr.prov_and_relative_offset();
868Some((prov.alloc_id(), offset, prov.immutable()))
869 }
870871#[inline(always)]
872fn get_global_alloc_salt(
873 _ecx: &InterpCx<$tcx, Self>,
874 _instance: Option<ty::Instance<$tcx>>,
875 ) -> usize {
876 CTFE_ALLOC_SALT
877 }
878}