4 use syntax::source_map::{self, Span, DUMMY_SP};
5 use rustc::hir::def_id::DefId;
6 use rustc::hir::def::Def;
8 use rustc::ty::layout::{
9 self, Size, Align, HasDataLayout, LayoutOf, TyLayout
11 use rustc::ty::subst::{Subst, Substs};
12 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
13 use rustc::ty::query::TyCtxtAt;
14 use rustc_data_structures::indexed_vec::IndexVec;
15 use rustc::mir::interpret::{
17 GlobalId, Scalar, FrameInfo, AllocId,
18 EvalResult, EvalErrorKind,
19 truncate, sign_extend,
21 use rustc_data_structures::fx::FxHashMap;
24 Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
28 pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
29 /// Stores the `Machine` instance.
32 /// The results of the type checker, from rustc.
33 pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
35 /// Bounds in scope for polymorphic evaluations.
36 pub(crate) param_env: ty::ParamEnv<'tcx>,
38 /// The virtual memory system.
39 pub(crate) memory: Memory<'a, 'mir, 'tcx, M>,
41 /// The virtual call stack.
42 pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
44 /// A cache for deduplicating vtables
45 pub(super) vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), AllocId>,
50 pub struct Frame<'mir, 'tcx: 'mir, Tag=(), Extra=()> {
51 ////////////////////////////////////////////////////////////////////////////////
52 // Function and callsite information
53 ////////////////////////////////////////////////////////////////////////////////
54 /// The MIR for the function called on this frame.
55 pub mir: &'mir 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: source_map::Span,
63 ////////////////////////////////////////////////////////////////////////////////
64 // Return place and locals
65 ////////////////////////////////////////////////////////////////////////////////
66 /// Work to perform when returning from this function
67 pub return_to_block: StackPopCleanup,
69 /// The location where the result of the current stack frame should be written to,
70 /// and its layout in the caller.
71 pub return_place: Option<PlaceTy<'tcx, Tag>>,
73 /// The list of locals for this stack frame, stored in order as
74 /// `[return_ptr, arguments..., variables..., temporaries...]`.
75 /// The locals are stored as `Option<Value>`s.
76 /// `None` represents a local that is currently dead, while a live local
77 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
78 pub locals: IndexVec<mir::Local, LocalValue<Tag>>,
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 statement.
90 /// Extra data for the machine
94 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
95 pub enum StackPopCleanup {
96 /// Jump to the next block in the caller, or cause UB if None (that's a function
97 /// that may never return). Also store layout of return place so
98 /// we can validate it at that layout.
99 Goto(Option<mir::BasicBlock>),
100 /// Just do nohing: Used by Main and for the box_alloc hook in miri.
101 /// `cleanup` says whether locals are deallocated. Static computation
102 /// wants them leaked to intern what they need (and just throw away
103 /// the entire `ecx` when it is done).
104 None { cleanup: bool },
107 // State of a local variable
108 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
109 pub enum LocalValue<Tag=(), Id=AllocId> {
111 // Mostly for convenience, we re-use the `Operand` type here.
112 // This is an optimization over just always having a pointer here;
113 // we can thus avoid doing an allocation when the local just stores
114 // immediate values *and* never has its address taken.
115 Live(Operand<Tag, Id>),
118 impl<'tcx, Tag> LocalValue<Tag> {
119 pub fn access(&self) -> EvalResult<'tcx, &Operand<Tag>> {
121 LocalValue::Dead => err!(DeadLocal),
122 LocalValue::Live(ref val) => Ok(val),
126 pub fn access_mut(&mut self) -> EvalResult<'tcx, &mut Operand<Tag>> {
128 LocalValue::Dead => err!(DeadLocal),
129 LocalValue::Live(ref mut val) => Ok(val),
134 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
135 for EvalContext<'a, 'mir, 'tcx, M>
138 fn data_layout(&self) -> &layout::TargetDataLayout {
139 &self.tcx.data_layout
143 impl<'a, 'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for EvalContext<'a, 'mir, 'tcx, M>
144 where M: Machine<'a, 'mir, 'tcx>
147 fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
152 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> LayoutOf
153 for EvalContext<'a, 'mir, 'tcx, M>
156 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
159 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
160 self.tcx.layout_of(self.param_env.and(ty))
161 .map_err(|layout| EvalErrorKind::Layout(layout).into())
165 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
167 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
168 param_env: ty::ParamEnv<'tcx>,
175 memory: Memory::new(tcx),
177 vtables: FxHashMap::default(),
182 pub fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
187 pub fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
192 pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
197 pub fn cur_frame(&self) -> usize {
198 assert!(self.stack.len() > 0);
203 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
204 self.stack.last().expect("no call frames exist")
208 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
209 self.stack.last_mut().expect("no call frames exist")
213 pub(super) fn mir(&self) -> &'mir mir::Mir<'tcx> {
217 pub fn substs(&self) -> &'tcx Substs<'tcx> {
218 if let Some(frame) = self.stack.last() {
219 frame.instance.substs
225 pub(super) fn resolve(
228 substs: &'tcx Substs<'tcx>
229 ) -> EvalResult<'tcx, ty::Instance<'tcx>> {
230 trace!("resolve: {:?}, {:#?}", def_id, substs);
231 trace!("substs: {:#?}", self.substs());
232 trace!("param_env: {:#?}", self.param_env);
233 let substs = self.tcx.subst_and_normalize_erasing_regions(
238 ty::Instance::resolve(
243 ).ok_or_else(|| EvalErrorKind::TooGeneric.into())
246 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
247 ty.is_sized(self.tcx, self.param_env)
250 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
251 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
256 instance: ty::InstanceDef<'tcx>,
257 ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
258 // do not continue if typeck errors occurred (can only occur in local crate)
259 let did = instance.def_id();
261 && self.tcx.has_typeck_tables(did)
262 && self.tcx.typeck_tables_of(did).tainted_by_errors
264 return err!(TypeckError);
266 trace!("load mir {:?}", instance);
268 ty::InstanceDef::Item(def_id) => {
269 self.tcx.maybe_optimized_mir(def_id).ok_or_else(||
270 EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
273 _ => Ok(self.tcx.instance_mir(instance)),
277 pub fn monomorphize<T: TypeFoldable<'tcx> + Subst<'tcx>>(
280 substs: &'tcx Substs<'tcx>
282 // miri doesn't care about lifetimes, and will choke on some crazy ones
283 // let's simply get rid of them
284 let substituted = t.subst(*self.tcx, substs);
285 self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substituted)
288 pub fn layout_of_local(
290 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
292 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
293 let local_ty = frame.mir.local_decls[local].ty;
294 let local_ty = self.monomorphize(local_ty, frame.instance.substs);
295 self.layout_of(local_ty)
298 pub fn str_to_immediate(&mut self, s: &str) -> EvalResult<'tcx, Immediate<M::PointerTag>> {
299 let ptr = self.memory.allocate_static_bytes(s.as_bytes()).with_default_tag();
300 Ok(Immediate::new_slice(Scalar::Ptr(ptr), s.len() as u64, self))
303 /// Return the actual dynamic size and alignment of the place at the given type.
304 /// Only the "meta" (metadata) part of the place matters.
305 /// This can fail to provide an answer for extern types.
306 pub(super) fn size_and_align_of(
308 metadata: Option<Scalar<M::PointerTag>>,
309 layout: TyLayout<'tcx>,
310 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
311 if !layout.is_unsized() {
312 return Ok(Some((layout.size, layout.align.abi)));
314 match layout.ty.sty {
315 ty::Adt(..) | ty::Tuple(..) => {
316 // First get the size of all statically known fields.
317 // Don't use type_of::sizing_type_of because that expects t to be sized,
318 // and it also rounds up to alignment, which we want to avoid,
319 // as the unsized field's alignment could be smaller.
320 assert!(!layout.ty.is_simd());
321 trace!("DST layout: {:?}", layout);
323 let sized_size = layout.fields.offset(layout.fields.count() - 1);
324 let sized_align = layout.align.abi;
326 "DST {} statically sized prefix size: {:?} align: {:?}",
332 // Recurse to get the size of the dynamically sized field (must be
333 // the last field). Can't have foreign types here, how would we
334 // adjust alignment and size for them?
335 let field = layout.field(self, layout.fields.count() - 1)?;
336 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
337 Some(size_and_align) => size_and_align,
339 // A field with extern type. If this field is at offset 0, we behave
340 // like the underlying extern type.
341 // FIXME: Once we have made decisions for how to handle size and alignment
342 // of `extern type`, this should be adapted. It is just a temporary hack
343 // to get some code to work that probably ought to work.
344 if sized_size == Size::ZERO {
347 bug!("Fields cannot be extern types, unless they are at offset 0")
352 // FIXME (#26403, #27023): We should be adding padding
353 // to `sized_size` (to accommodate the `unsized_align`
354 // required of the unsized field that follows) before
355 // summing it with `sized_size`. (Note that since #26403
356 // is unfixed, we do not yet add the necessary padding
357 // here. But this is where the add would go.)
359 // Return the sum of sizes and max of aligns.
360 let size = sized_size + unsized_size;
362 // Choose max of two known alignments (combined value must
363 // be aligned according to more restrictive of the two).
364 let align = sized_align.max(unsized_align);
366 // Issue #27023: must add any necessary padding to `size`
367 // (to make it a multiple of `align`) before returning it.
369 // Namely, the returned size should be, in C notation:
371 // `size + ((size & (align-1)) ? align : 0)`
373 // emulated via the semi-standard fast bit trick:
375 // `(size + (align-1)) & -align`
377 Ok(Some((size.align_to(align), align)))
380 let vtable = metadata.expect("dyn trait fat ptr must have vtable").to_ptr()?;
381 // the second entry in the vtable is the dynamic size of the object.
382 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
385 ty::Slice(_) | ty::Str => {
386 let len = metadata.expect("slice fat ptr must have vtable").to_usize(self)?;
387 let elem = layout.field(self, 0)?;
388 Ok(Some((elem.size * len, elem.align.abi)))
395 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
399 pub fn size_and_align_of_mplace(
401 mplace: MPlaceTy<'tcx, M::PointerTag>
402 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
403 self.size_and_align_of(mplace.meta, mplace.layout)
406 pub fn push_stack_frame(
408 instance: ty::Instance<'tcx>,
409 span: source_map::Span,
410 mir: &'mir mir::Mir<'tcx>,
411 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
412 return_to_block: StackPopCleanup,
413 ) -> EvalResult<'tcx> {
414 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
415 info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
417 ::log_settings::settings().indentation += 1;
419 // first push a stack frame so we have access to the local substs
420 let extra = M::stack_push(self)?;
421 self.stack.push(Frame {
423 block: mir::START_BLOCK,
426 // empty local array, we fill it in below, after we are inside the stack frame and
427 // all methods actually know about the frame
428 locals: IndexVec::new(),
435 // don't allocate at all for trivial constants
436 if mir.local_decls.len() > 1 {
437 // We put some marker immediate into the locals that we later want to initialize.
438 // This can be anything except for LocalValue::Dead -- because *that* is the
439 // value we use for things that we know are initially dead.
441 LocalValue::Live(Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)));
442 let mut locals = IndexVec::from_elem(dummy, &mir.local_decls);
443 // Return place is handled specially by the `eval_place` functions, and the
444 // entry in `locals` should never be used. Make it dead, to be sure.
445 locals[mir::RETURN_PLACE] = LocalValue::Dead;
446 // Now mark those locals as dead that we do not want to initialize
447 match self.tcx.describe_def(instance.def_id()) {
448 // statics and constants don't have `Storage*` statements, no need to look for them
449 Some(Def::Static(..)) | Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {},
451 trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len());
452 for block in mir.basic_blocks() {
453 for stmt in block.statements.iter() {
454 use rustc::mir::StatementKind::{StorageDead, StorageLive};
457 StorageDead(local) => {
458 locals[local] = LocalValue::Dead;
466 // Finally, properly initialize all those that still have the dummy value
467 for (local, decl) in locals.iter_mut().zip(mir.local_decls.iter()) {
469 LocalValue::Live(_) => {
470 // This needs to be peoperly initialized.
471 let layout = self.layout_of(self.monomorphize(decl.ty, instance.substs))?;
472 *local = LocalValue::Live(self.uninit_operand(layout)?);
474 LocalValue::Dead => {
480 self.frame_mut().locals = locals;
483 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
484 info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
487 if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit {
488 err!(StackFrameLimitReached)
494 pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
495 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
496 info!("LEAVING({}) {}", self.cur_frame(), self.frame().instance);
498 ::log_settings::settings().indentation -= 1;
499 let frame = self.stack.pop().expect(
500 "tried to pop a stack frame, but there were none",
502 M::stack_pop(self, frame.extra)?;
503 // Abort early if we do not want to clean up: We also avoid validation in that case,
504 // because this is CTFE and the final value will be thoroughly validated anyway.
505 match frame.return_to_block {
506 StackPopCleanup::Goto(_) => {},
507 StackPopCleanup::None { cleanup } => {
509 assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
510 // Leak the locals, skip validation.
515 // Deallocate all locals that are backed by an allocation.
516 for local in frame.locals {
517 self.deallocate_local(local)?;
519 // Validate the return value. Do this after deallocating so that we catch dangling
521 if let Some(return_place) = frame.return_place {
522 if M::enforce_validity(self) {
523 // Data got changed, better make sure it matches the type!
524 // It is still possible that the return place held invalid data while
525 // the function is running, but that's okay because nobody could have
526 // accessed that same data from the "outside" to observe any broken
527 // invariant -- that is, unless a function somehow has a ptr to
528 // its return place... but the way MIR is currently generated, the
529 // return place is always a local and then this cannot happen.
530 self.validate_operand(
531 self.place_to_op(return_place)?,
538 // Uh, that shouldn't happen... the function did not intend to return
539 return err!(Unreachable);
541 // Jump to new block -- *after* validation so that the spans make more sense.
542 match frame.return_to_block {
543 StackPopCleanup::Goto(block) => {
544 self.goto_block(block)?;
546 StackPopCleanup::None { .. } => {}
549 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
550 info!("CONTINUING({}) {}", self.cur_frame(), self.frame().instance);
556 /// Mark a storage as live, killing the previous content and returning it.
557 /// Remember to deallocate that!
561 ) -> EvalResult<'tcx, LocalValue<M::PointerTag>> {
562 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
563 trace!("{:?} is now live", local);
565 let layout = self.layout_of_local(self.frame(), local)?;
566 let init = LocalValue::Live(self.uninit_operand(layout)?);
567 // StorageLive *always* kills the value that's currently stored
568 Ok(mem::replace(&mut self.frame_mut().locals[local], init))
571 /// Returns the old value of the local.
572 /// Remember to deallocate that!
573 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
574 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
575 trace!("{:?} is now dead", local);
577 mem::replace(&mut self.frame_mut().locals[local], LocalValue::Dead)
580 pub(super) fn deallocate_local(
582 local: LocalValue<M::PointerTag>,
583 ) -> EvalResult<'tcx> {
584 // FIXME: should we tell the user that there was a local which was never written to?
585 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
586 trace!("deallocating local");
587 let ptr = ptr.to_ptr()?;
588 self.memory.dump_alloc(ptr.alloc_id);
589 self.memory.deallocate_local(ptr)?;
594 pub fn const_eval_raw(
597 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
598 let param_env = if self.tcx.is_static(gid.instance.def_id()).is_some() {
599 ty::ParamEnv::reveal_all()
603 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
604 // Our result will later be validated anyway, and there seems no good reason
605 // to have to fail early here. This is also more consistent with
606 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
607 let val = self.tcx.const_eval_raw(param_env.and(gid)).map_err(|err| {
609 ErrorHandled::Reported => EvalErrorKind::ReferencedConstant,
610 ErrorHandled::TooGeneric => EvalErrorKind::TooGeneric,
613 self.raw_const_to_mplace(val)
616 pub fn dump_place(&self, place: Place<M::PointerTag>) {
618 if !log_enabled!(::log::Level::Trace) {
622 Place::Local { frame, local } => {
623 let mut allocs = Vec::new();
624 let mut msg = format!("{:?}", local);
625 if frame != self.cur_frame() {
626 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
628 write!(msg, ":").unwrap();
630 match self.stack[frame].locals[local].access() {
632 if let EvalErrorKind::DeadLocal = err.kind {
633 write!(msg, " is dead").unwrap();
635 panic!("Failed to access local: {:?}", err);
638 Ok(Operand::Indirect(mplace)) => {
639 let (ptr, align) = mplace.to_scalar_ptr_align();
641 Scalar::Ptr(ptr) => {
642 write!(msg, " by align({}) ref:", align.bytes()).unwrap();
643 allocs.push(ptr.alloc_id);
645 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
648 Ok(Operand::Immediate(Immediate::Scalar(val))) => {
649 write!(msg, " {:?}", val).unwrap();
650 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
651 allocs.push(ptr.alloc_id);
654 Ok(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
655 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
656 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
657 allocs.push(ptr.alloc_id);
659 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
660 allocs.push(ptr.alloc_id);
666 self.memory.dump_allocs(allocs);
668 Place::Ptr(mplace) => {
670 Scalar::Ptr(ptr) => {
671 trace!("by align({}) ref:", mplace.align.bytes());
672 self.memory.dump_alloc(ptr.alloc_id);
674 ptr => trace!(" integral by ref: {:?}", ptr),
680 pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
681 let mut last_span = None;
682 let mut frames = Vec::new();
683 for &Frame { instance, span, mir, block, stmt, .. } in self.stack().iter().rev() {
684 // make sure we don't emit frames that are duplicates of the previous
685 if explicit_span == Some(span) {
686 last_span = Some(span);
689 if let Some(last) = last_span {
694 last_span = Some(span);
696 let block = &mir.basic_blocks()[block];
697 let source_info = if stmt < block.statements.len() {
698 block.statements[stmt].source_info
700 block.terminator().source_info
702 let lint_root = match mir.source_scope_local_data {
703 mir::ClearCrossCrate::Set(ref ivs) => Some(ivs[source_info.scope].lint_root),
704 mir::ClearCrossCrate::Clear => None,
706 frames.push(FrameInfo { call_site: span, instance, lint_root });
708 trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
713 pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
714 assert!(ty.abi.is_signed());
715 sign_extend(value, ty.size)
719 pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
720 truncate(value, ty.size)