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