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