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.
11 //! Functions concerning immediate values and operands, and reading from operands.
12 //! All high-level functions to read from memory work on operands as sources.
14 use std::convert::TryInto;
17 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
19 use rustc::mir::interpret::{
21 ConstValue, Pointer, Scalar,
22 EvalResult, EvalErrorKind,
24 use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
25 pub use rustc::mir::interpret::ScalarMaybeUndef;
27 /// A `Value` represents a single immediate self-contained Rust value.
29 /// For optimization of a few very common cases, there is also a representation for a pair of
30 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
31 /// operations and fat pointers. This idea was taken from rustc's codegen.
32 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
33 /// defined on `Immediate`, and do not have to work with a `Place`.
34 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
35 pub enum Immediate<Tag=(), Id=AllocId> {
36 Scalar(ScalarMaybeUndef<Tag, Id>),
37 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
42 pub fn with_default_tag<Tag>(self) -> Immediate<Tag>
46 Immediate::Scalar(x) => Immediate::Scalar(x.with_default_tag()),
47 Immediate::ScalarPair(x, y) =>
48 Immediate::ScalarPair(x.with_default_tag(), y.with_default_tag()),
53 impl<'tcx, Tag> Immediate<Tag> {
55 pub fn erase_tag(self) -> Immediate
58 Immediate::Scalar(x) => Immediate::Scalar(x.erase_tag()),
59 Immediate::ScalarPair(x, y) =>
60 Immediate::ScalarPair(x.erase_tag(), y.erase_tag()),
67 cx: &impl HasDataLayout
69 Immediate::ScalarPair(
71 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
75 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
76 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
80 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
82 Immediate::Scalar(val) => val,
83 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
88 pub fn to_scalar(self) -> EvalResult<'tcx, Scalar<Tag>> {
89 self.to_scalar_or_undef().not_undef()
93 pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
95 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
96 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
100 /// Convert the immediate into a pointer (or a pointer-sized integer).
101 /// Throws away the second half of a ScalarPair!
103 pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar<Tag>> {
105 Immediate::Scalar(ptr) |
106 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
110 /// Convert the value into its metadata.
111 /// Throws away the first half of a ScalarPair!
113 pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
115 Immediate::Scalar(_) => None,
116 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
121 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
122 // as input for binary and cast operations.
123 #[derive(Copy, Clone, Debug)]
124 pub struct ImmTy<'tcx, Tag=()> {
125 immediate: Immediate<Tag>,
126 pub layout: TyLayout<'tcx>,
129 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
130 type Target = Immediate<Tag>;
132 fn deref(&self) -> &Immediate<Tag> {
137 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
138 /// or still in memory. The latter is an optimization, to delay reading that chunk of
139 /// memory and to avoid having to store arbitrary-sized data here.
140 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
141 pub enum Operand<Tag=(), Id=AllocId> {
142 Immediate(Immediate<Tag, Id>),
143 Indirect(MemPlace<Tag, Id>),
148 pub fn with_default_tag<Tag>(self) -> Operand<Tag>
152 Operand::Immediate(x) => Operand::Immediate(x.with_default_tag()),
153 Operand::Indirect(x) => Operand::Indirect(x.with_default_tag()),
158 impl<Tag> Operand<Tag> {
160 pub fn erase_tag(self) -> Operand
163 Operand::Immediate(x) => Operand::Immediate(x.erase_tag()),
164 Operand::Indirect(x) => Operand::Indirect(x.erase_tag()),
169 pub fn to_mem_place(self) -> MemPlace<Tag>
170 where Tag: ::std::fmt::Debug
173 Operand::Indirect(mplace) => mplace,
174 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
180 pub fn to_immediate(self) -> Immediate<Tag>
181 where Tag: ::std::fmt::Debug
184 Operand::Immediate(imm) => imm,
185 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
191 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
192 pub struct OpTy<'tcx, Tag=()> {
193 crate op: Operand<Tag>, // ideally we'd make this private, but const_prop needs this
194 pub layout: TyLayout<'tcx>,
197 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
198 type Target = Operand<Tag>;
200 fn deref(&self) -> &Operand<Tag> {
205 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
207 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
209 op: Operand::Indirect(*mplace),
210 layout: mplace.layout
215 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
217 fn from(val: ImmTy<'tcx, Tag>) -> Self {
219 op: Operand::Immediate(val.immediate),
225 impl<'tcx, Tag> OpTy<'tcx, Tag>
228 pub fn erase_tag(self) -> OpTy<'tcx>
231 op: self.op.erase_tag(),
237 // Use the existing layout if given (but sanity check in debug mode),
238 // or compute the layout.
240 fn from_known_layout<'tcx>(
241 layout: Option<TyLayout<'tcx>>,
242 compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
243 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
247 if cfg!(debug_assertions) {
248 let layout2 = compute()?;
249 assert_eq!(layout.details, layout2.details,
250 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
251 layout.ty, layout2.ty);
258 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
259 /// Try reading an immediate in memory; this is interesting particularly for ScalarPair.
260 /// Return None if the layout does not permit loading this as a value.
261 pub(super) fn try_read_immediate_from_mplace(
263 mplace: MPlaceTy<'tcx, M::PointerTag>,
264 ) -> EvalResult<'tcx, Option<Immediate<M::PointerTag>>> {
265 if mplace.layout.is_unsized() {
266 // Don't touch unsized
269 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
271 if mplace.layout.is_zst() {
272 // Not all ZSTs have a layout we would handle below, so just short-circuit them
274 self.memory.check_align(ptr, ptr_align)?;
275 return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
278 // check for integer pointers before alignment to report better errors
279 let ptr = ptr.to_ptr()?;
280 self.memory.check_align(ptr.into(), ptr_align)?;
281 match mplace.layout.abi {
282 layout::Abi::Scalar(..) => {
283 let scalar = self.memory
285 .read_scalar(self, ptr, mplace.layout.size)?;
286 Ok(Some(Immediate::Scalar(scalar)))
288 layout::Abi::ScalarPair(ref a, ref b) => {
289 let (a, b) = (&a.value, &b.value);
290 let (a_size, b_size) = (a.size(self), b.size(self));
292 let b_offset = a_size.align_to(b.align(self).abi);
293 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
294 let b_ptr = ptr.offset(b_offset, self)?;
295 let a_val = self.memory
297 .read_scalar(self, a_ptr, a_size)?;
298 let b_align = ptr_align.restrict_for_offset(b_offset);
299 self.memory.check_align(b_ptr.into(), b_align)?;
300 let b_val = self.memory
302 .read_scalar(self, b_ptr, b_size)?;
303 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
309 /// Try returning an immediate for the operand.
310 /// If the layout does not permit loading this as an immediate, return where in memory
311 /// we can find the data.
312 /// Note that for a given layout, this operation will either always fail or always
313 /// succeed! Whether it succeeds depends on whether the layout can be represented
314 /// in a `Immediate`, not on which data is stored there currently.
315 pub(crate) fn try_read_immediate(
317 src: OpTy<'tcx, M::PointerTag>,
318 ) -> EvalResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
319 Ok(match src.try_as_mplace() {
321 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
331 /// Read an immediate from a place, asserting that that is possible with the given layout.
333 pub fn read_immediate(
335 op: OpTy<'tcx, M::PointerTag>
336 ) -> EvalResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
337 if let Ok(immediate) = self.try_read_immediate(op)? {
338 Ok(ImmTy { immediate, layout: op.layout })
340 bug!("primitive read failed for type: {:?}", op.layout.ty);
344 /// Read a scalar from a place
347 op: OpTy<'tcx, M::PointerTag>
348 ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
349 Ok(self.read_immediate(op)?.to_scalar_or_undef())
352 // Turn the MPlace into a string (must already be dereferenced!)
355 mplace: MPlaceTy<'tcx, M::PointerTag>,
356 ) -> EvalResult<'tcx, &str> {
357 let len = mplace.len(self)?;
358 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
359 let str = ::std::str::from_utf8(bytes)
360 .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
364 pub fn uninit_operand(
366 layout: TyLayout<'tcx>
367 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
368 // This decides which types we will use the Immediate optimization for, and hence should
369 // match what `try_read_immediate` and `eval_place_to_op` support.
371 return Ok(Operand::Immediate(Immediate::Scalar(Scalar::zst().into())));
374 Ok(match layout.abi {
375 layout::Abi::Scalar(..) =>
376 Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)),
377 layout::Abi::ScalarPair(..) =>
378 Operand::Immediate(Immediate::ScalarPair(
379 ScalarMaybeUndef::Undef,
380 ScalarMaybeUndef::Undef,
383 trace!("Forcing allocation for local of type {:?}", layout.ty);
385 *self.allocate(layout, MemoryKind::Stack)?
391 /// Projection functions
392 pub fn operand_field(
394 op: OpTy<'tcx, M::PointerTag>,
396 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
397 let base = match op.try_as_mplace() {
400 let field = self.mplace_field(mplace, field)?;
401 return Ok(field.into());
406 let field = field.try_into().unwrap();
407 let field_layout = op.layout.field(self, field)?;
408 if field_layout.is_zst() {
409 let immediate = Immediate::Scalar(Scalar::zst().into());
410 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
412 let offset = op.layout.fields.offset(field);
413 let immediate = match base {
414 // the field covers the entire type
415 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
416 // extract fields from types with `ScalarPair` ABI
417 Immediate::ScalarPair(a, b) => {
418 let val = if offset.bytes() == 0 { a } else { b };
419 Immediate::Scalar(val)
421 Immediate::Scalar(val) =>
422 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
424 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
427 pub fn operand_downcast(
429 op: OpTy<'tcx, M::PointerTag>,
431 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
432 // Downcasts only change the layout
433 Ok(match op.try_as_mplace() {
435 self.mplace_downcast(mplace, variant)?.into()
438 let layout = op.layout.for_variant(self, variant);
439 OpTy { layout, ..op }
444 pub fn operand_projection(
446 base: OpTy<'tcx, M::PointerTag>,
447 proj_elem: &mir::PlaceElem<'tcx>,
448 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
449 use rustc::mir::ProjectionElem::*;
450 Ok(match *proj_elem {
451 Field(field, _) => self.operand_field(base, field.index() as u64)?,
452 Downcast(_, variant) => self.operand_downcast(base, variant)?,
453 Deref => self.deref_operand(base)?.into(),
454 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
456 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
457 // the actual index doesn't matter, so we just pick a convenient one like 0
458 layout: base.layout.field(self, 0)?,
461 // The rest should only occur as mplace, we do not use Immediates for types
462 // allowing such operations. This matches place_projection forcing an allocation.
463 let mplace = base.to_mem_place();
464 self.mplace_projection(mplace, proj_elem)?.into()
469 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
471 /// When you know the layout of the local in advance, you can pass it as last argument
474 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
476 layout: Option<TyLayout<'tcx>>,
477 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
478 assert_ne!(local, mir::RETURN_PLACE);
479 let op = *frame.locals[local].access()?;
480 let layout = from_known_layout(layout,
481 || self.layout_of_local(frame, local))?;
482 Ok(OpTy { op, layout })
485 // Evaluate a place with the goal of reading from it. This lets us sometimes
486 // avoid allocations. If you already know the layout, you can pass it in
487 // to avoid looking it up again.
490 mir_place: &mir::Place<'tcx>,
491 layout: Option<TyLayout<'tcx>>,
492 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
493 use rustc::mir::Place::*;
494 let op = match *mir_place {
495 Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
496 Local(local) => self.access_local(self.frame(), local, layout)?,
498 Projection(ref proj) => {
499 let op = self.eval_place_to_op(&proj.base, None)?;
500 self.operand_projection(op, &proj.elem)?
503 _ => self.eval_place_to_mplace(mir_place)?.into(),
506 trace!("eval_place_to_op: got {:?}", *op);
510 /// Evaluate the operand, returning a place where you can then find the data.
511 /// if you already know the layout, you can save two some table lookups
512 /// by passing it in here.
515 mir_op: &mir::Operand<'tcx>,
516 layout: Option<TyLayout<'tcx>>,
517 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
518 use rustc::mir::Operand::*;
519 let op = match *mir_op {
520 // FIXME: do some more logic on `move` to invalidate the old location
523 self.eval_place_to_op(place, layout)?,
525 Constant(ref constant) => {
526 let layout = from_known_layout(layout, || {
527 let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
530 let op = self.const_value_to_op(constant.literal.val)?;
534 trace!("{:?}: {:?}", mir_op, *op);
538 /// Evaluate a bunch of operands at once
539 pub(super) fn eval_operands(
541 ops: &[mir::Operand<'tcx>],
542 ) -> EvalResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
544 .map(|op| self.eval_operand(op, None))
548 // Used when miri runs into a constant, and by CTFE.
549 // FIXME: CTFE should use allocations, then we can make this private (embed it into
550 // `eval_operand`, ideally).
551 pub(crate) fn const_value_to_op(
553 val: ConstValue<'tcx>,
554 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
555 trace!("const_value_to_op: {:?}", val);
557 ConstValue::Unevaluated(def_id, substs) => {
558 let instance = self.resolve(def_id, substs)?;
559 Ok(*OpTy::from(self.const_eval_raw(GlobalId {
564 ConstValue::ByRef(id, alloc, offset) => {
565 // We rely on mutability being set correctly in that allocation to prevent writes
566 // where none should happen -- and for `static mut`, we copy on demand anyway.
567 Ok(Operand::Indirect(
568 MemPlace::from_ptr(Pointer::new(id, offset), alloc.align)
569 ).with_default_tag())
571 ConstValue::ScalarPair(a, b) =>
572 Ok(Operand::Immediate(Immediate::ScalarPair(
575 )).with_default_tag()),
576 ConstValue::Scalar(x) =>
577 Ok(Operand::Immediate(Immediate::Scalar(x.into())).with_default_tag()),
581 /// Read discriminant, return the runtime value as well as the variant index.
582 pub fn read_discriminant(
584 rval: OpTy<'tcx, M::PointerTag>,
585 ) -> EvalResult<'tcx, (u128, VariantIdx)> {
586 trace!("read_discriminant_value {:#?}", rval.layout);
588 match rval.layout.variants {
589 layout::Variants::Single { index } => {
590 let discr_val = rval.layout.ty.ty_adt_def().map_or(
591 index.as_u32() as u128,
592 |def| def.discriminant_for_variant(*self.tcx, index).val);
593 return Ok((discr_val, index));
595 layout::Variants::Tagged { .. } |
596 layout::Variants::NicheFilling { .. } => {},
598 // read raw discriminant value
599 let discr_op = self.operand_field(rval, 0)?;
600 let discr_val = self.read_immediate(discr_op)?;
601 let raw_discr = discr_val.to_scalar_or_undef();
602 trace!("discr value: {:?}", raw_discr);
604 Ok(match rval.layout.variants {
605 layout::Variants::Single { .. } => bug!(),
606 layout::Variants::Tagged { .. } => {
607 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
608 Ok(raw_discr) => raw_discr,
609 Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
611 let real_discr = if discr_val.layout.ty.is_signed() {
612 let i = bits_discr as i128;
613 // going from layout tag type to typeck discriminant type
614 // requires first sign extending with the layout discriminant
615 let shift = 128 - discr_val.layout.size.bits();
616 let sexted = (i << shift) >> shift;
617 // and then zeroing with the typeck discriminant type
618 let discr_ty = rval.layout.ty
619 .ty_adt_def().expect("tagged layout corresponds to adt")
622 let discr_ty = layout::Integer::from_attr(self, discr_ty);
623 let shift = 128 - discr_ty.size().bits();
624 let truncatee = sexted as u128;
625 (truncatee << shift) >> shift
629 // Make sure we catch invalid discriminants
630 let index = rval.layout.ty
632 .expect("tagged layout for non adt")
633 .discriminants(self.tcx.tcx)
634 .find(|(_, var)| var.val == real_discr)
635 .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(raw_discr.erase_tag()))?;
636 (real_discr, index.0)
638 layout::Variants::NicheFilling {
644 let variants_start = niche_variants.start().as_u32() as u128;
645 let variants_end = niche_variants.end().as_u32() as u128;
647 ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) => {
648 // The niche must be just 0 (which an inbounds pointer value never is)
649 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
650 self.memory.check_bounds_ptr_maybe_dead(ptr).is_ok();
652 return err!(InvalidDiscriminant(raw_discr.erase_tag()));
654 (dataful_variant.as_u32() as u128, dataful_variant)
656 ScalarMaybeUndef::Scalar(Scalar::Bits { bits: raw_discr, size }) => {
657 assert_eq!(size as u64, discr_val.layout.size.bytes());
658 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
659 .wrapping_add(variants_start);
660 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
661 let index = adjusted_discr as usize;
662 assert_eq!(index as u128, adjusted_discr);
663 assert!(index < rval.layout.ty
665 .expect("tagged layout for non adt")
667 (adjusted_discr, VariantIdx::from_usize(index))
669 (dataful_variant.as_u32() as u128, dataful_variant)
672 ScalarMaybeUndef::Undef =>
673 return err!(InvalidDiscriminant(ScalarMaybeUndef::Undef)),