Skip to main content

rustc_const_eval/interpret/
eval_context.rs

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