5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
7 use rustc_hir::def::DefKind;
8 use rustc_hir::def_id::DefId;
9 use rustc_index::vec::IndexVec;
10 use rustc_macros::HashStable;
11 use rustc_middle::ich::StableHashingContext;
12 use rustc_middle::mir;
13 use rustc_middle::mir::interpret::{
14 sign_extend, truncate, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
16 use rustc_middle::ty::layout::{self, TyAndLayout};
17 use rustc_middle::ty::{
18 self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable,
20 use rustc_span::{source_map::DUMMY_SP, Span};
21 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
24 Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
25 ScalarMaybeUndef, StackPopJump,
27 use crate::util::storage::AlwaysLiveLocals;
29 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
30 /// Stores the `Machine` instance.
32 /// Note: the stack is provided by the machine.
35 /// The results of the type checker, from rustc.
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>>,
51 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
52 ////////////////////////////////////////////////////////////////////////////////
53 // Function and callsite information
54 ////////////////////////////////////////////////////////////////////////////////
55 /// The MIR for the function called on this frame.
56 pub body: &'mir mir::Body<'tcx>,
58 /// The def_id and substs of the current function.
59 pub instance: ty::Instance<'tcx>,
61 /// Extra data for the machine.
64 ////////////////////////////////////////////////////////////////////////////////
65 // Return place and locals
66 ////////////////////////////////////////////////////////////////////////////////
67 /// Work to perform when returning from this function.
68 pub return_to_block: StackPopCleanup,
70 /// The location where the result of the current stack frame should be written to,
71 /// and its layout in the caller.
72 pub return_place: Option<PlaceTy<'tcx, Tag>>,
74 /// The list of locals for this stack frame, stored in order as
75 /// `[return_ptr, arguments..., variables..., temporaries...]`.
76 /// The locals are stored as `Option<Value>`s.
77 /// `None` represents a local that is currently dead, while a live local
78 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
79 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
81 ////////////////////////////////////////////////////////////////////////////////
82 // Current position within the function
83 ////////////////////////////////////////////////////////////////////////////////
84 /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
85 /// Just continue the same as with `Resume`.
86 pub loc: Option<mir::Location>,
89 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
90 pub enum StackPopCleanup {
91 /// Jump to the next block in the caller, or cause UB if None (that's a function
92 /// that may never return). Also store layout of return place so
93 /// we can validate it at that layout.
94 /// `ret` stores the block we jump to on a normal return, while `unwind`
95 /// stores the block used for cleanup during unwinding.
96 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
97 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
98 /// `cleanup` says whether locals are deallocated. Static computation
99 /// wants them leaked to intern what they need (and just throw away
100 /// the entire `ecx` when it is done).
101 None { cleanup: bool },
104 /// State of a local variable including a memoized layout
105 #[derive(Clone, PartialEq, Eq, HashStable)]
106 pub struct LocalState<'tcx, Tag = ()> {
107 pub value: LocalValue<Tag>,
108 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
109 #[stable_hasher(ignore)]
110 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
113 /// Current value of a local variable
114 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
115 pub enum LocalValue<Tag = ()> {
116 /// This local is not currently alive, and cannot be used at all.
118 /// This local is alive but not yet initialized. It can be written to
119 /// but not read from or its address taken. Locals get initialized on
120 /// first write because for unsized locals, we do not know their size
123 /// A normal, live local.
124 /// Mostly for convenience, we re-use the `Operand` type here.
125 /// This is an optimization over just always having a pointer here;
126 /// we can thus avoid doing an allocation when the local just stores
127 /// immediate values *and* never has its address taken.
131 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
132 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
134 LocalValue::Dead => throw_ub!(DeadLocal),
135 LocalValue::Uninitialized => {
136 bug!("The type checker should prevent reading from a never-written local")
138 LocalValue::Live(val) => Ok(val),
142 /// Overwrite the local. If the local can be overwritten in place, return a reference
143 /// to do so; otherwise return the `MemPlace` to consult instead.
146 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
148 LocalValue::Dead => throw_ub!(DeadLocal),
149 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
151 local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
158 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
159 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
162 instance: self.instance,
163 return_to_block: self.return_to_block,
164 return_place: self.return_place,
172 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
173 /// Return the `SourceInfo` of the current instruction.
174 pub fn current_source_info(&self) -> Option<mir::SourceInfo> {
176 let block = &self.body.basic_blocks()[loc.block];
177 if loc.statement_index < block.statements.len() {
178 block.statements[loc.statement_index].source_info
180 block.terminator().source_info
186 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
188 fn data_layout(&self) -> &TargetDataLayout {
189 &self.tcx.data_layout
193 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
195 M: Machine<'mir, 'tcx>,
198 fn tcx(&self) -> TyCtxt<'tcx> {
203 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
205 M: Machine<'mir, 'tcx>,
207 fn param_env(&self) -> ty::ParamEnv<'tcx> {
212 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
214 type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
217 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
219 .layout_of(self.param_env.and(ty))
220 .map_err(|layout| err_inval!(Layout(layout)).into())
224 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
225 /// This test should be symmetric, as it is primarily about layout compatibility.
226 pub(super) fn mir_assign_valid_types<'tcx>(
228 src: TyAndLayout<'tcx>,
229 dest: TyAndLayout<'tcx>,
231 if src.ty == dest.ty {
232 // Equal types, all is good.
235 if src.layout != dest.layout {
236 // Layout differs, definitely not equal.
237 // We do this here because Miri would *do the wrong thing* if we allowed layout-changing
242 // Type-changing assignments can happen for (at least) two reasons:
243 // 1. `&mut T` -> `&T` gets optimized from a reborrow to a mere assignment.
244 // 2. Subtyping is used. While all normal lifetimes are erased, higher-ranked types
245 // with their late-bound lifetimes are still around and can lead to type differences.
246 // Normalize both of them away.
247 let normalize = |ty: Ty<'tcx>| {
248 ty.fold_with(&mut BottomUpFolder {
250 // Normalize all references to immutable.
251 ty_op: |ty| match ty.kind {
252 ty::Ref(_, pointee, _) => tcx.mk_imm_ref(tcx.lifetimes.re_erased, pointee),
255 // We just erase all late-bound lifetimes, but this is not fully correct (FIXME):
256 // lifetimes in invariant positions could matter (e.g. through associated types).
257 // We rely on the fact that layout was confirmed to be equal above.
258 lt_op: |_| tcx.lifetimes.re_erased,
259 // Leave consts unchanged.
263 normalize(src.ty) == normalize(dest.ty)
266 /// Use the already known layout if given (but sanity check in debug mode),
267 /// or compute the layout.
268 #[cfg_attr(not(debug_assertions), inline(always))]
269 pub(super) fn from_known_layout<'tcx>(
271 known_layout: Option<TyAndLayout<'tcx>>,
272 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
273 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
276 Some(known_layout) => {
277 if cfg!(debug_assertions) {
278 let check_layout = compute()?;
279 if !mir_assign_valid_types(tcx.tcx, check_layout, known_layout) {
282 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
293 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
296 param_env: ty::ParamEnv<'tcx>,
298 memory_extra: M::MemoryExtra,
304 memory: Memory::new(tcx, memory_extra),
305 vtables: FxHashMap::default(),
310 pub fn set_span(&mut self, span: Span) {
311 self.tcx.span = span;
312 self.memory.tcx.span = span;
318 scalar: Scalar<M::PointerTag>,
319 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
320 self.memory.force_ptr(scalar)
326 scalar: Scalar<M::PointerTag>,
328 ) -> InterpResult<'tcx, u128> {
329 self.memory.force_bits(scalar, size)
332 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
333 /// the *canonical* machine pointer to the allocation. Must never be used
334 /// for any other pointers!
336 /// This represents a *direct* access to that memory, as opposed to access
337 /// through a pointer that was created by the program.
339 pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
340 self.memory.tag_global_base_pointer(ptr)
344 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
349 pub(crate) fn stack_mut(
351 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
356 pub fn frame_idx(&self) -> usize {
357 let stack = self.stack();
358 assert!(!stack.is_empty());
363 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
364 self.stack().last().expect("no call frames exist")
368 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
369 self.stack_mut().last_mut().expect("no call frames exist")
373 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
378 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
379 assert!(ty.abi.is_signed());
380 sign_extend(value, ty.size)
384 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
385 truncate(value, ty.size)
389 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
390 ty.is_sized(self.tcx, self.param_env)
394 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
395 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
400 instance: ty::InstanceDef<'tcx>,
401 promoted: Option<mir::Promoted>,
402 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
403 // do not continue if typeck errors occurred (can only occur in local crate)
404 let did = instance.def_id();
405 if let Some(did) = did.as_local() {
406 if self.tcx.has_typeck_tables(did) {
407 if let Some(error_reported) = self.tcx.typeck_tables_of(did).tainted_by_errors {
408 throw_inval!(TypeckError(error_reported))
412 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
413 if let Some(promoted) = promoted {
414 return Ok(&self.tcx.promoted_mir(did)[promoted]);
417 ty::InstanceDef::Item(def_id) => {
418 if self.tcx.is_mir_available(did) {
419 Ok(self.tcx.optimized_mir(did))
421 throw_unsup!(NoMirFor(def_id))
424 _ => Ok(self.tcx.instance_mir(instance)),
428 /// Call this on things you got out of the MIR (so it is as generic as the current
429 /// stack frame), to bring it into the proper environment for this interpreter.
430 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
434 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
437 /// Call this on things you got out of the MIR (so it is as generic as the provided
438 /// stack frame), to bring it into the proper environment for this interpreter.
439 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
441 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
444 if let Some(substs) = frame.instance.substs_for_mir_body() {
445 self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
447 self.tcx.normalize_erasing_regions(self.param_env, value)
451 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
452 pub(super) fn resolve(
455 substs: SubstsRef<'tcx>,
456 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
457 trace!("resolve: {:?}, {:#?}", def_id, substs);
458 trace!("param_env: {:#?}", self.param_env);
459 trace!("substs: {:#?}", substs);
460 match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) {
461 Ok(Some(instance)) => Ok(instance),
462 Ok(None) => throw_inval!(TooGeneric),
464 // FIXME(eddyb) this could be a bit more specific than `TypeckError`.
465 Err(error_reported) => throw_inval!(TypeckError(error_reported)),
469 pub fn layout_of_local(
471 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
473 layout: Option<TyAndLayout<'tcx>>,
474 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
475 // `const_prop` runs into this with an invalid (empty) frame, so we
476 // have to support that case (mostly by skipping all caching).
477 match frame.locals.get(local).and_then(|state| state.layout.get()) {
479 let layout = from_known_layout(self.tcx, layout, || {
480 let local_ty = frame.body.local_decls[local].ty;
482 self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
483 self.layout_of(local_ty)
485 if let Some(state) = frame.locals.get(local) {
486 // Layouts of locals are requested a lot, so we cache them.
487 state.layout.set(Some(layout));
491 Some(layout) => Ok(layout),
495 /// Returns the actual dynamic size and alignment of the place at the given type.
496 /// Only the "meta" (metadata) part of the place matters.
497 /// This can fail to provide an answer for extern types.
498 pub(super) fn size_and_align_of(
500 metadata: MemPlaceMeta<M::PointerTag>,
501 layout: TyAndLayout<'tcx>,
502 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
503 if !layout.is_unsized() {
504 return Ok(Some((layout.size, layout.align.abi)));
506 match layout.ty.kind {
507 ty::Adt(..) | ty::Tuple(..) => {
508 // First get the size of all statically known fields.
509 // Don't use type_of::sizing_type_of because that expects t to be sized,
510 // and it also rounds up to alignment, which we want to avoid,
511 // as the unsized field's alignment could be smaller.
512 assert!(!layout.ty.is_simd());
513 assert!(layout.fields.count() > 0);
514 trace!("DST layout: {:?}", layout);
516 let sized_size = layout.fields.offset(layout.fields.count() - 1);
517 let sized_align = layout.align.abi;
519 "DST {} statically sized prefix size: {:?} align: {:?}",
525 // Recurse to get the size of the dynamically sized field (must be
526 // the last field). Can't have foreign types here, how would we
527 // adjust alignment and size for them?
528 let field = layout.field(self, layout.fields.count() - 1)?;
529 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
530 Some(size_and_align) => size_and_align,
532 // A field with extern type. If this field is at offset 0, we behave
533 // like the underlying extern type.
534 // FIXME: Once we have made decisions for how to handle size and alignment
535 // of `extern type`, this should be adapted. It is just a temporary hack
536 // to get some code to work that probably ought to work.
537 if sized_size == Size::ZERO {
540 bug!("Fields cannot be extern types, unless they are at offset 0")
545 // FIXME (#26403, #27023): We should be adding padding
546 // to `sized_size` (to accommodate the `unsized_align`
547 // required of the unsized field that follows) before
548 // summing it with `sized_size`. (Note that since #26403
549 // is unfixed, we do not yet add the necessary padding
550 // here. But this is where the add would go.)
552 // Return the sum of sizes and max of aligns.
553 let size = sized_size + unsized_size; // `Size` addition
555 // Choose max of two known alignments (combined value must
556 // be aligned according to more restrictive of the two).
557 let align = sized_align.max(unsized_align);
559 // Issue #27023: must add any necessary padding to `size`
560 // (to make it a multiple of `align`) before returning it.
561 let size = size.align_to(align);
563 // Check if this brought us over the size limit.
564 if size.bytes() >= self.tcx.data_layout().obj_size_bound() {
565 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
567 Ok(Some((size, align)))
570 let vtable = metadata.unwrap_meta();
571 // Read size and align from vtable (already checks size).
572 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
575 ty::Slice(_) | ty::Str => {
576 let len = metadata.unwrap_meta().to_machine_usize(self)?;
577 let elem = layout.field(self, 0)?;
579 // Make sure the slice is not too big.
580 let size = elem.size.checked_mul(len, &*self.tcx).ok_or_else(|| {
581 err_ub!(InvalidMeta("slice is bigger than largest supported object"))
583 Ok(Some((size, elem.align.abi)))
586 ty::Foreign(_) => Ok(None),
588 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
592 pub fn size_and_align_of_mplace(
594 mplace: MPlaceTy<'tcx, M::PointerTag>,
595 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
596 self.size_and_align_of(mplace.meta, mplace.layout)
599 pub fn push_stack_frame(
601 instance: ty::Instance<'tcx>,
602 body: &'mir mir::Body<'tcx>,
603 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
604 return_to_block: StackPopCleanup,
605 ) -> InterpResult<'tcx> {
606 if !self.stack().is_empty() {
607 info!("PAUSING({}) {}", self.frame_idx(), self.frame().instance);
609 ::log_settings::settings().indentation += 1;
611 // first push a stack frame so we have access to the local substs
612 let pre_frame = Frame {
614 loc: Some(mir::Location::START),
617 // empty local array, we fill it in below, after we are inside the stack frame and
618 // all methods actually know about the frame
619 locals: IndexVec::new(),
623 let frame = M::init_frame_extra(self, pre_frame)?;
624 self.stack_mut().push(frame);
626 // Locals are initially uninitialized.
627 let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
628 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
630 // Now mark those locals as dead that we do not want to initialize
631 match self.tcx.def_kind(instance.def_id()) {
632 // statics and constants don't have `Storage*` statements, no need to look for them
634 // FIXME: The above is likely untrue. See
635 // <https://github.com/rust-lang/rust/pull/70004#issuecomment-602022110>. Is it
636 // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE?
637 DefKind::Static | DefKind::Const | DefKind::AssocConst => {}
639 // Mark locals that use `Storage*` annotations as dead on function entry.
640 let always_live = AlwaysLiveLocals::new(self.body());
641 for local in locals.indices() {
642 if !always_live.contains(local) {
643 locals[local].value = LocalValue::Dead;
649 self.frame_mut().locals = locals;
651 M::after_stack_push(self)?;
652 info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
654 if self.stack().len() > *self.tcx.sess.recursion_limit.get() {
655 throw_exhaust!(StackFrameLimitReached)
661 /// Jump to the given block.
663 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
664 self.frame_mut().loc = Some(mir::Location { block: target, statement_index: 0 });
667 /// *Return* to the given `target` basic block.
668 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
670 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
671 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
672 if let Some(target) = target {
673 self.go_to_block(target);
676 throw_ub!(Unreachable)
680 /// *Unwind* to the given `target` basic block.
681 /// Do *not* use for returning! Use `return_to_block` instead.
683 /// If `target` is `None`, that indicates the function does not need cleanup during
684 /// unwinding, and we will just keep propagating that upwards.
685 pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
686 self.frame_mut().loc = target.map(|block| mir::Location { block, statement_index: 0 });
689 /// Pops the current frame from the stack, deallocating the
690 /// memory for allocated locals.
692 /// If `unwinding` is `false`, then we are performing a normal return
693 /// from a function. In this case, we jump back into the frame of the caller,
694 /// and continue execution as normal.
696 /// If `unwinding` is `true`, then we are in the middle of a panic,
697 /// and need to unwind this frame. In this case, we jump to the
698 /// `cleanup` block for the function, which is responsible for running
699 /// `Drop` impls for any locals that have been initialized at this point.
700 /// The cleanup block ends with a special `Resume` terminator, which will
701 /// cause us to continue unwinding.
702 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
704 "LEAVING({}) {} (unwinding = {})",
706 self.frame().instance,
710 // Sanity check `unwinding`.
713 match self.frame().loc {
715 Some(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
719 ::log_settings::settings().indentation -= 1;
721 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
724 // Copy the return value to the caller's stack frame.
725 if let Some(return_place) = frame.return_place {
726 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
727 self.copy_op_transmute(op, return_place)?;
728 self.dump_place(*return_place);
730 throw_ub!(Unreachable);
734 // Now where do we jump next?
736 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
737 // In that case, we return early. We also avoid validation in that case,
738 // because this is CTFE and the final value will be thoroughly validated anyway.
739 let (cleanup, next_block) = match frame.return_to_block {
740 StackPopCleanup::Goto { ret, unwind } => {
741 (true, Some(if unwinding { unwind } else { ret }))
743 StackPopCleanup::None { cleanup, .. } => (cleanup, None),
747 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
748 assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
749 assert!(!unwinding, "tried to skip cleanup during unwinding");
750 // Leak the locals, skip validation, skip machine hook.
754 // Cleanup: deallocate all locals that are backed by an allocation.
755 for local in &frame.locals {
756 self.deallocate_local(local.value)?;
759 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
760 // The hook already did everything.
761 // We want to skip the `info!` below, hence early return.
764 // Normal return, figure out where to jump.
766 // Follow the unwind edge.
767 let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
768 self.unwind_to_block(unwind);
770 // Follow the normal return edge.
771 if let Some(ret) = next_block {
772 self.return_to_block(ret)?;
776 if !self.stack().is_empty() {
778 "CONTINUING({}) {} (unwinding = {})",
780 self.frame().instance,
788 /// Mark a storage as live, killing the previous content and returning it.
789 /// Remember to deallocate that!
793 ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
794 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
795 trace!("{:?} is now live", local);
797 let local_val = LocalValue::Uninitialized;
798 // StorageLive *always* kills the value that's currently stored.
799 // However, we do not error if the variable already is live;
800 // see <https://github.com/rust-lang/rust/issues/42371>.
801 Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
804 /// Returns the old value of the local.
805 /// Remember to deallocate that!
806 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
807 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
808 trace!("{:?} is now dead", local);
810 mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
813 pub(super) fn deallocate_local(
815 local: LocalValue<M::PointerTag>,
816 ) -> InterpResult<'tcx> {
817 // FIXME: should we tell the user that there was a local which was never written to?
818 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
819 trace!("deallocating local");
820 // All locals have a backing allocation, even if the allocation is empty
821 // due to the local having ZST type.
822 let ptr = ptr.assert_ptr();
823 if log_enabled!(::log::Level::Trace) {
824 self.memory.dump_alloc(ptr.alloc_id);
826 self.memory.deallocate_local(ptr)?;
831 pub(super) fn const_eval(
835 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
836 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
837 // and thus don't care about the parameter environment. While we could just use
838 // `self.param_env`, that would mean we invoke the query to evaluate the static
839 // with different parameter environments, thus causing the static to be evaluated
841 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
842 ty::ParamEnv::reveal_all()
846 let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
848 // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a
849 // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not
850 // return `ConstValue::Unevaluated`, which is the only way that `eval_const_to_op` will call
852 let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
853 self.eval_const_to_op(&const_, None)
856 pub fn const_eval_raw(
859 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
860 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
861 // and thus don't care about the parameter environment. While we could just use
862 // `self.param_env`, that would mean we invoke the query to evaluate the static
863 // with different parameter environments, thus causing the static to be evaluated
865 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
866 ty::ParamEnv::reveal_all()
870 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
871 // Our result will later be validated anyway, and there seems no good reason
872 // to have to fail early here. This is also more consistent with
873 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
874 let val = self.tcx.const_eval_raw(param_env.and(gid))?;
875 self.raw_const_to_mplace(val)
878 pub fn dump_place(&self, place: Place<M::PointerTag>) {
880 if !log_enabled!(::log::Level::Trace) {
884 Place::Local { frame, local } => {
885 let mut allocs = Vec::new();
886 let mut msg = format!("{:?}", local);
887 if frame != self.frame_idx() {
888 write!(msg, " ({} frames up)", self.frame_idx() - frame).unwrap();
890 write!(msg, ":").unwrap();
892 match self.stack()[frame].locals[local].value {
893 LocalValue::Dead => write!(msg, " is dead").unwrap(),
894 LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
895 LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
896 Scalar::Ptr(ptr) => {
899 " by align({}){} ref:",
900 mplace.align.bytes(),
902 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
903 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
907 allocs.push(ptr.alloc_id);
909 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
911 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
912 write!(msg, " {:?}", val).unwrap();
913 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
914 allocs.push(ptr.alloc_id);
917 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
918 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
919 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
920 allocs.push(ptr.alloc_id);
922 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
923 allocs.push(ptr.alloc_id);
929 self.memory.dump_allocs(allocs);
931 Place::Ptr(mplace) => match mplace.ptr {
932 Scalar::Ptr(ptr) => {
933 trace!("by align({}) ref:", mplace.align.bytes());
934 self.memory.dump_alloc(ptr.alloc_id);
936 ptr => trace!(" integral by ref: {:?}", ptr),
941 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
942 let mut frames = Vec::new();
943 for frame in self.stack().iter().rev() {
944 let source_info = frame.current_source_info();
945 let lint_root = source_info.and_then(|source_info| {
946 match &frame.body.source_scopes[source_info.scope].local_data {
947 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
948 mir::ClearCrossCrate::Clear => None,
951 let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
953 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
955 trace!("generate stacktrace: {:#?}", frames);
960 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
961 for Frame<'mir, 'tcx, Tag, Extra>
963 Extra: HashStable<StableHashingContext<'ctx>>,
964 Tag: HashStable<StableHashingContext<'ctx>>,
966 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
967 // Exhaustive match on fields to make sure we forget no field.
968 let Frame { body, instance, return_to_block, return_place, locals, loc, extra } = self;
969 body.hash_stable(hcx, hasher);
970 instance.hash_stable(hcx, hasher);
971 return_to_block.hash_stable(hcx, hasher);
972 return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
973 locals.hash_stable(hcx, hasher);
974 loc.hash_stable(hcx, hasher);
975 extra.hash_stable(hcx, hasher);