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