Skip to main content

rustc_const_eval/interpret/
machine.rs

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.
4
5use std::borrow::{Borrow, Cow};
6use std::fmt::Debug;
7use std::hash::Hash;
8
9use 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;
17
18use super::{
19    AllocBytes, AllocId, AllocKind, AllocRange, Allocation, AtomicRmwOp, CTFE_ALLOC_SALT,
20    ConstAllocation, CtfeProvenance, EnteredTraceSpan, FnArg, Frame, ImmTy, InterpCx, InterpResult,
21    MPlaceTy, MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, Scalar,
22    interp_ok, throw_unsup,
23};
24
25/// 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.
34    Normal,
35
36    /// Indicates that we should *not* jump to the return/unwind address, as the callback already
37    /// took care of everything.
38    NoJump,
39
40    /// Returned by [`InterpCx::pop_stack_frame_raw`] when no cleanup should be done.
41    NoCleanup,
42}
43
44/// 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.
48    Default,
49    /// Retag preparing for a two-phase borrow.
50    TwoPhase,
51    /// The initial retag of arguments when entering a function.
52    FnEntry,
53    /// Retagging for reference-to-raw-pointer cast.
54    Raw,
55    /// No retagging.
56    None,
57}
58
59/// Whether this kind of memory is allowed to leak
60pub trait MayLeak: Copy {
61    fn may_leak(self) -> bool;
62}
63
64/// 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`).
69    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
70    where
71        K: Borrow<Q>;
72
73    /// 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`).
77    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
78    where
79        K: Borrow<Q>;
80
81    /// Inserts a new entry into the map.
82    fn insert(&mut self, k: K, v: V) -> Option<V>;
83
84    /// Removes an entry from the map.
85    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
86    where
87        K: Borrow<Q>;
88
89    /// Returns data based on the keys and values in the map.
90    fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
91
92    /// 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*.
95    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
96
97    /// 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*.
100    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
101
102    /// Read-only lookup.
103    fn get(&self, k: K) -> Option<&V> {
104        self.get_or(k, || Err(())).ok()
105    }
106
107    /// Mutable lookup.
108    fn get_mut(&mut self, k: K) -> Option<&mut V> {
109        self.get_mut_or(k, || Err(())).ok()
110    }
111}
112
113/// 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
117    type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
118
119    /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
120    type Provenance: Provenance + Eq + Hash + 'static;
121
122    /// 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.
124    type ProvenanceExtra: Copy + 'static;
125
126    /// 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.
129    type ExtraFnVal: Debug + Copy;
130
131    /// Extra data stored in every call frame.
132    type FrameExtra;
133
134    /// Extra data stored in every allocation.
135    type AllocExtra: Debug + Clone + 'tcx;
136
137    /// Type for the bytes of the allocation.
138    type Bytes: AllocBytes + 'static;
139
140    /// Memory's allocation map
141    type MemoryMap: AllocMap<
142            AllocId,
143            (
144                MemoryKind<Self::MemoryKind>,
145                Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>,
146            ),
147        > + Default
148        + Clone;
149
150    /// 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.
156    const GLOBAL_KIND: Option<Self::MemoryKind>;
157
158    /// Should the machine panic on allocation failures?
159    const PANIC_ON_ALLOC_FAIL: bool;
160
161    /// Determines whether `eval_mir_constant` can never fail because all required consts have
162    /// already been checked before.
163    const ALL_CONSTS_ARE_PRECHECKED: bool = true;
164
165    /// Whether memory accesses should be alignment-checked.
166    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool;
167
168    /// Gives the machine a chance to detect more misalignment than the built-in checks would catch.
169    #[inline(always)]
170    fn 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> {
178        None
179    }
180
181    /// Whether to enforce the validity invariant for a specific layout.
182    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool;
183    /// Whether to enforce the validity invariant *recursively*.
184    fn enforce_validity_recursively(
185        _ecx: &InterpCx<'tcx, Self>,
186        _layout: TyAndLayout<'tcx>,
187    ) -> bool {
188        false
189    }
190
191    /// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
192    /// check for overflow.
193    fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
194
195    /// 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, ...
198    fn load_mir(
199        ecx: &InterpCx<'tcx, Self>,
200        instance: ty::InstanceKind<'tcx>,
201    ) -> &'tcx mir::Body<'tcx> {
202        ecx.tcx.instance_mir(instance)
203    }
204
205    /// 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.
215    fn 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>)>>;
224
225    /// Execute `fn_val`. It is the hook's responsibility to advance the instruction
226    /// pointer as appropriate.
227    fn 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>;
236
237    /// 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.
242    fn 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>>>;
250
251    /// Directly process an LLVM intrinsic without pushing a stack frame. It is the hook's
252    /// responsibility to advance the instruction pointer as appropriate.
253    fn 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>;
260
261    /// Check whether the given function may be executed on the current machine, in terms of the
262    /// target features is requires.
263    fn check_fn_target_features(
264        _ecx: &InterpCx<'tcx, Self>,
265        _instance: ty::Instance<'tcx>,
266    ) -> InterpResult<'tcx>;
267
268    /// Called to evaluate `Assert` MIR terminators that trigger a panic.
269    fn assert_panic(
270        ecx: &mut InterpCx<'tcx, Self>,
271        msg: &mir::AssertMessage<'tcx>,
272        unwind: mir::UnwindAction,
273    ) -> InterpResult<'tcx>;
274
275    /// Called to trigger a non-unwinding panic.
276    fn panic_nounwind(_ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx>;
277
278    /// Called when unwinding reached a state where execution should be terminated.
279    fn unwind_terminate(
280        ecx: &mut InterpCx<'tcx, Self>,
281        reason: mir::UnwindTerminateReason,
282    ) -> InterpResult<'tcx>;
283
284    /// Called for all binary operations where the LHS has pointer type.
285    fn 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>>;
291
292    /// Generate the NaN returned by a float operation, given the list of inputs.
293    /// (This is all inputs, not just NaN inputs!)
294    fn 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.
299        F2::NAN
300    }
301
302    /// Apply non-determinism to float operations that do not return a precise result.
303    fn apply_float_nondet(
304        _ecx: &mut InterpCx<'tcx, Self>,
305        val: ImmTy<'tcx, Self::Provenance>,
306    ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
307        interp_ok(val)
308    }
309
310    /// Determines the result of `min`/`max` on floats when the arguments are equal.
311    fn equal_float_min_max<F: Float>(_ecx: &InterpCx<'tcx, Self>, a: F, _b: F) -> F {
312        // By default, we pick the left argument.
313        a
314    }
315
316    /// Determines whether the `fmuladd` intrinsics fuse the multiply-add or use separate operations.
317    fn float_fuse_mul_add(ecx: &InterpCx<'tcx, Self>) -> bool;
318
319    fn atomic_load(
320        ecx: &InterpCx<'tcx, Self>,
321        place: &MPlaceTy<'tcx, Self::Provenance>,
322        ordering: AtomicOrdering,
323    ) -> InterpResult<'tcx, Scalar<Self::Provenance>>;
324
325    fn 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>;
331
332    /// Returns the old value.
333    fn 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>>;
340
341    /// Returns a pair of the old value and a boolean indicating whether the update happened.
342    fn 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)>;
351
352    fn atomic_fence(
353        ecx: &InterpCx<'tcx, Self>,
354        ordering: AtomicOrdering,
355        singlethread: bool,
356    ) -> InterpResult<'tcx>;
357
358    /// Called before a basic block terminator is executed.
359    #[inline]
360    fn before_terminator(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
361        interp_ok(())
362    }
363
364    /// Determines the result of a `Operand::RuntimeChecks` invocation.
365    fn runtime_checks(
366        _ecx: &InterpCx<'tcx, Self>,
367        r: mir::RuntimeChecks,
368    ) -> InterpResult<'tcx, bool>;
369
370    /// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
371    /// You can use this to detect long or endlessly running programs.
372    #[inline]
373    fn increment_const_eval_counter(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
374        interp_ok(())
375    }
376
377    /// Called before a global allocation is accessed.
378    /// `def_id` is `Some` if this is the "lazy" allocation of a static.
379    #[inline]
380    fn 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> {
388        interp_ok(())
389    }
390
391    /// Return the `AllocId` for the given thread-local static in the current thread.
392    fn thread_local_static_pointer(
393        _ecx: &mut InterpCx<'tcx, Self>,
394        def_id: DefId,
395    ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
396        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ThreadLocalStatic(def_id))throw_unsup!(ThreadLocalStatic(def_id))
397    }
398
399    /// Return the `AllocId` for the given `extern static`.
400    fn extern_static_pointer(
401        ecx: &InterpCx<'tcx, Self>,
402        def_id: DefId,
403    ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
404
405    /// "Int-to-pointer cast"
406    fn ptr_from_addr_cast(
407        ecx: &InterpCx<'tcx, Self>,
408        addr: u64,
409    ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
410
411    /// Marks a pointer as exposed, allowing its provenance
412    /// to be recovered. "Pointer-to-int cast"
413    fn expose_provenance(
414        ecx: &InterpCx<'tcx, Self>,
415        provenance: Self::Provenance,
416    ) -> InterpResult<'tcx>;
417
418    /// 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.
429    fn ptr_get_alloc(
430        ecx: &InterpCx<'tcx, Self>,
431        ptr: Pointer<Self::Provenance>,
432        size: i64,
433    ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
434
435    /// 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`.
442    fn adjust_alloc_root_pointer(
443        ecx: &InterpCx<'tcx, Self>,
444        ptr: Pointer,
445        kind: Option<MemoryKind<Self::MemoryKind>>,
446    ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
447
448    /// 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.)
456    fn 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>>>;
461
462    /// 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.
467    fn 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>;
474
475    /// 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)]
487    fn 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> {
495        interp_ok(())
496    }
497
498    /// 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.
505    fn before_alloc_access(
506        _tcx: TyCtxtAt<'tcx>,
507        _machine: &Self,
508        _alloc_id: AllocId,
509    ) -> InterpResult<'tcx> {
510        interp_ok(())
511    }
512
513    /// 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)]
518    fn 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> {
526        interp_ok(())
527    }
528
529    /// 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)]
533    fn 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> {
543        interp_ok(())
544    }
545
546    /// 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]
553    fn 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>>> {
558        interp_ok(None)
559    }
560
561    /// Invoke `f` in a state where calls to `retag_ptr_value` will use the given retag mode.
562    #[inline(always)]
563    fn 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> {
568        f(ecx)
569    }
570
571    /// 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..
575    fn 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.
581        ecx.write_uninit(mplace)
582    }
583
584    /// Called immediately before a new stack frame gets pushed.
585    fn init_frame(
586        ecx: &mut InterpCx<'tcx, Self>,
587        frame: Frame<'tcx, Self::Provenance>,
588    ) -> InterpResult<'tcx, Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
589
590    /// Borrow the current thread's stack.
591    fn stack<'a>(
592        ecx: &'a InterpCx<'tcx, Self>,
593    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>];
594
595    /// Mutably borrow the current thread's stack.
596    fn stack_mut<'a>(
597        ecx: &'a mut InterpCx<'tcx, Self>,
598    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
599
600    /// Called immediately after a stack frame got pushed and its locals got initialized.
601    fn after_stack_push(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
602        interp_ok(())
603    }
604
605    /// Called just before the frame is removed from the stack (followed by return value copy and
606    /// local cleanup).
607    fn before_stack_pop(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
608        interp_ok(())
609    }
610
611    /// 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)]
614    fn 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
620        if !!unwinding { ::core::panicking::panic("assertion failed: !unwinding") };assert!(!unwinding);
621        interp_ok(ReturnAction::Normal)
622    }
623
624    /// 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)]
627    fn after_local_read(
628        _ecx: &InterpCx<'tcx, Self>,
629        _frame: &Frame<'tcx, Self::Provenance, Self::FrameExtra>,
630        _local: mir::Local,
631    ) -> InterpResult<'tcx> {
632        interp_ok(())
633    }
634
635    /// 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)]
639    fn after_local_write(
640        _ecx: &mut InterpCx<'tcx, Self>,
641        _local: mir::Local,
642        _storage_live: bool,
643    ) -> InterpResult<'tcx> {
644        interp_ok(())
645    }
646
647    /// 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)]
650    fn after_local_moved_to_memory(
651        _ecx: &mut InterpCx<'tcx, Self>,
652        _local: mir::Local,
653        _mplace: &MPlaceTy<'tcx, Self::Provenance>,
654    ) -> InterpResult<'tcx> {
655        interp_ok(())
656    }
657
658    /// 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).
661    fn get_global_alloc_salt(
662        ecx: &InterpCx<'tcx, Self>,
663        instance: Option<ty::Instance<'tcx>>,
664    ) -> usize;
665
666    fn 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.
672        Cow::Owned(compute_range())
673    }
674
675    /// Compute the value passed to the constructors of the `AllocBytes` type for
676    /// abstract machine allocations.
677    fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
678
679    /// 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)]
686    fn enter_trace_span(_span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan {
687        ()
688    }
689}
690
691/// 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>) {
694    type Provenance = CtfeProvenance;
695    type ProvenanceExtra = bool; // the "immutable" flag
696
697    type ExtraFnVal = !;
698
699    type MemoryKind = $crate::const_eval::MemoryKind;
700    type MemoryMap =
701        rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
702    const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
703
704    type AllocExtra = ();
705    type FrameExtra = ();
706    type Bytes = Box<[u8]>;
707
708    #[inline(always)]
709    fn ignore_optional_overflow_checks(_ecx: &InterpCx<$tcx, Self>) -> bool {
710        false
711    }
712
713    #[inline(always)]
714    fn unwind_terminate(
715        _ecx: &mut InterpCx<$tcx, Self>,
716        _reason: mir::UnwindTerminateReason,
717    ) -> InterpResult<$tcx> {
718        unreachable!("unwinding cannot happen during compile-time evaluation")
719    }
720
721    #[inline(always)]
722    fn 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.
728        interp_ok(())
729    }
730
731    #[inline(always)]
732    fn 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> {
741        match fn_val {}
742    }
743
744    #[inline(always)]
745    fn float_fuse_mul_add(_ecx: &InterpCx<$tcx, Self>) -> bool {
746        true
747    }
748
749    #[inline(always)]
750    fn 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.
756        ecx.read_scalar(place)
757    }
758
759    #[inline(always)]
760    fn 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.
767        ecx.write_scalar(val.to_scalar(), place)
768    }
769
770    fn 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.
778        let old_val = ecx.read_immediate(place)?;
779        let 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    }
783
784    fn 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.
795        let actual_old = ecx.read_immediate(place)?;
796        let eq = ecx.binary_op(mir::BinOp::Eq, &actual_old, expected_old)?.to_scalar().to_bool()?;
797        if eq {
798            ecx.write_immediate(**new, place)?;
799        }
800        interp_ok((actual_old.to_scalar(), eq))
801    }
802
803    #[inline(always)]
804    fn 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.
810        interp_ok(())
811    }
812
813    #[inline(always)]
814    fn 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.
820        interp_ok(Cow::Borrowed(alloc))
821    }
822
823    fn 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    }
832
833    fn 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.
838        interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(), Size::ZERO))
839    }
840
841    #[inline(always)]
842    fn 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    }
849
850    #[inline(always)]
851    fn 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.
858        interp_ok(Pointer::without_provenance(addr))
859    }
860
861    #[inline(always)]
862    fn ptr_get_alloc(
863        _ecx: &InterpCx<$tcx, Self>,
864        ptr: Pointer<CtfeProvenance>,
865        _size: i64,
866    ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
867        let (prov, offset) = ptr.prov_and_relative_offset();
868        Some((prov.alloc_id(), offset, prov.immutable()))
869    }
870
871    #[inline(always)]
872    fn get_global_alloc_salt(
873        _ecx: &InterpCx<$tcx, Self>,
874        _instance: Option<ty::Instance<$tcx>>,
875    ) -> usize {
876        CTFE_ALLOC_SALT
877    }
878}