1 use std::collections::HashSet;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::map::definitions::DefPathData;
6 use rustc::middle::const_val::ConstVal;
8 use rustc::traits::Reveal;
9 use rustc::ty::layout::{self, Size, Align, HasDataLayout, LayoutOf, TyLayout};
10 use rustc::ty::subst::{Subst, Substs, Kind};
11 use rustc::ty::{self, Ty, TyCtxt};
12 use rustc_data_structures::indexed_vec::Idx;
13 use syntax::codemap::{self, DUMMY_SP};
14 use syntax::ast::Mutability;
15 use rustc::mir::interpret::{
16 GlobalId, Value, Pointer, PrimVal, PrimValKind,
17 EvalError, EvalResult, EvalErrorKind, MemoryPointer,
20 use super::{Place, PlaceExtra, Memory,
21 HasMemory, MemoryKind, operator,
24 pub struct EvalContext<'a, 'tcx: 'a, M: Machine<'tcx>> {
25 /// Stores the `Machine` instance.
28 /// The results of the type checker, from rustc.
29 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
31 /// Bounds in scope for polymorphic evaluations.
32 pub param_env: ty::ParamEnv<'tcx>,
34 /// The virtual memory system.
35 pub memory: Memory<'a, 'tcx, M>,
37 /// The virtual call stack.
38 pub(crate) stack: Vec<Frame<'tcx>>,
40 /// The maximum number of stack frames allowed
41 pub(crate) stack_limit: usize,
43 /// The maximum number of operations that may be executed.
44 /// This prevents infinite loops and huge computations from freezing up const eval.
45 /// Remove once halting problem is solved.
46 pub(crate) steps_remaining: u64,
50 pub struct Frame<'tcx> {
51 ////////////////////////////////////////////////////////////////////////////////
52 // Function and callsite information
53 ////////////////////////////////////////////////////////////////////////////////
54 /// The MIR for the function called on this frame.
55 pub mir: &'tcx mir::Mir<'tcx>,
57 /// The def_id and substs of the current function
58 pub instance: ty::Instance<'tcx>,
60 /// The span of the call site.
61 pub span: codemap::Span,
63 ////////////////////////////////////////////////////////////////////////////////
64 // Return place and locals
65 ////////////////////////////////////////////////////////////////////////////////
66 /// The block to return to when returning from the current stack frame
67 pub return_to_block: StackPopCleanup,
69 /// The location where the result of the current stack frame should be written to.
70 pub return_place: Place,
72 /// The list of locals for this stack frame, stored in order as
73 /// `[arguments..., variables..., temporaries...]`. The locals are stored as `Option<Value>`s.
74 /// `None` represents a local that is currently dead, while a live local
75 /// can either directly contain `PrimVal` or refer to some part of an `Allocation`.
77 /// Before being initialized, arguments are `Value::ByVal(PrimVal::Undef)` and other locals are `None`.
78 pub locals: Vec<Option<Value>>,
80 ////////////////////////////////////////////////////////////////////////////////
81 // Current position within the function
82 ////////////////////////////////////////////////////////////////////////////////
83 /// The block that is currently executed (or will be executed after the above call stacks
85 pub block: mir::BasicBlock,
87 /// The index of the currently evaluated statment.
91 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
92 pub enum StackPopCleanup {
93 /// The stackframe existed to compute the initial value of a static/constant, make sure it
94 /// isn't modifyable afterwards in case of constants.
95 /// In case of `static mut`, mark the memory to ensure it's never marked as immutable through
96 /// references or deallocated
97 MarkStatic(Mutability),
98 /// A regular stackframe added due to a function call will need to get forwarded to the next
100 Goto(mir::BasicBlock),
101 /// The main function and diverging functions have nowhere to return to
105 #[derive(Copy, Clone, Debug)]
106 pub struct ResourceLimits {
107 pub memory_size: u64,
109 pub stack_limit: usize,
112 impl Default for ResourceLimits {
113 fn default() -> Self {
115 memory_size: 100 * 1024 * 1024, // 100 MB
116 step_limit: 1_000_000,
122 #[derive(Copy, Clone, Debug)]
123 pub struct TyAndPacked<'tcx> {
128 #[derive(Copy, Clone, Debug)]
129 pub struct ValTy<'tcx> {
134 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
136 fn deref(&self) -> &Value {
141 impl<'a, 'tcx, M: Machine<'tcx>> HasDataLayout for &'a EvalContext<'a, 'tcx, M> {
143 fn data_layout(&self) -> &layout::TargetDataLayout {
144 &self.tcx.data_layout
148 impl<'c, 'b, 'a, 'tcx, M: Machine<'tcx>> HasDataLayout
149 for &'c &'b mut EvalContext<'a, 'tcx, M> {
151 fn data_layout(&self) -> &layout::TargetDataLayout {
152 &self.tcx.data_layout
156 impl<'a, 'tcx, M: Machine<'tcx>> layout::HasTyCtxt<'tcx> for &'a EvalContext<'a, 'tcx, M> {
158 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
163 impl<'c, 'b, 'a, 'tcx, M: Machine<'tcx>> layout::HasTyCtxt<'tcx>
164 for &'c &'b mut EvalContext<'a, 'tcx, M> {
166 fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
171 impl<'a, 'tcx, M: Machine<'tcx>> LayoutOf<Ty<'tcx>> for &'a EvalContext<'a, 'tcx, M> {
172 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
174 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
175 (self.tcx, self.param_env).layout_of(ty)
176 .map_err(|layout| EvalErrorKind::Layout(layout).into())
180 impl<'c, 'b, 'a, 'tcx, M: Machine<'tcx>> LayoutOf<Ty<'tcx>>
181 for &'c &'b mut EvalContext<'a, 'tcx, M> {
182 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
185 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
186 (&**self).layout_of(ty)
190 impl<'a, 'tcx, M: Machine<'tcx>> EvalContext<'a, 'tcx, M> {
192 tcx: TyCtxt<'a, 'tcx, 'tcx>,
193 param_env: ty::ParamEnv<'tcx>,
194 limits: ResourceLimits,
196 memory_data: M::MemoryData,
202 memory: Memory::new(tcx, limits.memory_size, memory_data),
204 stack_limit: limits.stack_limit,
205 steps_remaining: limits.step_limit,
209 pub fn alloc_ptr(&mut self, ty: Ty<'tcx>) -> EvalResult<'tcx, MemoryPointer> {
210 let layout = self.layout_of(ty)?;
211 assert!(!layout.is_unsized(), "cannot alloc memory for unsized type");
213 let size = layout.size.bytes();
214 self.memory.allocate(size, layout.align, Some(MemoryKind::Stack))
217 pub fn memory(&self) -> &Memory<'a, 'tcx, M> {
221 pub fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx, M> {
225 pub fn stack(&self) -> &[Frame<'tcx>] {
230 pub fn cur_frame(&self) -> usize {
231 assert!(self.stack.len() > 0);
235 pub fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value> {
236 let ptr = self.memory.allocate_cached(s.as_bytes());
239 PrimVal::from_u128(s.len() as u128),
243 pub(super) fn const_to_value(&mut self, const_val: &ConstVal<'tcx>, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
244 use rustc::middle::const_val::ConstVal::*;
246 let primval = match *const_val {
247 Integral(const_int) => PrimVal::Bytes(const_int.to_u128_unchecked()),
249 Float(val) => PrimVal::Bytes(val.bits),
251 Bool(b) => PrimVal::from_bool(b),
252 Char(c) => PrimVal::from_char(c),
254 Str(ref s) => return self.str_to_value(s),
257 let ptr = self.memory.allocate_cached(bs.data);
261 Unevaluated(def_id, substs) => {
262 let instance = self.resolve(def_id, substs)?;
263 return Ok(self.read_global_as_value(GlobalId {
266 }, self.layout_of(ty)?));
270 Variant(_) => bug!("should not have aggregate or variant constants in MIR"),
271 // function items are zero sized and thus have no readable value
272 Function(..) => PrimVal::Undef,
275 Ok(Value::ByVal(primval))
278 pub(super) fn resolve(&self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, ty::Instance<'tcx>> {
279 let substs = self.tcx.trans_apply_param_substs(self.substs(), &substs);
280 ty::Instance::resolve(
285 ).ok_or(EvalErrorKind::TypeckError.into()) // turn error prop into a panic to expose associated type in const issue
288 pub(super) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
289 ty.is_sized(self.tcx, self.param_env, DUMMY_SP)
294 instance: ty::InstanceDef<'tcx>,
295 ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
296 // do not continue if typeck errors occurred (can only occur in local crate)
297 let did = instance.def_id();
298 if did.is_local() && self.tcx.has_typeck_tables(did) && self.tcx.typeck_tables_of(did).tainted_by_errors {
299 return err!(TypeckError);
301 trace!("load mir {:?}", instance);
303 ty::InstanceDef::Item(def_id) => {
304 self.tcx.maybe_optimized_mir(def_id).ok_or_else(|| {
305 EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
308 _ => Ok(self.tcx.instance_mir(instance)),
312 pub fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
313 // miri doesn't care about lifetimes, and will choke on some crazy ones
314 // let's simply get rid of them
315 let without_lifetimes = self.tcx.erase_regions(&ty);
316 let substituted = without_lifetimes.subst(self.tcx, substs);
317 let substituted = self.tcx.fully_normalize_monormophic_ty(&substituted);
321 /// Return the size and aligment of the value at the given type.
322 /// Note that the value does not matter if the type is sized. For unsized types,
323 /// the value has to be a fat pointer, and we only care about the "extra" data in it.
324 pub fn size_and_align_of_dst(
328 ) -> EvalResult<'tcx, (Size, Align)> {
329 let layout = self.layout_of(ty)?;
330 if !layout.is_unsized() {
331 Ok(layout.size_and_align())
334 ty::TyAdt(..) | ty::TyTuple(..) => {
335 // First get the size of all statically known fields.
336 // Don't use type_of::sizing_type_of because that expects t to be sized,
337 // and it also rounds up to alignment, which we want to avoid,
338 // as the unsized field's alignment could be smaller.
339 assert!(!ty.is_simd());
340 debug!("DST {} layout: {:?}", ty, layout);
342 let sized_size = layout.fields.offset(layout.fields.count() - 1);
343 let sized_align = layout.align;
345 "DST {} statically sized prefix size: {:?} align: {:?}",
351 // Recurse to get the size of the dynamically sized field (must be
353 let field_ty = layout.field(&self, layout.fields.count() - 1)?.ty;
354 let (unsized_size, unsized_align) =
355 self.size_and_align_of_dst(field_ty, value)?;
357 // FIXME (#26403, #27023): We should be adding padding
358 // to `sized_size` (to accommodate the `unsized_align`
359 // required of the unsized field that follows) before
360 // summing it with `sized_size`. (Note that since #26403
361 // is unfixed, we do not yet add the necessary padding
362 // here. But this is where the add would go.)
364 // Return the sum of sizes and max of aligns.
365 let size = sized_size + unsized_size;
367 // Choose max of two known alignments (combined value must
368 // be aligned according to more restrictive of the two).
369 let align = sized_align.max(unsized_align);
371 // Issue #27023: must add any necessary padding to `size`
372 // (to make it a multiple of `align`) before returning it.
374 // Namely, the returned size should be, in C notation:
376 // `size + ((size & (align-1)) ? align : 0)`
378 // emulated via the semi-standard fast bit trick:
380 // `(size + (align-1)) & -align`
382 Ok((size.abi_align(align), align))
384 ty::TyDynamic(..) => {
385 let (_, vtable) = self.into_ptr_vtable_pair(value)?;
386 // the second entry in the vtable is the dynamic size of the object.
387 self.read_size_and_align_from_vtable(vtable)
390 ty::TySlice(_) | ty::TyStr => {
391 let (elem_size, align) = layout.field(&self, 0)?.size_and_align();
392 let (_, len) = self.into_slice(value)?;
393 Ok((elem_size * len, align))
396 _ => bug!("size_of_val::<{:?}>", ty),
401 pub fn push_stack_frame(
403 instance: ty::Instance<'tcx>,
405 mir: &'tcx mir::Mir<'tcx>,
407 return_to_block: StackPopCleanup,
408 ) -> EvalResult<'tcx> {
409 ::log_settings::settings().indentation += 1;
411 /// Return the set of locals that have a storage annotation anywhere
412 fn collect_storage_annotations<'tcx>(mir: &'tcx mir::Mir<'tcx>) -> HashSet<mir::Local> {
413 use rustc::mir::StatementKind::*;
415 let mut set = HashSet::new();
416 for block in mir.basic_blocks() {
417 for stmt in block.statements.iter() {
420 StorageDead(local) => {
430 // Subtract 1 because `local_decls` includes the ReturnMemoryPointer, but we don't store a local
432 let num_locals = mir.local_decls.len() - 1;
435 let annotated_locals = collect_storage_annotations(mir);
436 let mut locals = vec![None; num_locals];
437 for i in 0..num_locals {
438 let local = mir::Local::new(i + 1);
439 if !annotated_locals.contains(&local) {
440 locals[i] = Some(Value::ByVal(PrimVal::Undef));
446 self.stack.push(Frame {
448 block: mir::START_BLOCK,
457 self.memory.cur_frame = self.cur_frame();
459 if self.stack.len() > self.stack_limit {
460 err!(StackFrameLimitReached)
466 pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
467 ::log_settings::settings().indentation -= 1;
468 M::end_region(self, None)?;
469 let frame = self.stack.pop().expect(
470 "tried to pop a stack frame, but there were none",
472 if !self.stack.is_empty() {
473 // TODO: Is this the correct time to start considering these accesses as originating from the returned-to stack frame?
474 self.memory.cur_frame = self.cur_frame();
476 match frame.return_to_block {
477 StackPopCleanup::MarkStatic(mutable) => {
478 if let Place::Ptr { ptr, .. } = frame.return_place {
479 // FIXME: to_ptr()? might be too extreme here, static zsts might reach this under certain conditions
480 self.memory.mark_static_initalized(
481 ptr.to_ptr()?.alloc_id,
485 bug!("StackPopCleanup::MarkStatic on: {:?}", frame.return_place);
488 StackPopCleanup::Goto(target) => self.goto_block(target),
489 StackPopCleanup::None => {}
491 // deallocate all locals that are backed by an allocation
492 for local in frame.locals {
493 self.deallocate_local(local)?;
499 pub fn deallocate_local(&mut self, local: Option<Value>) -> EvalResult<'tcx> {
500 if let Some(Value::ByRef(ptr, _align)) = local {
501 trace!("deallocating local");
502 let ptr = ptr.to_ptr()?;
503 self.memory.dump_alloc(ptr.alloc_id);
504 self.memory.deallocate_local(ptr)?;
509 /// Evaluate an assignment statement.
511 /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
512 /// type writes its results directly into the memory specified by the place.
513 pub(super) fn eval_rvalue_into_place(
515 rvalue: &mir::Rvalue<'tcx>,
516 place: &mir::Place<'tcx>,
517 ) -> EvalResult<'tcx> {
518 let dest = self.eval_place(place)?;
519 let dest_ty = self.place_ty(place);
521 use rustc::mir::Rvalue::*;
523 Use(ref operand) => {
524 let value = self.eval_operand(operand)?.value;
529 self.write_value(valty, dest)?;
532 BinaryOp(bin_op, ref left, ref right) => {
533 let left = self.eval_operand(left)?;
534 let right = self.eval_operand(right)?;
535 if self.intrinsic_overflowing(
543 // There was an overflow in an unchecked binop. Right now, we consider this an error and bail out.
544 // The rationale is that the reason rustc emits unchecked binops in release mode (vs. the checked binops
545 // it emits in debug mode) is performance, but it doesn't cost us any performance in miri.
546 // If, however, the compiler ever starts transforming unchecked intrinsics into unchecked binops,
547 // we have to go back to just ignoring the overflow here.
548 return err!(OverflowingMath);
552 CheckedBinaryOp(bin_op, ref left, ref right) => {
553 let left = self.eval_operand(left)?;
554 let right = self.eval_operand(right)?;
555 self.intrinsic_with_overflow(
564 UnaryOp(un_op, ref operand) => {
565 let val = self.eval_operand_to_primval(operand)?;
566 let kind = self.ty_to_primval_kind(dest_ty)?;
569 operator::unary_op(un_op, val, kind)?,
574 Aggregate(ref kind, ref operands) => {
575 self.inc_step_counter_and_check_limit(operands.len() as u64)?;
577 let (dest, active_field_index) = match **kind {
578 mir::AggregateKind::Adt(adt_def, variant_index, _, active_field_index) => {
579 self.write_discriminant_value(dest_ty, dest, variant_index)?;
580 if adt_def.is_enum() {
581 (self.place_downcast(dest, variant_index)?, active_field_index)
583 (dest, active_field_index)
589 let layout = self.layout_of(dest_ty)?;
590 for (i, operand) in operands.iter().enumerate() {
591 let value = self.eval_operand(operand)?;
592 // Ignore zero-sized fields.
593 if !self.layout_of(value.ty)?.is_zst() {
594 let field_index = active_field_index.unwrap_or(i);
595 let (field_dest, _) = self.place_field(dest, mir::Field::new(field_index), layout)?;
596 self.write_value(value, field_dest)?;
601 Repeat(ref operand, _) => {
602 let (elem_ty, length) = match dest_ty.sty {
603 ty::TyArray(elem_ty, n) => (elem_ty, n.val.to_const_int().unwrap().to_u64().unwrap()),
606 "tried to assign array-repeat to non-array type {:?}",
611 let elem_size = self.layout_of(elem_ty)?.size.bytes();
612 let value = self.eval_operand(operand)?.value;
614 let (dest, dest_align) = self.force_allocation(dest)?.to_ptr_align();
616 // FIXME: speed up repeat filling
618 let elem_dest = dest.offset(i * elem_size, &self)?;
619 self.write_value_to_ptr(value, elem_dest, dest_align, elem_ty)?;
624 // FIXME(CTFE): don't allow computing the length of arrays in const eval
625 let src = self.eval_place(place)?;
626 let ty = self.place_ty(place);
627 let (_, len) = src.elem_ty_and_len(ty);
630 PrimVal::from_u128(len as u128),
635 Ref(_, _, ref place) => {
636 let src = self.eval_place(place)?;
637 // We ignore the alignment of the place here -- special handling for packed structs ends
638 // at the `&` operator.
639 let (ptr, _align, extra) = self.force_allocation(src)?.to_ptr_align_extra();
641 let val = match extra {
642 PlaceExtra::None => ptr.to_value(),
643 PlaceExtra::Length(len) => ptr.to_value_with_len(len),
644 PlaceExtra::Vtable(vtable) => ptr.to_value_with_vtable(vtable),
645 PlaceExtra::DowncastVariant(..) => {
646 bug!("attempted to take a reference to an enum downcast place")
653 self.write_value(valty, dest)?;
656 NullaryOp(mir::NullOp::Box, ty) => {
657 let ty = self.monomorphize(ty, self.substs());
658 M::box_alloc(self, ty, dest)?;
661 NullaryOp(mir::NullOp::SizeOf, ty) => {
662 let ty = self.monomorphize(ty, self.substs());
663 let layout = self.layout_of(ty)?;
664 assert!(!layout.is_unsized(),
665 "SizeOf nullary MIR operator called for unsized type");
668 PrimVal::from_u128(layout.size.bytes() as u128),
673 Cast(kind, ref operand, cast_ty) => {
674 debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest_ty);
675 use rustc::mir::CastKind::*;
678 let src = self.eval_operand(operand)?;
679 let src_layout = self.layout_of(src.ty)?;
680 let dst_layout = self.layout_of(dest_ty)?;
681 self.unsize_into(src.value, src_layout, dest, dst_layout)?;
685 let src = self.eval_operand(operand)?;
686 if self.type_is_fat_ptr(src.ty) {
687 match (src.value, self.type_is_fat_ptr(dest_ty)) {
688 (Value::ByRef { .. }, _) |
689 (Value::ByValPair(..), true) => {
694 self.write_value(valty, dest)?;
696 (Value::ByValPair(data, _), false) => {
698 value: Value::ByVal(data),
701 self.write_value(valty, dest)?;
703 (Value::ByVal(_), _) => bug!("expected fat ptr"),
706 let src_val = self.value_to_primval(src)?;
707 let dest_val = self.cast_primval(src_val, src.ty, dest_ty)?;
709 value: Value::ByVal(dest_val),
712 self.write_value(valty, dest)?;
717 match self.eval_operand(operand)?.ty.sty {
718 ty::TyFnDef(def_id, substs) => {
719 let instance = self.resolve(def_id, substs)?;
720 let fn_ptr = self.memory.create_fn_alloc(instance);
722 value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
725 self.write_value(valty, dest)?;
727 ref other => bug!("reify fn pointer on {:?}", other),
734 let mut src = self.eval_operand(operand)?;
736 self.write_value(src, dest)?;
738 ref other => bug!("fn to unsafe fn cast on {:?}", other),
742 ClosureFnPointer => {
743 match self.eval_operand(operand)?.ty.sty {
744 ty::TyClosure(def_id, substs) => {
745 let substs = self.tcx.trans_apply_param_substs(self.substs(), &substs);
746 let instance = ty::Instance::resolve_closure(
750 ty::ClosureKind::FnOnce,
752 let fn_ptr = self.memory.create_fn_alloc(instance);
754 value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
757 self.write_value(valty, dest)?;
759 ref other => bug!("closure fn pointer on {:?}", other),
765 Discriminant(ref place) => {
766 let ty = self.place_ty(place);
767 let place = self.eval_place(place)?;
768 let discr_val = self.read_discriminant_value(place, ty)?;
769 if let ty::TyAdt(adt_def, _) = ty.sty {
770 trace!("Read discriminant {}, valid discriminants {:?}", discr_val, adt_def.discriminants(self.tcx).collect::<Vec<_>>());
771 if adt_def.discriminants(self.tcx).all(|v| {
772 discr_val != v.to_u128_unchecked()
775 return err!(InvalidDiscriminant);
777 self.write_primval(dest, PrimVal::Bytes(discr_val), dest_ty)?;
779 bug!("rustc only generates Rvalue::Discriminant for enums");
784 if log_enabled!(::log::Level::Trace) {
785 self.dump_local(dest);
791 pub(super) fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
793 ty::TyRawPtr(ref tam) |
794 ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
795 ty::TyAdt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
800 pub(super) fn eval_operand_to_primval(
802 op: &mir::Operand<'tcx>,
803 ) -> EvalResult<'tcx, PrimVal> {
804 let valty = self.eval_operand(op)?;
805 self.value_to_primval(valty)
808 pub(crate) fn operands_to_args(
810 ops: &[mir::Operand<'tcx>],
811 ) -> EvalResult<'tcx, Vec<ValTy<'tcx>>> {
813 .map(|op| self.eval_operand(op))
817 pub fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
818 use rustc::mir::Operand::*;
819 let ty = self.monomorphize(op.ty(self.mir(), self.tcx), self.substs());
821 // FIXME: do some more logic on `move` to invalidate the old location
825 value: self.eval_and_read_place(place)?,
830 Constant(ref constant) => {
831 use rustc::mir::Literal;
832 let mir::Constant { ref literal, .. } = **constant;
833 let value = match *literal {
834 Literal::Value { ref value } => self.const_to_value(&value.val, ty)?,
836 Literal::Promoted { index } => {
837 self.read_global_as_value(GlobalId {
838 instance: self.frame().instance,
839 promoted: Some(index),
840 }, self.layout_of(ty)?)
852 pub fn read_discriminant_value(
856 ) -> EvalResult<'tcx, u128> {
857 let layout = self.layout_of(ty)?;
858 //trace!("read_discriminant_value {:#?}", layout);
860 match layout.variants {
861 layout::Variants::Single { index } => {
862 return Ok(index as u128);
864 layout::Variants::Tagged { .. } |
865 layout::Variants::NicheFilling { .. } => {},
868 let (discr_place, discr) = self.place_field(place, mir::Field::new(0), layout)?;
869 let raw_discr = self.value_to_primval(ValTy {
870 value: self.read_place(discr_place)?,
873 let discr_val = match layout.variants {
874 layout::Variants::Single { .. } => bug!(),
875 layout::Variants::Tagged { .. } => raw_discr.to_bytes()?,
876 layout::Variants::NicheFilling {
882 let variants_start = niche_variants.start as u128;
883 let variants_end = niche_variants.end as u128;
886 assert!(niche_start == 0);
887 assert!(variants_start == variants_end);
888 dataful_variant as u128
890 PrimVal::Bytes(raw_discr) => {
891 let discr = raw_discr.wrapping_sub(niche_start)
892 .wrapping_add(variants_start);
893 if variants_start <= discr && discr <= variants_end {
896 dataful_variant as u128
899 PrimVal::Undef => return err!(ReadUndefBytes),
908 pub(crate) fn write_discriminant_value(
912 variant_index: usize,
913 ) -> EvalResult<'tcx> {
914 let layout = self.layout_of(dest_ty)?;
916 match layout.variants {
917 layout::Variants::Single { index } => {
918 if index != variant_index {
919 // If the layout of an enum is `Single`, all
920 // other variants are necessarily uninhabited.
921 assert_eq!(layout.for_variant(&self, variant_index).abi,
922 layout::Abi::Uninhabited);
925 layout::Variants::Tagged { .. } => {
926 let discr_val = dest_ty.ty_adt_def().unwrap()
927 .discriminant_for_variant(self.tcx, variant_index)
928 .to_u128_unchecked();
930 let (discr_dest, discr) = self.place_field(dest, mir::Field::new(0), layout)?;
931 self.write_primval(discr_dest, PrimVal::Bytes(discr_val), discr.ty)?;
933 layout::Variants::NicheFilling {
939 if variant_index != dataful_variant {
940 let (niche_dest, niche) =
941 self.place_field(dest, mir::Field::new(0), layout)?;
942 let niche_value = ((variant_index - niche_variants.start) as u128)
943 .wrapping_add(niche_start);
944 self.write_primval(niche_dest, PrimVal::Bytes(niche_value), niche.ty)?;
952 pub fn read_global_as_value(&self, gid: GlobalId, layout: TyLayout) -> Value {
953 let alloc = self.tcx.interpret_interner.borrow().get_cached(gid).expect("global not cached");
954 Value::ByRef(MemoryPointer::new(alloc, 0).into(), layout.align)
957 pub fn force_allocation(&mut self, place: Place) -> EvalResult<'tcx, Place> {
958 let new_place = match place {
959 Place::Local { frame, local } => {
960 // -1 since we don't store the return value
961 match self.stack[frame].locals[local.index() - 1] {
962 None => return err!(DeadLocal),
963 Some(Value::ByRef(ptr, align)) => {
967 extra: PlaceExtra::None,
971 let ty = self.stack[frame].mir.local_decls[local].ty;
972 let ty = self.monomorphize(ty, self.stack[frame].instance.substs);
973 let layout = self.layout_of(ty)?;
974 let ptr = self.alloc_ptr(ty)?;
975 self.stack[frame].locals[local.index() - 1] =
976 Some(Value::ByRef(ptr.into(), layout.align)); // it stays live
977 let place = Place::from_ptr(ptr, layout.align);
978 self.write_value(ValTy { value: val, ty }, place)?;
983 Place::Ptr { .. } => place,
988 /// ensures this Value is not a ByRef
989 pub fn follow_by_ref_value(
993 ) -> EvalResult<'tcx, Value> {
995 Value::ByRef(ptr, align) => {
996 self.read_value(ptr, align, ty)
1002 pub fn value_to_primval(
1004 ValTy { value, ty } : ValTy<'tcx>,
1005 ) -> EvalResult<'tcx, PrimVal> {
1006 match self.follow_by_ref_value(value, ty)? {
1007 Value::ByRef { .. } => bug!("follow_by_ref_value can't result in `ByRef`"),
1009 Value::ByVal(primval) => {
1010 // TODO: Do we really want insta-UB here?
1011 self.ensure_valid_value(primval, ty)?;
1015 Value::ByValPair(..) => bug!("value_to_primval can't work with fat pointers"),
1019 pub fn write_ptr(&mut self, dest: Place, val: Pointer, dest_ty: Ty<'tcx>) -> EvalResult<'tcx> {
1021 value: val.to_value(),
1024 self.write_value(valty, dest)
1027 pub fn write_primval(
1032 ) -> EvalResult<'tcx> {
1034 value: Value::ByVal(val),
1037 self.write_value(valty, dest)
1042 ValTy { value: src_val, ty: dest_ty } : ValTy<'tcx>,
1044 ) -> EvalResult<'tcx> {
1045 //trace!("Writing {:?} to {:?} at type {:?}", src_val, dest, dest_ty);
1046 // Note that it is really important that the type here is the right one, and matches the type things are read at.
1047 // In case `src_val` is a `ByValPair`, we don't do any magic here to handle padding properly, which is only
1048 // correct if we never look at this data with the wrong type.
1051 Place::Ptr { ptr, align, extra } => {
1052 assert_eq!(extra, PlaceExtra::None);
1053 self.write_value_to_ptr(src_val, ptr, align, dest_ty)
1056 Place::Local { frame, local } => {
1057 let dest = self.stack[frame].get_local(local)?;
1058 self.write_value_possibly_by_val(
1060 |this, val| this.stack[frame].set_local(local, val),
1068 // The cases here can be a bit subtle. Read carefully!
1069 fn write_value_possibly_by_val<F: FnOnce(&mut Self, Value) -> EvalResult<'tcx>>(
1073 old_dest_val: Value,
1075 ) -> EvalResult<'tcx> {
1076 if let Value::ByRef(dest_ptr, align) = old_dest_val {
1077 // If the value is already `ByRef` (that is, backed by an `Allocation`),
1078 // then we must write the new value into this allocation, because there may be
1079 // other pointers into the allocation. These other pointers are logically
1080 // pointers into the local variable, and must be able to observe the change.
1082 // Thus, it would be an error to replace the `ByRef` with a `ByVal`, unless we
1083 // knew for certain that there were no outstanding pointers to this allocation.
1084 self.write_value_to_ptr(src_val, dest_ptr, align, dest_ty)?;
1085 } else if let Value::ByRef(src_ptr, align) = src_val {
1086 // If the value is not `ByRef`, then we know there are no pointers to it
1087 // and we can simply overwrite the `Value` in the locals array directly.
1089 // In this specific case, where the source value is `ByRef`, we must duplicate
1090 // the allocation, because this is a by-value operation. It would be incorrect
1091 // if they referred to the same allocation, since then a change to one would
1092 // implicitly change the other.
1094 // It is a valid optimization to attempt reading a primitive value out of the
1095 // source and write that into the destination without making an allocation, so
1097 if let Ok(Some(src_val)) = self.try_read_value(src_ptr, align, dest_ty) {
1098 write_dest(self, src_val)?;
1100 let dest_ptr = self.alloc_ptr(dest_ty)?.into();
1101 let layout = self.layout_of(dest_ty)?;
1102 self.memory.copy(src_ptr, align.min(layout.align), dest_ptr, layout.align, layout.size.bytes(), false)?;
1103 write_dest(self, Value::ByRef(dest_ptr, layout.align))?;
1106 // Finally, we have the simple case where neither source nor destination are
1107 // `ByRef`. We may simply copy the source value over the the destintion.
1108 write_dest(self, src_val)?;
1113 pub fn write_value_to_ptr(
1119 ) -> EvalResult<'tcx> {
1120 trace!("write_value_to_ptr: {:#?}", value);
1121 let layout = self.layout_of(dest_ty)?;
1123 Value::ByRef(ptr, align) => {
1124 self.memory.copy(ptr, align.min(layout.align), dest, dest_align.min(layout.align), layout.size.bytes(), false)
1126 Value::ByVal(primval) => {
1128 layout::Abi::Scalar(_) => {}
1129 _ if primval.is_undef() => {}
1130 _ => bug!("write_value_to_ptr: invalid ByVal layout: {:#?}", layout)
1132 // TODO: Do we need signedness?
1133 self.memory.write_primval(dest.to_ptr()?, dest_align, primval, layout.size.bytes(), false)
1135 Value::ByValPair(a_val, b_val) => {
1136 let ptr = dest.to_ptr()?;
1137 trace!("write_value_to_ptr valpair: {:#?}", layout);
1138 let (a, b) = match layout.abi {
1139 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
1140 _ => bug!("write_value_to_ptr: invalid ByValPair layout: {:#?}", layout)
1142 let (a_size, b_size) = (a.size(&self), b.size(&self));
1144 let b_offset = a_size.abi_align(b.align(&self));
1145 let b_ptr = ptr.offset(b_offset.bytes(), &self)?.into();
1146 // TODO: What about signedess?
1147 self.memory.write_primval(a_ptr, dest_align, a_val, a_size.bytes(), false)?;
1148 self.memory.write_primval(b_ptr, dest_align, b_val, b_size.bytes(), false)
1153 pub fn ty_to_primval_kind(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimValKind> {
1154 use syntax::ast::FloatTy;
1156 let kind = match ty.sty {
1157 ty::TyBool => PrimValKind::Bool,
1158 ty::TyChar => PrimValKind::Char,
1160 ty::TyInt(int_ty) => {
1161 use syntax::ast::IntTy::*;
1162 let size = match int_ty {
1168 Isize => self.memory.pointer_size(),
1170 PrimValKind::from_int_size(size)
1173 ty::TyUint(uint_ty) => {
1174 use syntax::ast::UintTy::*;
1175 let size = match uint_ty {
1181 Usize => self.memory.pointer_size(),
1183 PrimValKind::from_uint_size(size)
1186 ty::TyFloat(FloatTy::F32) => PrimValKind::F32,
1187 ty::TyFloat(FloatTy::F64) => PrimValKind::F64,
1189 ty::TyFnPtr(_) => PrimValKind::FnPtr,
1191 ty::TyRef(_, ref tam) |
1192 ty::TyRawPtr(ref tam) if self.type_is_sized(tam.ty) => PrimValKind::Ptr,
1194 ty::TyAdt(def, _) if def.is_box() => PrimValKind::Ptr,
1197 match self.layout_of(ty)?.abi {
1198 layout::Abi::Scalar(ref scalar) => {
1199 use rustc::ty::layout::Primitive::*;
1200 match scalar.value {
1201 Int(i, false) => PrimValKind::from_uint_size(i.size().bytes()),
1202 Int(i, true) => PrimValKind::from_int_size(i.size().bytes()),
1203 F32 => PrimValKind::F32,
1204 F64 => PrimValKind::F64,
1205 Pointer => PrimValKind::Ptr,
1209 _ => return err!(TypeNotPrimitive(ty)),
1213 _ => return err!(TypeNotPrimitive(ty)),
1219 fn ensure_valid_value(&self, val: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
1221 ty::TyBool if val.to_bytes()? > 1 => err!(InvalidBool),
1223 ty::TyChar if ::std::char::from_u32(val.to_bytes()? as u32).is_none() => {
1224 err!(InvalidChar(val.to_bytes()? as u32 as u128))
1231 pub fn read_value(&self, ptr: Pointer, align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1232 if let Some(val) = self.try_read_value(ptr, align, ty)? {
1235 bug!("primitive read failed for type: {:?}", ty);
1239 pub(crate) fn read_ptr(
1243 pointee_ty: Ty<'tcx>,
1244 ) -> EvalResult<'tcx, Value> {
1245 let ptr_size = self.memory.pointer_size();
1246 let p: Pointer = self.memory.read_ptr_sized_unsigned(ptr, ptr_align)?.into();
1247 if self.type_is_sized(pointee_ty) {
1250 trace!("reading fat pointer extra of type {}", pointee_ty);
1251 let extra = ptr.offset(ptr_size, self)?;
1252 match self.tcx.struct_tail(pointee_ty).sty {
1253 ty::TyDynamic(..) => Ok(p.to_value_with_vtable(
1254 self.memory.read_ptr_sized_unsigned(extra, ptr_align)?.to_ptr()?,
1256 ty::TySlice(..) | ty::TyStr => Ok(
1257 p.to_value_with_len(self.memory.read_ptr_sized_unsigned(extra, ptr_align)?.to_bytes()? as u64),
1259 _ => bug!("unsized primval ptr read from {:?}", pointee_ty),
1264 pub fn try_read_value(&self, ptr: Pointer, ptr_align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<Value>> {
1265 use syntax::ast::FloatTy;
1267 let ptr = ptr.to_ptr()?;
1268 let val = match ty.sty {
1270 let val = self.memory.read_primval(ptr, ptr_align, 1, false)?;
1271 let val = match val {
1272 PrimVal::Bytes(0) => false,
1273 PrimVal::Bytes(1) => true,
1274 // TODO: This seems a little overeager, should reading at bool type already be insta-UB?
1275 _ => return err!(InvalidBool),
1277 PrimVal::from_bool(val)
1280 let c = self.memory.read_primval(ptr, ptr_align, 4, false)?.to_bytes()? as u32;
1281 match ::std::char::from_u32(c) {
1282 Some(ch) => PrimVal::from_char(ch),
1283 None => return err!(InvalidChar(c as u128)),
1287 ty::TyInt(int_ty) => {
1288 use syntax::ast::IntTy::*;
1289 let size = match int_ty {
1295 Isize => self.memory.pointer_size(),
1297 self.memory.read_primval(ptr, ptr_align, size, true)?
1300 ty::TyUint(uint_ty) => {
1301 use syntax::ast::UintTy::*;
1302 let size = match uint_ty {
1308 Usize => self.memory.pointer_size(),
1310 self.memory.read_primval(ptr, ptr_align, size, false)?
1313 ty::TyFloat(FloatTy::F32) => {
1314 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 4, false)?.to_bytes()?)
1316 ty::TyFloat(FloatTy::F64) => {
1317 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 8, false)?.to_bytes()?)
1320 ty::TyFnPtr(_) => self.memory.read_ptr_sized_unsigned(ptr, ptr_align)?,
1321 ty::TyRef(_, ref tam) |
1322 ty::TyRawPtr(ref tam) => return self.read_ptr(ptr, ptr_align, tam.ty).map(Some),
1324 ty::TyAdt(def, _) => {
1326 return self.read_ptr(ptr, ptr_align, ty.boxed_ty()).map(Some);
1329 if let layout::Abi::Scalar(ref scalar) = self.layout_of(ty)?.abi {
1330 let mut signed = false;
1331 if let layout::Int(_, s) = scalar.value {
1334 let size = scalar.value.size(self).bytes();
1335 self.memory.read_primval(ptr, ptr_align, size, signed)?
1341 _ => return Ok(None),
1344 Ok(Some(Value::ByVal(val)))
1347 pub fn frame(&self) -> &Frame<'tcx> {
1348 self.stack.last().expect("no call frames exist")
1351 pub fn frame_mut(&mut self) -> &mut Frame<'tcx> {
1352 self.stack.last_mut().expect("no call frames exist")
1355 pub(super) fn mir(&self) -> &'tcx mir::Mir<'tcx> {
1359 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1360 if let Some(frame) = self.stack.last() {
1361 frame.instance.substs
1375 ) -> EvalResult<'tcx> {
1376 // A<Struct> -> A<Trait> conversion
1377 let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
1379 match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
1380 (&ty::TyArray(_, length), &ty::TySlice(_)) => {
1381 let ptr = self.into_ptr(src)?;
1382 // u64 cast is from usize to u64, which is always good
1384 value: ptr.to_value_with_len(length.val.to_const_int().unwrap().to_u64().unwrap() ),
1387 self.write_value(valty, dest)
1389 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
1390 // For now, upcasts are limited to changes in marker
1391 // traits, and hence never actually require an actual
1392 // change to the vtable.
1397 self.write_value(valty, dest)
1399 (_, &ty::TyDynamic(ref data, _)) => {
1400 let trait_ref = data.principal().unwrap().with_self_ty(
1404 let trait_ref = self.tcx.erase_regions(&trait_ref);
1405 let vtable = self.get_vtable(src_pointee_ty, trait_ref)?;
1406 let ptr = self.into_ptr(src)?;
1408 value: ptr.to_value_with_vtable(vtable),
1411 self.write_value(valty, dest)
1414 _ => bug!("invalid unsizing {:?} -> {:?}", src_ty, dest_ty),
1421 src_layout: TyLayout<'tcx>,
1423 dst_layout: TyLayout<'tcx>,
1424 ) -> EvalResult<'tcx> {
1425 match (&src_layout.ty.sty, &dst_layout.ty.sty) {
1426 (&ty::TyRef(_, ref s), &ty::TyRef(_, ref d)) |
1427 (&ty::TyRef(_, ref s), &ty::TyRawPtr(ref d)) |
1428 (&ty::TyRawPtr(ref s), &ty::TyRawPtr(ref d)) => {
1429 self.unsize_into_ptr(src, src_layout.ty, dst, dst_layout.ty, s.ty, d.ty)
1431 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
1432 assert_eq!(def_a, def_b);
1433 if def_a.is_box() || def_b.is_box() {
1434 if !def_a.is_box() || !def_b.is_box() {
1435 bug!("invalid unsizing between {:?} -> {:?}", src_layout, dst_layout);
1437 return self.unsize_into_ptr(
1442 src_layout.ty.boxed_ty(),
1443 dst_layout.ty.boxed_ty(),
1447 // unsizing of generic struct with pointer fields
1448 // Example: `Arc<T>` -> `Arc<Trait>`
1449 // here we need to increase the size of every &T thin ptr field to a fat ptr
1450 for i in 0..src_layout.fields.count() {
1451 let (dst_f_place, dst_field) =
1452 self.place_field(dst, mir::Field::new(i), dst_layout)?;
1453 if dst_field.is_zst() {
1456 let (src_f_value, src_field) = match src {
1457 Value::ByRef(ptr, align) => {
1458 let src_place = Place::from_primval_ptr(ptr, align);
1459 let (src_f_place, src_field) =
1460 self.place_field(src_place, mir::Field::new(i), src_layout)?;
1461 (self.read_place(src_f_place)?, src_field)
1463 Value::ByVal(_) | Value::ByValPair(..) => {
1464 let src_field = src_layout.field(&self, i)?;
1465 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
1466 assert_eq!(src_field.size, src_layout.size);
1470 if src_field.ty == dst_field.ty {
1471 self.write_value(ValTy {
1476 self.unsize_into(src_f_value, src_field, dst_f_place, dst_field)?;
1483 "unsize_into: invalid conversion: {:?} -> {:?}",
1491 pub fn dump_local(&self, place: Place) {
1494 Place::Local { frame, local } => {
1495 let mut allocs = Vec::new();
1496 let mut msg = format!("{:?}", local);
1497 if frame != self.cur_frame() {
1498 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
1500 write!(msg, ":").unwrap();
1502 match self.stack[frame].get_local(local) {
1503 Err(EvalError { kind: EvalErrorKind::DeadLocal, .. }) => {
1504 write!(msg, " is dead").unwrap();
1507 panic!("Failed to access local: {:?}", err);
1509 Ok(Value::ByRef(ptr, align)) => {
1510 match ptr.into_inner_primval() {
1511 PrimVal::Ptr(ptr) => {
1512 write!(msg, " by align({}) ref:", align.abi()).unwrap();
1513 allocs.push(ptr.alloc_id);
1515 ptr => write!(msg, " integral by ref: {:?}", ptr).unwrap(),
1518 Ok(Value::ByVal(val)) => {
1519 write!(msg, " {:?}", val).unwrap();
1520 if let PrimVal::Ptr(ptr) = val {
1521 allocs.push(ptr.alloc_id);
1524 Ok(Value::ByValPair(val1, val2)) => {
1525 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
1526 if let PrimVal::Ptr(ptr) = val1 {
1527 allocs.push(ptr.alloc_id);
1529 if let PrimVal::Ptr(ptr) = val2 {
1530 allocs.push(ptr.alloc_id);
1536 self.memory.dump_allocs(allocs);
1538 Place::Ptr { ptr, align, .. } => {
1539 match ptr.into_inner_primval() {
1540 PrimVal::Ptr(ptr) => {
1541 trace!("by align({}) ref:", align.abi());
1542 self.memory.dump_alloc(ptr.alloc_id);
1544 ptr => trace!(" integral by ref: {:?}", ptr),
1550 /// Convenience function to ensure correct usage of locals
1551 pub fn modify_local<F>(&mut self, frame: usize, local: mir::Local, f: F) -> EvalResult<'tcx>
1553 F: FnOnce(&mut Self, Value) -> EvalResult<'tcx, Value>,
1555 let val = self.stack[frame].get_local(local)?;
1556 let new_val = f(self, val)?;
1557 self.stack[frame].set_local(local, new_val)?;
1558 // FIXME(solson): Run this when setting to Undef? (See previous version of this code.)
1559 // if let Value::ByRef(ptr) = self.stack[frame].get_local(local) {
1560 // self.memory.deallocate(ptr)?;
1565 pub fn report(&self, e: &mut EvalError) {
1566 if let Some(ref mut backtrace) = e.backtrace {
1567 let mut trace_text = "\n\nAn error occurred in miri:\n".to_string();
1568 backtrace.resolve();
1569 write!(trace_text, "backtrace frames: {}\n", backtrace.frames().len()).unwrap();
1570 'frames: for (i, frame) in backtrace.frames().iter().enumerate() {
1571 if frame.symbols().is_empty() {
1572 write!(trace_text, "{}: no symbols\n", i).unwrap();
1574 for symbol in frame.symbols() {
1575 write!(trace_text, "{}: ", i).unwrap();
1576 if let Some(name) = symbol.name() {
1577 write!(trace_text, "{}\n", name).unwrap();
1579 write!(trace_text, "<unknown>\n").unwrap();
1581 write!(trace_text, "\tat ").unwrap();
1582 if let Some(file_path) = symbol.filename() {
1583 write!(trace_text, "{}", file_path.display()).unwrap();
1585 write!(trace_text, "<unknown_file>").unwrap();
1587 if let Some(line) = symbol.lineno() {
1588 write!(trace_text, ":{}\n", line).unwrap();
1590 write!(trace_text, "\n").unwrap();
1594 error!("{}", trace_text);
1596 if let Some(frame) = self.stack().last() {
1597 let block = &frame.mir.basic_blocks()[frame.block];
1598 let span = if frame.stmt < block.statements.len() {
1599 block.statements[frame.stmt].source_info.span
1601 block.terminator().source_info.span
1603 let mut err = self.tcx.sess.struct_span_err(span, &e.to_string());
1604 for &Frame { instance, span, .. } in self.stack().iter().rev() {
1605 if self.tcx.def_key(instance.def_id()).disambiguated_data.data ==
1606 DefPathData::ClosureExpr
1608 err.span_note(span, "inside call to closure");
1611 err.span_note(span, &format!("inside call to {}", instance));
1615 self.tcx.sess.err(&e.to_string());
1620 impl<'tcx> Frame<'tcx> {
1621 pub fn get_local(&self, local: mir::Local) -> EvalResult<'tcx, Value> {
1622 // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1623 self.locals[local.index() - 1].ok_or(EvalErrorKind::DeadLocal.into())
1626 fn set_local(&mut self, local: mir::Local, value: Value) -> EvalResult<'tcx> {
1627 // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1628 match self.locals[local.index() - 1] {
1629 None => err!(DeadLocal),
1630 Some(ref mut local) => {
1637 pub fn storage_live(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
1638 trace!("{:?} is now live", local);
1640 let old = self.locals[local.index() - 1];
1641 self.locals[local.index() - 1] = Some(Value::ByVal(PrimVal::Undef)); // StorageLive *always* kills the value that's currently stored
1645 /// Returns the old value of the local
1646 pub fn storage_dead(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
1647 trace!("{:?} is now dead", local);
1649 let old = self.locals[local.index() - 1];
1650 self.locals[local.index() - 1] = None;
1655 // TODO(solson): Upstream these methods into rustc::ty::layout.
1657 pub fn resolve_drop_in_place<'a, 'tcx>(
1658 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1660 ) -> ty::Instance<'tcx> {
1661 let def_id = tcx.require_lang_item(::rustc::middle::lang_items::DropInPlaceFnLangItem);
1662 let substs = tcx.intern_substs(&[Kind::from(ty)]);
1663 ty::Instance::resolve(tcx, ty::ParamEnv::empty(Reveal::All), def_id, substs).unwrap()