Skip to main content

rustc_const_eval/interpret/
eval_context.rs

1use std::cell::RefCell;
2use std::collections::hash_map::Entry;
3
4use either::{Left, Right};
5use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout};
6use rustc_data_structures::Limit;
7use rustc_data_structures::fx::FxHashMap;
8use rustc_hir::def_id::DefId;
9use rustc_middle::mir::interpret::{ErrorHandled, InvalidMetaKind, ReportedErrorInfo};
10use rustc_middle::query::TyCtxtAt;
11use rustc_middle::ty::layout::{
12    self, FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf,
13    LayoutOfHelpers, TyAndLayout,
14};
15use rustc_middle::ty::{
16    self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingEnv, Variance,
17};
18use rustc_middle::{mir, span_bug};
19use rustc_span::Span;
20use rustc_target::callconv::FnAbi;
21use tracing::{debug, trace};
22
23use super::{
24    Frame, FrameInfo, GlobalId, InterpErrorKind, InterpResult, MPlaceTy, Machine, MemPlaceMeta,
25    Memory, OpTy, Place, PlaceTy, PointerArithmetic, Projectable, Provenance, err_inval, interp_ok,
26    throw_inval, throw_ub, throw_ub_format,
27};
28use crate::{enter_trace_span, util};
29
30pub struct InterpCx<'tcx, M: Machine<'tcx>> {
31    /// Stores the `Machine` instance.
32    ///
33    /// Note: the stack is provided by the machine.
34    pub machine: M,
35
36    /// The results of the type checker, from rustc.
37    /// The span in this is the "root" of the evaluation, i.e., the const
38    /// we are evaluating (if this is CTFE).
39    pub tcx: TyCtxtAt<'tcx>,
40
41    /// The current context in case we're evaluating in a
42    /// polymorphic context. This always uses `ty::TypingMode::PostAnalysis`.
43    pub(super) typing_env: ty::TypingEnv<'tcx>,
44
45    /// The query cache is slow so we have our own cache in front of it.
46    pub(super) layout_cache: RefCell<FxHashMap<Ty<'tcx>, rustc_abi::Layout<'tcx>>>,
47
48    /// The virtual memory system.
49    pub memory: Memory<'tcx, M>,
50
51    /// The recursion limit (cached from `tcx.recursion_limit(())`)
52    pub recursion_limit: Limit,
53}
54
55impl<'tcx, M: Machine<'tcx>> HasDataLayout for InterpCx<'tcx, M> {
56    #[inline]
57    fn data_layout(&self) -> &TargetDataLayout {
58        &self.tcx.data_layout
59    }
60}
61
62impl<'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'tcx, M>
63where
64    M: Machine<'tcx>,
65{
66    #[inline]
67    fn tcx(&self) -> TyCtxt<'tcx> {
68        *self.tcx
69    }
70}
71
72impl<'tcx, M> layout::HasTypingEnv<'tcx> for InterpCx<'tcx, M>
73where
74    M: Machine<'tcx>,
75{
76    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
77        self.typing_env
78    }
79}
80
81impl<'tcx, M: Machine<'tcx>> LayoutOfHelpers<'tcx> for InterpCx<'tcx, M> {
82    type LayoutOfResult = Result<TyAndLayout<'tcx>, InterpErrorKind<'tcx>>;
83
84    #[inline]
85    fn layout_tcx_at_span(&self) -> Span {
86        // Using the cheap root span for performance.
87        self.tcx.span
88    }
89
90    #[inline]
91    fn handle_layout_err(
92        &self,
93        mut err: LayoutError<'tcx>,
94        _: Span,
95        _: Ty<'tcx>,
96    ) -> InterpErrorKind<'tcx> {
97        // FIXME(#149283): This is really hacky and is only used to hide type
98        // system bugs. We use it as a temporary fix for #149081.
99        //
100        // While it's expected that we sometimes get ambiguity errors when
101        // entering another generic environment while the current environment
102        // itself is still generic, we should never fail to entirely prove
103        // something.
104        match err {
105            LayoutError::NormalizationFailure(ty, _) => {
106                if ty.has_non_region_param() {
107                    err = LayoutError::TooGeneric(ty);
108                }
109            }
110
111            LayoutError::Unknown(_)
112            | LayoutError::SizeOverflow(_)
113            | LayoutError::InvalidSimd { .. }
114            | LayoutError::TooGeneric(_)
115            | LayoutError::ReferencesError(_) => {}
116        }
117        ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(err))err_inval!(Layout(err))
118    }
119}
120
121impl<'tcx, M: Machine<'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'tcx, M> {
122    type FnAbiOfResult = Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, InterpErrorKind<'tcx>>;
123
124    fn handle_fn_abi_err(
125        &self,
126        err: FnAbiError<'tcx>,
127        _span: Span,
128        _fn_abi_request: FnAbiRequest<'tcx>,
129    ) -> InterpErrorKind<'tcx> {
130        match err {
131            FnAbiError::Layout(err) => ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(err))err_inval!(Layout(err)),
132        }
133    }
134}
135
136impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
137    /// This inherent method takes priority over the trait method with the same name in LayoutOf,
138    /// and allows wrapping the actual [LayoutOf::layout_of] with a tracing span.
139    /// See [LayoutOf::layout_of] for the original documentation.
140    #[inline]
141    pub fn layout_of(&self, ty: Ty<'tcx>) -> Result<TyAndLayout<'tcx>, InterpErrorKind<'tcx>> {
142        match self.layout_cache.borrow_mut().entry(ty) {
143            Entry::Occupied(occupied_entry) => {
144                Ok(TyAndLayout { ty, layout: *occupied_entry.get() })
145            }
146            Entry::Vacant(vacant_entry) => {
147                let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("layouting",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(147u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("layouting")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("layouting");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"layout_of")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, layouting::layout_of, ty = ?ty.kind());
148                let layout = LayoutOf::layout_of(self, ty)?;
149                vacant_entry.insert(layout.layout);
150                Ok(layout)
151            }
152        }
153    }
154
155    /// This inherent method takes priority over the trait method with the same name in FnAbiOf,
156    /// and allows wrapping the actual [FnAbiOf::fn_abi_of_fn_ptr] with a tracing span.
157    /// See [FnAbiOf::fn_abi_of_fn_ptr] for the original documentation.
158    #[inline(always)]
159    pub fn fn_abi_of_fn_ptr(
160        &self,
161        sig: ty::PolyFnSig<'tcx>,
162        extra_args: &'tcx ty::List<Ty<'tcx>>,
163    ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
164        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("layouting",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(164u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("layouting")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("layouting");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("sig")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("sig");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("extra_args")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("extra_args");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"fn_abi_of_fn_ptr")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, layouting::fn_abi_of_fn_ptr, ?sig, ?extra_args);
165        FnAbiOf::fn_abi_of_fn_ptr(self, sig, extra_args)
166    }
167
168    /// This inherent method takes priority over the trait method with the same name in FnAbiOf,
169    /// and allows wrapping the actual [FnAbiOf::fn_abi_of_instance_no_deduced_attrs] with a tracing span.
170    /// See [FnAbiOf::fn_abi_of_instance_no_deduced_attrs] for the original documentation.
171    #[inline(always)]
172    pub fn fn_abi_of_instance_no_deduced_attrs(
173        &self,
174        instance: ty::Instance<'tcx>,
175        extra_args: &'tcx ty::List<Ty<'tcx>>,
176    ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
177        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("layouting",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(177u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("layouting")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("layouting");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("instance")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("instance");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("extra_args")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("extra_args");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"fn_abi_of_instance")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, layouting::fn_abi_of_instance, ?instance, ?extra_args);
178        FnAbiOf::fn_abi_of_instance_no_deduced_attrs(self, instance, extra_args)
179    }
180}
181
182/// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
183pub(super) fn mir_assign_valid_types<'tcx>(
184    tcx: TyCtxt<'tcx>,
185    typing_env: TypingEnv<'tcx>,
186    src: TyAndLayout<'tcx>,
187    dest: TyAndLayout<'tcx>,
188) -> bool {
189    // We *could* check `Invariant` here since all subtyping must be explicit post-borrowck.
190    // However, this check is also used by the interpreter to figure out if a transmute can be
191    // turned into a regular assignment (which has a more efficient codepath), so we want the check
192    // to consider as many assignments as possible to be valid. Therefore we are happy to accept
193    // one-way subtyping.
194    if util::relate_types(tcx, typing_env, Variance::Covariant, src.ty, dest.ty) {
195        // Make sure the layout is equal, too -- just to be safe. Miri really needs layout equality.
196        // For performance reason we skip this check when the types are equal. Equal types *can*
197        // have different layouts when enum downcast is involved (as enum variants carry the type of
198        // the enum), but those should never occur in assignments.
199        if truecfg!(debug_assertions) || src.ty != dest.ty {
200            {
    match (&src.layout, &dest.layout) {
        (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!("{0} is a subtype of {1} but they have different layout",
                            src.ty, dest.ty)));
            }
        }
    }
};assert_eq!(
201                src.layout,
202                dest.layout,
203                "{src} is a subtype of {dest} but they have different layout",
204                src = src.ty,
205                dest = dest.ty,
206            );
207        }
208        true
209    } else {
210        false
211    }
212}
213
214/// Use the already known layout if given (but sanity check in debug mode),
215/// or compute the layout.
216#[cfg_attr(not(debug_assertions), inline(always))]
217pub(super) fn from_known_layout<'tcx>(
218    tcx: TyCtxtAt<'tcx>,
219    typing_env: TypingEnv<'tcx>,
220    known_layout: Option<TyAndLayout<'tcx>>,
221    compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
222) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
223    match known_layout {
224        None => compute(),
225        Some(known_layout) => {
226            if truecfg!(debug_assertions) {
227                let check_layout = compute()?;
228                if !mir_assign_valid_types(tcx.tcx, typing_env, check_layout, known_layout) {
229                    ::rustc_middle::util::bug::span_bug_fmt(tcx.span,
    format_args!("expected type differs from actual type.\nexpected: {0}\nactual: {1}",
        known_layout.ty, check_layout.ty));span_bug!(
230                        tcx.span,
231                        "expected type differs from actual type.\nexpected: {}\nactual: {}",
232                        known_layout.ty,
233                        check_layout.ty,
234                    );
235                }
236            }
237            interp_ok(known_layout)
238        }
239    }
240}
241
242impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
243    pub fn new(
244        tcx: TyCtxt<'tcx>,
245        root_span: Span,
246        typing_env: ty::TypingEnv<'tcx>,
247        machine: M,
248    ) -> Self {
249        crate::assert_typing_mode(typing_env.typing_mode());
250
251        InterpCx {
252            machine,
253            tcx: tcx.at(root_span),
254            typing_env,
255            layout_cache: RefCell::new(FxHashMap::default()),
256            memory: Memory::new(),
257            recursion_limit: tcx.recursion_limit(),
258        }
259    }
260
261    /// Returns the span of the currently executed statement/terminator.
262    /// This is the span typically used for error reporting.
263    #[inline(always)]
264    pub fn cur_span(&self) -> Span {
265        // This deliberately does *not* honor `requires_caller_location` since it is used for much
266        // more than just panics.
267        self.stack().last().map_or(self.tcx.span, |f| f.current_span())
268    }
269
270    pub(crate) fn stack(&self) -> &[Frame<'tcx, M::Provenance, M::FrameExtra>] {
271        M::stack(self)
272    }
273
274    #[inline(always)]
275    pub(crate) fn stack_mut(&mut self) -> &mut Vec<Frame<'tcx, M::Provenance, M::FrameExtra>> {
276        M::stack_mut(self)
277    }
278
279    #[inline(always)]
280    pub fn frame_idx(&self) -> usize {
281        let stack = self.stack();
282        if !!stack.is_empty() {
    ::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
283        stack.len() - 1
284    }
285
286    #[inline(always)]
287    pub fn frame(&self) -> &Frame<'tcx, M::Provenance, M::FrameExtra> {
288        self.stack().last().expect("no call frames exist")
289    }
290
291    #[inline(always)]
292    pub fn frame_mut(&mut self) -> &mut Frame<'tcx, M::Provenance, M::FrameExtra> {
293        self.stack_mut().last_mut().expect("no call frames exist")
294    }
295
296    #[inline(always)]
297    pub fn body(&self) -> &'tcx mir::Body<'tcx> {
298        self.frame().body
299    }
300
301    #[inline]
302    pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
303        ty.is_freeze(*self.tcx, self.typing_env)
304    }
305
306    pub fn load_mir(
307        &self,
308        instance: ty::InstanceKind<'tcx>,
309        promoted: Option<mir::Promoted>,
310    ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
311        {
    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/interpret/eval_context.rs:311",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(311u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("load mir(instance={0:?}, promoted={1:?})",
                                                    instance, promoted) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
312        let body = if let Some(promoted) = promoted {
313            let def = instance.def_id();
314            &self.tcx.promoted_mir(def)[promoted]
315        } else {
316            M::load_mir(self, instance)
317        };
318        // do not continue if typeck errors occurred (can only occur in local crate)
319        if let Some(err) = body.tainted_by_errors {
320            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::non_const_eval_error(err)));throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(err)));
321        }
322        interp_ok(body)
323    }
324
325    /// Call this on things you got out of the MIR (so it is as generic as the current
326    /// stack frame), to bring it into the proper environment for this interpreter.
327    pub fn instantiate_from_current_frame_and_normalize_erasing_regions<
328        T: TypeFoldable<TyCtxt<'tcx>>,
329    >(
330        &self,
331        value: T,
332    ) -> Result<T, ErrorHandled> {
333        self.instantiate_from_frame_and_normalize_erasing_regions(self.frame(), value)
334    }
335
336    /// Call this on things you got out of the MIR (so it is as generic as the provided
337    /// stack frame), to bring it into the proper environment for this interpreter.
338    pub fn instantiate_from_frame_and_normalize_erasing_regions<T: TypeFoldable<TyCtxt<'tcx>>>(
339        &self,
340        frame: &Frame<'tcx, M::Provenance, M::FrameExtra>,
341        value: T,
342    ) -> Result<T, ErrorHandled> {
343        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("instantiate_from_frame_and_normalize_erasing_regions",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(343u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("frame.instance")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("frame.instance");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&frame.instance)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(
344            M,
345            "instantiate_from_frame_and_normalize_erasing_regions",
346            %frame.instance
347        );
348        frame
349            .instance
350            .try_instantiate_mir_and_normalize_erasing_regions(
351                *self.tcx,
352                self.typing_env,
353                ty::EarlyBinder::bind(self.tcx.tcx, value),
354            )
355            .map_err(|_| ErrorHandled::TooGeneric(self.cur_span()))
356    }
357
358    /// The `args` are assumed to already be in our interpreter "universe".
359    pub(super) fn resolve(
360        &self,
361        def: DefId,
362        args: GenericArgsRef<'tcx>,
363    ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
364        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("resolve",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(364u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("resolve")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("resolve");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"try_resolve")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, resolve::try_resolve, def = ?def);
365        {
    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/interpret/eval_context.rs:365",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(365u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("resolve: {0:?}, {1:#?}",
                                                    def, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("resolve: {:?}, {:#?}", def, args);
366        {
    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/interpret/eval_context.rs:366",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(366u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("typing_env: {0:#?}",
                                                    self.typing_env) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("typing_env: {:#?}", self.typing_env);
367        {
    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/interpret/eval_context.rs:367",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(367u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("args: {0:#?}",
                                                    args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("args: {:#?}", args);
368        match ty::Instance::try_resolve(*self.tcx, self.typing_env, def, args) {
369            Ok(Some(instance)) => interp_ok(instance),
370            Ok(None) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)throw_inval!(TooGeneric),
371
372            // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
373            Err(error_guaranteed) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::non_const_eval_error(error_guaranteed)))throw_inval!(AlreadyReported(
374                ReportedErrorInfo::non_const_eval_error(error_guaranteed)
375            )),
376        }
377    }
378
379    /// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
380    /// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic,
381    /// and is primarily intended for the panic machinery.
382    pub(crate) fn find_closest_untracked_caller_location(&self) -> Span {
383        for frame in self.stack().iter().rev() {
384            {
    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/interpret/eval_context.rs:384",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(384u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::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_closest_untracked_caller_location: checking frame {0:?}",
                                                    frame.instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_closest_untracked_caller_location: checking frame {:?}", frame.instance);
385
386            // Assert that the frame we look at is actually executing code currently
387            // (`loc` is `Right` when we are unwinding and the frame does not require cleanup).
388            let loc = frame.loc.left().unwrap();
389
390            // This could be a non-`Call` terminator (such as `Drop`), or not a terminator at all
391            // (such as `box`). Use the normal span by default.
392            let mut source_info = *frame.body.source_info(loc);
393
394            // If this is a `Call` terminator, use the `fn_span` instead.
395            let block = &frame.body.basic_blocks[loc.block];
396            if loc.statement_index == block.statements.len() {
397                {
    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/interpret/eval_context.rs:397",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(397u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::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_closest_untracked_caller_location: got terminator {0:?} ({1:?})",
                                                    block.terminator(), block.terminator().kind) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
398                    "find_closest_untracked_caller_location: got terminator {:?} ({:?})",
399                    block.terminator(),
400                    block.terminator().kind,
401                );
402                if let mir::TerminatorKind::Call { fn_span, .. } = block.terminator().kind {
403                    source_info.span = fn_span;
404                }
405            }
406
407            let caller_location = if frame.instance.def.requires_caller_location(*self.tcx) {
408                // We use `Err(())` as indication that we should continue up the call stack since
409                // this is a `#[track_caller]` function.
410                Some(Err(()))
411            } else {
412                None
413            };
414            if let Ok(span) =
415                frame.body.caller_location_span(source_info, caller_location, *self.tcx, Ok)
416            {
417                return span;
418            }
419        }
420
421        ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("no non-`#[track_caller]` frame found"))span_bug!(self.cur_span(), "no non-`#[track_caller]` frame found")
422    }
423
424    /// Returns the actual dynamic size and alignment of the place at the given type.
425    /// Only the "meta" (metadata) part of the place matters.
426    /// This can fail to provide an answer for extern types.
427    pub(super) fn size_and_align_from_meta(
428        &self,
429        metadata: &MemPlaceMeta<M::Provenance>,
430        layout: &TyAndLayout<'tcx>,
431    ) -> InterpResult<'tcx, Option<(Size, Align)>> {
432        if layout.is_sized() {
433            return interp_ok(Some((layout.size, layout.align.abi)));
434        }
435        match layout.ty.kind() {
436            ty::Adt(..) | ty::Tuple(..) => {
437                // First get the size of all statically known fields.
438                // Don't use type_of::sizing_type_of because that expects t to be sized,
439                // and it also rounds up to alignment, which we want to avoid,
440                // as the unsized field's alignment could be smaller.
441                if !!layout.ty.is_simd() {
    ::core::panicking::panic("assertion failed: !layout.ty.is_simd()")
};assert!(!layout.ty.is_simd());
442                if !(layout.fields.count() > 0) {
    ::core::panicking::panic("assertion failed: layout.fields.count() > 0")
};assert!(layout.fields.count() > 0);
443                {
    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/interpret/eval_context.rs:443",
                        "rustc_const_eval::interpret::eval_context",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                        ::tracing_core::__macro_support::Option::Some(443u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("DST layout: {0:?}",
                                                    layout) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("DST layout: {:?}", layout);
444
445                let unsized_offset_unadjusted = layout.fields.offset(layout.fields.count() - 1);
446                let sized_align = layout.align.abi;
447
448                // Recurse to get the size of the dynamically sized field (must be
449                // the last field). Can't have foreign types here, how would we
450                // adjust alignment and size for them?
451                let field = layout.field(self, layout.fields.count() - 1);
452                let Some((unsized_size, mut unsized_align)) =
453                    self.size_and_align_from_meta(metadata, &field)?
454                else {
455                    // A field with an extern type. We don't know the actual dynamic size
456                    // or the alignment.
457                    return interp_ok(None);
458                };
459
460                // # First compute the dynamic alignment
461
462                // Packed type alignment needs to be capped.
463                if let ty::Adt(def, _) = layout.ty.kind()
464                    && let Some(packed) = def.repr().pack
465                {
466                    unsized_align = unsized_align.min(packed);
467                }
468
469                // Choose max of two known alignments (combined value must
470                // be aligned according to more restrictive of the two).
471                let full_align = sized_align.max(unsized_align);
472
473                // # Then compute the dynamic size
474
475                let unsized_offset_adjusted = unsized_offset_unadjusted.align_to(unsized_align);
476                let full_size = (unsized_offset_adjusted + unsized_size).align_to(full_align);
477
478                // Just for our sanitiy's sake, assert that this is equal to what codegen would compute.
479                {
    match (&full_size,
            &(unsized_offset_unadjusted + unsized_size).align_to(full_align))
        {
        (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!(
480                    full_size,
481                    (unsized_offset_unadjusted + unsized_size).align_to(full_align)
482                );
483
484                // Check if this brought us over the size limit.
485                if full_size > self.max_size_of_val() {
486                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidMeta(InvalidMetaKind::TooBig));throw_ub!(InvalidMeta(InvalidMetaKind::TooBig));
487                }
488                interp_ok(Some((full_size, full_align)))
489            }
490            ty::Dynamic(expected_trait, _) => {
491                let vtable = metadata.unwrap_meta().to_pointer(self);
492                // Read size and align from vtable (already checks size).
493                interp_ok(Some(self.get_vtable_size_and_align(vtable, Some(expected_trait))?))
494            }
495
496            ty::Slice(_) | ty::Str => {
497                let len = metadata.unwrap_meta().to_target_usize(self)?;
498                let elem = layout.field(self, 0);
499
500                // Make sure the slice is not too big.
501                let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`.
502                let size = Size::from_bytes(size);
503                if size > self.max_size_of_val() {
504                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidMeta(InvalidMetaKind::SliceTooBig));throw_ub!(InvalidMeta(InvalidMetaKind::SliceTooBig));
505                }
506                interp_ok(Some((size, elem.align.abi)))
507            }
508
509            ty::Foreign(_) => interp_ok(None),
510
511            _ => ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("size_and_align_of::<{0}> not supported", layout.ty))span_bug!(self.cur_span(), "size_and_align_of::<{}> not supported", layout.ty),
512        }
513    }
514    #[inline]
515    pub fn size_and_align_of_val(
516        &self,
517        val: &impl Projectable<'tcx, M::Provenance>,
518    ) -> InterpResult<'tcx, Option<(Size, Align)>> {
519        self.size_and_align_from_meta(&val.meta(), &val.layout())
520    }
521
522    /// Jump to the given block.
523    #[inline]
524    pub fn go_to_block(&mut self, target: mir::BasicBlock) {
525        self.frame_mut().loc = Left(mir::Location { block: target, statement_index: 0 });
526    }
527
528    /// *Return* to the given `target` basic block.
529    /// Do *not* use for unwinding! Use `unwind_to_block` instead.
530    ///
531    /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
532    pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
533        if let Some(target) = target {
534            self.go_to_block(target);
535            interp_ok(())
536        } else {
537            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Unreachable)throw_ub!(Unreachable)
538        }
539    }
540
541    /// *Unwind* to the given `target` basic block.
542    /// Do *not* use for returning! Use `return_to_block` instead.
543    ///
544    /// If `target` is `UnwindAction::Continue`, that indicates the function does not need cleanup
545    /// during unwinding, and we will just keep propagating that upwards.
546    ///
547    /// If `target` is `UnwindAction::Unreachable`, that indicates the function does not allow
548    /// unwinding, and doing so is UB.
549    #[cold] // usually we have normal returns, not unwinding
550    pub fn unwind_to_block(&mut self, target: mir::UnwindAction) -> InterpResult<'tcx> {
551        self.frame_mut().loc = match target {
552            mir::UnwindAction::Cleanup(block) => Left(mir::Location { block, statement_index: 0 }),
553            mir::UnwindAction::Continue => Right(self.frame_mut().body.span),
554            mir::UnwindAction::Unreachable => {
555                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("unwinding past a stack frame that does not allow unwinding"))
                })));throw_ub_format!("unwinding past a stack frame that does not allow unwinding");
556            }
557            mir::UnwindAction::Terminate(reason) => {
558                self.frame_mut().loc = Right(self.frame_mut().body.span);
559                M::unwind_terminate(self, reason)?;
560                // This might have pushed a new stack frame, or it terminated execution.
561                // Either way, `loc` will not be updated.
562                return interp_ok(());
563            }
564        };
565        interp_ok(())
566    }
567
568    /// Call a query that can return `ErrorHandled`. Should be used for statics and other globals.
569    /// (`mir::Const`/`ty::Const` have `eval` methods that can be used directly instead.)
570    pub fn ctfe_query<T>(
571        &self,
572        query: impl FnOnce(TyCtxtAt<'tcx>) -> Result<T, ErrorHandled>,
573    ) -> Result<T, ErrorHandled> {
574        // Use a precise span for better cycle errors.
575        query(self.tcx.at(self.cur_span())).map_err(|err| {
576            err.emit_note(*self.tcx);
577            err
578        })
579    }
580
581    pub fn eval_global(
582        &self,
583        instance: ty::Instance<'tcx>,
584    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
585        let gid = GlobalId { instance, promoted: None };
586        let val = if self.tcx.is_static(gid.instance.def_id()) {
587            let alloc_id = self.tcx.reserve_and_set_static_alloc(gid.instance.def_id());
588
589            let ty = instance.ty(self.tcx.tcx, self.typing_env);
590            mir::ConstAlloc { alloc_id, ty }
591        } else {
592            self.ctfe_query(|tcx| tcx.eval_to_allocation_raw(self.typing_env.as_query_input(gid)))?
593        };
594        self.raw_const_to_mplace(val)
595    }
596
597    pub fn eval_mir_constant(
598        &self,
599        val: &mir::Const<'tcx>,
600        span: Span,
601        layout: Option<TyAndLayout<'tcx>>,
602    ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
603        let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("const_eval",
                                "rustc_const_eval::interpret::eval_context",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
                                ::tracing_core::__macro_support::Option::Some(603u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("const_eval")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("const_eval");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("val")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("val");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"eval_mir_constant")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&val)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, const_eval::eval_mir_constant, ?val);
604        let const_val = val.eval(*self.tcx, self.typing_env, span).map_err(|err| {
605                if M::ALL_CONSTS_ARE_PRECHECKED {
606                    match err {
607                        ErrorHandled::TooGeneric(..) => {},
608                        ErrorHandled::Reported(reported, span) => {
609                            if reported.is_allowed_in_infallible() {
610                                // These errors can just sometimes happen, even when the expression
611                                // is nominally "infallible", e.g. when running out of memory
612                                // or when some layout could not be computed.
613                            } else {
614                                // Looks like the const is not captured by `required_consts`, that's bad.
615                                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("interpret const eval failure of {0:?} which is not in required_consts",
        val));span_bug!(span, "interpret const eval failure of {val:?} which is not in required_consts");
616                            }
617                        }
618                    }
619                }
620                err.emit_note(*self.tcx);
621                err
622            })?;
623        self.const_val_to_op(const_val, val.ty(), layout)
624    }
625
626    #[must_use]
627    pub fn dump_place(&self, place: &PlaceTy<'tcx, M::Provenance>) -> PlacePrinter<'_, 'tcx, M> {
628        PlacePrinter { ecx: self, place: *place.place() }
629    }
630
631    #[must_use]
632    pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
633        Frame::generate_stacktrace_from_stack(self.stack(), *self.tcx)
634    }
635
636    pub fn adjust_nan<F1, F2>(&self, f: F2, inputs: &[F1]) -> F2
637    where
638        F1: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F2>,
639        F2: rustc_apfloat::Float,
640    {
641        if f.is_nan() { M::generate_nan(self, inputs) } else { f }
642    }
643}
644
645#[doc(hidden)]
646/// Helper struct for the `dump_place` function.
647pub struct PlacePrinter<'a, 'tcx, M: Machine<'tcx>> {
648    ecx: &'a InterpCx<'tcx, M>,
649    place: Place<M::Provenance>,
650}
651
652impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for PlacePrinter<'a, 'tcx, M> {
653    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
654        match self.place {
655            Place::Local { local, offset, locals_addr } => {
656                if true {
    {
        match (&locals_addr, &self.ecx.frame().locals_addr()) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(locals_addr, self.ecx.frame().locals_addr());
657                let mut allocs = Vec::new();
658                fmt.write_fmt(format_args!("{0:?}", local))write!(fmt, "{local:?}")?;
659                if let Some(offset) = offset {
660                    fmt.write_fmt(format_args!("+{0:#x}", offset.bytes()))write!(fmt, "+{:#x}", offset.bytes())?;
661                }
662                fmt.write_fmt(format_args!(":"))write!(fmt, ":")?;
663
664                self.ecx.frame().locals[local].print(&mut allocs, fmt)?;
665
666                fmt.write_fmt(format_args!(": {0:?}",
        self.ecx.dump_allocs(allocs.into_iter().flatten().collect())))write!(fmt, ": {:?}", self.ecx.dump_allocs(allocs.into_iter().flatten().collect()))
667            }
668            Place::Ptr(mplace) => match mplace.ptr.provenance.and_then(Provenance::get_alloc_id) {
669                Some(alloc_id) => {
670                    fmt.write_fmt(format_args!("by ref {0:?}: {1:?}", mplace.ptr,
        self.ecx.dump_alloc(alloc_id)))write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))
671                }
672                ptr => fmt.write_fmt(format_args!(" integral by ref: {0:?}", ptr))write!(fmt, " integral by ref: {ptr:?}"),
673            },
674        }
675    }
676}