Skip to main content

rustc_const_eval/const_eval/
machine.rs

1use std::borrow::{Borrow, Cow};
2use std::fmt;
3use std::hash::Hash;
4
5use rustc_abi::{Align, FIRST_VARIANT, Size};
6use rustc_ast::Mutability;
7use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
8use rustc_errors::msg;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem, 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, Ty, TyCtxt};
16use rustc_middle::{bug, mir};
17use rustc_span::{Span, Symbol, sym};
18use rustc_target::callconv::FnAbi;
19use tracing::debug;
20
21use super::error::*;
22use crate::errors::{LongRunning, LongRunningWarn};
23use crate::interpret::{
24    self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
25    GlobalAlloc, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, Scalar,
26    compile_time_machine, err_inval, interp_ok, throw_exhaust, throw_inval, throw_ub,
27    throw_ub_custom, throw_unsup, throw_unsup_format, type_implements_dyn_trait,
28};
29
30/// When hitting this many interpreted terminators we emit a deny by default lint
31/// that notfies the user that their constant takes a long time to evaluate. If that's
32/// what they intended, they can just allow the lint.
33const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
34/// The limit used by `-Z tiny-const-eval-limit`. This smaller limit is useful for internal
35/// tests not needing to run 30s or more to show some behaviour.
36const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
37/// After this many interpreted terminators, we start emitting progress indicators at every
38/// power of two of interpreted terminators.
39const PROGRESS_INDICATOR_START: usize = 4_000_000;
40
41/// Extra machine state for CTFE, and the Machine instance.
42//
43// Should be public because out-of-tree rustc consumers need this
44// if they want to interact with constant values.
45pub struct CompileTimeMachine<'tcx> {
46    /// The number of terminators that have been evaluated.
47    ///
48    /// This is used to produce lints informing the user that the compiler is not stuck.
49    /// Set to `usize::MAX` to never report anything.
50    pub(super) num_evaluated_steps: usize,
51
52    /// The virtual call stack.
53    pub(super) stack: Vec<Frame<'tcx>>,
54
55    /// Pattern matching on consts with references would be unsound if those references
56    /// could point to anything mutable. Therefore, when evaluating consts and when constructing valtrees,
57    /// we ensure that only immutable global memory can be accessed.
58    pub(super) can_access_mut_global: CanAccessMutGlobal,
59
60    /// Whether to check alignment during evaluation.
61    pub(super) check_alignment: CheckAlignment,
62
63    /// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
64    /// storing the result in the given `AllocId`.
65    /// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
66    pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
67
68    /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
69    union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
70}
71
72#[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)]
73pub enum CheckAlignment {
74    /// Ignore all alignment requirements.
75    /// This is mainly used in interning.
76    No,
77    /// Hard error when dereferencing a misaligned pointer.
78    Error,
79}
80
81#[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)]
82pub(crate) enum CanAccessMutGlobal {
83    No,
84    Yes,
85}
86
87impl From<bool> for CanAccessMutGlobal {
88    fn from(value: bool) -> Self {
89        if value { Self::Yes } else { Self::No }
90    }
91}
92
93impl<'tcx> CompileTimeMachine<'tcx> {
94    pub(crate) fn new(
95        can_access_mut_global: CanAccessMutGlobal,
96        check_alignment: CheckAlignment,
97    ) -> Self {
98        CompileTimeMachine {
99            num_evaluated_steps: 0,
100            stack: Vec::new(),
101            can_access_mut_global,
102            check_alignment,
103            static_root_ids: None,
104            union_data_ranges: FxHashMap::default(),
105        }
106    }
107}
108
109impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
110    #[inline(always)]
111    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
112    where
113        K: Borrow<Q>,
114    {
115        FxIndexMap::contains_key(self, k)
116    }
117
118    #[inline(always)]
119    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
120    where
121        K: Borrow<Q>,
122    {
123        FxIndexMap::contains_key(self, k)
124    }
125
126    #[inline(always)]
127    fn insert(&mut self, k: K, v: V) -> Option<V> {
128        FxIndexMap::insert(self, k, v)
129    }
130
131    #[inline(always)]
132    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
133    where
134        K: Borrow<Q>,
135    {
136        // FIXME(#120456) - is `swap_remove` correct?
137        FxIndexMap::swap_remove(self, k)
138    }
139
140    #[inline(always)]
141    fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
142        self.iter().filter_map(move |(k, v)| f(k, v)).collect()
143    }
144
145    #[inline(always)]
146    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
147        match self.get(&k) {
148            Some(v) => Ok(v),
149            None => {
150                vacant()?;
151                ::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")
152            }
153        }
154    }
155
156    #[inline(always)]
157    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
158        match self.entry(k) {
159            IndexEntry::Occupied(e) => Ok(e.into_mut()),
160            IndexEntry::Vacant(e) => {
161                let v = vacant()?;
162                Ok(e.insert(v))
163            }
164        }
165    }
166}
167
168pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
169
170#[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 {
    #[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)]
171pub enum MemoryKind {
172    Heap {
173        /// Indicates whether `make_global` was called on this allocation.
174        /// If this is `true`, the allocation must be immutable.
175        was_made_global: bool,
176    },
177}
178
179impl fmt::Display for MemoryKind {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        match self {
182            MemoryKind::Heap { was_made_global } => {
183                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 { "" })
184            }
185        }
186    }
187}
188
189impl interpret::MayLeak for MemoryKind {
190    #[inline(always)]
191    fn may_leak(self) -> bool {
192        match self {
193            MemoryKind::Heap { was_made_global } => was_made_global,
194        }
195    }
196}
197
198impl interpret::MayLeak for ! {
199    #[inline(always)]
200    fn may_leak(self) -> bool {
201        // `self` is uninhabited
202        self
203    }
204}
205
206impl<'tcx> CompileTimeInterpCx<'tcx> {
207    fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
208        let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
209        let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
210
211        use rustc_span::RemapPathScopeComponents;
212        (
213            Symbol::intern(
214                &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
215            ),
216            u32::try_from(caller.line).unwrap(),
217            u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
218        )
219    }
220
221    /// "Intercept" a function call, because we have something special to do for it.
222    /// All `#[rustc_do_not_const_check]` functions MUST be hooked here.
223    /// If this returns `Some` function, which may be `instance` or a different function with
224    /// compatible arguments, then evaluation should continue with that function.
225    /// If this returns `None`, the function call has been handled and the function has returned.
226    fn hook_special_const_fn(
227        &mut self,
228        instance: ty::Instance<'tcx>,
229        args: &[FnArg<'tcx>],
230        _dest: &PlaceTy<'tcx>,
231        _ret: Option<mir::BasicBlock>,
232    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
233        let def_id = instance.def_id();
234
235        if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
236            || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
237        {
238            let args = Self::copy_fn_args(args);
239            // &str or &&str
240            if !(args.len() == 1) {
    ::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
241
242            let mut msg_place = self.deref_pointer(&args[0])?;
243            while msg_place.layout.ty.is_ref() {
244                msg_place = self.deref_pointer(&msg_place)?;
245            }
246
247            let msg = Symbol::intern(self.read_str(&msg_place)?);
248            let span = self.find_closest_untracked_caller_location();
249            let (file, line, col) = self.location_triple_for_span(span);
250            return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
251        } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
252            // For panic_fmt, call const_panic_fmt instead.
253            let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
254            let new_instance = ty::Instance::expect_resolve(
255                *self.tcx,
256                self.typing_env(),
257                const_def_id,
258                instance.args,
259                self.cur_span(),
260            );
261
262            return interp_ok(Some(new_instance));
263        }
264        interp_ok(Some(instance))
265    }
266
267    /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
268    /// Returns `2` if the result is unknown.
269    /// Returns `1` if the pointers are guaranteed equal.
270    /// Returns `0` if the pointers are guaranteed inequal.
271    ///
272    /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any
273    /// change to this function that affects comparison with null is insta-stable!
274    fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
275        interp_ok(match (a, b) {
276            // Comparisons between integers are always known.
277            (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
278            // Comparing a pointer `ptr` with an integer `int` is equivalent to comparing
279            // `ptr-int` with null, so we can reduce this case to a `scalar_may_be_null` test.
280            (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
281                let int = int.to_target_usize(*self.tcx);
282                // The `wrapping_neg` here may produce a value that is not
283                // a valid target usize any more... but `wrapping_offset` handles that correctly.
284                let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
285                if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
286                    // `ptr.wrapping_sub(int)` is definitely not equal to `0`, so `ptr != int`
287                    0
288                } else {
289                    // `ptr.wrapping_sub(int)` could be equal to `0`, but might not be,
290                    // so we cannot know for sure if `ptr == int` or not
291                    2
292                }
293            }
294            (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
295                let (a_prov, a_offset) = a.prov_and_relative_offset();
296                let (b_prov, b_offset) = b.prov_and_relative_offset();
297                let a_allocid = a_prov.alloc_id();
298                let b_allocid = b_prov.alloc_id();
299                let a_info = self.get_alloc_info(a_allocid);
300                let b_info = self.get_alloc_info(b_allocid);
301
302                // Check if the pointers cannot be equal due to alignment
303                if a_info.align > Align::ONE && b_info.align > Align::ONE {
304                    let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
305                    let a_residue = a_offset.bytes() % min_align;
306                    let b_residue = b_offset.bytes() % min_align;
307                    if a_residue != b_residue {
308                        // If the two pointers have a different residue modulo their
309                        // common alignment, they cannot be equal.
310                        return interp_ok(0);
311                    }
312                    // The pointers have the same residue modulo their common alignment,
313                    // so they could be equal. Try the other checks.
314                }
315
316                if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
317                    self.tcx.try_get_global_alloc(a_allocid),
318                    self.tcx.try_get_global_alloc(b_allocid),
319                ) {
320                    if a_allocid == b_allocid {
321                        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!(
322                            a_did, b_did,
323                            "different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
324                        );
325                        // Comparing two pointers into the same static. As per
326                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
327                        // a static cannot be duplicated, so if two pointers are into the same
328                        // static, they are equal if and only if their offsets are equal.
329                        (a_offset == b_offset) as u8
330                    } else {
331                        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!(
332                            a_did, b_did,
333                            "same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
334                        );
335                        // Comparing two pointers into the different statics.
336                        // We can never determine for sure that two pointers into different statics
337                        // are *equal*, but we can know that they are *inequal* if they are both
338                        // strictly in-bounds (i.e. in-bounds and not one-past-the-end) of
339                        // their respective static, as different non-zero-sized statics cannot
340                        // overlap or be deduplicated as per
341                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
342                        // (non-deduplication), and
343                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
344                        // (non-overlapping).
345                        if a_offset < a_info.size && b_offset < b_info.size {
346                            0
347                        } else {
348                            // Otherwise, conservatively say we don't know.
349                            // There are some cases we could still return `0` for, e.g.
350                            // if the pointers being equal would require their statics to overlap
351                            // one or more bytes, but for simplicity we currently only check
352                            // strictly in-bounds pointers.
353                            2
354                        }
355                    }
356                } else {
357                    // All other cases we conservatively say we don't know.
358                    //
359                    // For comparing statics to non-statics, as per https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
360                    // immutable statics can overlap with other kinds of allocations sometimes.
361                    //
362                    // FIXME: We could be more decisive for (non-zero-sized) mutable statics,
363                    // which cannot overlap with other kinds of allocations.
364                    //
365                    // Functions and vtables can be duplicated and deduplicated, so we
366                    // cannot be sure of runtime equality of pointers to the same one, or the
367                    // runtime inequality of pointers to different ones (see e.g. #73722),
368                    // so comparing those should return 2, whether they are the same allocation
369                    // or not.
370                    //
371                    // `GlobalAlloc::TypeId` exists mostly to prevent consteval from comparing
372                    // `TypeId`s, so comparing those should always return 2, whether they are the
373                    // same allocation or not.
374                    //
375                    // FIXME: We could revisit comparing pointers into the same
376                    // `GlobalAlloc::Memory` once https://github.com/rust-lang/rust/issues/128775
377                    // is fixed (but they can be deduplicated, so comparing pointers into different
378                    // ones should return 2).
379                    2
380                }
381            }
382        })
383    }
384}
385
386impl<'tcx> CompileTimeMachine<'tcx> {
387    #[inline(always)]
388    /// Find the first stack frame that is within the current crate, if any.
389    /// Otherwise, return the crate's HirId
390    pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> hir::HirId {
391        self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
392    }
393}
394
395impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
396    CtfeProvenance
bool
!
crate::const_eval::MemoryKind
rustc_data_structures::fx::FxIndexMap<AllocId,
(MemoryKind<Self::MemoryKind>, Allocation)>
Option<Self::MemoryKind>
None
()
()
Box<[u8]>
&InterpCx<'tcx, Self>
_ecx
bool
false;
&mut InterpCx<'tcx, Self>
_ecx
mir::UnwindTerminateReason
_reason
InterpResult<'tcx>
{
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unwinding cannot happen during compile-time evaluation")));
}
&InterpCx<'tcx, Self>
_ecx
ty::Instance<'tcx>
_instance
InterpResult<'tcx>
interp_ok(());
&mut InterpCx<'tcx, Self>
_ecx
!
fn_val
&FnAbi<'tcx, Ty<'tcx>>
_abi
&[FnArg<'tcx>]
_args
&PlaceTy<'tcx, Self::Provenance>
_destination
Option<mir::BasicBlock>
_target
mir::UnwindAction
_unwind
InterpResult<'tcx>
match fn_val {}
&InterpCx<'tcx, Self>
_ecx
bool
true;
&InterpCx<'tcx, Self>
_ecx
AllocId
_id
&'b Allocation
alloc
InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance>>>
interp_ok(Cow::Borrowed(alloc));
&InterpCx<'tcx, Self>
_ecx
AllocId
_id
MemoryKind<Self::MemoryKind>
_kind
Size
_size
Align
_align
InterpResult<'tcx, Self::AllocExtra>
interp_ok(());
&InterpCx<'tcx, Self>
ecx
DefId
def_id
InterpResult<'tcx, Pointer>
interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(),
        Size::ZERO));
&InterpCx<'tcx, Self>
_ecx
Pointer<CtfeProvenance>
ptr
Option<MemoryKind<Self::MemoryKind>>
_kind
InterpResult<'tcx, Pointer<CtfeProvenance>>
interp_ok(ptr);
&InterpCx<'tcx, Self>
_ecx
u64
addr
InterpResult<'tcx, Pointer<Option<CtfeProvenance>>>
interp_ok(Pointer::without_provenance(addr));
&InterpCx<'tcx, Self>
_ecx
Pointer<CtfeProvenance>
ptr
i64
_size
Option<(AllocId, Size, Self::ProvenanceExtra)>
let (prov, offset) = ptr.prov_and_relative_offset();
Some((prov.alloc_id(), offset, prov.immutable()));
&InterpCx<'tcx, Self>
_ecx
Option<ty::Instance<'tcx>>
_instance
usize
CTFE_ALLOC_SALT;compile_time_machine!(<'tcx>);
397
398    const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
399
400    #[inline(always)]
401    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
402        #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.check_alignment {
    CheckAlignment::Error => true,
    _ => false,
}matches!(ecx.machine.check_alignment, CheckAlignment::Error)
403    }
404
405    #[inline(always)]
406    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
407        ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
408    }
409
410    fn load_mir(
411        ecx: &InterpCx<'tcx, Self>,
412        instance: ty::InstanceKind<'tcx>,
413    ) -> &'tcx mir::Body<'tcx> {
414        match instance {
415            ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
416            _ => ecx.tcx.instance_mir(instance),
417        }
418    }
419
420    fn find_mir_or_eval_fn(
421        ecx: &mut InterpCx<'tcx, Self>,
422        orig_instance: ty::Instance<'tcx>,
423        _abi: &FnAbi<'tcx, Ty<'tcx>>,
424        args: &[FnArg<'tcx>],
425        dest: &PlaceTy<'tcx>,
426        ret: Option<mir::BasicBlock>,
427        _unwind: mir::UnwindAction, // unwinding is not supported in consts
428    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
429        {
    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:429",
                        "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(429u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("find_mir_or_eval_fn: {0:?}",
                                                    orig_instance) as &dyn Value))])
            });
    } else { ; }
};debug!("find_mir_or_eval_fn: {:?}", orig_instance);
430
431        // Replace some functions.
432        let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
433            // Call has already been handled.
434            return interp_ok(None);
435        };
436
437        // Only check non-glue functions
438        if let ty::InstanceKind::Item(def) = instance.def {
439            // Execution might have wandered off into other crates, so we cannot do a stability-
440            // sensitive check here. But we can at least rule out functions that are not const at
441            // all. That said, we have to allow calling functions inside a `const trait`. These
442            // *are* const-checked!
443            if !ecx.tcx.is_const_fn(def) || {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in ecx.tcx.get_all_attrs(def) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcDoNotConstCheck) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
444                // We certainly do *not* want to actually call the fn
445                // though, so be sure we return here.
446                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)
447            }
448        }
449
450        // This is a const fn. Call it.
451        // In case of replacement, we return the *original* instance to make backtraces work out
452        // (and we hope this does not confuse the FnAbi checks too much).
453        interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
454    }
455
456    fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
457        let msg = Symbol::intern(msg);
458        let span = ecx.find_closest_untracked_caller_location();
459        let (file, line, col) = ecx.location_triple_for_span(span);
460        Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
461    }
462
463    fn call_intrinsic(
464        ecx: &mut InterpCx<'tcx, Self>,
465        instance: ty::Instance<'tcx>,
466        args: &[OpTy<'tcx>],
467        dest: &PlaceTy<'tcx, Self::Provenance>,
468        target: Option<mir::BasicBlock>,
469        _unwind: mir::UnwindAction,
470    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
471        // Shared intrinsics.
472        if ecx.eval_intrinsic(instance, args, dest, target)? {
473            return interp_ok(None);
474        }
475        let intrinsic_name = ecx.tcx.item_name(instance.def_id());
476
477        // CTFE-specific intrinsics.
478        match intrinsic_name {
479            sym::ptr_guaranteed_cmp => {
480                let a = ecx.read_scalar(&args[0])?;
481                let b = ecx.read_scalar(&args[1])?;
482                let cmp = ecx.guaranteed_cmp(a, b)?;
483                ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
484            }
485            sym::const_allocate => {
486                let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
487                let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
488
489                let align = match Align::from_bytes(align) {
490                    Ok(a) => a,
491                    Err(err) => do yeet {
        let (name, err_kind, align) =
            ("const_allocate", err.diag_ident(), err.align());
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("invalid align passed to `{$name}`: {$align} is {$err_kind ->\n                                [not_power_of_two] not a power of 2\n                                [too_large] too large\n                                *[other] {\"\"}\n                            }")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                                set_arg("err_kind".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(err_kind,
                                        &mut None));
                                set_arg("align".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(align, &mut None));
                            }),
                }))
    }throw_ub_custom!(
492                        msg!(
493                            "invalid align passed to `{$name}`: {$align} is {$err_kind ->
494                                [not_power_of_two] not a power of 2
495                                [too_large] too large
496                                *[other] {\"\"}
497                            }"
498                        ),
499                        name = "const_allocate",
500                        err_kind = err.diag_ident(),
501                        align = err.align()
502                    ),
503                };
504
505                let ptr = ecx.allocate_ptr(
506                    Size::from_bytes(size),
507                    align,
508                    interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
509                    AllocInit::Uninit,
510                )?;
511                ecx.write_pointer(ptr, dest)?;
512            }
513            sym::const_deallocate => {
514                let ptr = ecx.read_pointer(&args[0])?;
515                let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
516                let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
517
518                let size = Size::from_bytes(size);
519                let align = match Align::from_bytes(align) {
520                    Ok(a) => a,
521                    Err(err) => do yeet {
        let (name, err_kind, align) =
            ("const_deallocate", err.diag_ident(), err.align());
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("invalid align passed to `{$name}`: {$align} is {$err_kind ->\n                                [not_power_of_two] not a power of 2\n                                [too_large] too large\n                                *[other] {\"\"}\n                            }")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                                set_arg("err_kind".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(err_kind,
                                        &mut None));
                                set_arg("align".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(align, &mut None));
                            }),
                }))
    }throw_ub_custom!(
522                        msg!(
523                            "invalid align passed to `{$name}`: {$align} is {$err_kind ->
524                                [not_power_of_two] not a power of 2
525                                [too_large] too large
526                                *[other] {\"\"}
527                            }"
528                        ),
529                        name = "const_deallocate",
530                        err_kind = err.diag_ident(),
531                        align = err.align()
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_middle::util::bug::bug_fmt(format_args!("handled earlier"))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_middle::util::bug::bug_fmt(format_args!("assert_uninit_valid doesn\'t exist"))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_of => {
618                let ty = ecx.read_type_id(&args[0])?;
619                ecx.write_type_info(ty, dest)?;
620            }
621
622            _ => {
623                // We haven't handled the intrinsic, let's see if we can use a fallback body.
624                if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
625                    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!(
626                        "intrinsic `{intrinsic_name}` is not supported at compile-time"
627                    );
628                }
629                return interp_ok(Some(ty::Instance {
630                    def: ty::InstanceKind::Item(instance.def_id()),
631                    args: instance.args,
632                }));
633            }
634        }
635
636        // Intrinsic is done, jump to next block.
637        ecx.return_to_block(target)?;
638        interp_ok(None)
639    }
640
641    fn assert_panic(
642        ecx: &mut InterpCx<'tcx, Self>,
643        msg: &AssertMessage<'tcx>,
644        _unwind: mir::UnwindAction,
645    ) -> InterpResult<'tcx> {
646        use rustc_middle::mir::AssertKind::*;
647        // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
648        let eval_to_int =
649            |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
650        let err = match msg {
651            BoundsCheck { len, index } => {
652                let len = eval_to_int(len)?;
653                let index = eval_to_int(index)?;
654                BoundsCheck { len, index }
655            }
656            Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
657            OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
658            DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
659            RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
660            ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
661            ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
662            ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
663            MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
664                required: eval_to_int(required)?,
665                found: eval_to_int(found)?,
666            },
667            NullPointerDereference => NullPointerDereference,
668            InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
669        };
670        Err(ConstEvalErrKind::AssertFailure(err)).into()
671    }
672
673    #[inline(always)]
674    fn runtime_checks(
675        _ecx: &InterpCx<'tcx, Self>,
676        _r: mir::RuntimeChecks,
677    ) -> InterpResult<'tcx, bool> {
678        // We can't look at `tcx.sess` here as that can differ across crates, which can lead to
679        // unsound differences in evaluating the same constant at different instantiation sites.
680        interp_ok(true)
681    }
682
683    fn binary_ptr_op(
684        _ecx: &InterpCx<'tcx, Self>,
685        _bin_op: mir::BinOp,
686        _left: &ImmTy<'tcx>,
687        _right: &ImmTy<'tcx>,
688    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
689        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");
690    }
691
692    fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
693        // The step limit has already been hit in a previous call to `increment_const_eval_counter`.
694
695        if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
696            let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
697                (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
698            } else {
699                (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
700            };
701
702            ecx.machine.num_evaluated_steps = new_steps;
703            // By default, we have a *deny* lint kicking in after some time
704            // to ensure `loop {}` doesn't just go forever.
705            // In case that lint got reduced, in particular for `--cap-lint` situations, we also
706            // have a hard warning shown every now and then for really long executions.
707            if new_steps == limit {
708                // By default, we stop after a million steps, but the user can disable this lint
709                // to be able to run until the heat death of the universe or power loss, whichever
710                // comes first.
711                let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
712                let is_error = ecx
713                    .tcx
714                    .lint_level_at_node(
715                        rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
716                        hir_id,
717                    )
718                    .level
719                    .is_error();
720                let span = ecx.cur_span();
721                ecx.tcx.emit_node_span_lint(
722                    rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
723                    hir_id,
724                    span,
725                    LongRunning { item_span: ecx.tcx.span },
726                );
727                // If this was a hard error, don't bother continuing evaluation.
728                if is_error {
729                    let guard = ecx
730                        .tcx
731                        .dcx()
732                        .span_delayed_bug(span, "The deny lint should have already errored");
733                    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)));
734                }
735            } else if new_steps > start && new_steps.is_power_of_two() {
736                // Only report after a certain number of terminators have been evaluated and the
737                // current number of evaluated terminators is a power of 2. The latter gives us a cheap
738                // way to implement exponential backoff.
739                let span = ecx.cur_span();
740                // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`.
741                // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is
742                // always increasing.
743                ecx.tcx.dcx().emit_warn(LongRunningWarn {
744                    span,
745                    item_span: ecx.tcx.span,
746                    force_duplicate: new_steps,
747                });
748            }
749        }
750
751        interp_ok(())
752    }
753
754    #[inline(always)]
755    fn expose_provenance(
756        _ecx: &InterpCx<'tcx, Self>,
757        _provenance: Self::Provenance,
758    ) -> InterpResult<'tcx> {
759        // This is only reachable with -Zunleash-the-miri-inside-of-you.
760        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")
761    }
762
763    #[inline(always)]
764    fn init_frame(
765        ecx: &mut InterpCx<'tcx, Self>,
766        frame: Frame<'tcx>,
767    ) -> InterpResult<'tcx, Frame<'tcx>> {
768        // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
769        if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
770            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)
771        } else {
772            interp_ok(frame)
773        }
774    }
775
776    #[inline(always)]
777    fn stack<'a>(
778        ecx: &'a InterpCx<'tcx, Self>,
779    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
780        &ecx.machine.stack
781    }
782
783    #[inline(always)]
784    fn stack_mut<'a>(
785        ecx: &'a mut InterpCx<'tcx, Self>,
786    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
787        &mut ecx.machine.stack
788    }
789
790    fn before_access_global(
791        _tcx: TyCtxtAt<'tcx>,
792        machine: &Self,
793        alloc_id: AllocId,
794        alloc: ConstAllocation<'tcx>,
795        _static_def_id: Option<DefId>,
796        is_write: bool,
797    ) -> InterpResult<'tcx> {
798        let alloc = alloc.inner();
799        if is_write {
800            // Write access. These are never allowed, but we give a targeted error message.
801            match alloc.mutability {
802                Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
803                Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
804            }
805        } else {
806            // Read access. These are usually allowed, with some exceptions.
807            if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
808                // Machine configuration allows us read from anything (e.g., `static` initializer).
809                interp_ok(())
810            } else if alloc.mutability == Mutability::Mut {
811                // Machine configuration does not allow us to read statics (e.g., `const`
812                // initializer).
813                Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
814            } else {
815                // Immutable global, this read is fine.
816                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);
817                interp_ok(())
818            }
819        }
820    }
821
822    fn retag_ptr_value(
823        ecx: &mut InterpCx<'tcx, Self>,
824        _kind: mir::RetagKind,
825        val: &ImmTy<'tcx, CtfeProvenance>,
826    ) -> InterpResult<'tcx, ImmTy<'tcx, CtfeProvenance>> {
827        // If it's a frozen shared reference that's not already immutable, potentially make it immutable.
828        // (Do nothing on `None` provenance, that cannot store immutability anyway.)
829        if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
830            && *mutbl == Mutability::Not
831            && val
832                .to_scalar_and_meta()
833                .0
834                .to_pointer(ecx)?
835                .provenance
836                .is_some_and(|p| !p.immutable())
837        {
838            // That next check is expensive, that's why we have all the guards above.
839            let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
840            let place = ecx.ref_to_mplace(val)?;
841            let new_place = if is_immutable {
842                place.map_provenance(CtfeProvenance::as_immutable)
843            } else {
844                // Even if it is not immutable, remember that it is a shared reference.
845                // This allows it to become part of the final value of the constant.
846                // (See <https://github.com/rust-lang/rust/pull/128543> for why we allow this
847                // even when there is interior mutability.)
848                place.map_provenance(CtfeProvenance::as_shared_ref)
849            };
850            interp_ok(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout))
851        } else {
852            interp_ok(val.clone())
853        }
854    }
855
856    fn before_memory_write(
857        _tcx: TyCtxtAt<'tcx>,
858        _machine: &mut Self,
859        _alloc_extra: &mut Self::AllocExtra,
860        _ptr: Pointer<Option<Self::Provenance>>,
861        (_alloc_id, immutable): (AllocId, bool),
862        range: AllocRange,
863    ) -> InterpResult<'tcx> {
864        if range.size == Size::ZERO {
865            // Nothing to check.
866            return interp_ok(());
867        }
868        // Reject writes through immutable pointers.
869        if immutable {
870            return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
871        }
872        // Everything else is fine.
873        interp_ok(())
874    }
875
876    fn before_alloc_access(
877        tcx: TyCtxtAt<'tcx>,
878        machine: &Self,
879        alloc_id: AllocId,
880    ) -> InterpResult<'tcx> {
881        if machine.stack.is_empty() {
882            // Get out of the way for the final copy.
883            return interp_ok(());
884        }
885        // Check if this is the currently evaluated static.
886        if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
887            return Err(ConstEvalErrKind::RecursiveStatic).into();
888        }
889        // If this is another static, make sure we fire off the query to detect cycles.
890        // But only do that when checks for static recursion are enabled.
891        if machine.static_root_ids.is_some() {
892            if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
893                if tcx.is_foreign_item(def_id) {
894                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
895                }
896                tcx.eval_static_initializer(def_id)?;
897            }
898        }
899        interp_ok(())
900    }
901
902    fn cached_union_data_range<'e>(
903        ecx: &'e mut InterpCx<'tcx, Self>,
904        ty: Ty<'tcx>,
905        compute_range: impl FnOnce() -> RangeSet,
906    ) -> Cow<'e, RangeSet> {
907        if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
908            Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
909        } else {
910            // Don't bother caching, we're only doing one validation at the end anyway.
911            Cow::Owned(compute_range())
912        }
913    }
914
915    fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
916    }
917}
918
919// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
920// so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
921// at the bottom of this file.