]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
Rollup merge of #71980 - steveklabnik:warnings-fixes, r=Mark-Simulacrum
[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_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,
15 };
16 use rustc_middle::ty::layout::{self, TyAndLayout};
17 use rustc_middle::ty::{
18     self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable,
19 };
20 use rustc_span::{source_map::DUMMY_SP, Span};
21 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
22
23 use super::{
24     Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
25     ScalarMaybeUndef, StackPopJump,
26 };
27 use crate::util::storage::AlwaysLiveLocals;
28
29 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
30     /// Stores the `Machine` instance.
31     ///
32     /// Note: the stack is provided by the machine.
33     pub machine: M,
34
35     /// The results of the type checker, from rustc.
36     pub tcx: TyCtxtAt<'tcx>,
37
38     /// Bounds in scope for polymorphic evaluations.
39     pub(crate) param_env: ty::ParamEnv<'tcx>,
40
41     /// The virtual memory system.
42     pub memory: Memory<'mir, 'tcx, M>,
43
44     /// A cache for deduplicating vtables
45     pub(super) vtables:
46         FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
47 }
48
49 /// A stack frame.
50 #[derive(Clone)]
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>,
57
58     /// The def_id and substs of the current function.
59     pub instance: ty::Instance<'tcx>,
60
61     /// Extra data for the machine.
62     pub extra: Extra,
63
64     ////////////////////////////////////////////////////////////////////////////////
65     // Return place and locals
66     ////////////////////////////////////////////////////////////////////////////////
67     /// Work to perform when returning from this function.
68     pub return_to_block: StackPopCleanup,
69
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>>,
73
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>>,
80
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>,
87 }
88
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 },
102 }
103
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>>>,
111 }
112
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.
117     Dead,
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
121     /// before that.
122     Uninitialized,
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.
128     Live(Operand<Tag>),
129 }
130
131 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
132     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
133         match self.value {
134             LocalValue::Dead => throw_ub!(DeadLocal),
135             LocalValue::Uninitialized => {
136                 bug!("The type checker should prevent reading from a never-written local")
137             }
138             LocalValue::Live(val) => Ok(val),
139         }
140     }
141
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.
144     pub fn access_mut(
145         &mut self,
146     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
147         match self.value {
148             LocalValue::Dead => throw_ub!(DeadLocal),
149             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
150             ref mut
151             local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
152                 Ok(Ok(local))
153             }
154         }
155     }
156 }
157
158 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
159     pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
160         Frame {
161             body: self.body,
162             instance: self.instance,
163             return_to_block: self.return_to_block,
164             return_place: self.return_place,
165             locals: self.locals,
166             loc: self.loc,
167             extra,
168         }
169     }
170 }
171
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> {
175         self.loc.map(|loc| {
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
179             } else {
180                 block.terminator().source_info
181             }
182         })
183     }
184 }
185
186 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
187     #[inline]
188     fn data_layout(&self) -> &TargetDataLayout {
189         &self.tcx.data_layout
190     }
191 }
192
193 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
194 where
195     M: Machine<'mir, 'tcx>,
196 {
197     #[inline]
198     fn tcx(&self) -> TyCtxt<'tcx> {
199         *self.tcx
200     }
201 }
202
203 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
204 where
205     M: Machine<'mir, 'tcx>,
206 {
207     fn param_env(&self) -> ty::ParamEnv<'tcx> {
208         self.param_env
209     }
210 }
211
212 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
213     type Ty = Ty<'tcx>;
214     type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
215
216     #[inline]
217     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
218         self.tcx
219             .layout_of(self.param_env.and(ty))
220             .map_err(|layout| err_inval!(Layout(layout)).into())
221     }
222 }
223
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>(
227     tcx: TyCtxt<'tcx>,
228     src: TyAndLayout<'tcx>,
229     dest: TyAndLayout<'tcx>,
230 ) -> bool {
231     if src.ty == dest.ty {
232         // Equal types, all is good.
233         return true;
234     }
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
238         // assignments.
239         return false;
240     }
241
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 {
249             tcx,
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),
253                 _ => ty,
254             },
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.
260             ct_op: |ct| ct,
261         })
262     };
263     normalize(src.ty) == normalize(dest.ty)
264 }
265
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>(
270     tcx: TyCtxtAt<'tcx>,
271     known_layout: Option<TyAndLayout<'tcx>>,
272     compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
273 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
274     match known_layout {
275         None => compute(),
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) {
280                     span_bug!(
281                         tcx.span,
282                         "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
283                         known_layout.ty,
284                         check_layout.ty,
285                     );
286                 }
287             }
288             Ok(known_layout)
289         }
290     }
291 }
292
293 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
294     pub fn new(
295         tcx: TyCtxtAt<'tcx>,
296         param_env: ty::ParamEnv<'tcx>,
297         machine: M,
298         memory_extra: M::MemoryExtra,
299     ) -> Self {
300         InterpCx {
301             machine,
302             tcx,
303             param_env,
304             memory: Memory::new(tcx, memory_extra),
305             vtables: FxHashMap::default(),
306         }
307     }
308
309     #[inline(always)]
310     pub fn set_span(&mut self, span: Span) {
311         self.tcx.span = span;
312         self.memory.tcx.span = span;
313     }
314
315     #[inline(always)]
316     pub fn force_ptr(
317         &self,
318         scalar: Scalar<M::PointerTag>,
319     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
320         self.memory.force_ptr(scalar)
321     }
322
323     #[inline(always)]
324     pub fn force_bits(
325         &self,
326         scalar: Scalar<M::PointerTag>,
327         size: Size,
328     ) -> InterpResult<'tcx, u128> {
329         self.memory.force_bits(scalar, size)
330     }
331
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!
335     ///
336     /// This represents a *direct* access to that memory, as opposed to access
337     /// through a pointer that was created by the program.
338     #[inline(always)]
339     pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
340         self.memory.tag_global_base_pointer(ptr)
341     }
342
343     #[inline(always)]
344     pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
345         M::stack(self)
346     }
347
348     #[inline(always)]
349     pub(crate) fn stack_mut(
350         &mut self,
351     ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
352         M::stack_mut(self)
353     }
354
355     #[inline(always)]
356     pub fn frame_idx(&self) -> usize {
357         let stack = self.stack();
358         assert!(!stack.is_empty());
359         stack.len() - 1
360     }
361
362     #[inline(always)]
363     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
364         self.stack().last().expect("no call frames exist")
365     }
366
367     #[inline(always)]
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")
370     }
371
372     #[inline(always)]
373     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
374         self.frame().body
375     }
376
377     #[inline(always)]
378     pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
379         assert!(ty.abi.is_signed());
380         sign_extend(value, ty.size)
381     }
382
383     #[inline(always)]
384     pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
385         truncate(value, ty.size)
386     }
387
388     #[inline]
389     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
390         ty.is_sized(self.tcx, self.param_env)
391     }
392
393     #[inline]
394     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
395         ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
396     }
397
398     pub fn load_mir(
399         &self,
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))
409                 }
410             }
411         }
412         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
413         if let Some(promoted) = promoted {
414             return Ok(&self.tcx.promoted_mir(did)[promoted]);
415         }
416         match instance {
417             ty::InstanceDef::Item(def_id) => {
418                 if self.tcx.is_mir_available(did) {
419                     Ok(self.tcx.optimized_mir(did))
420                 } else {
421                     throw_unsup!(NoMirFor(def_id))
422                 }
423             }
424             _ => Ok(self.tcx.instance_mir(instance)),
425         }
426     }
427
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>>(
431         &self,
432         value: T,
433     ) -> T {
434         self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
435     }
436
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>>(
440         &self,
441         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
442         value: T,
443     ) -> T {
444         if let Some(substs) = frame.instance.substs_for_mir_body() {
445             self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
446         } else {
447             self.tcx.normalize_erasing_regions(self.param_env, value)
448         }
449     }
450
451     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
452     pub(super) fn resolve(
453         &self,
454         def_id: DefId,
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),
463
464             // FIXME(eddyb) this could be a bit more specific than `TypeckError`.
465             Err(error_reported) => throw_inval!(TypeckError(error_reported)),
466         }
467     }
468
469     pub fn layout_of_local(
470         &self,
471         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
472         local: mir::Local,
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()) {
478             None => {
479                 let layout = from_known_layout(self.tcx, layout, || {
480                     let local_ty = frame.body.local_decls[local].ty;
481                     let local_ty =
482                         self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
483                     self.layout_of(local_ty)
484                 })?;
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));
488                 }
489                 Ok(layout)
490             }
491             Some(layout) => Ok(layout),
492         }
493     }
494
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(
499         &self,
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)));
505         }
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);
515
516                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
517                 let sized_align = layout.align.abi;
518                 trace!(
519                     "DST {} statically sized prefix size: {:?} align: {:?}",
520                     layout.ty,
521                     sized_size,
522                     sized_align
523                 );
524
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,
531                     None => {
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 {
538                             return Ok(None);
539                         } else {
540                             bug!("Fields cannot be extern types, unless they are at offset 0")
541                         }
542                     }
543                 };
544
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.)
551
552                 // Return the sum of sizes and max of aligns.
553                 let size = sized_size + unsized_size; // `Size` addition
554
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);
558
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);
562
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"));
566                 }
567                 Ok(Some((size, align)))
568             }
569             ty::Dynamic(..) => {
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)?))
573             }
574
575             ty::Slice(_) | ty::Str => {
576                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
577                 let elem = layout.field(self, 0)?;
578
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"))
582                 })?;
583                 Ok(Some((size, elem.align.abi)))
584             }
585
586             ty::Foreign(_) => Ok(None),
587
588             _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
589         }
590     }
591     #[inline]
592     pub fn size_and_align_of_mplace(
593         &self,
594         mplace: MPlaceTy<'tcx, M::PointerTag>,
595     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
596         self.size_and_align_of(mplace.meta, mplace.layout)
597     }
598
599     pub fn push_stack_frame(
600         &mut self,
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);
608         }
609         ::log_settings::settings().indentation += 1;
610
611         // first push a stack frame so we have access to the local substs
612         let pre_frame = Frame {
613             body,
614             loc: Some(mir::Location::START),
615             return_to_block,
616             return_place,
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(),
620             instance,
621             extra: (),
622         };
623         let frame = M::init_frame_extra(self, pre_frame)?;
624         self.stack_mut().push(frame);
625
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);
629
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
633             //
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 => {}
638             _ => {
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;
644                     }
645                 }
646             }
647         }
648         // done
649         self.frame_mut().locals = locals;
650
651         M::after_stack_push(self)?;
652         info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
653
654         if self.stack().len() > *self.tcx.sess.recursion_limit.get() {
655             throw_exhaust!(StackFrameLimitReached)
656         } else {
657             Ok(())
658         }
659     }
660
661     /// Jump to the given block.
662     #[inline]
663     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
664         self.frame_mut().loc = Some(mir::Location { block: target, statement_index: 0 });
665     }
666
667     /// *Return* to the given `target` basic block.
668     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
669     ///
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);
674             Ok(())
675         } else {
676             throw_ub!(Unreachable)
677         }
678     }
679
680     /// *Unwind* to the given `target` basic block.
681     /// Do *not* use for returning! Use `return_to_block` instead.
682     ///
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 });
687     }
688
689     /// Pops the current frame from the stack, deallocating the
690     /// memory for allocated locals.
691     ///
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.
695     ///
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> {
703         info!(
704             "LEAVING({}) {} (unwinding = {})",
705             self.frame_idx(),
706             self.frame().instance,
707             unwinding
708         );
709
710         // Sanity check `unwinding`.
711         assert_eq!(
712             unwinding,
713             match self.frame().loc {
714                 None => true,
715                 Some(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
716             }
717         );
718
719         ::log_settings::settings().indentation -= 1;
720         let frame =
721             self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
722
723         if !unwinding {
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);
729             } else {
730                 throw_ub!(Unreachable);
731             }
732         }
733
734         // Now where do we jump next?
735
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 }))
742             }
743             StackPopCleanup::None { cleanup, .. } => (cleanup, None),
744         };
745
746         if !cleanup {
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.
751             return Ok(());
752         }
753
754         // Cleanup: deallocate all locals that are backed by an allocation.
755         for local in &frame.locals {
756             self.deallocate_local(local.value)?;
757         }
758
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.
762             return Ok(());
763         }
764         // Normal return, figure out where to jump.
765         if unwinding {
766             // Follow the unwind edge.
767             let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
768             self.unwind_to_block(unwind);
769         } else {
770             // Follow the normal return edge.
771             if let Some(ret) = next_block {
772                 self.return_to_block(ret)?;
773             }
774         }
775
776         if !self.stack().is_empty() {
777             info!(
778                 "CONTINUING({}) {} (unwinding = {})",
779                 self.frame_idx(),
780                 self.frame().instance,
781                 unwinding
782             );
783         }
784
785         Ok(())
786     }
787
788     /// Mark a storage as live, killing the previous content and returning it.
789     /// Remember to deallocate that!
790     pub fn storage_live(
791         &mut self,
792         local: mir::Local,
793     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
794         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
795         trace!("{:?} is now live", local);
796
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))
802     }
803
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);
809
810         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
811     }
812
813     pub(super) fn deallocate_local(
814         &mut self,
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);
825             }
826             self.memory.deallocate_local(ptr)?;
827         };
828         Ok(())
829     }
830
831     pub(super) fn const_eval(
832         &self,
833         gid: GlobalId<'tcx>,
834         ty: Ty<'tcx>,
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
840         // multiple times.
841         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
842             ty::ParamEnv::reveal_all()
843         } else {
844             self.param_env
845         };
846         let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
847
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
851         // `ecx.const_eval`.
852         let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
853         self.eval_const_to_op(&const_, None)
854     }
855
856     pub fn const_eval_raw(
857         &self,
858         gid: GlobalId<'tcx>,
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
864         // multiple times.
865         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
866             ty::ParamEnv::reveal_all()
867         } else {
868             self.param_env
869         };
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)
876     }
877
878     pub fn dump_place(&self, place: Place<M::PointerTag>) {
879         // Debug output
880         if !log_enabled!(::log::Level::Trace) {
881             return;
882         }
883         match place {
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();
889                 }
890                 write!(msg, ":").unwrap();
891
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) => {
897                             write!(
898                                 msg,
899                                 " by align({}){} ref:",
900                                 mplace.align.bytes(),
901                                 match mplace.meta {
902                                     MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
903                                     MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
904                                 }
905                             )
906                             .unwrap();
907                             allocs.push(ptr.alloc_id);
908                         }
909                         ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
910                     },
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);
915                         }
916                     }
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);
921                         }
922                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
923                             allocs.push(ptr.alloc_id);
924                         }
925                     }
926                 }
927
928                 trace!("{}", msg);
929                 self.memory.dump_allocs(allocs);
930             }
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);
935                 }
936                 ptr => trace!(" integral by ref: {:?}", ptr),
937             },
938         }
939     }
940
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,
949                 }
950             });
951             let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
952
953             frames.push(FrameInfo { span, instance: frame.instance, lint_root });
954         }
955         trace!("generate stacktrace: {:#?}", frames);
956         frames
957     }
958 }
959
960 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
961     for Frame<'mir, 'tcx, Tag, Extra>
962 where
963     Extra: HashStable<StableHashingContext<'ctx>>,
964     Tag: HashStable<StableHashingContext<'ctx>>,
965 {
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);
976     }
977 }