Skip to main content

rustc_const_eval/const_eval/
machine.rs

1use std::borrow::{Borrow, Cow};
2use std::hash::Hash;
3use std::{fmt, mem};
4
5use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx};
6use rustc_ast::Mutability;
7use rustc_attr_ir::find_attr;
8use rustc_attr_ir::lang_items::LangItem;
9use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::{CRATE_HIR_ID, HirId};
12use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL;
13use rustc_middle::mir::AssertMessage;
14use rustc_middle::mir::interpret::ReportedErrorInfo;
15use rustc_middle::query::TyCtxtAt;
16use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement};
17use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt};
18use rustc_middle::{mir, throw_machine_stop};
19use rustc_span::{Span, Symbol, bug, span_bug, sym};
20use rustc_target::callconv::FnAbi;
21use tracing::debug;
22
23use super::error::*;
24use crate::diagnostics::{LongRunning, LongRunningWarn};
25use crate::interpret::{
26    self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
27    GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet,
28    RetagMode, Scalar, compile_time_machine, ensure_monomorphic_enough, err_inval, interp_ok,
29    throw_exhaust, throw_inval, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format,
30    type_implements_dyn_trait,
31};
32
33/// When hitting this many interpreted terminators we emit a deny by default lint
34/// that notfies the user that their constant takes a long time to evaluate. If that's
35/// what they intended, they can just allow the lint.
36const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
37/// The limit used by `-Z tiny-const-eval-limit`. This smaller limit is useful for internal
38/// tests not needing to run 30s or more to show some behaviour.
39const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
40/// After this many interpreted terminators, we start emitting progress indicators at every
41/// power of two of interpreted terminators.
42const PROGRESS_INDICATOR_START: usize = 4_000_000;
43
44/// Extra machine state for CTFE, and the Machine instance.
45//
46// Should be public because out-of-tree rustc consumers need this
47// if they want to interact with constant values.
48pub struct CompileTimeMachine<'tcx> {
49    /// The number of terminators that have been evaluated.
50    ///
51    /// This is used to produce lints informing the user that the compiler is not stuck.
52    /// Set to `usize::MAX` to never report anything.
53    pub(super) num_evaluated_steps: usize,
54
55    /// The virtual call stack.
56    pub(super) stack: Vec<Frame<'tcx>>,
57
58    /// Pattern matching on consts with references would be unsound if those references
59    /// could point to anything mutable. Therefore, when evaluating consts and when constructing valtrees,
60    /// we ensure that only immutable global memory can be accessed.
61    pub(super) can_access_mut_global: CanAccessMutGlobal,
62
63    /// Whether to check alignment during evaluation.
64    pub(super) check_alignment: CheckAlignment,
65
66    /// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
67    /// storing the result in the given `AllocId`.
68    /// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
69    pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
70
71    /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
72    union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
73
74    /// The current retag mode.
75    retag_mode: RetagMode,
76}
77
78#[derive(#[automatically_derived]
impl ::core::marker::Copy for CheckAlignment { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CheckAlignment { }
#[automatically_derived]
impl ::core::clone::Clone for CheckAlignment {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone)]
79pub enum CheckAlignment {
80    /// Ignore all alignment requirements.
81    /// This is mainly used in interning.
82    No,
83    /// Hard error when dereferencing a misaligned pointer.
84    Error,
85}
86
87#[derive(#[automatically_derived]
impl ::core::marker::Copy for CanAccessMutGlobal { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CanAccessMutGlobal { }
#[automatically_derived]
impl ::core::clone::Clone for CanAccessMutGlobal {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CanAccessMutGlobal { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CanAccessMutGlobal {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
88pub(crate) enum CanAccessMutGlobal {
89    No,
90    Yes,
91}
92
93impl From<bool> for CanAccessMutGlobal {
94    fn from(value: bool) -> Self {
95        if value { Self::Yes } else { Self::No }
96    }
97}
98
99impl<'tcx> CompileTimeMachine<'tcx> {
100    pub(crate) fn new(
101        can_access_mut_global: CanAccessMutGlobal,
102        check_alignment: CheckAlignment,
103    ) -> Self {
104        CompileTimeMachine {
105            num_evaluated_steps: 0,
106            stack: Vec::new(),
107            can_access_mut_global,
108            check_alignment,
109            static_root_ids: None,
110            union_data_ranges: FxHashMap::default(),
111            retag_mode: RetagMode::Default,
112        }
113    }
114}
115
116impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
117    #[inline(always)]
118    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
119    where
120        K: Borrow<Q>,
121    {
122        FxIndexMap::contains_key(self, k)
123    }
124
125    #[inline(always)]
126    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
127    where
128        K: Borrow<Q>,
129    {
130        FxIndexMap::contains_key(self, k)
131    }
132
133    #[inline(always)]
134    fn insert(&mut self, k: K, v: V) -> Option<V> {
135        FxIndexMap::insert(self, k, v)
136    }
137
138    #[inline(always)]
139    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
140    where
141        K: Borrow<Q>,
142    {
143        // FIXME(#120456) - is `swap_remove` correct?
144        FxIndexMap::swap_remove(self, k)
145    }
146
147    #[inline(always)]
148    fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
149        self.iter().filter_map(move |(k, v)| f(k, v)).collect()
150    }
151
152    #[inline(always)]
153    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
154        match self.get(&k) {
155            Some(v) => Ok(v),
156            None => {
157                vacant()?;
158                ::rustc_span::macros::bug_impl(None,
    format_args!("The CTFE machine shouldn\'t ever need to extend the alloc_map when reading"),
    Location::caller())bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
159            }
160        }
161    }
162
163    #[inline(always)]
164    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
165        match self.entry(k) {
166            IndexEntry::Occupied(e) => Ok(e.into_mut()),
167            IndexEntry::Vacant(e) => {
168                let v = vacant()?;
169                Ok(e.insert(v))
170            }
171        }
172    }
173}
174
175pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
176
177#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MemoryKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Heap { was_made_global: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Heap",
                    "was_made_global", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MemoryKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MemoryKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Heap { was_made_global: __self_0 }, Self::Heap {
                was_made_global: __arg1_0 }) => __self_0 == __arg1_0,
        }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MemoryKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::Copy for MemoryKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MemoryKind { }
#[automatically_derived]
impl ::core::clone::Clone for MemoryKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone)]
178pub enum MemoryKind {
179    Heap {
180        /// Indicates whether `make_global` was called on this allocation.
181        /// If this is `true`, the allocation must be immutable.
182        was_made_global: bool,
183    },
184}
185
186impl fmt::Display for MemoryKind {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        match self {
189            MemoryKind::Heap { was_made_global } => {
190                f.write_fmt(format_args!("heap allocation{0}",
        if *was_made_global { " (made global)" } else { "" }))write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })
191            }
192        }
193    }
194}
195
196impl interpret::MayLeak for MemoryKind {
197    #[inline(always)]
198    fn may_leak(self) -> bool {
199        match self {
200            MemoryKind::Heap { was_made_global } => was_made_global,
201        }
202    }
203}
204
205impl interpret::MayLeak for ! {
206    #[inline(always)]
207    fn may_leak(self) -> bool {
208        // `self` is uninhabited
209        self
210    }
211}
212
213impl<'tcx> CompileTimeInterpCx<'tcx> {
214    fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
215        let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
216        let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
217
218        use rustc_span::RemapPathScopeComponents;
219        (
220            Symbol::intern(
221                &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
222            ),
223            u32::try_from(caller.line).unwrap(),
224            u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
225        )
226    }
227
228    /// "Intercept" a function call, because we have something special to do for it.
229    /// All `#[rustc_do_not_const_check]` functions MUST be hooked here.
230    /// If this returns `Some` function, which may be `instance` or a different function with
231    /// compatible arguments, then evaluation should continue with that function.
232    /// If this returns `None`, the function call has been handled and the function has returned.
233    fn hook_special_const_fn(
234        &mut self,
235        instance: ty::Instance<'tcx>,
236        args: &[FnArg<'tcx>],
237        _dest: &PlaceTy<'tcx>,
238        _ret: Option<mir::BasicBlock>,
239    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
240        let def_id = instance.def_id();
241
242        if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
243            || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
244        {
245            let args = Self::copy_fn_args(args);
246            // &str or &&str
247            if !(args.len() == 1) {
    ::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
248
249            let mut msg_place = self.deref_pointer(&args[0])?;
250            while msg_place.layout.ty.is_ref() {
251                msg_place = self.deref_pointer(&msg_place)?;
252            }
253
254            let msg = Symbol::intern(self.read_str(&msg_place)?);
255            let span = self.find_closest_untracked_caller_location();
256            let (file, line, col) = self.location_triple_for_span(span);
257            return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
258        } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
259            // For panic_fmt, call const_panic_fmt instead.
260            let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
261            let new_instance = ty::Instance::expect_resolve(
262                *self.tcx,
263                self.typing_env(),
264                const_def_id,
265                instance.args,
266                self.cur_span(),
267            );
268
269            return interp_ok(Some(new_instance));
270        }
271        interp_ok(Some(instance))
272    }
273
274    /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
275    /// Returns `2` if the result is unknown.
276    /// Returns `1` if the pointers are guaranteed equal.
277    /// Returns `0` if the pointers are guaranteed inequal.
278    ///
279    /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any
280    /// change to this function that affects comparison with null is insta-stable!
281    fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
282        interp_ok(match (a, b) {
283            // Comparisons between integers are always known.
284            (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
285            // Comparing a pointer `ptr` with an integer `int` is equivalent to comparing
286            // `ptr-int` with null, so we can reduce this case to a `scalar_may_be_null` test.
287            (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
288                let int = int.to_target_usize(*self.tcx);
289                // The `wrapping_neg` here may produce a value that is not
290                // a valid target usize any more... but `wrapping_offset` handles that correctly.
291                let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
292                if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
293                    // `ptr.wrapping_sub(int)` is definitely not equal to `0`, so `ptr != int`
294                    0
295                } else {
296                    // `ptr.wrapping_sub(int)` could be equal to `0`, but might not be,
297                    // so we cannot know for sure if `ptr == int` or not
298                    2
299                }
300            }
301            (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
302                let (a_prov, a_offset) = a.prov_and_relative_offset();
303                let (b_prov, b_offset) = b.prov_and_relative_offset();
304                let a_allocid = a_prov.alloc_id();
305                let b_allocid = b_prov.alloc_id();
306                let a_info = self.get_alloc_info(a_allocid);
307                let b_info = self.get_alloc_info(b_allocid);
308
309                // Check if the pointers cannot be equal due to alignment
310                if a_info.align > Align::ONE && b_info.align > Align::ONE {
311                    let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
312                    let a_residue = a_offset.bytes() % min_align;
313                    let b_residue = b_offset.bytes() % min_align;
314                    if a_residue != b_residue {
315                        // If the two pointers have a different residue modulo their
316                        // common alignment, they cannot be equal.
317                        return interp_ok(0);
318                    }
319                    // The pointers have the same residue modulo their common alignment,
320                    // so they could be equal. Try the other checks.
321                }
322
323                if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
324                    self.tcx.try_get_global_alloc(a_allocid),
325                    self.tcx.try_get_global_alloc(b_allocid),
326                ) {
327                    if a_allocid == b_allocid {
328                        if true {
    {
        match (&a_did, &b_did) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("different static item DefIds had same AllocId? {0:?} == {1:?}, {2:?} != {3:?}",
                                a_allocid, b_allocid, a_did, b_did)));
                }
            }
        }
    };
};debug_assert_eq!(
329                            a_did, b_did,
330                            "different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
331                        );
332                        // Comparing two pointers into the same static. As per
333                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
334                        // a static cannot be duplicated, so if two pointers are into the same
335                        // static, they are equal if and only if their offsets are equal.
336                        (a_offset == b_offset) as u8
337                    } else {
338                        if true {
    {
        match (&(a_did), &(b_did)) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("same static item DefId had two different AllocIds? {0:?} != {1:?}, {2:?} == {3:?}",
                                a_allocid, b_allocid, a_did, b_did)));
                }
            }
        }
    };
};debug_assert_ne!(
339                            a_did, b_did,
340                            "same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
341                        );
342                        // Comparing two pointers into the different statics.
343                        // We can never determine for sure that two pointers into different statics
344                        // are *equal*, but we can know that they are *inequal* if they are both
345                        // strictly in-bounds (i.e. in-bounds and not one-past-the-end) of
346                        // their respective static, as different non-zero-sized statics cannot
347                        // overlap or be deduplicated as per
348                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
349                        // (non-deduplication), and
350                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
351                        // (non-overlapping).
352                        if a_offset < a_info.size && b_offset < b_info.size {
353                            0
354                        } else {
355                            // Otherwise, conservatively say we don't know.
356                            // There are some cases we could still return `0` for, e.g.
357                            // if the pointers being equal would require their statics to overlap
358                            // one or more bytes, but for simplicity we currently only check
359                            // strictly in-bounds pointers.
360                            2
361                        }
362                    }
363                } else {
364                    // All other cases we conservatively say we don't know.
365                    //
366                    // For comparing statics to non-statics, as per https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
367                    // immutable statics can overlap with other kinds of allocations sometimes.
368                    //
369                    // FIXME: We could be more decisive for (non-zero-sized) mutable statics,
370                    // which cannot overlap with other kinds of allocations.
371                    //
372                    // Functions and vtables can be duplicated and deduplicated, so we
373                    // cannot be sure of runtime equality of pointers to the same one, or the
374                    // runtime inequality of pointers to different ones (see e.g. #73722),
375                    // so comparing those should return 2, whether they are the same allocation
376                    // or not.
377                    //
378                    // `GlobalAlloc::TypeId` exists mostly to prevent consteval from comparing
379                    // `TypeId`s, so comparing those should always return 2, whether they are the
380                    // same allocation or not.
381                    //
382                    // FIXME: We could revisit comparing pointers into the same
383                    // `GlobalAlloc::Memory` once https://github.com/rust-lang/rust/issues/128775
384                    // is fixed (but they can be deduplicated, so comparing pointers into different
385                    // ones should return 2).
386                    2
387                }
388            }
389        })
390    }
391}
392
393impl<'tcx> CompileTimeMachine<'tcx> {
394    #[inline(always)]
395    /// Find the first stack frame that is within the current crate, if any.
396    /// Otherwise, return the crate's HirId
397    pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> HirId {
398        self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
399    }
400}
401
402impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
403    type Provenance = CtfeProvenance;
type ProvenanceExtra = bool;
type ExtraFnVal = !;
type MemoryKind = crate::const_eval::MemoryKind;
type MemoryMap =
    rustc_data_structures::fx::FxIndexMap<AllocId,
    (MemoryKind<Self::MemoryKind>, Allocation)>;
const GLOBAL_KIND: Option<Self::MemoryKind> = None;
type AllocExtra = ();
type FrameExtra = ();
type Bytes = Box<[u8]>;
#[inline(always)]
fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool {
    false
}
#[inline(always)]
fn unwind_terminate(_ecx: &mut InterpCx<'tcx, Self>,
    _reason: mir::UnwindTerminateReason) -> InterpResult<'tcx> {
    {
        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                format_args!("unwinding cannot happen during compile-time evaluation")));
    }
}
#[inline(always)]
fn check_fn_target_features(_ecx: &InterpCx<'tcx, Self>,
    _instance: ty::Instance<'tcx>) -> InterpResult<'tcx> {
    interp_ok(())
}
#[inline(always)]
fn call_extra_fn(_ecx: &mut InterpCx<'tcx, Self>, fn_val: !,
    _abi: &FnAbi<'tcx, Ty<'tcx>>, _args: &[FnArg<'tcx>],
    _destination: &PlaceTy<'tcx, Self::Provenance>,
    _target: Option<mir::BasicBlock>, _unwind: mir::UnwindAction)
    -> InterpResult<'tcx> {
    match fn_val {}
}
#[inline(always)]
fn float_fuse_mul_add(_ecx: &InterpCx<'tcx, Self>) -> bool { true }
#[inline(always)]
fn atomic_load(ecx: &InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx, Scalar<Self::Provenance>> {
    ecx.read_scalar(place)
}
#[inline(always)]
fn atomic_store(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>,
    val: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx> {
    ecx.write_scalar(val.to_scalar(), place)
}
fn atomic_rmw(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>, op: AtomicRmwOp,
    operand: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx, Scalar<Self::Provenance>> {
    let old_val = ecx.read_immediate(place)?;
    let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
    ecx.write_immediate(*new_val, place)?;
    interp_ok(old_val.to_scalar())
}
fn atomic_compare_exchange(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>,
    expected_old: &ImmTy<'tcx, Self::Provenance>,
    new: &ImmTy<'tcx, Self::Provenance>, _can_fail_spuriously: bool,
    _success_ordering: AtomicOrdering, _failure_ordering: AtomicOrdering)
    -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)> {
    let actual_old = ecx.read_immediate(place)?;
    let eq =
        ecx.binary_op(mir::BinOp::Eq, &actual_old,
                            expected_old)?.to_scalar().to_bool()?;
    if eq { ecx.write_immediate(**new, place)?; }
    interp_ok((actual_old.to_scalar(), eq))
}
#[inline(always)]
fn atomic_fence(_ecx: &InterpCx<'tcx, Self>, _ordering: AtomicOrdering,
    _singlethread: bool) -> InterpResult<'tcx> {
    interp_ok(())
}
#[inline(always)]
fn adjust_global_allocation<'b>(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
    alloc: &'b Allocation)
    -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance>>> {
    interp_ok(Cow::Borrowed(alloc))
}
fn init_local_allocation(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
    _kind: MemoryKind<Self::MemoryKind>, _size: Size, _align: Align)
    -> InterpResult<'tcx, Self::AllocExtra> {
    interp_ok(())
}
fn extern_static_pointer(ecx: &InterpCx<'tcx, Self>, def_id: DefId)
    -> InterpResult<'tcx, Pointer> {
    interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(),
            Size::ZERO))
}
#[inline(always)]
fn adjust_alloc_root_pointer(_ecx: &InterpCx<'tcx, Self>,
    ptr: Pointer<CtfeProvenance>, _kind: Option<MemoryKind<Self::MemoryKind>>)
    -> InterpResult<'tcx, Pointer<CtfeProvenance>> {
    interp_ok(ptr)
}
#[inline(always)]
fn ptr_from_addr_cast(_ecx: &InterpCx<'tcx, Self>, addr: u64)
    -> InterpResult<'tcx, Pointer<Option<CtfeProvenance>>> {
    interp_ok(Pointer::without_provenance(addr))
}
#[inline(always)]
fn ptr_get_alloc(_ecx: &InterpCx<'tcx, Self>, ptr: Pointer<CtfeProvenance>,
    _size: i64) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
    let (prov, offset) = ptr.prov_and_relative_offset();
    Some((prov.alloc_id(), offset, prov.immutable()))
}
#[inline(always)]
fn get_global_alloc_salt(_ecx: &InterpCx<'tcx, Self>,
    _instance: Option<ty::Instance<'tcx>>) -> usize {
    CTFE_ALLOC_SALT
}compile_time_machine!(<'tcx>);
404
405    const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
406
407    #[inline(always)]
408    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
409        #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.check_alignment {
    CheckAlignment::Error => true,
    _ => false,
}matches!(ecx.machine.check_alignment, CheckAlignment::Error)
410    }
411
412    #[inline(always)]
413    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
414        ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
415    }
416
417    fn load_mir(
418        ecx: &InterpCx<'tcx, Self>,
419        instance: ty::InstanceKind<'tcx>,
420    ) -> &'tcx mir::Body<'tcx> {
421        match instance {
422            ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
423            _ => ecx.tcx.instance_mir(instance),
424        }
425    }
426
427    fn find_mir_or_eval_fn(
428        ecx: &mut InterpCx<'tcx, Self>,
429        orig_instance: ty::Instance<'tcx>,
430        _abi: &FnAbi<'tcx, Ty<'tcx>>,
431        args: &[FnArg<'tcx>],
432        dest: &PlaceTy<'tcx>,
433        ret: Option<mir::BasicBlock>,
434        _unwind: mir::UnwindAction, // unwinding is not supported in consts
435    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
436        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/8006091eb71ae7d9e9bccb66c6122c9d68af4466/compiler/rustc_const_eval/src/const_eval/machine.rs:436",
                        "rustc_const_eval::const_eval::machine",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/8006091eb71ae7d9e9bccb66c6122c9d68af4466/compiler/rustc_const_eval/src/const_eval/machine.rs"),
                        ::tracing_core::__macro_support::Option::Some(436u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::machine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_mir_or_eval_fn: {0:?}",
                                                    orig_instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_mir_or_eval_fn: {:?}", orig_instance);
437
438        // Replace some functions.
439        let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
440            // Call has already been handled.
441            return interp_ok(None);
442        };
443
444        // Only check non-glue functions
445        if let ty::InstanceKind::Item(def) = instance.def {
446            // Execution might have wandered off into other crates, so we cannot do a stability-
447            // sensitive check here. But we can at least rule out functions that are not const at
448            // all. That said, we have to allow calling functions inside a `const trait`. These
449            // *are* const-checked!
450            if !ecx.tcx.is_const_fn(def) || {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def, &ecx.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
451                // We certainly do *not* want to actually call this fn. const-checking should have
452                // prevented this, but this can be reached with unleashed-miri, so make testing
453                // simpler by avoiding ICEs there. (Technically this can still ICE if miri-unleash
454                // was set in a dependency rather than the current crate. That's okay, it's an
455                // internal unstable feature.)
456                if ecx.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
457                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("calling non-const function `{0}`",
                            instance))
                })))throw_unsup_format!("calling non-const function `{}`", instance)
458                } else {
459                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("calling non-const function `{0}`", instance),
    Location::caller())span_bug!(ecx.cur_span(), "calling non-const function `{}`", instance)
460                }
461            }
462        }
463
464        // This is a const fn. Call it.
465        // In case of replacement, we return the *original* instance to make backtraces work out
466        // (and we hope this does not confuse the FnAbi checks too much).
467        interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
468    }
469
470    fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
471        let msg = Symbol::intern(msg);
472        let span = ecx.find_closest_untracked_caller_location();
473        let (file, line, col) = ecx.location_triple_for_span(span);
474        Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
475    }
476
477    fn call_intrinsic(
478        ecx: &mut InterpCx<'tcx, Self>,
479        instance: ty::Instance<'tcx>,
480        args: &[OpTy<'tcx>],
481        dest: &PlaceTy<'tcx, Self::Provenance>,
482        target: Option<mir::BasicBlock>,
483        _unwind: mir::UnwindAction,
484    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
485        // Shared intrinsics.
486        if ecx.eval_intrinsic(instance, args, dest, target)? {
487            return interp_ok(None);
488        }
489        let intrinsic_name = ecx.tcx.item_name(instance.def_id());
490
491        // CTFE-specific intrinsics.
492        match intrinsic_name {
493            sym::abort_immediate => {
494                // Note that `abort_immediate` is also hooked separately in Miri.
495                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::MachineStop(Box::new(ConstEvalErrKind::Abort));throw_machine_stop!(ConstEvalErrKind::Abort);
496            }
497            sym::ptr_guaranteed_cmp => {
498                let a = ecx.read_scalar(&args[0])?;
499                let b = ecx.read_scalar(&args[1])?;
500                let cmp = ecx.guaranteed_cmp(a, b)?;
501                ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
502            }
503            sym::const_allocate => {
504                let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
505                let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
506
507                let align = match Align::from_bytes(align) {
508                    Ok(a) => a,
509                    Err(err) => {
510                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid align passed to `const_allocate`: {0}",
                            err))
                })))throw_ub_format!("invalid align passed to `const_allocate`: {err}")
511                    }
512                };
513
514                let ptr = ecx.allocate_ptr(
515                    Size::from_bytes(size),
516                    align,
517                    interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
518                    AllocInit::Uninit,
519                )?;
520                ecx.write_pointer(ptr, dest)?;
521            }
522            sym::const_deallocate => {
523                let ptr = ecx.read_pointer(&args[0])?;
524                let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
525                let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
526
527                let size = Size::from_bytes(size);
528                let align = match Align::from_bytes(align) {
529                    Ok(a) => a,
530                    Err(err) => {
531                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid align passed to `const_deallocate`: {0}",
                            err))
                })))throw_ub_format!("invalid align passed to `const_deallocate`: {err}")
532                    }
533                };
534
535                // If an allocation is created in an another const,
536                // we don't deallocate it.
537                let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?;
538                let is_allocated_in_another_const = #[allow(non_exhaustive_omitted_patterns)] match ecx.tcx.try_get_global_alloc(alloc_id)
    {
    Some(interpret::GlobalAlloc::Memory(_)) => true,
    _ => false,
}matches!(
539                    ecx.tcx.try_get_global_alloc(alloc_id),
540                    Some(interpret::GlobalAlloc::Memory(_))
541                );
542
543                if !is_allocated_in_another_const {
544                    ecx.deallocate_ptr(
545                        ptr,
546                        Some((size, align)),
547                        interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
548                    )?;
549                }
550            }
551
552            sym::const_make_global => {
553                let ptr = ecx.read_pointer(&args[0])?;
554                ecx.make_const_heap_ptr_global(ptr)?;
555                ecx.write_pointer(ptr, dest)?;
556            }
557
558            // The intrinsic represents whether the value is known to the optimizer (LLVM).
559            // We're not doing any optimizations here, so there is no optimizer that could know the value.
560            // (We know the value here in the machine of course, but this is the runtime of that code,
561            // not the optimization stage.)
562            sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?,
563
564            // We handle these here since Miri does not want to have them.
565            sym::assert_inhabited
566            | sym::assert_zero_valid
567            | sym::assert_mem_uninitialized_valid => {
568                let ty = instance.args.type_at(0);
569                let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap();
570
571                let should_panic = !ecx
572                    .tcx
573                    .check_validity_requirement((requirement, ecx.typing_env().as_query_input(ty)))
574                    .map_err(|_| ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)err_inval!(TooGeneric))?;
575
576                if should_panic {
577                    let layout = ecx.layout_of(ty)?;
578
579                    let msg = match requirement {
580                        // For *all* intrinsics we first check `is_uninhabited` to give a more specific
581                        // error message.
582                        _ if layout.is_uninhabited() => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("aborted execution: attempted to instantiate uninhabited type `{0}`",
                ty))
    })format!(
583                            "aborted execution: attempted to instantiate uninhabited type `{ty}`"
584                        ),
585                        ValidityRequirement::Inhabited => ::rustc_span::macros::bug_impl(None, format_args!("handled earlier"),
    Location::caller())bug!("handled earlier"),
586                        ValidityRequirement::Zero => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("aborted execution: attempted to zero-initialize type `{0}`, which is invalid",
                ty))
    })format!(
587                            "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
588                        ),
589                        ValidityRequirement::UninitMitigated0x01Fill => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("aborted execution: attempted to leave type `{0}` uninitialized, which is invalid",
                ty))
    })format!(
590                            "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
591                        ),
592                        ValidityRequirement::Uninit => ::rustc_span::macros::bug_impl(None,
    format_args!("assert_uninit_valid doesn\'t exist"), Location::caller())bug!("assert_uninit_valid doesn't exist"),
593                    };
594
595                    Self::panic_nounwind(ecx, &msg)?;
596                    // Skip the `return_to_block` at the end (we panicked, we do not return).
597                    return interp_ok(None);
598                }
599            }
600
601            sym::type_id_vtable => {
602                let tp_ty = ecx.read_type_id(&args[0])?;
603                let result_ty = ecx.read_type_id(&args[1])?;
604
605                let (implements_trait, preds) = type_implements_dyn_trait(ecx, tp_ty, result_ty)?;
606
607                if implements_trait {
608                    let vtable_ptr = ecx.get_vtable_ptr(tp_ty, preds)?;
609                    // Writing a non-null pointer into an `Option<NonNull>` will automatically make it `Some`.
610                    ecx.write_pointer(vtable_ptr, dest)?;
611                } else {
612                    // Write `None`
613                    ecx.write_discriminant(FIRST_VARIANT, dest)?;
614                }
615            }
616
617            sym::type_id_type_of => {
618                let ty = ecx.read_type_id(&args[0])?;
619                ecx.write_type_info(ty, dest)?;
620            }
621
622            sym::type_id_is_signed => {
623                let ty = ecx.read_type_id(&args[0])?;
624                ecx.write_scalar(Scalar::from_bool(ty.is_signed()), dest)?;
625            }
626
627            sym::type_id_points_mutably => {
628                let ty = ecx.read_type_id(&args[0])?;
629                let is_mutable = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut) => true,
    _ => false,
}matches!(
630                    ty.kind(),
631                    ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut)
632                );
633                ecx.write_scalar(Scalar::from_bool(is_mutable), dest)?;
634            }
635
636            sym::type_id_size_of => {
637                let ty = ecx.read_type_id(&args[0])?;
638                let layout = ecx.layout_of(ty)?;
639                let variant_index = if layout.is_sized() {
640                    let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
641                    let size_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
642                    ecx.write_scalar(
643                        ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(),
644                        &size_field_place,
645                    )?;
646                    variant
647                } else {
648                    ecx.project_downcast_named(dest, sym::None)?.0
649                };
650                ecx.write_discriminant(variant_index, dest)?;
651            }
652
653            sym::type_id_element_ty => {
654                let ty = ecx.read_type_id(&args[0])?;
655                let variant_index = if let ty::Array(ty, _) | ty::Slice(ty) = ty.kind() {
656                    let (variant_idx, variant_place) =
657                        ecx.project_downcast_named(dest, sym::Some)?;
658                    let type_id_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
659                    ecx.write_type_id(*ty, &type_id_field_place)?;
660                    variant_idx
661                } else {
662                    ecx.project_downcast_named(dest, sym::None)?.0
663                };
664                ecx.write_discriminant(variant_index, dest)?;
665            }
666
667            sym::type_id_array_len => {
668                let ty = ecx.read_type_id(&args[0])?;
669                let len = if let ty::Array(_, len) = ty.kind() {
670                    len.to_leaf().to_target_usize(ecx.tcx.tcx())
671                } else {
672                    0
673                };
674                ecx.write_scalar(Scalar::from_target_usize(len, ecx), dest)?;
675            }
676
677            sym::type_id_fields => {
678                let ty = ecx.read_type_id(&args[0])?;
679                let variant_idx = ecx.read_target_usize(&args[1])? as usize;
680
681                let variants_num =
682                    ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
683                if variant_idx >= variants_num {
684                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
            len: variants_num as u64,
            index: variant_idx as u64,
        });throw_ub!(BoundsCheckFailed {
685                        len: variants_num as u64,
686                        index: variant_idx as u64
687                    });
688                }
689
690                let fields_num = match ty.kind() {
691                    ty::Adt(adt_def, _) => {
692                        let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
693                        variant_def.fields.len()
694                    }
695                    ty::Tuple(fields) => fields.len(),
696                    _ => 0, // Other types have no fields
697                };
698
699                ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?;
700            }
701
702            sym::type_id_field_representing_type => {
703                let ty = ecx.read_type_id(&args[0])?;
704                let variant_idx = ecx.read_target_usize(&args[1])? as usize;
705                let field_idx = ecx.read_target_usize(&args[2])? as usize;
706
707                let variants_num =
708                    ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
709                if variant_idx >= variants_num {
710                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
            len: variants_num as u64,
            index: variant_idx as u64,
        });throw_ub!(BoundsCheckFailed {
711                        len: variants_num as u64,
712                        index: variant_idx as u64
713                    });
714                }
715
716                let fields_num = match ty.kind() {
717                    ty::Adt(adt_def, _) => {
718                        let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
719                        variant_def.fields.len()
720                    }
721                    ty::Tuple(fields) => fields.len(),
722                    _ => 0, // Other types have no fields
723                };
724                if field_idx >= fields_num {
725                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
            len: fields_num as u64,
            index: field_idx as u64,
        });throw_ub!(BoundsCheckFailed {
726                        len: fields_num as u64,
727                        index: field_idx as u64
728                    });
729                }
730
731                let frt = Ty::new_field_representing_type(
732                    *ecx.tcx,
733                    ty,
734                    VariantIdx::from_usize(variant_idx),
735                    FieldIdx::from_usize(field_idx),
736                );
737                ecx.write_type_id(frt, dest)?;
738            }
739            sym::type_id_function_ptr => {
740                let ty = ecx.read_type_id(&args[0])?;
741                let variant_index = if let ty::FnPtr(sig, fn_header) = ty.kind() {
742                    let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
743                    let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
744                    let sig = sig.skip_binder(); // FIXME: handle lifetime bounds
745                    ecx.write_fn_ptr_type_info(field_place, &sig, fn_header)?;
746                    variant
747                } else {
748                    ecx.project_downcast_named(dest, sym::None)?.0
749                };
750                ecx.write_discriminant(variant_index, dest)?;
751            }
752            sym::type_id_points_to => {
753                let ty = ecx.read_type_id(&args[0])?;
754                let variant_index = if let ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) =
755                    ty.kind()
756                {
757                    let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
758                    let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
759                    ecx.write_type_id(*pointee_ty, &field_place)?;
760                    variant
761                } else {
762                    ecx.project_downcast_named(dest, sym::None)?.0
763                };
764                ecx.write_discriminant(variant_index, dest)?;
765            }
766
767            sym::type_id_variants => {
768                let ty = ecx.read_type_id(&args[0])?;
769                let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1);
770                ecx.write_scalar(Scalar::from_target_usize(variants_num as u64, ecx), dest)?;
771            }
772
773            sym::type_id_variant_name => {
774                let base = ecx.read_type_id(&args[0])?;
775
776                let field_name = if let ty::Adt(def, _) = base.kind() {
777                    let variant_idx = ecx.read_target_usize(&args[1])? as usize;
778                    if variant_idx >= def.variants().len() {
779                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
            len: def.variants().len() as u64,
            index: variant_idx as u64,
        });throw_ub!(BoundsCheckFailed {
780                            len: def.variants().len() as u64,
781                            index: variant_idx as u64
782                        });
783                    }
784                    let variant_idx = VariantIdx::from_usize(variant_idx);
785                    def.variant(variant_idx).name
786                } else {
787                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
788                };
789                let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
790                ecx.write_immediate(
791                    Immediate::ScalarPair(
792                        Scalar::from_pointer(ptr, ecx),
793                        Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
794                    ),
795                    dest,
796                )?;
797            }
798
799            sym::type_id_variant_non_exhaustive => {
800                let base = ecx.read_type_id(&args[0])?;
801
802                let non_exhaustive = if let ty::Adt(def, _) = base.kind() {
803                    let variant_idx = ecx.read_target_usize(&args[1])? as usize;
804                    if variant_idx >= def.variants().len() {
805                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
            len: def.variants().len() as u64,
            index: variant_idx as u64,
        });throw_ub!(BoundsCheckFailed {
806                            len: def.variants().len() as u64,
807                            index: variant_idx as u64
808                        });
809                    }
810                    let variant_idx = VariantIdx::from_usize(variant_idx);
811                    def.variant(variant_idx).is_field_list_non_exhaustive()
812                } else {
813                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
814                };
815                ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
816            }
817
818            sym::field_offset => {
819                let frt_ty = instance.args.type_at(0);
820                ensure_monomorphic_enough(frt_ty)?;
821
822                let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
823                    && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
824                        def.field_representing_type_info(ecx.tcx.tcx, args)
825                {
826                    (base, variant_idx, field_idx)
827                } else {
828                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected field representing type, got {0}", frt_ty),
    Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
829                };
830                let layout = ecx.layout_of(ty)?;
831                let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
832
833                let layout = layout.for_variant(&cx, variant);
834                let offset = layout.fields.offset(field.index()).bytes();
835
836                ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
837            }
838
839            sym::field_representing_type_name => {
840                let frt_ty = ecx.read_type_id(&args[0])?;
841
842                let field_name = if let ty::Adt(def, args) = frt_ty.kind()
843                    && let Some(FieldInfo { name, .. }) =
844                        def.field_representing_type_info(ecx.tcx.tcx, args)
845                {
846                    name
847                } else {
848                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected field representing type, got {0}", frt_ty),
    Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
849                };
850                let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
851                ecx.write_immediate(
852                    Immediate::ScalarPair(
853                        Scalar::from_pointer(ptr, ecx),
854                        Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
855                    ),
856                    dest,
857                )?;
858            }
859
860            sym::field_representing_type_offset => {
861                let frt_ty = ecx.read_type_id(&args[0])?;
862
863                let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
864                    && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
865                        def.field_representing_type_info(ecx.tcx.tcx, args)
866                {
867                    (base, variant_idx, field_idx)
868                } else {
869                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected field representing type, got {0}", frt_ty),
    Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
870                };
871                let layout = ecx.layout_of(ty)?;
872                let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
873
874                let layout = layout.for_variant(&cx, variant);
875                let offset = layout.fields.offset(field.index()).bytes();
876
877                ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
878            }
879
880            sym::field_representing_type_actual_type_id => {
881                let frt_ty = ecx.read_type_id(&args[0])?;
882
883                let field_ty = if let ty::Adt(def, args) = frt_ty.kind()
884                    && let Some(FieldInfo { ty, .. }) =
885                        def.field_representing_type_info(ecx.tcx.tcx, args)
886                {
887                    ecx.tcx.erase_and_anonymize_regions(ty)
888                } else {
889                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("expected field representing type, got {0}", frt_ty),
    Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
890                };
891                ecx.write_type_id(field_ty, dest)?;
892            }
893
894            sym::type_id_generics => {
895                let ty = ecx.read_type_id(&args[0])?;
896                ecx.write_type_id_generics(dest, ty)?;
897            }
898
899            sym::type_id_non_exhaustive => {
900                let ty = ecx.read_type_id(&args[0])?;
901
902                // FIXME(reflection): need a way to obtain non-exhaustiveness of a variant's fields.
903                let non_exhaustive = if let ty::Adt(def, _) = ty.kind() {
904                    if def.is_enum() {
905                        def.is_variant_list_non_exhaustive()
906                    } else {
907                        def.non_enum_variant().is_field_list_non_exhaustive()
908                    }
909                } else {
910                    false
911                };
912
913                ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
914            }
915
916            _ => {
917                // We haven't handled the intrinsic, let's see if we can use a fallback body.
918                if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
919                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("intrinsic `{0}` is not supported at compile-time",
                            intrinsic_name))
                })));throw_unsup_format!(
920                        "intrinsic `{intrinsic_name}` is not supported at compile-time"
921                    );
922                }
923                return interp_ok(Some(ty::Instance {
924                    def: ty::InstanceKind::Item(instance.def_id()),
925                    args: instance.args,
926                }));
927            }
928        }
929
930        // Intrinsic is done, jump to next block.
931        ecx.return_to_block(target)?;
932        interp_ok(None)
933    }
934
935    fn call_llvm_intrinsic(
936        ecx: &mut InterpCx<'tcx, Self>,
937        instance: ty::Instance<'tcx>,
938        _args: &[OpTy<'tcx>],
939        _dest: &PlaceTy<'tcx, Self::Provenance>,
940        _target: Option<mir::BasicBlock>,
941    ) -> InterpResult<'tcx> {
942        let intrinsic_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
943
944        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("LLVM intrinsic `{0}` is not supported at compile-time",
                            intrinsic_name))
                })));throw_unsup_format!("LLVM intrinsic `{intrinsic_name}` is not supported at compile-time");
945    }
946
947    fn assert_panic(
948        ecx: &mut InterpCx<'tcx, Self>,
949        msg: &AssertMessage<'tcx>,
950        _unwind: mir::UnwindAction,
951    ) -> InterpResult<'tcx> {
952        use rustc_middle::mir::AssertKind::*;
953        // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
954        let eval_to_int =
955            |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
956        let err = match msg {
957            BoundsCheck { len, index } => {
958                let len = eval_to_int(len)?;
959                let index = eval_to_int(index)?;
960                BoundsCheck { len, index }
961            }
962            Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
963            OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
964            DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
965            RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
966            ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
967            ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
968            ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
969            MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
970                required: eval_to_int(required)?,
971                found: eval_to_int(found)?,
972            },
973            NullPointerDereference => NullPointerDereference,
974            NullReferenceConstructed => NullReferenceConstructed,
975            InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
976        };
977        Err(ConstEvalErrKind::AssertFailure(err)).into()
978    }
979
980    #[inline(always)]
981    fn runtime_checks(
982        _ecx: &InterpCx<'tcx, Self>,
983        _r: mir::RuntimeChecks,
984    ) -> InterpResult<'tcx, bool> {
985        // We can't look at `tcx.sess` here as that can differ across crates, which can lead to
986        // unsound differences in evaluating the same constant at different instantiation sites.
987        interp_ok(true)
988    }
989
990    fn binary_ptr_op(
991        _ecx: &InterpCx<'tcx, Self>,
992        _bin_op: mir::BinOp,
993        _left: &ImmTy<'tcx>,
994        _right: &ImmTy<'tcx>,
995    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
996        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("pointer arithmetic or comparison is not supported at compile-time"))
                })));throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
997    }
998
999    fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1000        // The step limit has already been hit in a previous call to `increment_const_eval_counter`.
1001
1002        if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
1003            let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
1004                (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
1005            } else {
1006                (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
1007            };
1008
1009            ecx.machine.num_evaluated_steps = new_steps;
1010            // By default, we have a *deny* lint kicking in after some time
1011            // to ensure `loop {}` doesn't just go forever.
1012            // In case that lint got reduced, in particular for `--cap-lint` situations, we also
1013            // have a hard warning shown every now and then for really long executions.
1014            if new_steps == limit {
1015                // By default, we stop after a million steps, but the user can disable this lint
1016                // to be able to run until the heat death of the universe or power loss, whichever
1017                // comes first.
1018                let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
1019                let is_error = ecx
1020                    .tcx
1021                    .lint_level_spec_at_node(LONG_RUNNING_CONST_EVAL, hir_id)
1022                    .level()
1023                    .is_error();
1024                let span = ecx.cur_span();
1025                ecx.tcx.emit_node_span_lint(
1026                    LONG_RUNNING_CONST_EVAL,
1027                    hir_id,
1028                    span,
1029                    LongRunning { item_span: ecx.tcx.span },
1030                );
1031                // If this was a hard error, don't bother continuing evaluation.
1032                if is_error {
1033                    let guard = ecx
1034                        .tcx
1035                        .dcx()
1036                        .span_delayed_bug(span, "The deny lint should have already errored");
1037                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
1038                }
1039            } else if new_steps > start && new_steps.is_power_of_two() {
1040                // Only report after a certain number of terminators have been evaluated and the
1041                // current number of evaluated terminators is a power of 2. The latter gives us a cheap
1042                // way to implement exponential backoff.
1043                let span = ecx.cur_span();
1044                let mut warn =
1045                    ecx.tcx.dcx().create_warn(LongRunningWarn { span, item_span: ecx.tcx.span });
1046                // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`.
1047                // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is
1048                // always increasing.
1049                warn.arg("force_duplicate", new_steps);
1050                warn.emit();
1051            }
1052        }
1053
1054        interp_ok(())
1055    }
1056
1057    #[inline(always)]
1058    fn expose_provenance(
1059        _ecx: &InterpCx<'tcx, Self>,
1060        _provenance: Self::Provenance,
1061    ) -> InterpResult<'tcx> {
1062        // This is only reachable with -Zunleash-the-miri-inside-of-you.
1063        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("exposing pointers is not possible at compile-time"))
                })))throw_unsup_format!("exposing pointers is not possible at compile-time")
1064    }
1065
1066    #[inline(always)]
1067    fn init_frame(
1068        ecx: &mut InterpCx<'tcx, Self>,
1069        frame: Frame<'tcx>,
1070    ) -> InterpResult<'tcx, Frame<'tcx>> {
1071        // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
1072        if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
1073            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)
1074        } else {
1075            interp_ok(frame)
1076        }
1077    }
1078
1079    #[inline(always)]
1080    fn stack<'a>(
1081        ecx: &'a InterpCx<'tcx, Self>,
1082    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
1083        &ecx.machine.stack
1084    }
1085
1086    #[inline(always)]
1087    fn stack_mut<'a>(
1088        ecx: &'a mut InterpCx<'tcx, Self>,
1089    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
1090        &mut ecx.machine.stack
1091    }
1092
1093    fn before_access_global(
1094        _tcx: TyCtxtAt<'tcx>,
1095        machine: &Self,
1096        alloc_id: AllocId,
1097        alloc: ConstAllocation<'tcx>,
1098        _static_def_id: Option<DefId>,
1099        is_write: bool,
1100    ) -> InterpResult<'tcx> {
1101        let alloc = alloc.inner();
1102        if is_write {
1103            // Write access. These are never allowed, but we give a targeted error message.
1104            match alloc.mutability {
1105                Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
1106                Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
1107            }
1108        } else {
1109            // Read access. These are usually allowed, with some exceptions.
1110            if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
1111                // Machine configuration allows us read from anything (e.g., `static` initializer).
1112                interp_ok(())
1113            } else if alloc.mutability == Mutability::Mut {
1114                // Machine configuration does not allow us to read statics (e.g., `const`
1115                // initializer).
1116                Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
1117            } else {
1118                // Immutable global, this read is fine.
1119                {
    match (&alloc.mutability, &Mutability::Not) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(alloc.mutability, Mutability::Not);
1120                interp_ok(())
1121            }
1122        }
1123    }
1124
1125    fn retag_ptr_value(
1126        ecx: &mut InterpCx<'tcx, Self>,
1127        val: &ImmTy<'tcx, CtfeProvenance>,
1128        _ty: Ty<'tcx>,
1129    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, CtfeProvenance>>> {
1130        if #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.retag_mode {
    RetagMode::None | RetagMode::Raw => true,
    _ => false,
}matches!(ecx.machine.retag_mode, RetagMode::None | RetagMode::Raw) {
1131            return interp_ok(None);
1132        }
1133        // If it's a frozen shared reference that's not already immutable, potentially make it immutable.
1134        // (Do nothing on `None` provenance, that cannot be used to perform mutation anyway.)
1135        // Note that const-checking relies on the UB detection we are implementing here! Specifically,
1136        // the analysis for which destructors may be invoked relies on `&impl Freeze` references not
1137        // being able to change what gets dropped.
1138        if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
1139            && *mutbl == Mutability::Not
1140            && val.to_scalar_and_meta().0.to_pointer(ecx).provenance.is_some_and(|p| !p.immutable())
1141        {
1142            // That next check is expensive, that's why we have all the guards above.
1143            let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
1144            let place = ecx.imm_ptr_to_mplace(val)?;
1145            let new_place = if is_immutable {
1146                place.map_provenance(CtfeProvenance::as_immutable)
1147            } else {
1148                // Even if it is not immutable, remember that it is a shared reference.
1149                // This allows it to become part of the final value of the constant.
1150                // (See <https://github.com/rust-lang/rust/pull/128543> for why we allow this
1151                // even when there is interior mutability.)
1152                place.map_provenance(CtfeProvenance::as_shared_ref)
1153            };
1154            interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
1155        } else {
1156            interp_ok(None)
1157        }
1158    }
1159
1160    fn with_retag_mode<T>(
1161        ecx: &mut InterpCx<'tcx, Self>,
1162        mode: RetagMode,
1163        f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
1164    ) -> InterpResult<'tcx, T> {
1165        let old_mode = mem::replace(&mut ecx.machine.retag_mode, mode);
1166        let ret = f(ecx);
1167        ecx.machine.retag_mode = old_mode;
1168        ret
1169    }
1170
1171    fn before_memory_write(
1172        _tcx: TyCtxtAt<'tcx>,
1173        _machine: &mut Self,
1174        _alloc_extra: &mut Self::AllocExtra,
1175        _ptr: Pointer<Option<Self::Provenance>>,
1176        (_alloc_id, immutable): (AllocId, bool),
1177        range: AllocRange,
1178    ) -> InterpResult<'tcx> {
1179        if range.size == Size::ZERO {
1180            // Nothing to check.
1181            return interp_ok(());
1182        }
1183        // Reject writes through immutable pointers.
1184        if immutable {
1185            return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
1186        }
1187        // Everything else is fine.
1188        interp_ok(())
1189    }
1190
1191    fn before_alloc_access(
1192        tcx: TyCtxtAt<'tcx>,
1193        machine: &Self,
1194        alloc_id: AllocId,
1195    ) -> InterpResult<'tcx> {
1196        if machine.stack.is_empty() {
1197            // Get out of the way for the final copy.
1198            return interp_ok(());
1199        }
1200        // Check if this is the currently evaluated static.
1201        if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
1202            return Err(ConstEvalErrKind::RecursiveStatic).into();
1203        }
1204        // If this is another static, make sure we fire off the query to detect cycles.
1205        // But only do that when checks for static recursion are enabled.
1206        if machine.static_root_ids.is_some() {
1207            if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
1208                if tcx.is_foreign_item(def_id) {
1209                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
1210                }
1211                tcx.eval_static_initializer(def_id)?;
1212            }
1213        }
1214        interp_ok(())
1215    }
1216
1217    fn cached_union_data_range<'e>(
1218        ecx: &'e mut InterpCx<'tcx, Self>,
1219        ty: Ty<'tcx>,
1220        compute_range: impl FnOnce() -> RangeSet,
1221    ) -> Cow<'e, RangeSet> {
1222        if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
1223            Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
1224        } else {
1225            // Don't bother caching, we're only doing one validation at the end anyway.
1226            Cow::Owned(compute_range())
1227        }
1228    }
1229
1230    fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
1231    }
1232}
1233
1234// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
1235// so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
1236// at the bottom of this file.