rustc_const_eval/interpret/
eval_context.rs

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