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