1 //! Functions concerning immediate values and operands, and reading from operands.
2 //! All high-level functions to read from memory work on operands as sources.
4 use std::convert::TryInto;
7 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
9 use rustc::mir::interpret::{
10 GlobalId, AllocId, InboundsCheck,
11 ConstValue, Pointer, Scalar,
12 EvalResult, EvalErrorKind,
16 MemPlace, MPlaceTy, PlaceTy, Place, MemoryKind,
18 pub use rustc::mir::interpret::ScalarMaybeUndef;
20 /// A `Value` represents a single immediate self-contained Rust value.
22 /// For optimization of a few very common cases, there is also a representation for a pair of
23 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
24 /// operations and fat pointers. This idea was taken from rustc's codegen.
25 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
26 /// defined on `Immediate`, and do not have to work with a `Place`.
27 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
28 pub enum Immediate<Tag=(), Id=AllocId> {
29 Scalar(ScalarMaybeUndef<Tag, Id>),
30 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
35 pub fn with_default_tag<Tag>(self) -> Immediate<Tag>
39 Immediate::Scalar(x) => Immediate::Scalar(x.with_default_tag()),
40 Immediate::ScalarPair(x, y) =>
41 Immediate::ScalarPair(x.with_default_tag(), y.with_default_tag()),
46 impl<'tcx, Tag> Immediate<Tag> {
48 pub fn from_scalar(val: Scalar<Tag>) -> Self {
49 Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
53 pub fn erase_tag(self) -> Immediate
56 Immediate::Scalar(x) => Immediate::Scalar(x.erase_tag()),
57 Immediate::ScalarPair(x, y) =>
58 Immediate::ScalarPair(x.erase_tag(), y.erase_tag()),
65 cx: &impl HasDataLayout
67 Immediate::ScalarPair(
69 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
73 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
74 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
78 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
80 Immediate::Scalar(val) => val,
81 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
86 pub fn to_scalar(self) -> EvalResult<'tcx, Scalar<Tag>> {
87 self.to_scalar_or_undef().not_undef()
91 pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
93 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
94 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
98 /// Converts the immediate into a pointer (or a pointer-sized integer).
99 /// Throws away the second half of a ScalarPair!
101 pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar<Tag>> {
103 Immediate::Scalar(ptr) |
104 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
108 /// Converts the value into its metadata.
109 /// Throws away the first half of a ScalarPair!
111 pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
113 Immediate::Scalar(_) => None,
114 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
119 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
120 // as input for binary and cast operations.
121 #[derive(Copy, Clone, Debug)]
122 pub struct ImmTy<'tcx, Tag=()> {
123 pub imm: Immediate<Tag>,
124 pub layout: TyLayout<'tcx>,
127 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
128 type Target = Immediate<Tag>;
130 fn deref(&self) -> &Immediate<Tag> {
135 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
136 /// or still in memory. The latter is an optimization, to delay reading that chunk of
137 /// memory and to avoid having to store arbitrary-sized data here.
138 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
139 pub enum Operand<Tag=(), Id=AllocId> {
140 Immediate(Immediate<Tag, Id>),
141 Indirect(MemPlace<Tag, Id>),
146 pub fn with_default_tag<Tag>(self) -> Operand<Tag>
150 Operand::Immediate(x) => Operand::Immediate(x.with_default_tag()),
151 Operand::Indirect(x) => Operand::Indirect(x.with_default_tag()),
156 impl<Tag> Operand<Tag> {
158 pub fn erase_tag(self) -> Operand
161 Operand::Immediate(x) => Operand::Immediate(x.erase_tag()),
162 Operand::Indirect(x) => Operand::Indirect(x.erase_tag()),
167 pub fn to_mem_place(self) -> MemPlace<Tag>
168 where Tag: ::std::fmt::Debug
171 Operand::Indirect(mplace) => mplace,
172 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
178 pub fn to_immediate(self) -> Immediate<Tag>
179 where Tag: ::std::fmt::Debug
182 Operand::Immediate(imm) => imm,
183 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
189 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
190 pub struct OpTy<'tcx, Tag=()> {
192 pub layout: TyLayout<'tcx>,
195 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
196 type Target = Operand<Tag>;
198 fn deref(&self) -> &Operand<Tag> {
203 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
205 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
207 op: Operand::Indirect(*mplace),
208 layout: mplace.layout
213 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
215 fn from(val: ImmTy<'tcx, Tag>) -> Self {
217 op: Operand::Immediate(val.imm),
223 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
226 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
227 ImmTy { imm: Immediate::from_scalar(val), layout }
231 pub fn to_bits(self) -> EvalResult<'tcx, u128> {
232 self.to_scalar()?.to_bits(self.layout.size)
236 impl<'tcx, Tag> OpTy<'tcx, Tag>
239 pub fn erase_tag(self) -> OpTy<'tcx>
242 op: self.op.erase_tag(),
248 // Use the existing layout if given (but sanity check in debug mode),
249 // or compute the layout.
251 pub(super) fn from_known_layout<'tcx>(
252 layout: Option<TyLayout<'tcx>>,
253 compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
254 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
258 if cfg!(debug_assertions) {
259 let layout2 = compute()?;
260 assert_eq!(layout.details, layout2.details,
261 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
262 layout.ty, layout2.ty);
269 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
270 /// Try reading an immediate in memory; this is interesting particularly for ScalarPair.
271 /// Returns `None` if the layout does not permit loading this as a value.
272 fn try_read_immediate_from_mplace(
274 mplace: MPlaceTy<'tcx, M::PointerTag>,
275 ) -> EvalResult<'tcx, Option<Immediate<M::PointerTag>>> {
276 if mplace.layout.is_unsized() {
277 // Don't touch unsized
280 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
282 if mplace.layout.is_zst() {
283 // Not all ZSTs have a layout we would handle below, so just short-circuit them
285 self.memory.check_align(ptr, ptr_align)?;
286 return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
289 // check for integer pointers before alignment to report better errors
290 let ptr = ptr.to_ptr()?;
291 self.memory.check_align(ptr.into(), ptr_align)?;
292 match mplace.layout.abi {
293 layout::Abi::Scalar(..) => {
294 let scalar = self.memory
296 .read_scalar(self, ptr, mplace.layout.size)?;
297 Ok(Some(Immediate::Scalar(scalar)))
299 layout::Abi::ScalarPair(ref a, ref b) => {
300 let (a, b) = (&a.value, &b.value);
301 let (a_size, b_size) = (a.size(self), b.size(self));
303 let b_offset = a_size.align_to(b.align(self).abi);
304 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
305 let b_ptr = ptr.offset(b_offset, self)?;
306 let a_val = self.memory
308 .read_scalar(self, a_ptr, a_size)?;
309 let b_align = ptr_align.restrict_for_offset(b_offset);
310 self.memory.check_align(b_ptr.into(), b_align)?;
311 let b_val = self.memory
313 .read_scalar(self, b_ptr, b_size)?;
314 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
320 /// Try returning an immediate for the operand.
321 /// If the layout does not permit loading this as an immediate, return where in memory
322 /// we can find the data.
323 /// Note that for a given layout, this operation will either always fail or always
324 /// succeed! Whether it succeeds depends on whether the layout can be represented
325 /// in a `Immediate`, not on which data is stored there currently.
326 pub(super) fn try_read_immediate(
328 src: OpTy<'tcx, M::PointerTag>,
329 ) -> EvalResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
330 Ok(match src.try_as_mplace() {
332 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
342 /// Read an immediate from a place, asserting that that is possible with the given layout.
344 pub fn read_immediate(
346 op: OpTy<'tcx, M::PointerTag>
347 ) -> EvalResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
348 if let Ok(imm) = self.try_read_immediate(op)? {
349 Ok(ImmTy { imm, layout: op.layout })
351 bug!("primitive read failed for type: {:?}", op.layout.ty);
355 /// Read a scalar from a place
358 op: OpTy<'tcx, M::PointerTag>
359 ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
360 Ok(self.read_immediate(op)?.to_scalar_or_undef())
363 // Turn the MPlace into a string (must already be dereferenced!)
366 mplace: MPlaceTy<'tcx, M::PointerTag>,
367 ) -> EvalResult<'tcx, &str> {
368 let len = mplace.len(self)?;
369 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
370 let str = ::std::str::from_utf8(bytes)
371 .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
375 pub fn uninit_operand(
377 layout: TyLayout<'tcx>
378 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
379 // This decides which types we will use the Immediate optimization for, and hence should
380 // match what `try_read_immediate` and `eval_place_to_op` support.
382 return Ok(Operand::Immediate(Immediate::Scalar(Scalar::zst().into())));
385 Ok(match layout.abi {
386 layout::Abi::Scalar(..) =>
387 Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)),
388 layout::Abi::ScalarPair(..) =>
389 Operand::Immediate(Immediate::ScalarPair(
390 ScalarMaybeUndef::Undef,
391 ScalarMaybeUndef::Undef,
394 trace!("Forcing allocation for local of type {:?}", layout.ty);
396 *self.allocate(layout, MemoryKind::Stack)
402 /// Projection functions
403 pub fn operand_field(
405 op: OpTy<'tcx, M::PointerTag>,
407 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
408 let base = match op.try_as_mplace() {
411 let field = self.mplace_field(mplace, field)?;
412 return Ok(field.into());
417 let field = field.try_into().unwrap();
418 let field_layout = op.layout.field(self, field)?;
419 if field_layout.is_zst() {
420 let immediate = Immediate::Scalar(Scalar::zst().into());
421 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
423 let offset = op.layout.fields.offset(field);
424 let immediate = match base {
425 // the field covers the entire type
426 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
427 // extract fields from types with `ScalarPair` ABI
428 Immediate::ScalarPair(a, b) => {
429 let val = if offset.bytes() == 0 { a } else { b };
430 Immediate::Scalar(val)
432 Immediate::Scalar(val) =>
433 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
435 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
438 pub fn operand_downcast(
440 op: OpTy<'tcx, M::PointerTag>,
442 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
443 // Downcasts only change the layout
444 Ok(match op.try_as_mplace() {
446 self.mplace_downcast(mplace, variant)?.into()
449 let layout = op.layout.for_variant(self, variant);
450 OpTy { layout, ..op }
455 pub fn operand_projection(
457 base: OpTy<'tcx, M::PointerTag>,
458 proj_elem: &mir::PlaceElem<'tcx>,
459 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
460 use rustc::mir::ProjectionElem::*;
461 Ok(match *proj_elem {
462 Field(field, _) => self.operand_field(base, field.index() as u64)?,
463 Downcast(_, variant) => self.operand_downcast(base, variant)?,
464 Deref => self.deref_operand(base)?.into(),
465 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
467 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
468 // the actual index doesn't matter, so we just pick a convenient one like 0
469 layout: base.layout.field(self, 0)?,
472 // The rest should only occur as mplace, we do not use Immediates for types
473 // allowing such operations. This matches place_projection forcing an allocation.
474 let mplace = base.to_mem_place();
475 self.mplace_projection(mplace, proj_elem)?.into()
480 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
483 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
485 layout: Option<TyLayout<'tcx>>,
486 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
487 assert_ne!(local, mir::RETURN_PLACE);
488 let op = *frame.locals[local].access()?;
489 let layout = self.layout_of_local(frame, local, layout)?;
490 Ok(OpTy { op, layout })
493 /// Every place can be read from, so we can turm them into an operand
497 place: PlaceTy<'tcx, M::PointerTag>
498 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
499 let op = match *place {
500 Place::Ptr(mplace) => {
501 Operand::Indirect(mplace)
503 Place::Local { frame, local } =>
504 *self.stack[frame].locals[local].access()?
506 Ok(OpTy { op, layout: place.layout })
509 // Evaluate a place with the goal of reading from it. This lets us sometimes
510 // avoid allocations.
511 pub(super) fn eval_place_to_op(
513 mir_place: &mir::Place<'tcx>,
514 layout: Option<TyLayout<'tcx>>,
515 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
516 use rustc::mir::Place::*;
517 let op = match *mir_place {
518 Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
519 Local(local) => self.access_local(self.frame(), local, layout)?,
521 Projection(ref proj) => {
522 let op = self.eval_place_to_op(&proj.base, None)?;
523 self.operand_projection(op, &proj.elem)?
526 _ => self.eval_place_to_mplace(mir_place)?.into(),
529 trace!("eval_place_to_op: got {:?}", *op);
533 /// Evaluate the operand, returning a place where you can then find the data.
534 /// if you already know the layout, you can save two some table lookups
535 /// by passing it in here.
538 mir_op: &mir::Operand<'tcx>,
539 layout: Option<TyLayout<'tcx>>,
540 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
541 use rustc::mir::Operand::*;
542 let op = match *mir_op {
543 // FIXME: do some more logic on `move` to invalidate the old location
546 self.eval_place_to_op(place, layout)?,
548 Constant(ref constant) => self.eval_lazy_const_to_op(*constant.literal, layout)?,
550 trace!("{:?}: {:?}", mir_op, *op);
554 /// Evaluate a bunch of operands at once
555 pub(super) fn eval_operands(
557 ops: &[mir::Operand<'tcx>],
558 ) -> EvalResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
560 .map(|op| self.eval_operand(op, None))
564 // Used when Miri runs into a constant, and by const propagation.
565 pub fn eval_lazy_const_to_op(
567 val: ty::LazyConst<'tcx>,
568 layout: Option<TyLayout<'tcx>>,
569 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
570 trace!("const_to_op: {:?}", val);
572 ty::LazyConst::Unevaluated(def_id, substs) => {
573 let instance = self.resolve(def_id, substs)?;
574 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
579 ty::LazyConst::Evaluated(c) => self.const_to_op(c, layout),
583 // Used when the miri-engine runs into a constant.
584 crate fn const_to_op(
586 val: ty::Const<'tcx>,
587 layout: Option<TyLayout<'tcx>>,
588 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
589 let layout = from_known_layout(layout, || {
590 let ty = self.monomorphize(val.ty)?;
593 let op = match val.val {
594 ConstValue::ByRef(ptr, alloc) => {
595 // We rely on mutability being set correctly in that allocation to prevent writes
596 // where none should happen -- and for `static mut`, we copy on demand anyway.
598 MemPlace::from_ptr(ptr, alloc.align)
601 ConstValue::Slice(a, b) =>
602 Operand::Immediate(Immediate::ScalarPair(
604 Scalar::from_uint(b, self.tcx.data_layout.pointer_size).into(),
605 )).with_default_tag(),
606 ConstValue::Scalar(x) =>
607 Operand::Immediate(Immediate::Scalar(x.into())).with_default_tag(),
615 /// Read discriminant, return the runtime value as well as the variant index.
616 pub fn read_discriminant(
618 rval: OpTy<'tcx, M::PointerTag>,
619 ) -> EvalResult<'tcx, (u128, VariantIdx)> {
620 trace!("read_discriminant_value {:#?}", rval.layout);
622 match rval.layout.variants {
623 layout::Variants::Single { index } => {
624 let discr_val = rval.layout.ty.ty_adt_def().map_or(
625 index.as_u32() as u128,
626 |def| def.discriminant_for_variant(*self.tcx, index).val);
627 return Ok((discr_val, index));
629 layout::Variants::Tagged { .. } |
630 layout::Variants::NicheFilling { .. } => {},
632 // read raw discriminant value
633 let discr_op = self.operand_field(rval, 0)?;
634 let discr_val = self.read_immediate(discr_op)?;
635 let raw_discr = discr_val.to_scalar_or_undef();
636 trace!("discr value: {:?}", raw_discr);
638 Ok(match rval.layout.variants {
639 layout::Variants::Single { .. } => bug!(),
640 layout::Variants::Tagged { .. } => {
641 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
642 Ok(raw_discr) => raw_discr,
643 Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
645 let real_discr = if discr_val.layout.ty.is_signed() {
646 let i = bits_discr as i128;
647 // going from layout tag type to typeck discriminant type
648 // requires first sign extending with the layout discriminant
649 let shift = 128 - discr_val.layout.size.bits();
650 let sexted = (i << shift) >> shift;
651 // and then zeroing with the typeck discriminant type
652 let discr_ty = rval.layout.ty
653 .ty_adt_def().expect("tagged layout corresponds to adt")
656 let discr_ty = layout::Integer::from_attr(self, discr_ty);
657 let shift = 128 - discr_ty.size().bits();
658 let truncatee = sexted as u128;
659 (truncatee << shift) >> shift
663 // Make sure we catch invalid discriminants
664 let index = rval.layout.ty
666 .expect("tagged layout for non adt")
667 .discriminants(self.tcx.tcx)
668 .find(|(_, var)| var.val == real_discr)
669 .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(raw_discr.erase_tag()))?;
670 (real_discr, index.0)
672 layout::Variants::NicheFilling {
678 let variants_start = niche_variants.start().as_u32() as u128;
679 let variants_end = niche_variants.end().as_u32() as u128;
681 ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) => {
682 // The niche must be just 0 (which an inbounds pointer value never is)
683 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
684 self.memory.check_bounds_ptr(ptr, InboundsCheck::MaybeDead).is_ok();
686 return err!(InvalidDiscriminant(raw_discr.erase_tag()));
688 (dataful_variant.as_u32() as u128, dataful_variant)
690 ScalarMaybeUndef::Scalar(Scalar::Bits { bits: raw_discr, size }) => {
691 assert_eq!(size as u64, discr_val.layout.size.bytes());
692 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
693 .wrapping_add(variants_start);
694 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
695 let index = adjusted_discr as usize;
696 assert_eq!(index as u128, adjusted_discr);
697 assert!(index < rval.layout.ty
699 .expect("tagged layout for non adt")
701 (adjusted_discr, VariantIdx::from_usize(index))
703 (dataful_variant.as_u32() as u128, dataful_variant)
706 ScalarMaybeUndef::Undef =>
707 return err!(InvalidDiscriminant(ScalarMaybeUndef::Undef)),