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