]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
Update const_forget.rs
[rust.git] / src / librustc_mir / interpret / eval_context.rs
1 use std::cell::Cell;
2 use std::fmt::Write;
3 use std::mem;
4
5 use rustc::ich::StableHashingContext;
6 use rustc::mir;
7 use rustc::mir::interpret::{
8     sign_extend, truncate, AllocId, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
9 };
10 use rustc::ty::layout::{self, Align, HasDataLayout, LayoutOf, Size, TyLayout};
11 use rustc::ty::query::TyCtxtAt;
12 use rustc::ty::subst::SubstsRef;
13 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16 use rustc_hir::def::DefKind;
17 use rustc_hir::def_id::DefId;
18 use rustc_index::vec::IndexVec;
19 use rustc_macros::HashStable;
20 use rustc_span::source_map::{self, Span, DUMMY_SP};
21
22 use super::{
23     Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
24     ScalarMaybeUndef, StackPopInfo,
25 };
26
27 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
28     /// Stores the `Machine` instance.
29     pub machine: M,
30
31     /// The results of the type checker, from rustc.
32     pub tcx: TyCtxtAt<'tcx>,
33
34     /// Bounds in scope for polymorphic evaluations.
35     pub(crate) param_env: ty::ParamEnv<'tcx>,
36
37     /// The virtual memory system.
38     pub memory: Memory<'mir, 'tcx, M>,
39
40     /// The virtual call stack.
41     pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
42
43     /// A cache for deduplicating vtables
44     pub(super) vtables:
45         FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
46 }
47
48 /// A stack frame.
49 #[derive(Clone)]
50 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
51     ////////////////////////////////////////////////////////////////////////////////
52     // Function and callsite information
53     ////////////////////////////////////////////////////////////////////////////////
54     /// The MIR for the function called on this frame.
55     pub body: &'mir mir::Body<'tcx>,
56
57     /// The def_id and substs of the current function.
58     pub instance: ty::Instance<'tcx>,
59
60     /// The span of the call site.
61     pub span: source_map::Span,
62
63     /// Extra data for the machine.
64     pub extra: Extra,
65
66     ////////////////////////////////////////////////////////////////////////////////
67     // Return place and locals
68     ////////////////////////////////////////////////////////////////////////////////
69     /// Work to perform when returning from this function.
70     pub return_to_block: StackPopCleanup,
71
72     /// The location where the result of the current stack frame should be written to,
73     /// and its layout in the caller.
74     pub return_place: Option<PlaceTy<'tcx, Tag>>,
75
76     /// The list of locals for this stack frame, stored in order as
77     /// `[return_ptr, arguments..., variables..., temporaries...]`.
78     /// The locals are stored as `Option<Value>`s.
79     /// `None` represents a local that is currently dead, while a live local
80     /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
81     pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
82
83     ////////////////////////////////////////////////////////////////////////////////
84     // Current position within the function
85     ////////////////////////////////////////////////////////////////////////////////
86     /// The block that is currently executed (or will be executed after the above call stacks
87     /// return).
88     /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
89     /// Just continue the same as with `Resume`.
90     pub block: Option<mir::BasicBlock>,
91
92     /// The index of the currently evaluated statement.
93     pub stmt: usize,
94 }
95
96 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
97 pub enum StackPopCleanup {
98     /// Jump to the next block in the caller, or cause UB if None (that's a function
99     /// that may never return). Also store layout of return place so
100     /// we can validate it at that layout.
101     /// `ret` stores the block we jump to on a normal return, while 'unwind'
102     /// stores the block used for cleanup during unwinding
103     Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
104     /// Just do nohing: Used by Main and for the box_alloc hook in miri.
105     /// `cleanup` says whether locals are deallocated. Static computation
106     /// wants them leaked to intern what they need (and just throw away
107     /// the entire `ecx` when it is done).
108     None { cleanup: bool },
109 }
110
111 /// State of a local variable including a memoized layout
112 #[derive(Clone, PartialEq, Eq, HashStable)]
113 pub struct LocalState<'tcx, Tag = (), Id = AllocId> {
114     pub value: LocalValue<Tag, Id>,
115     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
116     #[stable_hasher(ignore)]
117     pub layout: Cell<Option<TyLayout<'tcx>>>,
118 }
119
120 /// Current value of a local variable
121 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
122 pub enum LocalValue<Tag = (), Id = AllocId> {
123     /// This local is not currently alive, and cannot be used at all.
124     Dead,
125     /// This local is alive but not yet initialized. It can be written to
126     /// but not read from or its address taken. Locals get initialized on
127     /// first write because for unsized locals, we do not know their size
128     /// before that.
129     Uninitialized,
130     /// A normal, live local.
131     /// Mostly for convenience, we re-use the `Operand` type here.
132     /// This is an optimization over just always having a pointer here;
133     /// we can thus avoid doing an allocation when the local just stores
134     /// immediate values *and* never has its address taken.
135     Live(Operand<Tag, Id>),
136 }
137
138 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
139     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
140         match self.value {
141             LocalValue::Dead => throw_unsup!(DeadLocal),
142             LocalValue::Uninitialized => {
143                 bug!("The type checker should prevent reading from a never-written local")
144             }
145             LocalValue::Live(val) => Ok(val),
146         }
147     }
148
149     /// Overwrite the local.  If the local can be overwritten in place, return a reference
150     /// to do so; otherwise return the `MemPlace` to consult instead.
151     pub fn access_mut(
152         &mut self,
153     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
154         match self.value {
155             LocalValue::Dead => throw_unsup!(DeadLocal),
156             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
157             ref mut local @ LocalValue::Live(Operand::Immediate(_))
158             | ref mut local @ LocalValue::Uninitialized => Ok(Ok(local)),
159         }
160     }
161 }
162
163 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
164     /// Return the `SourceInfo` of the current instruction.
165     pub fn current_source_info(&self) -> Option<mir::SourceInfo> {
166         self.block.map(|block| {
167             let block = &self.body.basic_blocks()[block];
168             if self.stmt < block.statements.len() {
169                 block.statements[self.stmt].source_info
170             } else {
171                 block.terminator().source_info
172             }
173         })
174     }
175 }
176
177 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
178     #[inline]
179     fn data_layout(&self) -> &layout::TargetDataLayout {
180         &self.tcx.data_layout
181     }
182 }
183
184 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
185 where
186     M: Machine<'mir, 'tcx>,
187 {
188     #[inline]
189     fn tcx(&self) -> TyCtxt<'tcx> {
190         *self.tcx
191     }
192 }
193
194 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
195 where
196     M: Machine<'mir, 'tcx>,
197 {
198     fn param_env(&self) -> ty::ParamEnv<'tcx> {
199         self.param_env
200     }
201 }
202
203 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
204     type Ty = Ty<'tcx>;
205     type TyLayout = InterpResult<'tcx, TyLayout<'tcx>>;
206
207     #[inline]
208     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
209         self.tcx
210             .layout_of(self.param_env.and(ty))
211             .map_err(|layout| err_inval!(Layout(layout)).into())
212     }
213 }
214
215 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
216     pub fn new(
217         tcx: TyCtxtAt<'tcx>,
218         param_env: ty::ParamEnv<'tcx>,
219         machine: M,
220         memory_extra: M::MemoryExtra,
221     ) -> Self {
222         InterpCx {
223             machine,
224             tcx,
225             param_env,
226             memory: Memory::new(tcx, memory_extra),
227             stack: Vec::new(),
228             vtables: FxHashMap::default(),
229         }
230     }
231
232     #[inline(always)]
233     pub fn force_ptr(
234         &self,
235         scalar: Scalar<M::PointerTag>,
236     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
237         self.memory.force_ptr(scalar)
238     }
239
240     #[inline(always)]
241     pub fn force_bits(
242         &self,
243         scalar: Scalar<M::PointerTag>,
244         size: Size,
245     ) -> InterpResult<'tcx, u128> {
246         self.memory.force_bits(scalar, size)
247     }
248
249     /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
250     /// the *canonical* machine pointer to the allocation.  Must never be used
251     /// for any other pointers!
252     ///
253     /// This represents a *direct* access to that memory, as opposed to access
254     /// through a pointer that was created by the program.
255     #[inline(always)]
256     pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
257         self.memory.tag_static_base_pointer(ptr)
258     }
259
260     #[inline(always)]
261     pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
262         &self.stack
263     }
264
265     #[inline(always)]
266     pub fn cur_frame(&self) -> usize {
267         assert!(!self.stack.is_empty());
268         self.stack.len() - 1
269     }
270
271     #[inline(always)]
272     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
273         self.stack.last().expect("no call frames exist")
274     }
275
276     #[inline(always)]
277     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
278         self.stack.last_mut().expect("no call frames exist")
279     }
280
281     #[inline(always)]
282     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
283         self.frame().body
284     }
285
286     #[inline(always)]
287     pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
288         assert!(ty.abi.is_signed());
289         sign_extend(value, ty.size)
290     }
291
292     #[inline(always)]
293     pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
294         truncate(value, ty.size)
295     }
296
297     #[inline]
298     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
299         ty.is_sized(self.tcx, self.param_env)
300     }
301
302     #[inline]
303     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
304         ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
305     }
306
307     pub fn load_mir(
308         &self,
309         instance: ty::InstanceDef<'tcx>,
310         promoted: Option<mir::Promoted>,
311     ) -> InterpResult<'tcx, mir::ReadOnlyBodyAndCache<'tcx, 'tcx>> {
312         // do not continue if typeck errors occurred (can only occur in local crate)
313         let did = instance.def_id();
314         if did.is_local()
315             && self.tcx.has_typeck_tables(did)
316             && self.tcx.typeck_tables_of(did).tainted_by_errors
317         {
318             throw_inval!(TypeckError)
319         }
320         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
321         if let Some(promoted) = promoted {
322             return Ok(self.tcx.promoted_mir(did)[promoted].unwrap_read_only());
323         }
324         match instance {
325             ty::InstanceDef::Item(def_id) => {
326                 if self.tcx.is_mir_available(did) {
327                     Ok(self.tcx.optimized_mir(did).unwrap_read_only())
328                 } else {
329                     throw_unsup!(NoMirFor(self.tcx.def_path_str(def_id)))
330                 }
331             }
332             _ => Ok(self.tcx.instance_mir(instance)),
333         }
334     }
335
336     /// Call this on things you got out of the MIR (so it is as generic as the current
337     /// stack frame), to bring it into the proper environment for this interpreter.
338     pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
339         &self,
340         value: T,
341     ) -> T {
342         self.tcx.subst_and_normalize_erasing_regions(
343             self.frame().instance.substs,
344             self.param_env,
345             &value,
346         )
347     }
348
349     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
350     pub(super) fn resolve(
351         &self,
352         def_id: DefId,
353         substs: SubstsRef<'tcx>,
354     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
355         trace!("resolve: {:?}, {:#?}", def_id, substs);
356         trace!("param_env: {:#?}", self.param_env);
357         trace!("substs: {:#?}", substs);
358         ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs)
359             .ok_or_else(|| err_inval!(TooGeneric).into())
360     }
361
362     pub fn layout_of_local(
363         &self,
364         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
365         local: mir::Local,
366         layout: Option<TyLayout<'tcx>>,
367     ) -> InterpResult<'tcx, TyLayout<'tcx>> {
368         // `const_prop` runs into this with an invalid (empty) frame, so we
369         // have to support that case (mostly by skipping all caching).
370         match frame.locals.get(local).and_then(|state| state.layout.get()) {
371             None => {
372                 let layout = crate::interpret::operand::from_known_layout(layout, || {
373                     let local_ty = frame.body.local_decls[local].ty;
374                     let local_ty = self.tcx.subst_and_normalize_erasing_regions(
375                         frame.instance.substs,
376                         self.param_env,
377                         &local_ty,
378                     );
379                     self.layout_of(local_ty)
380                 })?;
381                 if let Some(state) = frame.locals.get(local) {
382                     // Layouts of locals are requested a lot, so we cache them.
383                     state.layout.set(Some(layout));
384                 }
385                 Ok(layout)
386             }
387             Some(layout) => Ok(layout),
388         }
389     }
390
391     /// Returns the actual dynamic size and alignment of the place at the given type.
392     /// Only the "meta" (metadata) part of the place matters.
393     /// This can fail to provide an answer for extern types.
394     pub(super) fn size_and_align_of(
395         &self,
396         metadata: MemPlaceMeta<M::PointerTag>,
397         layout: TyLayout<'tcx>,
398     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
399         if !layout.is_unsized() {
400             return Ok(Some((layout.size, layout.align.abi)));
401         }
402         match layout.ty.kind {
403             ty::Adt(..) | ty::Tuple(..) => {
404                 // First get the size of all statically known fields.
405                 // Don't use type_of::sizing_type_of because that expects t to be sized,
406                 // and it also rounds up to alignment, which we want to avoid,
407                 // as the unsized field's alignment could be smaller.
408                 assert!(!layout.ty.is_simd());
409                 trace!("DST layout: {:?}", layout);
410
411                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
412                 let sized_align = layout.align.abi;
413                 trace!(
414                     "DST {} statically sized prefix size: {:?} align: {:?}",
415                     layout.ty,
416                     sized_size,
417                     sized_align
418                 );
419
420                 // Recurse to get the size of the dynamically sized field (must be
421                 // the last field).  Can't have foreign types here, how would we
422                 // adjust alignment and size for them?
423                 let field = layout.field(self, layout.fields.count() - 1)?;
424                 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
425                     Some(size_and_align) => size_and_align,
426                     None => {
427                         // A field with extern type.  If this field is at offset 0, we behave
428                         // like the underlying extern type.
429                         // FIXME: Once we have made decisions for how to handle size and alignment
430                         // of `extern type`, this should be adapted.  It is just a temporary hack
431                         // to get some code to work that probably ought to work.
432                         if sized_size == Size::ZERO {
433                             return Ok(None);
434                         } else {
435                             bug!("Fields cannot be extern types, unless they are at offset 0")
436                         }
437                     }
438                 };
439
440                 // FIXME (#26403, #27023): We should be adding padding
441                 // to `sized_size` (to accommodate the `unsized_align`
442                 // required of the unsized field that follows) before
443                 // summing it with `sized_size`. (Note that since #26403
444                 // is unfixed, we do not yet add the necessary padding
445                 // here. But this is where the add would go.)
446
447                 // Return the sum of sizes and max of aligns.
448                 let size = sized_size + unsized_size;
449
450                 // Choose max of two known alignments (combined value must
451                 // be aligned according to more restrictive of the two).
452                 let align = sized_align.max(unsized_align);
453
454                 // Issue #27023: must add any necessary padding to `size`
455                 // (to make it a multiple of `align`) before returning it.
456                 let size = size.align_to(align);
457
458                 // Check if this brought us over the size limit.
459                 if size.bytes() >= self.tcx.data_layout().obj_size_bound() {
460                     throw_ub_format!(
461                         "wide pointer metadata contains invalid information: \
462                         total size is bigger than largest supported object"
463                     );
464                 }
465                 Ok(Some((size, align)))
466             }
467             ty::Dynamic(..) => {
468                 let vtable = metadata.unwrap_meta();
469                 // Read size and align from vtable (already checks size).
470                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
471             }
472
473             ty::Slice(_) | ty::Str => {
474                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
475                 let elem = layout.field(self, 0)?;
476
477                 // Make sure the slice is not too big.
478                 let size = elem.size.checked_mul(len, &*self.tcx).ok_or_else(|| {
479                     err_ub_format!(
480                         "invalid slice: \
481                         total size is bigger than largest supported object"
482                     )
483                 })?;
484                 Ok(Some((size, elem.align.abi)))
485             }
486
487             ty::Foreign(_) => Ok(None),
488
489             _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
490         }
491     }
492     #[inline]
493     pub fn size_and_align_of_mplace(
494         &self,
495         mplace: MPlaceTy<'tcx, M::PointerTag>,
496     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
497         self.size_and_align_of(mplace.meta, mplace.layout)
498     }
499
500     pub fn push_stack_frame(
501         &mut self,
502         instance: ty::Instance<'tcx>,
503         span: Span,
504         body: &'mir mir::Body<'tcx>,
505         return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
506         return_to_block: StackPopCleanup,
507     ) -> InterpResult<'tcx> {
508         if !self.stack.is_empty() {
509             info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
510         }
511         ::log_settings::settings().indentation += 1;
512
513         // first push a stack frame so we have access to the local substs
514         let extra = M::stack_push(self)?;
515         self.stack.push(Frame {
516             body,
517             block: Some(mir::START_BLOCK),
518             return_to_block,
519             return_place,
520             // empty local array, we fill it in below, after we are inside the stack frame and
521             // all methods actually know about the frame
522             locals: IndexVec::new(),
523             span,
524             instance,
525             stmt: 0,
526             extra,
527         });
528
529         // don't allocate at all for trivial constants
530         if body.local_decls.len() > 1 {
531             // Locals are initially uninitialized.
532             let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
533             let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
534             // Return place is handled specially by the `eval_place` functions, and the
535             // entry in `locals` should never be used. Make it dead, to be sure.
536             locals[mir::RETURN_PLACE].value = LocalValue::Dead;
537             // Now mark those locals as dead that we do not want to initialize
538             match self.tcx.def_kind(instance.def_id()) {
539                 // statics and constants don't have `Storage*` statements, no need to look for them
540                 Some(DefKind::Static) | Some(DefKind::Const) | Some(DefKind::AssocConst) => {}
541                 _ => {
542                     trace!("push_stack_frame: {:?}: num_bbs: {}", span, body.basic_blocks().len());
543                     for block in body.basic_blocks() {
544                         for stmt in block.statements.iter() {
545                             use rustc::mir::StatementKind::{StorageDead, StorageLive};
546                             match stmt.kind {
547                                 StorageLive(local) | StorageDead(local) => {
548                                     locals[local].value = LocalValue::Dead;
549                                 }
550                                 _ => {}
551                             }
552                         }
553                     }
554                 }
555             }
556             // done
557             self.frame_mut().locals = locals;
558         }
559
560         info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
561
562         if self.stack.len() > *self.tcx.sess.recursion_limit.get() {
563             throw_exhaust!(StackFrameLimitReached)
564         } else {
565             Ok(())
566         }
567     }
568
569     /// Jump to the given block.
570     #[inline]
571     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
572         let frame = self.frame_mut();
573         frame.block = Some(target);
574         frame.stmt = 0;
575     }
576
577     /// *Return* to the given `target` basic block.
578     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
579     ///
580     /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
581     pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
582         if let Some(target) = target {
583             Ok(self.go_to_block(target))
584         } else {
585             throw_ub!(Unreachable)
586         }
587     }
588
589     /// *Unwind* to the given `target` basic block.
590     /// Do *not* use for returning! Use `return_to_block` instead.
591     ///
592     /// If `target` is `None`, that indicates the function does not need cleanup during
593     /// unwinding, and we will just keep propagating that upwards.
594     pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
595         let frame = self.frame_mut();
596         frame.block = target;
597         frame.stmt = 0;
598     }
599
600     /// Pops the current frame from the stack, deallocating the
601     /// memory for allocated locals.
602     ///
603     /// If `unwinding` is `false`, then we are performing a normal return
604     /// from a function. In this case, we jump back into the frame of the caller,
605     /// and continue execution as normal.
606     ///
607     /// If `unwinding` is `true`, then we are in the middle of a panic,
608     /// and need to unwind this frame. In this case, we jump to the
609     /// `cleanup` block for the function, which is responsible for running
610     /// `Drop` impls for any locals that have been initialized at this point.
611     /// The cleanup block ends with a special `Resume` terminator, which will
612     /// cause us to continue unwinding.
613     pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
614         info!(
615             "LEAVING({}) {} (unwinding = {})",
616             self.cur_frame(),
617             self.frame().instance,
618             unwinding
619         );
620
621         // Sanity check `unwinding`.
622         assert_eq!(
623             unwinding,
624             match self.frame().block {
625                 None => true,
626                 Some(block) => self.body().basic_blocks()[block].is_cleanup,
627             }
628         );
629
630         ::log_settings::settings().indentation -= 1;
631         let frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
632         let stack_pop_info = M::stack_pop(self, frame.extra, unwinding)?;
633         if let (false, StackPopInfo::StopUnwinding) = (unwinding, stack_pop_info) {
634             bug!("Attempted to stop unwinding while there is no unwinding!");
635         }
636
637         // Now where do we jump next?
638
639         // Determine if we leave this function normally or via unwinding.
640         let cur_unwinding =
641             if let StackPopInfo::StopUnwinding = stack_pop_info { false } else { unwinding };
642
643         // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
644         // In that case, we return early. We also avoid validation in that case,
645         // because this is CTFE and the final value will be thoroughly validated anyway.
646         let (cleanup, next_block) = match frame.return_to_block {
647             StackPopCleanup::Goto { ret, unwind } => {
648                 (true, Some(if cur_unwinding { unwind } else { ret }))
649             }
650             StackPopCleanup::None { cleanup, .. } => (cleanup, None),
651         };
652
653         if !cleanup {
654             assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
655             assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
656             // Leak the locals, skip validation.
657             return Ok(());
658         }
659
660         // Cleanup: deallocate all locals that are backed by an allocation.
661         for local in frame.locals {
662             self.deallocate_local(local.value)?;
663         }
664
665         trace!(
666             "StackPopCleanup: {:?} StackPopInfo: {:?} cur_unwinding = {:?}",
667             frame.return_to_block,
668             stack_pop_info,
669             cur_unwinding
670         );
671         if cur_unwinding {
672             // Follow the unwind edge.
673             let unwind = next_block.expect("Encounted StackPopCleanup::None when unwinding!");
674             self.unwind_to_block(unwind);
675         } else {
676             // Follow the normal return edge.
677             // Validate the return value. Do this after deallocating so that we catch dangling
678             // references.
679             if let Some(return_place) = frame.return_place {
680                 if M::enforce_validity(self) {
681                     // Data got changed, better make sure it matches the type!
682                     // It is still possible that the return place held invalid data while
683                     // the function is running, but that's okay because nobody could have
684                     // accessed that same data from the "outside" to observe any broken
685                     // invariant -- that is, unless a function somehow has a ptr to
686                     // its return place... but the way MIR is currently generated, the
687                     // return place is always a local and then this cannot happen.
688                     self.validate_operand(self.place_to_op(return_place)?, vec![], None)?;
689                 }
690             } else {
691                 // Uh, that shouldn't happen... the function did not intend to return
692                 throw_ub!(Unreachable);
693             }
694
695             // Jump to new block -- *after* validation so that the spans make more sense.
696             if let Some(ret) = next_block {
697                 self.return_to_block(ret)?;
698             }
699         }
700
701         if !self.stack.is_empty() {
702             info!(
703                 "CONTINUING({}) {} (unwinding = {})",
704                 self.cur_frame(),
705                 self.frame().instance,
706                 cur_unwinding
707             );
708         }
709
710         Ok(())
711     }
712
713     /// Mark a storage as live, killing the previous content and returning it.
714     /// Remember to deallocate that!
715     pub fn storage_live(
716         &mut self,
717         local: mir::Local,
718     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
719         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
720         trace!("{:?} is now live", local);
721
722         let local_val = LocalValue::Uninitialized;
723         // StorageLive *always* kills the value that's currently stored.
724         // However, we do not error if the variable already is live;
725         // see <https://github.com/rust-lang/rust/issues/42371>.
726         Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
727     }
728
729     /// Returns the old value of the local.
730     /// Remember to deallocate that!
731     pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
732         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
733         trace!("{:?} is now dead", local);
734
735         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
736     }
737
738     pub(super) fn deallocate_local(
739         &mut self,
740         local: LocalValue<M::PointerTag>,
741     ) -> InterpResult<'tcx> {
742         // FIXME: should we tell the user that there was a local which was never written to?
743         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
744             trace!("deallocating local");
745             // All locals have a backing allocation, even if the allocation is empty
746             // due to the local having ZST type.
747             let ptr = ptr.assert_ptr();
748             if log_enabled!(::log::Level::Trace) {
749                 self.memory.dump_alloc(ptr.alloc_id);
750             }
751             self.memory.deallocate_local(ptr)?;
752         };
753         Ok(())
754     }
755
756     pub(super) fn const_eval(
757         &self,
758         gid: GlobalId<'tcx>,
759         ty: Ty<'tcx>,
760     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
761         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
762         // and thus don't care about the parameter environment. While we could just use
763         // `self.param_env`, that would mean we invoke the query to evaluate the static
764         // with different parameter environments, thus causing the static to be evaluated
765         // multiple times.
766         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
767             ty::ParamEnv::reveal_all()
768         } else {
769             self.param_env
770         };
771         let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
772
773         // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a
774         // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not
775         // return `ConstValue::Unevaluated`, which is the only way that `eval_const_to_op` will call
776         // `ecx.const_eval`.
777         let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
778         self.eval_const_to_op(&const_, None)
779     }
780
781     pub fn const_eval_raw(
782         &self,
783         gid: GlobalId<'tcx>,
784     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
785         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
786         // and thus don't care about the parameter environment. While we could just use
787         // `self.param_env`, that would mean we invoke the query to evaluate the static
788         // with different parameter environments, thus causing the static to be evaluated
789         // multiple times.
790         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
791             ty::ParamEnv::reveal_all()
792         } else {
793             self.param_env
794         };
795         // We use `const_eval_raw` here, and get an unvalidated result.  That is okay:
796         // Our result will later be validated anyway, and there seems no good reason
797         // to have to fail early here.  This is also more consistent with
798         // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
799         let val = self.tcx.const_eval_raw(param_env.and(gid))?;
800         self.raw_const_to_mplace(val)
801     }
802
803     pub fn dump_place(&self, place: Place<M::PointerTag>) {
804         // Debug output
805         if !log_enabled!(::log::Level::Trace) {
806             return;
807         }
808         match place {
809             Place::Local { frame, local } => {
810                 let mut allocs = Vec::new();
811                 let mut msg = format!("{:?}", local);
812                 if frame != self.cur_frame() {
813                     write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
814                 }
815                 write!(msg, ":").unwrap();
816
817                 match self.stack[frame].locals[local].value {
818                     LocalValue::Dead => write!(msg, " is dead").unwrap(),
819                     LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
820                     LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
821                         Scalar::Ptr(ptr) => {
822                             write!(
823                                 msg,
824                                 " by align({}){} ref:",
825                                 mplace.align.bytes(),
826                                 match mplace.meta {
827                                     MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
828                                     MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
829                                 }
830                             )
831                             .unwrap();
832                             allocs.push(ptr.alloc_id);
833                         }
834                         ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
835                     },
836                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
837                         write!(msg, " {:?}", val).unwrap();
838                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
839                             allocs.push(ptr.alloc_id);
840                         }
841                     }
842                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
843                         write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
844                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
845                             allocs.push(ptr.alloc_id);
846                         }
847                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
848                             allocs.push(ptr.alloc_id);
849                         }
850                     }
851                 }
852
853                 trace!("{}", msg);
854                 self.memory.dump_allocs(allocs);
855             }
856             Place::Ptr(mplace) => match mplace.ptr {
857                 Scalar::Ptr(ptr) => {
858                     trace!("by align({}) ref:", mplace.align.bytes());
859                     self.memory.dump_alloc(ptr.alloc_id);
860                 }
861                 ptr => trace!(" integral by ref: {:?}", ptr),
862             },
863         }
864     }
865
866     pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
867         let mut last_span = None;
868         let mut frames = Vec::new();
869         for frame in self.stack().iter().rev() {
870             // make sure we don't emit frames that are duplicates of the previous
871             if explicit_span == Some(frame.span) {
872                 last_span = Some(frame.span);
873                 continue;
874             }
875             if let Some(last) = last_span {
876                 if last == frame.span {
877                     continue;
878                 }
879             } else {
880                 last_span = Some(frame.span);
881             }
882
883             let lint_root = frame.current_source_info().and_then(|source_info| {
884                 match &frame.body.source_scopes[source_info.scope].local_data {
885                     mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
886                     mir::ClearCrossCrate::Clear => None,
887                 }
888             });
889
890             frames.push(FrameInfo { call_site: frame.span, instance: frame.instance, lint_root });
891         }
892         trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
893         frames
894     }
895 }
896
897 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
898     for Frame<'mir, 'tcx, Tag, Extra>
899 where
900     Extra: HashStable<StableHashingContext<'ctx>>,
901     Tag: HashStable<StableHashingContext<'ctx>>,
902 {
903     fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
904         self.body.hash_stable(hcx, hasher);
905         self.instance.hash_stable(hcx, hasher);
906         self.span.hash_stable(hcx, hasher);
907         self.return_to_block.hash_stable(hcx, hasher);
908         self.return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
909         self.locals.hash_stable(hcx, hasher);
910         self.block.hash_stable(hcx, hasher);
911         self.stmt.hash_stable(hcx, hasher);
912         self.extra.hash_stable(hcx, hasher);
913     }
914 }