1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use syntax::source_map::{self, Span, DUMMY_SP};
15 use rustc::hir::def_id::DefId;
16 use rustc::hir::def::Def;
18 use rustc::ty::layout::{
19 self, Size, Align, HasDataLayout, LayoutOf, TyLayout
21 use rustc::ty::subst::{Subst, Substs};
22 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
23 use rustc::ty::query::TyCtxtAt;
24 use rustc_data_structures::indexed_vec::IndexVec;
25 use rustc::mir::interpret::{
27 GlobalId, Scalar, FrameInfo, AllocId,
28 EvalResult, EvalErrorKind,
29 truncate, sign_extend,
31 use rustc_data_structures::fx::FxHashMap;
34 Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
38 pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
39 /// Stores the `Machine` instance.
42 /// The results of the type checker, from rustc.
43 pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
45 /// Bounds in scope for polymorphic evaluations.
46 pub(crate) param_env: ty::ParamEnv<'tcx>,
48 /// The virtual memory system.
49 pub(crate) memory: Memory<'a, 'mir, 'tcx, M>,
51 /// The virtual call stack.
52 pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
54 /// A cache for deduplicating vtables
55 pub(super) vtables: FxHashMap<(Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>), AllocId>,
60 pub struct Frame<'mir, 'tcx: 'mir, Tag=(), Extra=()> {
61 ////////////////////////////////////////////////////////////////////////////////
62 // Function and callsite information
63 ////////////////////////////////////////////////////////////////////////////////
64 /// The MIR for the function called on this frame.
65 pub mir: &'mir mir::Mir<'tcx>,
67 /// The def_id and substs of the current function
68 pub instance: ty::Instance<'tcx>,
70 /// The span of the call site.
71 pub span: source_map::Span,
73 ////////////////////////////////////////////////////////////////////////////////
74 // Return place and locals
75 ////////////////////////////////////////////////////////////////////////////////
76 /// Work to perform when returning from this function
77 pub return_to_block: StackPopCleanup,
79 /// The location where the result of the current stack frame should be written to,
80 /// and its layout in the caller.
81 pub return_place: Option<PlaceTy<'tcx, Tag>>,
83 /// The list of locals for this stack frame, stored in order as
84 /// `[return_ptr, arguments..., variables..., temporaries...]`.
85 /// The locals are stored as `Option<Value>`s.
86 /// `None` represents a local that is currently dead, while a live local
87 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
88 pub locals: IndexVec<mir::Local, LocalValue<Tag>>,
90 ////////////////////////////////////////////////////////////////////////////////
91 // Current position within the function
92 ////////////////////////////////////////////////////////////////////////////////
93 /// The block that is currently executed (or will be executed after the above call stacks
95 pub block: mir::BasicBlock,
97 /// The index of the currently evaluated statement.
100 /// Extra data for the machine
104 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
105 pub enum StackPopCleanup {
106 /// Jump to the next block in the caller, or cause UB if None (that's a function
107 /// that may never return). Also store layout of return place so
108 /// we can validate it at that layout.
109 Goto(Option<mir::BasicBlock>),
110 /// Just do nohing: Used by Main and for the box_alloc hook in miri.
111 /// `cleanup` says whether locals are deallocated. Static computation
112 /// wants them leaked to intern what they need (and just throw away
113 /// the entire `ecx` when it is done).
114 None { cleanup: bool },
117 // State of a local variable
118 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
119 pub enum LocalValue<Tag=(), Id=AllocId> {
121 // Mostly for convenience, we re-use the `Operand` type here.
122 // This is an optimization over just always having a pointer here;
123 // we can thus avoid doing an allocation when the local just stores
124 // immediate values *and* never has its address taken.
125 Live(Operand<Tag, Id>),
128 impl<'tcx, Tag> LocalValue<Tag> {
129 pub fn access(&self) -> EvalResult<'tcx, &Operand<Tag>> {
131 LocalValue::Dead => err!(DeadLocal),
132 LocalValue::Live(ref val) => Ok(val),
136 pub fn access_mut(&mut self) -> EvalResult<'tcx, &mut Operand<Tag>> {
138 LocalValue::Dead => err!(DeadLocal),
139 LocalValue::Live(ref mut val) => Ok(val),
144 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
145 for EvalContext<'a, 'mir, 'tcx, M>
148 fn data_layout(&self) -> &layout::TargetDataLayout {
149 &self.tcx.data_layout
153 impl<'a, 'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for EvalContext<'a, 'mir, 'tcx, M>
154 where M: Machine<'a, 'mir, 'tcx>
157 fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
162 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> LayoutOf
163 for EvalContext<'a, 'mir, 'tcx, M>
166 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
169 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
170 self.tcx.layout_of(self.param_env.and(ty))
171 .map_err(|layout| EvalErrorKind::Layout(layout).into())
175 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
177 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
178 param_env: ty::ParamEnv<'tcx>,
185 memory: Memory::new(tcx),
187 vtables: FxHashMap::default(),
192 pub fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
197 pub fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
202 pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
207 pub fn cur_frame(&self) -> usize {
208 assert!(self.stack.len() > 0);
213 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
214 self.stack.last().expect("no call frames exist")
218 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
219 self.stack.last_mut().expect("no call frames exist")
223 pub(super) fn mir(&self) -> &'mir mir::Mir<'tcx> {
227 pub fn substs(&self) -> &'tcx Substs<'tcx> {
228 if let Some(frame) = self.stack.last() {
229 frame.instance.substs
235 pub(super) fn resolve(
238 substs: &'tcx Substs<'tcx>
239 ) -> EvalResult<'tcx, ty::Instance<'tcx>> {
240 trace!("resolve: {:?}, {:#?}", def_id, substs);
241 trace!("substs: {:#?}", self.substs());
242 trace!("param_env: {:#?}", self.param_env);
243 let substs = self.tcx.subst_and_normalize_erasing_regions(
248 ty::Instance::resolve(
253 ).ok_or_else(|| EvalErrorKind::TooGeneric.into())
256 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
257 ty.is_sized(self.tcx, self.param_env)
260 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
261 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
266 instance: ty::InstanceDef<'tcx>,
267 ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
268 // do not continue if typeck errors occurred (can only occur in local crate)
269 let did = instance.def_id();
271 && self.tcx.has_typeck_tables(did)
272 && self.tcx.typeck_tables_of(did).tainted_by_errors
274 return err!(TypeckError);
276 trace!("load mir {:?}", instance);
278 ty::InstanceDef::Item(def_id) => {
279 self.tcx.maybe_optimized_mir(def_id).ok_or_else(||
280 EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
283 _ => Ok(self.tcx.instance_mir(instance)),
287 pub fn monomorphize<T: TypeFoldable<'tcx> + Subst<'tcx>>(
290 substs: &'tcx Substs<'tcx>
292 // miri doesn't care about lifetimes, and will choke on some crazy ones
293 // let's simply get rid of them
294 let substituted = t.subst(*self.tcx, substs);
295 self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substituted)
298 pub fn layout_of_local(
300 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
302 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
303 let local_ty = frame.mir.local_decls[local].ty;
304 let local_ty = self.monomorphize(local_ty, frame.instance.substs);
305 self.layout_of(local_ty)
308 pub fn str_to_immediate(&mut self, s: &str) -> EvalResult<'tcx, Immediate<M::PointerTag>> {
309 let ptr = self.memory.allocate_static_bytes(s.as_bytes()).with_default_tag();
310 Ok(Immediate::new_slice(Scalar::Ptr(ptr), s.len() as u64, self))
313 /// Return the actual dynamic size and alignment of the place at the given type.
314 /// Only the "meta" (metadata) part of the place matters.
315 /// This can fail to provide an answer for extern types.
316 pub(super) fn size_and_align_of(
318 metadata: Option<Scalar<M::PointerTag>>,
319 layout: TyLayout<'tcx>,
320 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
321 if !layout.is_unsized() {
322 return Ok(Some((layout.size, layout.align.abi)));
324 match layout.ty.sty {
325 ty::Adt(..) | ty::Tuple(..) => {
326 // First get the size of all statically known fields.
327 // Don't use type_of::sizing_type_of because that expects t to be sized,
328 // and it also rounds up to alignment, which we want to avoid,
329 // as the unsized field's alignment could be smaller.
330 assert!(!layout.ty.is_simd());
331 trace!("DST layout: {:?}", layout);
333 let sized_size = layout.fields.offset(layout.fields.count() - 1);
334 let sized_align = layout.align.abi;
336 "DST {} statically sized prefix size: {:?} align: {:?}",
342 // Recurse to get the size of the dynamically sized field (must be
343 // the last field). Can't have foreign types here, how would we
344 // adjust alignment and size for them?
345 let field = layout.field(self, layout.fields.count() - 1)?;
346 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
347 Some(size_and_align) => size_and_align,
349 // A field with extern type. If this field is at offset 0, we behave
350 // like the underlying extern type.
351 // FIXME: Once we have made decisions for how to handle size and alignment
352 // of `extern type`, this should be adapted. It is just a temporary hack
353 // to get some code to work that probably ought to work.
354 if sized_size == Size::ZERO {
357 bug!("Fields cannot be extern types, unless they are at offset 0")
362 // FIXME (#26403, #27023): We should be adding padding
363 // to `sized_size` (to accommodate the `unsized_align`
364 // required of the unsized field that follows) before
365 // summing it with `sized_size`. (Note that since #26403
366 // is unfixed, we do not yet add the necessary padding
367 // here. But this is where the add would go.)
369 // Return the sum of sizes and max of aligns.
370 let size = sized_size + unsized_size;
372 // Choose max of two known alignments (combined value must
373 // be aligned according to more restrictive of the two).
374 let align = sized_align.max(unsized_align);
376 // Issue #27023: must add any necessary padding to `size`
377 // (to make it a multiple of `align`) before returning it.
379 // Namely, the returned size should be, in C notation:
381 // `size + ((size & (align-1)) ? align : 0)`
383 // emulated via the semi-standard fast bit trick:
385 // `(size + (align-1)) & -align`
387 Ok(Some((size.align_to(align), align)))
390 let vtable = metadata.expect("dyn trait fat ptr must have vtable").to_ptr()?;
391 // the second entry in the vtable is the dynamic size of the object.
392 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
395 ty::Slice(_) | ty::Str => {
396 let len = metadata.expect("slice fat ptr must have vtable").to_usize(self)?;
397 let elem = layout.field(self, 0)?;
398 Ok(Some((elem.size * len, elem.align.abi)))
405 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
409 pub fn size_and_align_of_mplace(
411 mplace: MPlaceTy<'tcx, M::PointerTag>
412 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
413 self.size_and_align_of(mplace.meta, mplace.layout)
416 pub fn push_stack_frame(
418 instance: ty::Instance<'tcx>,
419 span: source_map::Span,
420 mir: &'mir mir::Mir<'tcx>,
421 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
422 return_to_block: StackPopCleanup,
423 ) -> EvalResult<'tcx> {
424 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
425 info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
427 ::log_settings::settings().indentation += 1;
429 // first push a stack frame so we have access to the local substs
430 let extra = M::stack_push(self)?;
431 self.stack.push(Frame {
433 block: mir::START_BLOCK,
436 // empty local array, we fill it in below, after we are inside the stack frame and
437 // all methods actually know about the frame
438 locals: IndexVec::new(),
445 // don't allocate at all for trivial constants
446 if mir.local_decls.len() > 1 {
447 // We put some marker immediate into the locals that we later want to initialize.
448 // This can be anything except for LocalValue::Dead -- because *that* is the
449 // value we use for things that we know are initially dead.
451 LocalValue::Live(Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)));
452 let mut locals = IndexVec::from_elem(dummy, &mir.local_decls);
453 // Return place is handled specially by the `eval_place` functions, and the
454 // entry in `locals` should never be used. Make it dead, to be sure.
455 locals[mir::RETURN_PLACE] = LocalValue::Dead;
456 // Now mark those locals as dead that we do not want to initialize
457 match self.tcx.describe_def(instance.def_id()) {
458 // statics and constants don't have `Storage*` statements, no need to look for them
459 Some(Def::Static(..)) | Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {},
461 trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len());
462 for block in mir.basic_blocks() {
463 for stmt in block.statements.iter() {
464 use rustc::mir::StatementKind::{StorageDead, StorageLive};
467 StorageDead(local) => {
468 locals[local] = LocalValue::Dead;
476 // Finally, properly initialize all those that still have the dummy value
477 for (local, decl) in locals.iter_mut().zip(mir.local_decls.iter()) {
479 LocalValue::Live(_) => {
480 // This needs to be peoperly initialized.
481 let layout = self.layout_of(self.monomorphize(decl.ty, instance.substs))?;
482 *local = LocalValue::Live(self.uninit_operand(layout)?);
484 LocalValue::Dead => {
490 self.frame_mut().locals = locals;
493 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
494 info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
497 if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit {
498 err!(StackFrameLimitReached)
504 pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
505 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
506 info!("LEAVING({}) {}", self.cur_frame(), self.frame().instance);
508 ::log_settings::settings().indentation -= 1;
509 let frame = self.stack.pop().expect(
510 "tried to pop a stack frame, but there were none",
512 M::stack_pop(self, frame.extra)?;
513 // Abort early if we do not want to clean up: We also avoid validation in that case,
514 // because this is CTFE and the final value will be thoroughly validated anyway.
515 match frame.return_to_block {
516 StackPopCleanup::Goto(_) => {},
517 StackPopCleanup::None { cleanup } => {
519 assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
520 // Leak the locals, skip validation.
525 // Deallocate all locals that are backed by an allocation.
526 for local in frame.locals {
527 self.deallocate_local(local)?;
529 // Validate the return value. Do this after deallocating so that we catch dangling
531 if let Some(return_place) = frame.return_place {
532 if M::enforce_validity(self) {
533 // Data got changed, better make sure it matches the type!
534 // It is still possible that the return place held invalid data while
535 // the function is running, but that's okay because nobody could have
536 // accessed that same data from the "outside" to observe any broken
537 // invariant -- that is, unless a function somehow has a ptr to
538 // its return place... but the way MIR is currently generated, the
539 // return place is always a local and then this cannot happen.
540 self.validate_operand(
541 self.place_to_op(return_place)?,
548 // Uh, that shouldn't happen... the function did not intend to return
549 return err!(Unreachable);
551 // Jump to new block -- *after* validation so that the spans make more sense.
552 match frame.return_to_block {
553 StackPopCleanup::Goto(block) => {
554 self.goto_block(block)?;
556 StackPopCleanup::None { .. } => {}
559 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
560 info!("CONTINUING({}) {}", self.cur_frame(), self.frame().instance);
566 /// Mark a storage as live, killing the previous content and returning it.
567 /// Remember to deallocate that!
571 ) -> EvalResult<'tcx, LocalValue<M::PointerTag>> {
572 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
573 trace!("{:?} is now live", local);
575 let layout = self.layout_of_local(self.frame(), local)?;
576 let init = LocalValue::Live(self.uninit_operand(layout)?);
577 // StorageLive *always* kills the value that's currently stored
578 Ok(mem::replace(&mut self.frame_mut().locals[local], init))
581 /// Returns the old value of the local.
582 /// Remember to deallocate that!
583 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
584 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
585 trace!("{:?} is now dead", local);
587 mem::replace(&mut self.frame_mut().locals[local], LocalValue::Dead)
590 pub(super) fn deallocate_local(
592 local: LocalValue<M::PointerTag>,
593 ) -> EvalResult<'tcx> {
594 // FIXME: should we tell the user that there was a local which was never written to?
595 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
596 trace!("deallocating local");
597 let ptr = ptr.to_ptr()?;
598 self.memory.dump_alloc(ptr.alloc_id);
599 self.memory.deallocate_local(ptr)?;
604 pub fn const_eval_raw(
607 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
608 let param_env = if self.tcx.is_static(gid.instance.def_id()).is_some() {
609 ty::ParamEnv::reveal_all()
613 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
614 // Our result will later be validated anyway, and there seems no good reason
615 // to have to fail early here. This is also more consistent with
616 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
617 let val = self.tcx.const_eval_raw(param_env.and(gid)).map_err(|err| {
619 ErrorHandled::Reported => EvalErrorKind::ReferencedConstant,
620 ErrorHandled::TooGeneric => EvalErrorKind::TooGeneric,
623 self.raw_const_to_mplace(val)
626 pub fn dump_place(&self, place: Place<M::PointerTag>) {
628 if !log_enabled!(::log::Level::Trace) {
632 Place::Local { frame, local } => {
633 let mut allocs = Vec::new();
634 let mut msg = format!("{:?}", local);
635 if frame != self.cur_frame() {
636 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
638 write!(msg, ":").unwrap();
640 match self.stack[frame].locals[local].access() {
642 if let EvalErrorKind::DeadLocal = err.kind {
643 write!(msg, " is dead").unwrap();
645 panic!("Failed to access local: {:?}", err);
648 Ok(Operand::Indirect(mplace)) => {
649 let (ptr, align) = mplace.to_scalar_ptr_align();
651 Scalar::Ptr(ptr) => {
652 write!(msg, " by align({}) ref:", align.bytes()).unwrap();
653 allocs.push(ptr.alloc_id);
655 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
658 Ok(Operand::Immediate(Immediate::Scalar(val))) => {
659 write!(msg, " {:?}", val).unwrap();
660 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
661 allocs.push(ptr.alloc_id);
664 Ok(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
665 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
666 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
667 allocs.push(ptr.alloc_id);
669 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
670 allocs.push(ptr.alloc_id);
676 self.memory.dump_allocs(allocs);
678 Place::Ptr(mplace) => {
680 Scalar::Ptr(ptr) => {
681 trace!("by align({}) ref:", mplace.align.bytes());
682 self.memory.dump_alloc(ptr.alloc_id);
684 ptr => trace!(" integral by ref: {:?}", ptr),
690 pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
691 let mut last_span = None;
692 let mut frames = Vec::new();
693 for &Frame { instance, span, mir, block, stmt, .. } in self.stack().iter().rev() {
694 // make sure we don't emit frames that are duplicates of the previous
695 if explicit_span == Some(span) {
696 last_span = Some(span);
699 if let Some(last) = last_span {
704 last_span = Some(span);
706 let block = &mir.basic_blocks()[block];
707 let source_info = if stmt < block.statements.len() {
708 block.statements[stmt].source_info
710 block.terminator().source_info
712 let lint_root = match mir.source_scope_local_data {
713 mir::ClearCrossCrate::Set(ref ivs) => Some(ivs[source_info.scope].lint_root),
714 mir::ClearCrossCrate::Clear => None,
716 frames.push(FrameInfo { call_site: span, instance, lint_root });
718 trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
723 pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
724 assert!(ty.abi.is_signed());
725 sign_extend(value, ty.size)
729 pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
730 truncate(value, ty.size)