5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
7 use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
8 use rustc_index::vec::IndexVec;
9 use rustc_macros::HashStable;
10 use rustc_middle::ich::StableHashingContext;
11 use rustc_middle::mir;
12 use rustc_middle::mir::interpret::{GlobalId, InterpResult, Pointer, Scalar};
13 use rustc_middle::ty::layout::{self, TyAndLayout};
14 use rustc_middle::ty::{
15 self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
17 use rustc_span::{Pos, Span};
18 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
21 Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, Operand, Place, PlaceTy,
22 ScalarMaybeUninit, StackPopJump,
24 use crate::transform::validate::equal_up_to_regions;
25 use crate::util::storage::AlwaysLiveLocals;
27 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
28 /// Stores the `Machine` instance.
30 /// Note: the stack is provided by the machine.
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>,
38 /// Bounds in scope for polymorphic evaluations.
39 pub(crate) param_env: ty::ParamEnv<'tcx>,
41 /// The virtual memory system.
42 pub memory: Memory<'mir, 'tcx, M>,
44 /// A cache for deduplicating vtables
46 FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
49 // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread
50 // boundary and dropped in the other thread, it would exit the span in the other thread.
51 struct SpanGuard(tracing::Span, std::marker::PhantomData<*const u8>);
54 /// By default a `SpanGuard` does nothing.
56 Self(tracing::Span::none(), std::marker::PhantomData)
59 /// If a span is entered, we exit the previous span (if any, normally none) and enter the
60 /// new span. This is mainly so we don't have to use `Option` for the `tracing_span` field of
61 /// `Frame` by creating a dummy span to being with and then entering it once the frame has
63 fn enter(&mut self, span: tracing::Span) {
64 // This executes the destructor on the previous instance of `SpanGuard`, ensuring that
65 // we never enter or exit more spans than vice versa. Unless you `mem::leak`, then we
66 // can't protect the tracing stack, but that'll just lead to weird logging, no actual
68 *self = Self(span, std::marker::PhantomData);
69 self.0.with_subscriber(|(id, dispatch)| {
75 impl Drop for SpanGuard {
77 self.0.with_subscriber(|(id, dispatch)| {
84 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
85 ////////////////////////////////////////////////////////////////////////////////
86 // Function and callsite information
87 ////////////////////////////////////////////////////////////////////////////////
88 /// The MIR for the function called on this frame.
89 pub body: &'mir mir::Body<'tcx>,
91 /// The def_id and substs of the current function.
92 pub instance: ty::Instance<'tcx>,
94 /// Extra data for the machine.
97 ////////////////////////////////////////////////////////////////////////////////
98 // Return place and locals
99 ////////////////////////////////////////////////////////////////////////////////
100 /// Work to perform when returning from this function.
101 pub return_to_block: StackPopCleanup,
103 /// The location where the result of the current stack frame should be written to,
104 /// and its layout in the caller.
105 pub return_place: Option<PlaceTy<'tcx, Tag>>,
107 /// The list of locals for this stack frame, stored in order as
108 /// `[return_ptr, arguments..., variables..., temporaries...]`.
109 /// The locals are stored as `Option<Value>`s.
110 /// `None` represents a local that is currently dead, while a live local
111 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
112 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
114 /// The span of the `tracing` crate is stored here.
115 /// When the guard is dropped, the span is exited. This gives us
116 /// a full stack trace on all tracing statements.
117 tracing_span: SpanGuard,
119 ////////////////////////////////////////////////////////////////////////////////
120 // Current position within the function
121 ////////////////////////////////////////////////////////////////////////////////
122 /// If this is `Err`, we are not currently executing any particular statement in
123 /// this frame (can happen e.g. during frame initialization, and during unwinding on
124 /// frames without cleanup code).
125 /// We basically abuse `Result` as `Either`.
126 pub(super) loc: Result<mir::Location, Span>,
129 /// What we store about a frame in an interpreter backtrace.
131 pub struct FrameInfo<'tcx> {
132 pub instance: ty::Instance<'tcx>,
134 pub lint_root: Option<hir::HirId>,
137 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
138 pub enum StackPopCleanup {
139 /// Jump to the next block in the caller, or cause UB if None (that's a function
140 /// that may never return). Also store layout of return place so
141 /// we can validate it at that layout.
142 /// `ret` stores the block we jump to on a normal return, while `unwind`
143 /// stores the block used for cleanup during unwinding.
144 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
145 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
146 /// `cleanup` says whether locals are deallocated. Static computation
147 /// wants them leaked to intern what they need (and just throw away
148 /// the entire `ecx` when it is done).
149 None { cleanup: bool },
152 /// State of a local variable including a memoized layout
153 #[derive(Clone, PartialEq, Eq, HashStable)]
154 pub struct LocalState<'tcx, Tag = ()> {
155 pub value: LocalValue<Tag>,
156 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
157 #[stable_hasher(ignore)]
158 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
161 /// Current value of a local variable
162 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
163 pub enum LocalValue<Tag = ()> {
164 /// This local is not currently alive, and cannot be used at all.
166 /// This local is alive but not yet initialized. It can be written to
167 /// but not read from or its address taken. Locals get initialized on
168 /// first write because for unsized locals, we do not know their size
171 /// A normal, live local.
172 /// Mostly for convenience, we re-use the `Operand` type here.
173 /// This is an optimization over just always having a pointer here;
174 /// we can thus avoid doing an allocation when the local just stores
175 /// immediate values *and* never has its address taken.
179 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
180 /// Read the local's value or error if the local is not yet live or not live anymore.
182 /// Note: This may only be invoked from the `Machine::access_local` hook and not from
183 /// anywhere else. You may be invalidating machine invariants if you do!
184 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
186 LocalValue::Dead => throw_ub!(DeadLocal),
187 LocalValue::Uninitialized => {
188 bug!("The type checker should prevent reading from a never-written local")
190 LocalValue::Live(val) => Ok(val),
194 /// Overwrite the local. If the local can be overwritten in place, return a reference
195 /// to do so; otherwise return the `MemPlace` to consult instead.
197 /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
198 /// anywhere else. You may be invalidating machine invariants if you do!
201 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
203 LocalValue::Dead => throw_ub!(DeadLocal),
204 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
206 local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
213 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
214 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
217 instance: self.instance,
218 return_to_block: self.return_to_block,
219 return_place: self.return_place,
223 tracing_span: self.tracing_span,
228 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
229 /// Get the current location within the Frame.
231 /// If this is `Err`, we are not currently executing any particular statement in
232 /// this frame (can happen e.g. during frame initialization, and during unwinding on
233 /// frames without cleanup code).
234 /// We basically abuse `Result` as `Either`.
235 pub fn current_loc(&self) -> Result<mir::Location, Span> {
239 /// Return the `SourceInfo` of the current instruction.
240 pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
241 self.loc.ok().map(|loc| self.body.source_info(loc))
244 pub fn current_span(&self) -> Span {
246 Ok(loc) => self.body.source_info(loc).span,
252 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 ty::tls::with(|tcx| {
255 if tcx.def_key(self.instance.def_id()).disambiguated_data.data
256 == DefPathData::ClosureExpr
258 write!(f, "inside closure")?;
260 write!(f, "inside `{}`", self.instance)?;
262 if !self.span.is_dummy() {
263 let lo = tcx.sess.source_map().lookup_char_pos(self.span.lo());
264 write!(f, " at {}:{}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1)?;
271 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
273 fn data_layout(&self) -> &TargetDataLayout {
274 &self.tcx.data_layout
278 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
280 M: Machine<'mir, 'tcx>,
283 fn tcx(&self) -> TyCtxt<'tcx> {
288 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
290 M: Machine<'mir, 'tcx>,
292 fn param_env(&self) -> ty::ParamEnv<'tcx> {
297 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
299 type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
302 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
304 .layout_of(self.param_env.and(ty))
305 .map_err(|layout| err_inval!(Layout(layout)).into())
309 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
310 /// This test should be symmetric, as it is primarily about layout compatibility.
311 pub(super) fn mir_assign_valid_types<'tcx>(
313 param_env: ParamEnv<'tcx>,
314 src: TyAndLayout<'tcx>,
315 dest: TyAndLayout<'tcx>,
317 // Type-changing assignments can happen when subtyping is used. While
318 // all normal lifetimes are erased, higher-ranked types with their
319 // late-bound lifetimes are still around and can lead to type
320 // differences. So we compare ignoring lifetimes.
321 if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
322 // Make sure the layout is equal, too -- just to be safe. Miri really
323 // needs layout equality. For performance reason we skip this check when
324 // the types are equal. Equal types *can* have different layouts when
325 // enum downcast is involved (as enum variants carry the type of the
326 // enum), but those should never occur in assignments.
327 if cfg!(debug_assertions) || src.ty != dest.ty {
328 assert_eq!(src.layout, dest.layout);
336 /// Use the already known layout if given (but sanity check in debug mode),
337 /// or compute the layout.
338 #[cfg_attr(not(debug_assertions), inline(always))]
339 pub(super) fn from_known_layout<'tcx>(
341 param_env: ParamEnv<'tcx>,
342 known_layout: Option<TyAndLayout<'tcx>>,
343 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
344 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
347 Some(known_layout) => {
348 if cfg!(debug_assertions) {
349 let check_layout = compute()?;
350 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
353 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
364 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
368 param_env: ty::ParamEnv<'tcx>,
370 memory_extra: M::MemoryExtra,
374 tcx: tcx.at(root_span),
376 memory: Memory::new(tcx, memory_extra),
377 vtables: FxHashMap::default(),
382 pub fn cur_span(&self) -> Span {
383 self.stack().last().map_or(self.tcx.span, |f| f.current_span())
389 scalar: Scalar<M::PointerTag>,
390 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
391 self.memory.force_ptr(scalar)
397 scalar: Scalar<M::PointerTag>,
399 ) -> InterpResult<'tcx, u128> {
400 self.memory.force_bits(scalar, size)
403 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
404 /// the machine pointer to the allocation. Must never be used
405 /// for any other pointers, nor for TLS statics.
407 /// Using the resulting pointer represents a *direct* access to that memory
408 /// (e.g. by directly using a `static`),
409 /// as opposed to access through a pointer that was created by the program.
411 /// This function can fail only if `ptr` points to an `extern static`.
413 pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
414 self.memory.global_base_pointer(ptr)
418 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
423 pub(crate) fn stack_mut(
425 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
430 pub fn frame_idx(&self) -> usize {
431 let stack = self.stack();
432 assert!(!stack.is_empty());
437 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
438 self.stack().last().expect("no call frames exist")
442 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
443 self.stack_mut().last_mut().expect("no call frames exist")
447 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
452 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
453 assert!(ty.abi.is_signed());
454 ty.size.sign_extend(value)
458 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
459 ty.size.truncate(value)
463 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
464 ty.is_sized(self.tcx, self.param_env)
468 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
469 ty.is_freeze(self.tcx, self.param_env)
474 instance: ty::InstanceDef<'tcx>,
475 promoted: Option<mir::Promoted>,
476 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
477 // do not continue if typeck errors occurred (can only occur in local crate)
478 let def = instance.with_opt_param();
479 if let Some(def) = def.as_local() {
480 if self.tcx.has_typeck_results(def.did) {
481 if let Some(error_reported) = self.tcx.typeck_opt_const_arg(def).tainted_by_errors {
482 throw_inval!(AlreadyReported(error_reported))
486 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
487 if let Some(promoted) = promoted {
488 return Ok(&self.tcx.promoted_mir_opt_const_arg(def)[promoted]);
490 M::load_mir(self, instance)
493 /// Call this on things you got out of the MIR (so it is as generic as the current
494 /// stack frame), to bring it into the proper environment for this interpreter.
495 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
499 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
502 /// Call this on things you got out of the MIR (so it is as generic as the provided
503 /// stack frame), to bring it into the proper environment for this interpreter.
504 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
506 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
509 frame.instance.subst_mir_and_normalize_erasing_regions(*self.tcx, self.param_env, value)
512 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
513 pub(super) fn resolve(
515 def: ty::WithOptConstParam<DefId>,
516 substs: SubstsRef<'tcx>,
517 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
518 trace!("resolve: {:?}, {:#?}", def, substs);
519 trace!("param_env: {:#?}", self.param_env);
520 trace!("substs: {:#?}", substs);
521 match ty::Instance::resolve_opt_const_arg(*self.tcx, self.param_env, def, substs) {
522 Ok(Some(instance)) => Ok(instance),
523 Ok(None) => throw_inval!(TooGeneric),
525 // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
526 Err(error_reported) => throw_inval!(AlreadyReported(error_reported)),
531 pub fn layout_of_local(
533 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
535 layout: Option<TyAndLayout<'tcx>>,
536 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
537 // `const_prop` runs into this with an invalid (empty) frame, so we
538 // have to support that case (mostly by skipping all caching).
539 match frame.locals.get(local).and_then(|state| state.layout.get()) {
541 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
542 let local_ty = frame.body.local_decls[local].ty;
544 self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
545 self.layout_of(local_ty)
547 if let Some(state) = frame.locals.get(local) {
548 // Layouts of locals are requested a lot, so we cache them.
549 state.layout.set(Some(layout));
553 Some(layout) => Ok(layout),
557 /// Returns the actual dynamic size and alignment of the place at the given type.
558 /// Only the "meta" (metadata) part of the place matters.
559 /// This can fail to provide an answer for extern types.
560 pub(super) fn size_and_align_of(
562 metadata: &MemPlaceMeta<M::PointerTag>,
563 layout: &TyAndLayout<'tcx>,
564 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
565 if !layout.is_unsized() {
566 return Ok(Some((layout.size, layout.align.abi)));
568 match layout.ty.kind() {
569 ty::Adt(..) | ty::Tuple(..) => {
570 // First get the size of all statically known fields.
571 // Don't use type_of::sizing_type_of because that expects t to be sized,
572 // and it also rounds up to alignment, which we want to avoid,
573 // as the unsized field's alignment could be smaller.
574 assert!(!layout.ty.is_simd());
575 assert!(layout.fields.count() > 0);
576 trace!("DST layout: {:?}", layout);
578 let sized_size = layout.fields.offset(layout.fields.count() - 1);
579 let sized_align = layout.align.abi;
581 "DST {} statically sized prefix size: {:?} align: {:?}",
587 // Recurse to get the size of the dynamically sized field (must be
588 // the last field). Can't have foreign types here, how would we
589 // adjust alignment and size for them?
590 let field = layout.field(self, layout.fields.count() - 1)?;
591 let (unsized_size, unsized_align) =
592 match self.size_and_align_of(metadata, &field)? {
593 Some(size_and_align) => size_and_align,
595 // A field with extern type. If this field is at offset 0, we behave
596 // like the underlying extern type.
597 // FIXME: Once we have made decisions for how to handle size and alignment
598 // of `extern type`, this should be adapted. It is just a temporary hack
599 // to get some code to work that probably ought to work.
600 if sized_size == Size::ZERO {
605 "Fields cannot be extern types, unless they are at offset 0"
611 // FIXME (#26403, #27023): We should be adding padding
612 // to `sized_size` (to accommodate the `unsized_align`
613 // required of the unsized field that follows) before
614 // summing it with `sized_size`. (Note that since #26403
615 // is unfixed, we do not yet add the necessary padding
616 // here. But this is where the add would go.)
618 // Return the sum of sizes and max of aligns.
619 let size = sized_size + unsized_size; // `Size` addition
621 // Choose max of two known alignments (combined value must
622 // be aligned according to more restrictive of the two).
623 let align = sized_align.max(unsized_align);
625 // Issue #27023: must add any necessary padding to `size`
626 // (to make it a multiple of `align`) before returning it.
627 let size = size.align_to(align);
629 // Check if this brought us over the size limit.
630 if size.bytes() >= self.tcx.data_layout.obj_size_bound() {
631 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
633 Ok(Some((size, align)))
636 let vtable = metadata.unwrap_meta();
637 // Read size and align from vtable (already checks size).
638 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
641 ty::Slice(_) | ty::Str => {
642 let len = metadata.unwrap_meta().to_machine_usize(self)?;
643 let elem = layout.field(self, 0)?;
645 // Make sure the slice is not too big.
646 let size = elem.size.checked_mul(len, self).ok_or_else(|| {
647 err_ub!(InvalidMeta("slice is bigger than largest supported object"))
649 Ok(Some((size, elem.align.abi)))
652 ty::Foreign(_) => Ok(None),
654 _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
658 pub fn size_and_align_of_mplace(
660 mplace: &MPlaceTy<'tcx, M::PointerTag>,
661 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
662 self.size_and_align_of(&mplace.meta, &mplace.layout)
665 pub fn push_stack_frame(
667 instance: ty::Instance<'tcx>,
668 body: &'mir mir::Body<'tcx>,
669 return_place: Option<&PlaceTy<'tcx, M::PointerTag>>,
670 return_to_block: StackPopCleanup,
671 ) -> InterpResult<'tcx> {
672 // first push a stack frame so we have access to the local substs
673 let pre_frame = Frame {
675 loc: Err(body.span), // Span used for errors caused during preamble.
677 return_place: return_place.copied(),
678 // empty local array, we fill it in below, after we are inside the stack frame and
679 // all methods actually know about the frame
680 locals: IndexVec::new(),
682 tracing_span: SpanGuard::new(),
685 let frame = M::init_frame_extra(self, pre_frame)?;
686 self.stack_mut().push(frame);
688 // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
689 for const_ in &body.required_consts {
690 let span = const_.span;
692 self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal);
693 self.mir_const_to_op(&const_, None).map_err(|err| {
694 // If there was an error, set the span of the current frame to this constant.
695 // Avoiding doing this when evaluation succeeds.
696 self.frame_mut().loc = Err(span);
701 // Locals are initially uninitialized.
702 let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
703 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
705 // Now mark those locals as dead that we do not want to initialize
706 // Mark locals that use `Storage*` annotations as dead on function entry.
707 let always_live = AlwaysLiveLocals::new(self.body());
708 for local in locals.indices() {
709 if !always_live.contains(local) {
710 locals[local].value = LocalValue::Dead;
714 self.frame_mut().locals = locals;
715 M::after_stack_push(self)?;
716 self.frame_mut().loc = Ok(mir::Location::START);
718 let span = info_span!("frame", "{}", instance);
719 self.frame_mut().tracing_span.enter(span);
724 /// Jump to the given block.
726 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
727 self.frame_mut().loc = Ok(mir::Location { block: target, statement_index: 0 });
730 /// *Return* to the given `target` basic block.
731 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
733 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
734 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
735 if let Some(target) = target {
736 self.go_to_block(target);
739 throw_ub!(Unreachable)
743 /// *Unwind* to the given `target` basic block.
744 /// Do *not* use for returning! Use `return_to_block` instead.
746 /// If `target` is `None`, that indicates the function does not need cleanup during
747 /// unwinding, and we will just keep propagating that upwards.
748 pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
749 self.frame_mut().loc = match target {
750 Some(block) => Ok(mir::Location { block, statement_index: 0 }),
751 None => Err(self.frame_mut().body.span),
755 /// Pops the current frame from the stack, deallocating the
756 /// memory for allocated locals.
758 /// If `unwinding` is `false`, then we are performing a normal return
759 /// from a function. In this case, we jump back into the frame of the caller,
760 /// and continue execution as normal.
762 /// If `unwinding` is `true`, then we are in the middle of a panic,
763 /// and need to unwind this frame. In this case, we jump to the
764 /// `cleanup` block for the function, which is responsible for running
765 /// `Drop` impls for any locals that have been initialized at this point.
766 /// The cleanup block ends with a special `Resume` terminator, which will
767 /// cause us to continue unwinding.
768 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
770 "popping stack frame ({})",
771 if unwinding { "during unwinding" } else { "returning from function" }
774 // Sanity check `unwinding`.
777 match self.frame().loc {
778 Ok(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
783 if unwinding && self.frame_idx() == 0 {
784 throw_ub_format!("unwinding past the topmost frame of the stack");
788 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
791 // Copy the return value to the caller's stack frame.
792 if let Some(ref return_place) = frame.return_place {
793 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
794 self.copy_op_transmute(&op, return_place)?;
795 trace!("{:?}", self.dump_place(**return_place));
797 throw_ub!(Unreachable);
801 // Now where do we jump next?
803 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
804 // In that case, we return early. We also avoid validation in that case,
805 // because this is CTFE and the final value will be thoroughly validated anyway.
806 let (cleanup, next_block) = match frame.return_to_block {
807 StackPopCleanup::Goto { ret, unwind } => {
808 (true, Some(if unwinding { unwind } else { ret }))
810 StackPopCleanup::None { cleanup, .. } => (cleanup, None),
814 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
815 assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
816 assert!(!unwinding, "tried to skip cleanup during unwinding");
817 // Leak the locals, skip validation, skip machine hook.
821 // Cleanup: deallocate all locals that are backed by an allocation.
822 for local in &frame.locals {
823 self.deallocate_local(local.value)?;
826 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
827 // The hook already did everything.
828 // We want to skip the `info!` below, hence early return.
831 // Normal return, figure out where to jump.
833 // Follow the unwind edge.
834 let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
835 self.unwind_to_block(unwind);
837 // Follow the normal return edge.
838 if let Some(ret) = next_block {
839 self.return_to_block(ret)?;
846 /// Mark a storage as live, killing the previous content.
847 pub fn storage_live(&mut self, local: mir::Local) -> InterpResult<'tcx> {
848 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
849 trace!("{:?} is now live", local);
851 let local_val = LocalValue::Uninitialized;
852 // StorageLive expects the local to be dead, and marks it live.
853 let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val);
854 if !matches!(old, LocalValue::Dead) {
855 throw_ub_format!("StorageLive on a local that was already live");
860 pub fn storage_dead(&mut self, local: mir::Local) -> InterpResult<'tcx> {
861 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
862 trace!("{:?} is now dead", local);
864 // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR)
865 let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead);
866 self.deallocate_local(old)?;
870 fn deallocate_local(&mut self, local: LocalValue<M::PointerTag>) -> InterpResult<'tcx> {
871 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
872 // All locals have a backing allocation, even if the allocation is empty
873 // due to the local having ZST type.
874 let ptr = ptr.assert_ptr();
875 trace!("deallocating local: {:?}", self.memory.dump_alloc(ptr.alloc_id));
876 self.memory.deallocate_local(ptr)?;
881 pub fn eval_to_allocation(
884 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
885 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
886 // and thus don't care about the parameter environment. While we could just use
887 // `self.param_env`, that would mean we invoke the query to evaluate the static
888 // with different parameter environments, thus causing the static to be evaluated
890 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
891 ty::ParamEnv::reveal_all()
895 let val = self.tcx.eval_to_allocation_raw(param_env.and(gid))?;
896 self.raw_const_to_mplace(val)
900 pub fn dump_place(&'a self, place: Place<M::PointerTag>) -> PlacePrinter<'a, 'mir, 'tcx, M> {
901 PlacePrinter { ecx: self, place }
905 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
906 let mut frames = Vec::new();
907 for frame in self.stack().iter().rev() {
908 let lint_root = frame.current_source_info().and_then(|source_info| {
909 match &frame.body.source_scopes[source_info.scope].local_data {
910 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
911 mir::ClearCrossCrate::Clear => None,
914 let span = frame.current_span();
916 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
918 trace!("generate stacktrace: {:#?}", frames);
924 /// Helper struct for the `dump_place` function.
925 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
926 ecx: &'a InterpCx<'mir, 'tcx, M>,
927 place: Place<M::PointerTag>,
930 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
931 for PlacePrinter<'a, 'mir, 'tcx, M>
933 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
935 Place::Local { frame, local } => {
936 let mut allocs = Vec::new();
937 write!(fmt, "{:?}", local)?;
938 if frame != self.ecx.frame_idx() {
939 write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
943 match self.ecx.stack()[frame].locals[local].value {
944 LocalValue::Dead => write!(fmt, " is dead")?,
945 LocalValue::Uninitialized => write!(fmt, " is uninitialized")?,
946 LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
947 Scalar::Ptr(ptr) => {
950 " by align({}){} ref:",
951 mplace.align.bytes(),
953 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
954 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
957 allocs.push(ptr.alloc_id);
959 ptr => write!(fmt, " by integral ref: {:?}", ptr)?,
961 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
962 write!(fmt, " {:?}", val)?;
963 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val {
964 allocs.push(ptr.alloc_id);
967 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
968 write!(fmt, " ({:?}, {:?})", val1, val2)?;
969 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val1 {
970 allocs.push(ptr.alloc_id);
972 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val2 {
973 allocs.push(ptr.alloc_id);
978 write!(fmt, ": {:?}", self.ecx.memory.dump_allocs(allocs))
980 Place::Ptr(mplace) => match mplace.ptr {
981 Scalar::Ptr(ptr) => write!(
983 "by align({}) ref: {:?}",
984 mplace.align.bytes(),
985 self.ecx.memory.dump_alloc(ptr.alloc_id)
987 ptr => write!(fmt, " integral by ref: {:?}", ptr),
993 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
994 for Frame<'mir, 'tcx, Tag, Extra>
996 Extra: HashStable<StableHashingContext<'ctx>>,
997 Tag: HashStable<StableHashingContext<'ctx>>,
999 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
1000 // Exhaustive match on fields to make sure we forget no field.
1011 body.hash_stable(hcx, hasher);
1012 instance.hash_stable(hcx, hasher);
1013 return_to_block.hash_stable(hcx, hasher);
1014 return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
1015 locals.hash_stable(hcx, hasher);
1016 loc.hash_stable(hcx, hasher);
1017 extra.hash_stable(hcx, hasher);