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