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