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