]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
7ab99976b404b0081f344a34da0bea3a97ca302f
[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 syntax::source_map::{self, Span, DUMMY_SP};
6 use rustc::hir::def_id::DefId;
7 use rustc::hir::def::DefKind;
8 use rustc::mir;
9 use rustc::ty::layout::{
10     self, Size, Align, HasDataLayout, LayoutOf, TyLayout
11 };
12 use rustc::ty::subst::{Subst, SubstsRef};
13 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
14 use rustc::ty::query::TyCtxtAt;
15 use rustc_data_structures::indexed_vec::IndexVec;
16 use rustc::mir::interpret::{
17     ErrorHandled,
18     GlobalId, Scalar, Pointer, FrameInfo, AllocId,
19     InterpResult, truncate, sign_extend,
20 };
21 use rustc_data_structures::fx::FxHashMap;
22
23 use super::{
24     Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
25     Memory, Machine
26 };
27
28 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
29     /// Stores the `Machine` instance.
30     pub machine: M,
31
32     /// The results of the type checker, from rustc.
33     pub tcx: TyCtxtAt<'tcx>,
34
35     /// Bounds in scope for polymorphic evaluations.
36     pub(crate) param_env: ty::ParamEnv<'tcx>,
37
38     /// The virtual memory system.
39     pub(crate) memory: Memory<'mir, 'tcx, M>,
40
41     /// The virtual call stack.
42     pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
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     /// The span of the call site.
62     pub span: source_map::Span,
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     /// The block that is currently executed (or will be executed after the above call stacks
85     /// return).
86     pub block: mir::BasicBlock,
87
88     /// The index of the currently evaluated statement.
89     pub stmt: usize,
90
91     /// Extra data for the machine.
92     pub extra: Extra,
93 }
94
95 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
96 pub enum StackPopCleanup {
97     /// Jump to the next block in the caller, or cause UB if None (that's a function
98     /// that may never return). Also store layout of return place so
99     /// we can validate it at that layout.
100     Goto(Option<mir::BasicBlock>),
101     /// Just do nohing: Used by Main and for the box_alloc hook in miri.
102     /// `cleanup` says whether locals are deallocated. Static computation
103     /// wants them leaked to intern what they need (and just throw away
104     /// the entire `ecx` when it is done).
105     None { cleanup: bool },
106 }
107
108 /// State of a local variable including a memoized layout
109 #[derive(Clone, PartialEq, Eq)]
110 pub struct LocalState<'tcx, Tag=(), Id=AllocId> {
111     pub value: LocalValue<Tag, Id>,
112     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
113     pub layout: Cell<Option<TyLayout<'tcx>>>,
114 }
115
116 /// Current value of a local variable
117 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
118 pub enum LocalValue<Tag=(), Id=AllocId> {
119     /// This local is not currently alive, and cannot be used at all.
120     Dead,
121     /// This local is alive but not yet initialized. It can be written to
122     /// but not read from or its address taken. Locals get initialized on
123     /// first write because for unsized locals, we do not know their size
124     /// before that.
125     Uninitialized,
126     /// A normal, live local.
127     /// Mostly for convenience, we re-use the `Operand` type here.
128     /// This is an optimization over just always having a pointer here;
129     /// we can thus avoid doing an allocation when the local just stores
130     /// immediate values *and* never has its address taken.
131     Live(Operand<Tag, Id>),
132 }
133
134 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
135     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
136         match self.value {
137             LocalValue::Dead => throw_unsup!(DeadLocal),
138             LocalValue::Uninitialized =>
139                 bug!("The type checker should prevent reading from a never-written local"),
140             LocalValue::Live(val) => Ok(val),
141         }
142     }
143
144     /// Overwrite the local.  If the local can be overwritten in place, return a reference
145     /// to do so; otherwise return the `MemPlace` to consult instead.
146     pub fn access_mut(
147         &mut self,
148     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
149         match self.value {
150             LocalValue::Dead => throw_unsup!(DeadLocal),
151             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
152             ref mut local @ LocalValue::Live(Operand::Immediate(_)) |
153             ref mut local @ LocalValue::Uninitialized => {
154                 Ok(Ok(local))
155             }
156         }
157     }
158 }
159
160 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
161     #[inline]
162     fn data_layout(&self) -> &layout::TargetDataLayout {
163         &self.tcx.data_layout
164     }
165 }
166
167 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
168 where
169     M: Machine<'mir, 'tcx>,
170 {
171     #[inline]
172     fn tcx(&self) -> TyCtxt<'tcx> {
173         *self.tcx
174     }
175 }
176
177 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
178 where
179     M: Machine<'mir, 'tcx>,
180 {
181     fn param_env(&self) -> ty::ParamEnv<'tcx> {
182         self.param_env
183     }
184 }
185
186 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
187     type Ty = Ty<'tcx>;
188     type TyLayout = InterpResult<'tcx, TyLayout<'tcx>>;
189
190     #[inline]
191     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
192         self.tcx
193             .layout_of(self.param_env.and(ty))
194             .map_err(|layout| {
195                 err_inval!(Layout(layout)).into()
196             })
197     }
198 }
199
200 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
201     pub fn new(
202         tcx: TyCtxtAt<'tcx>,
203         param_env: ty::ParamEnv<'tcx>,
204         machine: M,
205         memory_extra: M::MemoryExtra,
206     ) -> Self {
207         InterpCx {
208             machine,
209             tcx,
210             param_env,
211             memory: Memory::new(tcx, memory_extra),
212             stack: Vec::new(),
213             vtables: FxHashMap::default(),
214         }
215     }
216
217     #[inline(always)]
218     pub fn memory(&self) -> &Memory<'mir, 'tcx, M> {
219         &self.memory
220     }
221
222     #[inline(always)]
223     pub fn memory_mut(&mut self) -> &mut Memory<'mir, 'tcx, M> {
224         &mut self.memory
225     }
226
227     #[inline(always)]
228     pub fn force_ptr(
229         &self,
230         scalar: Scalar<M::PointerTag>,
231     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
232         self.memory.force_ptr(scalar)
233     }
234
235     #[inline(always)]
236     pub fn force_bits(
237         &self,
238         scalar: Scalar<M::PointerTag>,
239         size: Size
240     ) -> InterpResult<'tcx, u128> {
241         self.memory.force_bits(scalar, size)
242     }
243
244     #[inline(always)]
245     pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
246         self.memory.tag_static_base_pointer(ptr)
247     }
248
249     #[inline(always)]
250     pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
251         &self.stack
252     }
253
254     #[inline(always)]
255     pub fn cur_frame(&self) -> usize {
256         assert!(self.stack.len() > 0);
257         self.stack.len() - 1
258     }
259
260     #[inline(always)]
261     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
262         self.stack.last().expect("no call frames exist")
263     }
264
265     #[inline(always)]
266     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
267         self.stack.last_mut().expect("no call frames exist")
268     }
269
270     #[inline(always)]
271     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
272         self.frame().body
273     }
274
275     #[inline(always)]
276     pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
277         assert!(ty.abi.is_signed());
278         sign_extend(value, ty.size)
279     }
280
281     #[inline(always)]
282     pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
283         truncate(value, ty.size)
284     }
285
286     #[inline]
287     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
288         ty.is_sized(self.tcx, self.param_env)
289     }
290
291     #[inline]
292     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
293         ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
294     }
295
296     pub(super) fn subst_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
297         &self,
298         substs: T,
299     ) -> InterpResult<'tcx, T> {
300         match self.stack.last() {
301             Some(frame) => Ok(self.tcx.subst_and_normalize_erasing_regions(
302                 frame.instance.substs,
303                 self.param_env,
304                 &substs,
305             )),
306             None => if substs.needs_subst() {
307                 throw_inval!(TooGeneric)
308             } else {
309                 Ok(substs)
310             },
311         }
312     }
313
314     pub(super) fn resolve(
315         &self,
316         def_id: DefId,
317         substs: SubstsRef<'tcx>
318     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
319         trace!("resolve: {:?}, {:#?}", def_id, substs);
320         trace!("param_env: {:#?}", self.param_env);
321         let substs = self.subst_and_normalize_erasing_regions(substs)?;
322         trace!("substs: {:#?}", substs);
323         ty::Instance::resolve(
324             *self.tcx,
325             self.param_env,
326             def_id,
327             substs,
328         ).ok_or_else(|| err_inval!(TooGeneric).into())
329     }
330
331     pub fn load_mir(
332         &self,
333         instance: ty::InstanceDef<'tcx>,
334     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
335         // do not continue if typeck errors occurred (can only occur in local crate)
336         let did = instance.def_id();
337         if did.is_local()
338             && self.tcx.has_typeck_tables(did)
339             && self.tcx.typeck_tables_of(did).tainted_by_errors
340         {
341             throw_inval!(TypeckError)
342         }
343         trace!("load mir {:?}", instance);
344         match instance {
345             ty::InstanceDef::Item(def_id) => if self.tcx.is_mir_available(did) {
346                 Ok(self.tcx.optimized_mir(did))
347             } else {
348                 throw_unsup!(NoMirFor(self.tcx.def_path_str(def_id)))
349             },
350             _ => Ok(self.tcx.instance_mir(instance)),
351         }
352     }
353
354     pub(super) fn monomorphize<T: TypeFoldable<'tcx> + Subst<'tcx>>(
355         &self,
356         t: T,
357     ) -> InterpResult<'tcx, T> {
358         match self.stack.last() {
359             Some(frame) => Ok(self.monomorphize_with_substs(t, frame.instance.substs)?),
360             None => if t.needs_subst() {
361                 throw_inval!(TooGeneric)
362             } else {
363                 Ok(t)
364             },
365         }
366     }
367
368     fn monomorphize_with_substs<T: TypeFoldable<'tcx> + Subst<'tcx>>(
369         &self,
370         t: T,
371         substs: SubstsRef<'tcx>
372     ) -> InterpResult<'tcx, T> {
373         // miri doesn't care about lifetimes, and will choke on some crazy ones
374         // let's simply get rid of them
375         let substituted = t.subst(*self.tcx, substs);
376
377         if substituted.needs_subst() {
378             throw_inval!(TooGeneric)
379         }
380
381         Ok(self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substituted))
382     }
383
384     pub fn layout_of_local(
385         &self,
386         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
387         local: mir::Local,
388         layout: Option<TyLayout<'tcx>>,
389     ) -> InterpResult<'tcx, TyLayout<'tcx>> {
390         match frame.locals[local].layout.get() {
391             None => {
392                 let layout = crate::interpret::operand::from_known_layout(layout, || {
393                     let local_ty = frame.body.local_decls[local].ty;
394                     let local_ty = self.monomorphize_with_substs(local_ty, frame.instance.substs)?;
395                     self.layout_of(local_ty)
396                 })?;
397                 // Layouts of locals are requested a lot, so we cache them.
398                 frame.locals[local].layout.set(Some(layout));
399                 Ok(layout)
400             }
401             Some(layout) => Ok(layout),
402         }
403     }
404
405     /// Returns the actual dynamic size and alignment of the place at the given type.
406     /// Only the "meta" (metadata) part of the place matters.
407     /// This can fail to provide an answer for extern types.
408     pub(super) fn size_and_align_of(
409         &self,
410         metadata: Option<Scalar<M::PointerTag>>,
411         layout: TyLayout<'tcx>,
412     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
413         if !layout.is_unsized() {
414             return Ok(Some((layout.size, layout.align.abi)));
415         }
416         match layout.ty.sty {
417             ty::Adt(..) | ty::Tuple(..) => {
418                 // First get the size of all statically known fields.
419                 // Don't use type_of::sizing_type_of because that expects t to be sized,
420                 // and it also rounds up to alignment, which we want to avoid,
421                 // as the unsized field's alignment could be smaller.
422                 assert!(!layout.ty.is_simd());
423                 trace!("DST layout: {:?}", layout);
424
425                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
426                 let sized_align = layout.align.abi;
427                 trace!(
428                     "DST {} statically sized prefix size: {:?} align: {:?}",
429                     layout.ty,
430                     sized_size,
431                     sized_align
432                 );
433
434                 // Recurse to get the size of the dynamically sized field (must be
435                 // the last field).  Can't have foreign types here, how would we
436                 // adjust alignment and size for them?
437                 let field = layout.field(self, layout.fields.count() - 1)?;
438                 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
439                     Some(size_and_align) => size_and_align,
440                     None => {
441                         // A field with extern type.  If this field is at offset 0, we behave
442                         // like the underlying extern type.
443                         // FIXME: Once we have made decisions for how to handle size and alignment
444                         // of `extern type`, this should be adapted.  It is just a temporary hack
445                         // to get some code to work that probably ought to work.
446                         if sized_size == Size::ZERO {
447                             return Ok(None)
448                         } else {
449                             bug!("Fields cannot be extern types, unless they are at offset 0")
450                         }
451                     }
452                 };
453
454                 // FIXME (#26403, #27023): We should be adding padding
455                 // to `sized_size` (to accommodate the `unsized_align`
456                 // required of the unsized field that follows) before
457                 // summing it with `sized_size`. (Note that since #26403
458                 // is unfixed, we do not yet add the necessary padding
459                 // here. But this is where the add would go.)
460
461                 // Return the sum of sizes and max of aligns.
462                 let size = sized_size + unsized_size;
463
464                 // Choose max of two known alignments (combined value must
465                 // be aligned according to more restrictive of the two).
466                 let align = sized_align.max(unsized_align);
467
468                 // Issue #27023: must add any necessary padding to `size`
469                 // (to make it a multiple of `align`) before returning it.
470                 //
471                 // Namely, the returned size should be, in C notation:
472                 //
473                 //   `size + ((size & (align-1)) ? align : 0)`
474                 //
475                 // emulated via the semi-standard fast bit trick:
476                 //
477                 //   `(size + (align-1)) & -align`
478
479                 Ok(Some((size.align_to(align), align)))
480             }
481             ty::Dynamic(..) => {
482                 let vtable = metadata.expect("dyn trait fat ptr must have vtable");
483                 // the second entry in the vtable is the dynamic size of the object.
484                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
485             }
486
487             ty::Slice(_) | ty::Str => {
488                 let len = metadata.expect("slice fat ptr must have vtable").to_usize(self)?;
489                 let elem = layout.field(self, 0)?;
490                 Ok(Some((elem.size * len, elem.align.abi)))
491             }
492
493             ty::Foreign(_) => {
494                 Ok(None)
495             }
496
497             _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
498         }
499     }
500     #[inline]
501     pub fn size_and_align_of_mplace(
502         &self,
503         mplace: MPlaceTy<'tcx, M::PointerTag>
504     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
505         self.size_and_align_of(mplace.meta, mplace.layout)
506     }
507
508     pub fn push_stack_frame(
509         &mut self,
510         instance: ty::Instance<'tcx>,
511         span: source_map::Span,
512         body: &'mir mir::Body<'tcx>,
513         return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
514         return_to_block: StackPopCleanup,
515     ) -> InterpResult<'tcx> {
516         if self.stack.len() > 0 {
517             info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
518         }
519         ::log_settings::settings().indentation += 1;
520
521         // first push a stack frame so we have access to the local substs
522         let extra = M::stack_push(self)?;
523         self.stack.push(Frame {
524             body,
525             block: mir::START_BLOCK,
526             return_to_block,
527             return_place,
528             // empty local array, we fill it in below, after we are inside the stack frame and
529             // all methods actually know about the frame
530             locals: IndexVec::new(),
531             span,
532             instance,
533             stmt: 0,
534             extra,
535         });
536
537         // don't allocate at all for trivial constants
538         if body.local_decls.len() > 1 {
539             // Locals are initially uninitialized.
540             let dummy = LocalState {
541                 value: LocalValue::Uninitialized,
542                 layout: Cell::new(None),
543             };
544             let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
545             // Return place is handled specially by the `eval_place` functions, and the
546             // entry in `locals` should never be used. Make it dead, to be sure.
547             locals[mir::RETURN_PLACE].value = LocalValue::Dead;
548             // Now mark those locals as dead that we do not want to initialize
549             match self.tcx.def_kind(instance.def_id()) {
550                 // statics and constants don't have `Storage*` statements, no need to look for them
551                 Some(DefKind::Static)
552                 | Some(DefKind::Const)
553                 | Some(DefKind::AssocConst) => {},
554                 _ => {
555                     trace!("push_stack_frame: {:?}: num_bbs: {}", span, body.basic_blocks().len());
556                     for block in body.basic_blocks() {
557                         for stmt in block.statements.iter() {
558                             use rustc::mir::StatementKind::{StorageDead, StorageLive};
559                             match stmt.kind {
560                                 StorageLive(local) |
561                                 StorageDead(local) => {
562                                     locals[local].value = LocalValue::Dead;
563                                 }
564                                 _ => {}
565                             }
566                         }
567                     }
568                 },
569             }
570             // done
571             self.frame_mut().locals = locals;
572         }
573
574         info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
575
576         if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit {
577             throw_exhaust!(StackFrameLimitReached)
578         } else {
579             Ok(())
580         }
581     }
582
583     pub(super) fn pop_stack_frame(&mut self) -> InterpResult<'tcx> {
584         info!("LEAVING({}) {}", self.cur_frame(), self.frame().instance);
585         ::log_settings::settings().indentation -= 1;
586         let frame = self.stack.pop().expect(
587             "tried to pop a stack frame, but there were none",
588         );
589         M::stack_pop(self, frame.extra)?;
590         // Abort early if we do not want to clean up: We also avoid validation in that case,
591         // because this is CTFE and the final value will be thoroughly validated anyway.
592         match frame.return_to_block {
593             StackPopCleanup::Goto(_) => {},
594             StackPopCleanup::None { cleanup } => {
595                 if !cleanup {
596                     assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
597                     // Leak the locals, skip validation.
598                     return Ok(());
599                 }
600             }
601         }
602         // Deallocate all locals that are backed by an allocation.
603         for local in frame.locals {
604             self.deallocate_local(local.value)?;
605         }
606         // Validate the return value. Do this after deallocating so that we catch dangling
607         // references.
608         if let Some(return_place) = frame.return_place {
609             if M::enforce_validity(self) {
610                 // Data got changed, better make sure it matches the type!
611                 // It is still possible that the return place held invalid data while
612                 // the function is running, but that's okay because nobody could have
613                 // accessed that same data from the "outside" to observe any broken
614                 // invariant -- that is, unless a function somehow has a ptr to
615                 // its return place... but the way MIR is currently generated, the
616                 // return place is always a local and then this cannot happen.
617                 self.validate_operand(
618                     self.place_to_op(return_place)?,
619                     vec![],
620                     None,
621                 )?;
622             }
623         } else {
624             // Uh, that shouldn't happen... the function did not intend to return
625             throw_ub!(Unreachable)
626         }
627         // Jump to new block -- *after* validation so that the spans make more sense.
628         match frame.return_to_block {
629             StackPopCleanup::Goto(block) => {
630                 self.goto_block(block)?;
631             }
632             StackPopCleanup::None { .. } => {}
633         }
634
635         if self.stack.len() > 0 {
636             info!("CONTINUING({}) {}", self.cur_frame(), self.frame().instance);
637         }
638
639         Ok(())
640     }
641
642     /// Mark a storage as live, killing the previous content and returning it.
643     /// Remember to deallocate that!
644     pub fn storage_live(
645         &mut self,
646         local: mir::Local
647     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
648         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
649         trace!("{:?} is now live", local);
650
651         let local_val = LocalValue::Uninitialized;
652         // StorageLive *always* kills the value that's currently stored.
653         // However, we do not error if the variable already is live;
654         // see <https://github.com/rust-lang/rust/issues/42371>.
655         Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
656     }
657
658     /// Returns the old value of the local.
659     /// Remember to deallocate that!
660     pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
661         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
662         trace!("{:?} is now dead", local);
663
664         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
665     }
666
667     pub(super) fn deallocate_local(
668         &mut self,
669         local: LocalValue<M::PointerTag>,
670     ) -> InterpResult<'tcx> {
671         // FIXME: should we tell the user that there was a local which was never written to?
672         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
673             trace!("deallocating local");
674             let ptr = ptr.to_ptr()?;
675             self.memory.dump_alloc(ptr.alloc_id);
676             self.memory.deallocate_local(ptr)?;
677         };
678         Ok(())
679     }
680
681     pub fn const_eval_raw(
682         &self,
683         gid: GlobalId<'tcx>,
684     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
685         // FIXME(oli-obk): make this check an assertion that it's not a static here
686         // FIXME(RalfJ, oli-obk): document that `Place::Static` can never be anything but a static
687         // and `ConstValue::Unevaluated` can never be a static
688         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
689             ty::ParamEnv::reveal_all()
690         } else {
691             self.param_env
692         };
693         // We use `const_eval_raw` here, and get an unvalidated result.  That is okay:
694         // Our result will later be validated anyway, and there seems no good reason
695         // to have to fail early here.  This is also more consistent with
696         // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
697         let val = self.tcx.const_eval_raw(param_env.and(gid)).map_err(|err| {
698             match err {
699                 ErrorHandled::Reported =>
700                     err_inval!(ReferencedConstant),
701                 ErrorHandled::TooGeneric =>
702                     err_inval!(TooGeneric),
703             }
704         })?;
705         self.raw_const_to_mplace(val)
706     }
707
708     pub fn dump_place(&self, place: Place<M::PointerTag>) {
709         // Debug output
710         if !log_enabled!(::log::Level::Trace) {
711             return;
712         }
713         match place {
714             Place::Local { frame, local } => {
715                 let mut allocs = Vec::new();
716                 let mut msg = format!("{:?}", local);
717                 if frame != self.cur_frame() {
718                     write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
719                 }
720                 write!(msg, ":").unwrap();
721
722                 match self.stack[frame].locals[local].value {
723                     LocalValue::Dead => write!(msg, " is dead").unwrap(),
724                     LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
725                     LocalValue::Live(Operand::Indirect(mplace)) => {
726                         match mplace.ptr {
727                             Scalar::Ptr(ptr) => {
728                                 write!(msg, " by align({}){} ref:",
729                                     mplace.align.bytes(),
730                                     match mplace.meta {
731                                         Some(meta) => format!(" meta({:?})", meta),
732                                         None => String::new()
733                                     }
734                                 ).unwrap();
735                                 allocs.push(ptr.alloc_id);
736                             }
737                             ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
738                         }
739                     }
740                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
741                         write!(msg, " {:?}", val).unwrap();
742                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
743                             allocs.push(ptr.alloc_id);
744                         }
745                     }
746                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
747                         write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
748                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
749                             allocs.push(ptr.alloc_id);
750                         }
751                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
752                             allocs.push(ptr.alloc_id);
753                         }
754                     }
755                 }
756
757                 trace!("{}", msg);
758                 self.memory.dump_allocs(allocs);
759             }
760             Place::Ptr(mplace) => {
761                 match mplace.ptr {
762                     Scalar::Ptr(ptr) => {
763                         trace!("by align({}) ref:", mplace.align.bytes());
764                         self.memory.dump_alloc(ptr.alloc_id);
765                     }
766                     ptr => trace!(" integral by ref: {:?}", ptr),
767                 }
768             }
769         }
770     }
771
772     pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
773         let mut last_span = None;
774         let mut frames = Vec::new();
775         for &Frame { instance, span, body, block, stmt, .. } in self.stack().iter().rev() {
776             // make sure we don't emit frames that are duplicates of the previous
777             if explicit_span == Some(span) {
778                 last_span = Some(span);
779                 continue;
780             }
781             if let Some(last) = last_span {
782                 if last == span {
783                     continue;
784                 }
785             } else {
786                 last_span = Some(span);
787             }
788             let block = &body.basic_blocks()[block];
789             let source_info = if stmt < block.statements.len() {
790                 block.statements[stmt].source_info
791             } else {
792                 block.terminator().source_info
793             };
794             let lint_root = match body.source_scope_local_data {
795                 mir::ClearCrossCrate::Set(ref ivs) => Some(ivs[source_info.scope].lint_root),
796                 mir::ClearCrossCrate::Clear => None,
797             };
798             frames.push(FrameInfo { call_site: span, instance, lint_root });
799         }
800         trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
801         frames
802     }
803 }