5 use syntax::source_map::{self, Span, DUMMY_SP};
6 use rustc::ich::StableHashingContext;
7 use rustc::hir::def_id::DefId;
8 use rustc::hir::def::DefKind;
10 use rustc::ty::layout::{
11 self, Size, Align, HasDataLayout, LayoutOf, TyLayout
13 use rustc::ty::subst::SubstsRef;
14 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
15 use rustc::ty::query::TyCtxtAt;
16 use rustc_index::vec::IndexVec;
17 use rustc::mir::interpret::{
18 GlobalId, Scalar, Pointer, FrameInfo, AllocId,
19 InterpResult, truncate, sign_extend,
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
23 use rustc_macros::HashStable;
26 Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
27 Memory, Machine, StackPopInfo
30 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
31 /// Stores the `Machine` instance.
34 /// The results of the type checker, from rustc.
35 pub tcx: TyCtxtAt<'tcx>,
37 /// Bounds in scope for polymorphic evaluations.
38 pub(crate) param_env: ty::ParamEnv<'tcx>,
40 /// The virtual memory system.
41 pub memory: Memory<'mir, 'tcx, M>,
43 /// The virtual call stack.
44 pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
46 /// A cache for deduplicating vtables
48 FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
53 pub struct Frame<'mir, 'tcx, Tag=(), Extra=()> {
54 ////////////////////////////////////////////////////////////////////////////////
55 // Function and callsite information
56 ////////////////////////////////////////////////////////////////////////////////
57 /// The MIR for the function called on this frame.
58 pub body: &'mir mir::Body<'tcx>,
60 /// The def_id and substs of the current function.
61 pub instance: ty::Instance<'tcx>,
63 /// The span of the call site.
64 pub span: source_map::Span,
66 /// Extra data for the machine.
69 ////////////////////////////////////////////////////////////////////////////////
70 // Return place and locals
71 ////////////////////////////////////////////////////////////////////////////////
72 /// Work to perform when returning from this function.
73 pub return_to_block: StackPopCleanup,
75 /// The location where the result of the current stack frame should be written to,
76 /// and its layout in the caller.
77 pub return_place: Option<PlaceTy<'tcx, Tag>>,
79 /// The list of locals for this stack frame, stored in order as
80 /// `[return_ptr, arguments..., variables..., temporaries...]`.
81 /// The locals are stored as `Option<Value>`s.
82 /// `None` represents a local that is currently dead, while a live local
83 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
84 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
86 ////////////////////////////////////////////////////////////////////////////////
87 // Current position within the function
88 ////////////////////////////////////////////////////////////////////////////////
89 /// The block that is currently executed (or will be executed after the above call stacks
91 /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
92 /// Just continue the same as with `Resume`.
93 pub block: Option<mir::BasicBlock>,
95 /// The index of the currently evaluated statement.
99 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
100 pub enum StackPopCleanup {
101 /// Jump to the next block in the caller, or cause UB if None (that's a function
102 /// that may never return). Also store layout of return place so
103 /// we can validate it at that layout.
104 /// `ret` stores the block we jump to on a normal return, while 'unwind'
105 /// stores the block used for cleanup during unwinding
106 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
107 /// Just do nohing: Used by Main and for the box_alloc hook in miri.
108 /// `cleanup` says whether locals are deallocated. Static computation
109 /// wants them leaked to intern what they need (and just throw away
110 /// the entire `ecx` when it is done).
111 None { cleanup: bool },
114 /// State of a local variable including a memoized layout
115 #[derive(Clone, PartialEq, Eq, HashStable)]
116 pub struct LocalState<'tcx, Tag=(), Id=AllocId> {
117 pub value: LocalValue<Tag, Id>,
118 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
119 #[stable_hasher(ignore)]
120 pub layout: Cell<Option<TyLayout<'tcx>>>,
123 /// Current value of a local variable
124 #[derive(Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
125 pub enum LocalValue<Tag=(), Id=AllocId> {
126 /// This local is not currently alive, and cannot be used at all.
128 /// This local is alive but not yet initialized. It can be written to
129 /// but not read from or its address taken. Locals get initialized on
130 /// first write because for unsized locals, we do not know their size
133 /// A normal, live local.
134 /// Mostly for convenience, we re-use the `Operand` type here.
135 /// This is an optimization over just always having a pointer here;
136 /// we can thus avoid doing an allocation when the local just stores
137 /// immediate values *and* never has its address taken.
138 Live(Operand<Tag, Id>),
141 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
142 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
144 LocalValue::Dead => throw_unsup!(DeadLocal),
145 LocalValue::Uninitialized =>
146 bug!("The type checker should prevent reading from a never-written local"),
147 LocalValue::Live(val) => Ok(val),
151 /// Overwrite the local. If the local can be overwritten in place, return a reference
152 /// to do so; otherwise return the `MemPlace` to consult instead.
155 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
157 LocalValue::Dead => throw_unsup!(DeadLocal),
158 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
159 ref mut local @ LocalValue::Live(Operand::Immediate(_)) |
160 ref mut local @ LocalValue::Uninitialized => {
167 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
169 fn data_layout(&self) -> &layout::TargetDataLayout {
170 &self.tcx.data_layout
174 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
176 M: Machine<'mir, 'tcx>,
179 fn tcx(&self) -> TyCtxt<'tcx> {
184 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
186 M: Machine<'mir, 'tcx>,
188 fn param_env(&self) -> ty::ParamEnv<'tcx> {
193 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
195 type TyLayout = InterpResult<'tcx, TyLayout<'tcx>>;
198 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
200 .layout_of(self.param_env.and(ty))
201 .map_err(|layout| err_inval!(Layout(layout)).into())
205 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
208 param_env: ty::ParamEnv<'tcx>,
210 memory_extra: M::MemoryExtra,
216 memory: Memory::new(tcx, memory_extra),
218 vtables: FxHashMap::default(),
225 scalar: Scalar<M::PointerTag>,
226 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
227 self.memory.force_ptr(scalar)
233 scalar: Scalar<M::PointerTag>,
235 ) -> InterpResult<'tcx, u128> {
236 self.memory.force_bits(scalar, size)
240 pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
241 self.memory.tag_static_base_pointer(ptr)
245 pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
250 pub fn cur_frame(&self) -> usize {
251 assert!(self.stack.len() > 0);
256 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
257 self.stack.last().expect("no call frames exist")
261 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
262 self.stack.last_mut().expect("no call frames exist")
266 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
271 pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
272 assert!(ty.abi.is_signed());
273 sign_extend(value, ty.size)
277 pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
278 truncate(value, ty.size)
282 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
283 ty.is_sized(self.tcx, self.param_env)
287 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
288 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
293 instance: ty::InstanceDef<'tcx>,
294 promoted: Option<mir::Promoted>,
295 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
296 // do not continue if typeck errors occurred (can only occur in local crate)
297 let did = instance.def_id();
299 && self.tcx.has_typeck_tables(did)
300 && self.tcx.typeck_tables_of(did).tainted_by_errors
302 throw_inval!(TypeckError)
304 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
305 if let Some(promoted) = promoted {
306 return Ok(&self.tcx.promoted_mir(did)[promoted]);
309 ty::InstanceDef::Item(def_id) => if self.tcx.is_mir_available(did) {
310 Ok(self.tcx.optimized_mir(did))
312 throw_unsup!(NoMirFor(self.tcx.def_path_str(def_id)))
314 _ => Ok(self.tcx.instance_mir(instance)),
318 /// Call this on things you got out of the MIR (so it is as generic as the current
319 /// stack frame), to bring it into the proper environment for this interpreter.
320 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
324 self.tcx.subst_and_normalize_erasing_regions(
325 self.frame().instance.substs,
331 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
332 pub(super) fn resolve(
335 substs: SubstsRef<'tcx>
336 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
337 trace!("resolve: {:?}, {:#?}", def_id, substs);
338 trace!("param_env: {:#?}", self.param_env);
339 trace!("substs: {:#?}", substs);
340 ty::Instance::resolve(
345 ).ok_or_else(|| err_inval!(TooGeneric).into())
348 pub fn layout_of_local(
350 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
352 layout: Option<TyLayout<'tcx>>,
353 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
354 // `const_prop` runs into this with an invalid (empty) frame, so we
355 // have to support that case (mostly by skipping all caching).
356 match frame.locals.get(local).and_then(|state| state.layout.get()) {
358 let layout = crate::interpret::operand::from_known_layout(layout, || {
359 let local_ty = frame.body.local_decls[local].ty;
360 let local_ty = self.tcx.subst_and_normalize_erasing_regions(
361 frame.instance.substs,
365 self.layout_of(local_ty)
367 if let Some(state) = frame.locals.get(local) {
368 // Layouts of locals are requested a lot, so we cache them.
369 state.layout.set(Some(layout));
373 Some(layout) => Ok(layout),
377 /// Returns the actual dynamic size and alignment of the place at the given type.
378 /// Only the "meta" (metadata) part of the place matters.
379 /// This can fail to provide an answer for extern types.
380 pub(super) fn size_and_align_of(
382 metadata: Option<Scalar<M::PointerTag>>,
383 layout: TyLayout<'tcx>,
384 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
385 if !layout.is_unsized() {
386 return Ok(Some((layout.size, layout.align.abi)));
388 match layout.ty.kind {
389 ty::Adt(..) | ty::Tuple(..) => {
390 // First get the size of all statically known fields.
391 // Don't use type_of::sizing_type_of because that expects t to be sized,
392 // and it also rounds up to alignment, which we want to avoid,
393 // as the unsized field's alignment could be smaller.
394 assert!(!layout.ty.is_simd());
395 trace!("DST layout: {:?}", layout);
397 let sized_size = layout.fields.offset(layout.fields.count() - 1);
398 let sized_align = layout.align.abi;
400 "DST {} statically sized prefix size: {:?} align: {:?}",
406 // Recurse to get the size of the dynamically sized field (must be
407 // the last field). Can't have foreign types here, how would we
408 // adjust alignment and size for them?
409 let field = layout.field(self, layout.fields.count() - 1)?;
410 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
411 Some(size_and_align) => size_and_align,
413 // A field with extern type. If this field is at offset 0, we behave
414 // like the underlying extern type.
415 // FIXME: Once we have made decisions for how to handle size and alignment
416 // of `extern type`, this should be adapted. It is just a temporary hack
417 // to get some code to work that probably ought to work.
418 if sized_size == Size::ZERO {
421 bug!("Fields cannot be extern types, unless they are at offset 0")
426 // FIXME (#26403, #27023): We should be adding padding
427 // to `sized_size` (to accommodate the `unsized_align`
428 // required of the unsized field that follows) before
429 // summing it with `sized_size`. (Note that since #26403
430 // is unfixed, we do not yet add the necessary padding
431 // here. But this is where the add would go.)
433 // Return the sum of sizes and max of aligns.
434 let size = sized_size + unsized_size;
436 // Choose max of two known alignments (combined value must
437 // be aligned according to more restrictive of the two).
438 let align = sized_align.max(unsized_align);
440 // Issue #27023: must add any necessary padding to `size`
441 // (to make it a multiple of `align`) before returning it.
442 let size = size.align_to(align);
444 // Check if this brought us over the size limit.
445 if size.bytes() >= self.tcx.data_layout().obj_size_bound() {
446 throw_ub_format!("wide pointer metadata contains invalid information: \
447 total size is bigger than largest supported object");
449 Ok(Some((size, align)))
452 let vtable = metadata.expect("dyn trait fat ptr must have vtable");
453 // Read size and align from vtable (already checks size).
454 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
457 ty::Slice(_) | ty::Str => {
458 let len = metadata.expect("slice fat ptr must have length").to_machine_usize(self)?;
459 let elem = layout.field(self, 0)?;
461 // Make sure the slice is not too big.
462 let size = elem.size.checked_mul(len, &*self.tcx)
463 .ok_or_else(|| err_ub_format!("invalid slice: \
464 total size is bigger than largest supported object"))?;
465 Ok(Some((size, elem.align.abi)))
472 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
476 pub fn size_and_align_of_mplace(
478 mplace: MPlaceTy<'tcx, M::PointerTag>
479 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
480 self.size_and_align_of(mplace.meta, mplace.layout)
483 pub fn push_stack_frame(
485 instance: ty::Instance<'tcx>,
487 body: &'mir mir::Body<'tcx>,
488 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
489 return_to_block: StackPopCleanup,
490 ) -> InterpResult<'tcx> {
491 if self.stack.len() > 0 {
492 info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
494 ::log_settings::settings().indentation += 1;
496 // first push a stack frame so we have access to the local substs
497 let extra = M::stack_push(self)?;
498 self.stack.push(Frame {
500 block: Some(mir::START_BLOCK),
503 // empty local array, we fill it in below, after we are inside the stack frame and
504 // all methods actually know about the frame
505 locals: IndexVec::new(),
512 // don't allocate at all for trivial constants
513 if body.local_decls.len() > 1 {
514 // Locals are initially uninitialized.
515 let dummy = LocalState {
516 value: LocalValue::Uninitialized,
517 layout: Cell::new(None),
519 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
520 // Return place is handled specially by the `eval_place` functions, and the
521 // entry in `locals` should never be used. Make it dead, to be sure.
522 locals[mir::RETURN_PLACE].value = LocalValue::Dead;
523 // Now mark those locals as dead that we do not want to initialize
524 match self.tcx.def_kind(instance.def_id()) {
525 // statics and constants don't have `Storage*` statements, no need to look for them
526 Some(DefKind::Static)
527 | Some(DefKind::Const)
528 | Some(DefKind::AssocConst) => {},
530 trace!("push_stack_frame: {:?}: num_bbs: {}", span, body.basic_blocks().len());
531 for block in body.basic_blocks() {
532 for stmt in block.statements.iter() {
533 use rustc::mir::StatementKind::{StorageDead, StorageLive};
536 StorageDead(local) => {
537 locals[local].value = LocalValue::Dead;
546 self.frame_mut().locals = locals;
549 info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
551 if self.stack.len() > *self.tcx.sess.recursion_limit.get() {
552 throw_exhaust!(StackFrameLimitReached)
558 /// Jump to the given block.
560 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
561 let frame = self.frame_mut();
562 frame.block = Some(target);
566 /// *Return* to the given `target` basic block.
567 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
569 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
570 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
571 if let Some(target) = target {
572 Ok(self.go_to_block(target))
574 throw_ub!(Unreachable)
578 /// *Unwind* to the given `target` basic block.
579 /// Do *not* use for returning! Use `return_to_block` instead.
581 /// If `target` is `None`, that indicates the function does not need cleanup during
582 /// unwinding, and we will just keep propagating that upwards.
583 pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
584 let frame = self.frame_mut();
585 frame.block = target;
589 /// Pops the current frame from the stack, deallocating the
590 /// memory for allocated locals.
592 /// If `unwinding` is `false`, then we are performing a normal return
593 /// from a function. In this case, we jump back into the frame of the caller,
594 /// and continue execution as normal.
596 /// If `unwinding` is `true`, then we are in the middle of a panic,
597 /// and need to unwind this frame. In this case, we jump to the
598 /// `cleanup` block for the function, which is responsible for running
599 /// `Drop` impls for any locals that have been initialized at this point.
600 /// The cleanup block ends with a special `Resume` terminator, which will
601 /// cause us to continue unwinding.
602 pub(super) fn pop_stack_frame(
605 ) -> InterpResult<'tcx> {
606 info!("LEAVING({}) {} (unwinding = {})",
607 self.cur_frame(), self.frame().instance, unwinding);
609 // Sanity check `unwinding`.
612 match self.frame().block {
614 Some(block) => self.body().basic_blocks()[block].is_cleanup
618 ::log_settings::settings().indentation -= 1;
619 let frame = self.stack.pop().expect(
620 "tried to pop a stack frame, but there were none",
622 let stack_pop_info = M::stack_pop(self, frame.extra, unwinding)?;
623 if let (false, StackPopInfo::StopUnwinding) = (unwinding, stack_pop_info) {
624 bug!("Attempted to stop unwinding while there is no unwinding!");
627 // Now where do we jump next?
629 // Determine if we leave this function normally or via unwinding.
630 let cur_unwinding = if let StackPopInfo::StopUnwinding = stack_pop_info {
636 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
637 // In that case, we return early. We also avoid validation in that case,
638 // because this is CTFE and the final value will be thoroughly validated anyway.
639 let (cleanup, next_block) = match frame.return_to_block {
640 StackPopCleanup::Goto { ret, unwind } => {
641 (true, Some(if cur_unwinding { unwind } else { ret }))
643 StackPopCleanup::None { cleanup, .. } => (cleanup, None)
647 assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
648 assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
649 // Leak the locals, skip validation.
653 // Cleanup: deallocate all locals that are backed by an allocation.
654 for local in frame.locals {
655 self.deallocate_local(local.value)?;
659 trace!("StackPopCleanup: {:?} StackPopInfo: {:?} cur_unwinding = {:?}",
660 frame.return_to_block, stack_pop_info, cur_unwinding);
662 // Follow the unwind edge.
663 let unwind = next_block.expect("Encounted StackPopCleanup::None when unwinding!");
664 self.unwind_to_block(unwind);
666 // Follow the normal return edge.
667 // Validate the return value. Do this after deallocating so that we catch dangling
669 if let Some(return_place) = frame.return_place {
670 if M::enforce_validity(self) {
671 // Data got changed, better make sure it matches the type!
672 // It is still possible that the return place held invalid data while
673 // the function is running, but that's okay because nobody could have
674 // accessed that same data from the "outside" to observe any broken
675 // invariant -- that is, unless a function somehow has a ptr to
676 // its return place... but the way MIR is currently generated, the
677 // return place is always a local and then this cannot happen.
678 self.validate_operand(
679 self.place_to_op(return_place)?,
685 // Uh, that shouldn't happen... the function did not intend to return
686 throw_ub!(Unreachable);
689 // Jump to new block -- *after* validation so that the spans make more sense.
690 if let Some(ret) = next_block {
691 self.return_to_block(ret)?;
695 if self.stack.len() > 0 {
696 info!("CONTINUING({}) {} (unwinding = {})",
697 self.cur_frame(), self.frame().instance, cur_unwinding);
703 /// Mark a storage as live, killing the previous content and returning it.
704 /// Remember to deallocate that!
708 ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
709 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
710 trace!("{:?} is now live", local);
712 let local_val = LocalValue::Uninitialized;
713 // StorageLive *always* kills the value that's currently stored.
714 // However, we do not error if the variable already is live;
715 // see <https://github.com/rust-lang/rust/issues/42371>.
716 Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
719 /// Returns the old value of the local.
720 /// Remember to deallocate that!
721 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
722 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
723 trace!("{:?} is now dead", local);
725 mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
728 pub(super) fn deallocate_local(
730 local: LocalValue<M::PointerTag>,
731 ) -> InterpResult<'tcx> {
732 // FIXME: should we tell the user that there was a local which was never written to?
733 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
734 trace!("deallocating local");
735 let ptr = ptr.to_ptr()?;
736 if log_enabled!(::log::Level::Trace) {
737 self.memory.dump_alloc(ptr.alloc_id);
739 self.memory.deallocate_local(ptr)?;
744 pub fn const_eval_raw(
747 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
748 // FIXME(oli-obk): make this check an assertion that it's not a static here
749 // FIXME(RalfJ, oli-obk): document that `Place::Static` can never be anything but a static
750 // and `ConstValue::Unevaluated` can never be a static
751 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
752 ty::ParamEnv::reveal_all()
756 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
757 // Our result will later be validated anyway, and there seems no good reason
758 // to have to fail early here. This is also more consistent with
759 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
760 let val = self.tcx.const_eval_raw(param_env.and(gid))?;
761 self.raw_const_to_mplace(val)
764 pub fn dump_place(&self, place: Place<M::PointerTag>) {
766 if !log_enabled!(::log::Level::Trace) {
770 Place::Local { frame, local } => {
771 let mut allocs = Vec::new();
772 let mut msg = format!("{:?}", local);
773 if frame != self.cur_frame() {
774 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
776 write!(msg, ":").unwrap();
778 match self.stack[frame].locals[local].value {
779 LocalValue::Dead => write!(msg, " is dead").unwrap(),
780 LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
781 LocalValue::Live(Operand::Indirect(mplace)) => {
783 Scalar::Ptr(ptr) => {
784 write!(msg, " by align({}){} ref:",
785 mplace.align.bytes(),
787 Some(meta) => format!(" meta({:?})", meta),
788 None => String::new()
791 allocs.push(ptr.alloc_id);
793 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
796 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
797 write!(msg, " {:?}", val).unwrap();
798 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
799 allocs.push(ptr.alloc_id);
802 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
803 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
804 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
805 allocs.push(ptr.alloc_id);
807 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
808 allocs.push(ptr.alloc_id);
814 self.memory.dump_allocs(allocs);
816 Place::Ptr(mplace) => {
818 Scalar::Ptr(ptr) => {
819 trace!("by align({}) ref:", mplace.align.bytes());
820 self.memory.dump_alloc(ptr.alloc_id);
822 ptr => trace!(" integral by ref: {:?}", ptr),
828 pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
829 let mut last_span = None;
830 let mut frames = Vec::new();
831 for &Frame { instance, span, body, block, stmt, .. } in self.stack().iter().rev() {
832 // make sure we don't emit frames that are duplicates of the previous
833 if explicit_span == Some(span) {
834 last_span = Some(span);
837 if let Some(last) = last_span {
842 last_span = Some(span);
845 let lint_root = block.and_then(|block| {
846 let block = &body.basic_blocks()[block];
847 let source_info = if stmt < block.statements.len() {
848 block.statements[stmt].source_info
850 block.terminator().source_info
852 match &body.source_scopes[source_info.scope].local_data {
853 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
854 mir::ClearCrossCrate::Clear => None,
858 frames.push(FrameInfo { call_site: span, instance, lint_root });
860 trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
865 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
866 for Frame<'mir, 'tcx, Tag, Extra>
867 where Extra: HashStable<StableHashingContext<'ctx>>,
868 Tag: HashStable<StableHashingContext<'ctx>>
870 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
871 self.body.hash_stable(hcx, hasher);
872 self.instance.hash_stable(hcx, hasher);
873 self.span.hash_stable(hcx, hasher);
874 self.return_to_block.hash_stable(hcx, hasher);
875 self.return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
876 self.locals.hash_stable(hcx, hasher);
877 self.block.hash_stable(hcx, hasher);
878 self.stmt.hash_stable(hcx, hasher);
879 self.extra.hash_stable(hcx, hasher);