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::{
8 self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx,
11 use rustc::mir::interpret::{
13 ConstValue, Pointer, Scalar,
14 InterpResult, InterpError,
15 sign_extend, truncate,
19 MemPlace, MPlaceTy, PlaceTy, Place,
21 pub use rustc::mir::interpret::ScalarMaybeUndef;
23 /// A `Value` represents a single immediate self-contained Rust value.
25 /// For optimization of a few very common cases, there is also a representation for a pair of
26 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
27 /// operations and fat pointers. This idea was taken from rustc's codegen.
28 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
29 /// defined on `Immediate`, and do not have to work with a `Place`.
30 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
31 pub enum Immediate<Tag=(), Id=AllocId> {
32 Scalar(ScalarMaybeUndef<Tag, Id>),
33 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
36 impl<'tcx, Tag> Immediate<Tag> {
38 pub fn from_scalar(val: Scalar<Tag>) -> Self {
39 Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
45 cx: &impl HasDataLayout
47 Immediate::ScalarPair(
49 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
53 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
54 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
58 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
60 Immediate::Scalar(val) => val,
61 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
66 pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
67 self.to_scalar_or_undef().not_undef()
71 pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
73 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
74 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
78 /// Converts the immediate into a pointer (or a pointer-sized integer).
79 /// Throws away the second half of a ScalarPair!
81 pub fn to_scalar_ptr(self) -> InterpResult<'tcx, Scalar<Tag>> {
83 Immediate::Scalar(ptr) |
84 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
88 /// Converts the value into its metadata.
89 /// Throws away the first half of a ScalarPair!
91 pub fn to_meta(self) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
93 Immediate::Scalar(_) => None,
94 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
99 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
100 // as input for binary and cast operations.
101 #[derive(Copy, Clone, Debug)]
102 pub struct ImmTy<'tcx, Tag=()> {
103 pub imm: Immediate<Tag>,
104 pub layout: TyLayout<'tcx>,
107 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
108 type Target = Immediate<Tag>;
110 fn deref(&self) -> &Immediate<Tag> {
115 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
116 /// or still in memory. The latter is an optimization, to delay reading that chunk of
117 /// memory and to avoid having to store arbitrary-sized data here.
118 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
119 pub enum Operand<Tag=(), Id=AllocId> {
120 Immediate(Immediate<Tag, Id>),
121 Indirect(MemPlace<Tag, Id>),
124 impl<Tag> Operand<Tag> {
126 pub fn assert_mem_place(self) -> MemPlace<Tag>
127 where Tag: ::std::fmt::Debug
130 Operand::Indirect(mplace) => mplace,
131 _ => bug!("assert_mem_place: expected Operand::Indirect, got {:?}", self),
137 pub fn assert_immediate(self) -> Immediate<Tag>
138 where Tag: ::std::fmt::Debug
141 Operand::Immediate(imm) => imm,
142 _ => bug!("assert_immediate: expected Operand::Immediate, got {:?}", self),
148 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
149 pub struct OpTy<'tcx, Tag=()> {
151 pub layout: TyLayout<'tcx>,
154 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
155 type Target = Operand<Tag>;
157 fn deref(&self) -> &Operand<Tag> {
162 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
164 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
166 op: Operand::Indirect(*mplace),
167 layout: mplace.layout
172 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
174 fn from(val: ImmTy<'tcx, Tag>) -> Self {
176 op: Operand::Immediate(val.imm),
182 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
185 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
186 ImmTy { imm: Immediate::from_scalar(val), layout }
190 pub fn to_bits(self) -> InterpResult<'tcx, u128> {
191 self.to_scalar()?.to_bits(self.layout.size)
195 // Use the existing layout if given (but sanity check in debug mode),
196 // or compute the layout.
198 pub(super) fn from_known_layout<'tcx>(
199 layout: Option<TyLayout<'tcx>>,
200 compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
201 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
205 if cfg!(debug_assertions) {
206 let layout2 = compute()?;
207 assert_eq!(layout.details, layout2.details,
208 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
209 layout.ty, layout2.ty);
216 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
217 /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
218 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
222 op: OpTy<'tcx, M::PointerTag>,
223 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
224 match op.try_as_mplace() {
225 Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
226 Err(imm) => Ok(imm.into()), // Nothing to cast/force
230 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
231 /// Returns `None` if the layout does not permit loading this as a value.
232 fn try_read_immediate_from_mplace(
234 mplace: MPlaceTy<'tcx, M::PointerTag>,
235 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
236 if mplace.layout.is_unsized() {
237 // Don't touch unsized
241 let ptr = match self.check_mplace_access(mplace, None)? {
243 None => return Ok(Some(ImmTy { // zero-sized type
244 imm: Immediate::Scalar(Scalar::zst().into()),
245 layout: mplace.layout,
249 match mplace.layout.abi {
250 layout::Abi::Scalar(..) => {
251 let scalar = self.memory
253 .read_scalar(self, ptr, mplace.layout.size)?;
255 imm: Immediate::Scalar(scalar),
256 layout: mplace.layout,
259 layout::Abi::ScalarPair(ref a, ref b) => {
260 // We checked `ptr_align` above, so all fields will have the alignment they need.
261 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
262 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
263 let (a, b) = (&a.value, &b.value);
264 let (a_size, b_size) = (a.size(self), b.size(self));
266 let b_offset = a_size.align_to(b.align(self).abi);
267 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
268 let b_ptr = ptr.offset(b_offset, self)?;
269 let a_val = self.memory
271 .read_scalar(self, a_ptr, a_size)?;
272 let b_val = self.memory
274 .read_scalar(self, b_ptr, b_size)?;
276 imm: Immediate::ScalarPair(a_val, b_val),
277 layout: mplace.layout,
284 /// Try returning an immediate for the operand.
285 /// If the layout does not permit loading this as an immediate, return where in memory
286 /// we can find the data.
287 /// Note that for a given layout, this operation will either always fail or always
288 /// succeed! Whether it succeeds depends on whether the layout can be represented
289 /// in a `Immediate`, not on which data is stored there currently.
290 pub(crate) fn try_read_immediate(
292 src: OpTy<'tcx, M::PointerTag>,
293 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
294 Ok(match src.try_as_mplace() {
296 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
306 /// Read an immediate from a place, asserting that that is possible with the given layout.
308 pub fn read_immediate(
310 op: OpTy<'tcx, M::PointerTag>
311 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
312 if let Ok(imm) = self.try_read_immediate(op)? {
315 bug!("primitive read failed for type: {:?}", op.layout.ty);
319 /// Read a scalar from a place
322 op: OpTy<'tcx, M::PointerTag>
323 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
324 Ok(self.read_immediate(op)?.to_scalar_or_undef())
327 // Turn the MPlace into a string (must already be dereferenced!)
330 mplace: MPlaceTy<'tcx, M::PointerTag>,
331 ) -> InterpResult<'tcx, &str> {
332 let len = mplace.len(self)?;
333 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
334 let str = ::std::str::from_utf8(bytes)
335 .map_err(|err| InterpError::ValidationFailure(err.to_string()))?;
339 /// Projection functions
340 pub fn operand_field(
342 op: OpTy<'tcx, M::PointerTag>,
344 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
345 let base = match op.try_as_mplace() {
348 let field = self.mplace_field(mplace, field)?;
349 return Ok(field.into());
354 let field = field.try_into().unwrap();
355 let field_layout = op.layout.field(self, field)?;
356 if field_layout.is_zst() {
357 let immediate = Immediate::Scalar(Scalar::zst().into());
358 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
360 let offset = op.layout.fields.offset(field);
361 let immediate = match *base {
362 // the field covers the entire type
363 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
364 // extract fields from types with `ScalarPair` ABI
365 Immediate::ScalarPair(a, b) => {
366 let val = if offset.bytes() == 0 { a } else { b };
367 Immediate::Scalar(val)
369 Immediate::Scalar(val) =>
370 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
372 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
375 pub fn operand_downcast(
377 op: OpTy<'tcx, M::PointerTag>,
379 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
380 // Downcasts only change the layout
381 Ok(match op.try_as_mplace() {
383 self.mplace_downcast(mplace, variant)?.into()
386 let layout = op.layout.for_variant(self, variant);
387 OpTy { layout, ..op }
392 pub fn operand_projection(
394 base: OpTy<'tcx, M::PointerTag>,
395 proj_elem: &mir::PlaceElem<'tcx>,
396 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
397 use rustc::mir::ProjectionElem::*;
398 Ok(match *proj_elem {
399 Field(field, _) => self.operand_field(base, field.index() as u64)?,
400 Downcast(_, variant) => self.operand_downcast(base, variant)?,
401 Deref => self.deref_operand(base)?.into(),
402 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
404 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
405 // the actual index doesn't matter, so we just pick a convenient one like 0
406 layout: base.layout.field(self, 0)?,
409 // The rest should only occur as mplace, we do not use Immediates for types
410 // allowing such operations. This matches place_projection forcing an allocation.
411 let mplace = base.assert_mem_place();
412 self.mplace_projection(mplace, proj_elem)?.into()
417 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
420 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
422 layout: Option<TyLayout<'tcx>>,
423 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
424 assert_ne!(local, mir::RETURN_PLACE);
425 let layout = self.layout_of_local(frame, local, layout)?;
426 let op = if layout.is_zst() {
427 // Do not read from ZST, they might not be initialized
428 Operand::Immediate(Immediate::Scalar(Scalar::zst().into()))
430 frame.locals[local].access()?
432 Ok(OpTy { op, layout })
435 /// Every place can be read from, so we can turn them into an operand
439 place: PlaceTy<'tcx, M::PointerTag>
440 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
441 let op = match *place {
442 Place::Ptr(mplace) => {
443 Operand::Indirect(mplace)
445 Place::Local { frame, local } =>
446 *self.access_local(&self.stack[frame], local, None)?
448 Ok(OpTy { op, layout: place.layout })
451 // Evaluate a place with the goal of reading from it. This lets us sometimes
452 // avoid allocations.
453 pub(super) fn eval_place_to_op(
455 mir_place: &mir::Place<'tcx>,
456 layout: Option<TyLayout<'tcx>>,
457 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
458 use rustc::mir::PlaceBase;
460 mir_place.iterate(|place_base, place_projection| {
461 let mut op = match place_base {
462 PlaceBase::Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
463 PlaceBase::Local(local) => {
464 // Do not use the layout passed in as argument if the base we are looking at
465 // here is not the entire place.
466 // FIXME use place_projection.is_empty() when is available
467 let layout = if mir_place.projection.is_none() {
473 self.access_local(self.frame(), *local, layout)?
475 PlaceBase::Static(place_static) => {
476 self.eval_static_to_mplace(place_static)?.into()
480 for proj in place_projection {
481 op = self.operand_projection(op, &proj.elem)?
484 trace!("eval_place_to_op: got {:?}", *op);
489 /// Evaluate the operand, returning a place where you can then find the data.
490 /// If you already know the layout, you can save two table lookups
491 /// by passing it in here.
494 mir_op: &mir::Operand<'tcx>,
495 layout: Option<TyLayout<'tcx>>,
496 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
497 use rustc::mir::Operand::*;
498 let op = match *mir_op {
499 // FIXME: do some more logic on `move` to invalidate the old location
502 self.eval_place_to_op(place, layout)?,
504 Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
506 trace!("{:?}: {:?}", mir_op, *op);
510 /// Evaluate a bunch of operands at once
511 pub(super) fn eval_operands(
513 ops: &[mir::Operand<'tcx>],
514 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
516 .map(|op| self.eval_operand(op, None))
520 // Used when the miri-engine runs into a constant and for extracting information from constants
521 // in patterns via the `const_eval` module
522 crate fn eval_const_to_op(
524 val: &'tcx ty::Const<'tcx>,
525 layout: Option<TyLayout<'tcx>>,
526 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
527 let tag_scalar = |scalar| match scalar {
528 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
529 Scalar::Raw { data, size } => Scalar::Raw { data, size },
531 // Early-return cases.
533 ConstValue::Param(_) => return err!(TooGeneric), // FIXME(oli-obk): try to monomorphize
534 ConstValue::Unevaluated(def_id, substs) => {
535 let instance = self.resolve(def_id, substs)?;
536 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
543 // Other cases need layout.
544 let layout = from_known_layout(layout, || {
545 self.layout_of(self.monomorphize(val.ty)?)
547 let op = match val.val {
548 ConstValue::ByRef { offset, align, alloc } => {
549 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
550 // We rely on mutability being set correctly in that allocation to prevent writes
551 // where none should happen.
552 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
553 Operand::Indirect(MemPlace::from_ptr(ptr, align))
555 ConstValue::Scalar(x) =>
556 Operand::Immediate(Immediate::Scalar(tag_scalar(x).into())),
557 ConstValue::Slice { data, start, end } => {
558 // We rely on mutability being set correctly in `data` to prevent writes
559 // where none should happen.
560 let ptr = Pointer::new(
561 self.tcx.alloc_map.lock().create_memory_alloc(data),
562 Size::from_bytes(start as u64), // offset: `start`
564 Operand::Immediate(Immediate::new_slice(
565 self.tag_static_base_pointer(ptr).into(),
566 (end - start) as u64, // len: `end - start`
570 ConstValue::Param(..) |
571 ConstValue::Infer(..) |
572 ConstValue::Placeholder(..) |
573 ConstValue::Unevaluated(..) =>
574 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
576 Ok(OpTy { op, layout })
579 /// Read discriminant, return the runtime value as well as the variant index.
580 pub fn read_discriminant(
582 rval: OpTy<'tcx, M::PointerTag>,
583 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
584 trace!("read_discriminant_value {:#?}", rval.layout);
586 let (discr_kind, discr_index) = match rval.layout.variants {
587 layout::Variants::Single { index } => {
588 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
589 index.as_u32() as u128,
591 return Ok((discr_val, index));
593 layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
594 (discr_kind, discr_index),
597 // read raw discriminant value
598 let discr_op = self.operand_field(rval, discr_index as u64)?;
599 let discr_val = self.read_immediate(discr_op)?;
600 let raw_discr = discr_val.to_scalar_or_undef();
601 trace!("discr value: {:?}", raw_discr);
603 Ok(match *discr_kind {
604 layout::DiscriminantKind::Tag => {
605 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
606 Ok(raw_discr) => raw_discr,
607 Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
609 let real_discr = if discr_val.layout.ty.is_signed() {
610 // going from layout tag type to typeck discriminant type
611 // requires first sign extending with the layout discriminant
612 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
613 // and then zeroing with the typeck discriminant type
614 let discr_ty = rval.layout.ty
615 .ty_adt_def().expect("tagged layout corresponds to adt")
618 let size = layout::Integer::from_attr(self, discr_ty).size();
619 let truncatee = sexted as u128;
620 truncate(truncatee, size)
624 // Make sure we catch invalid discriminants
625 let index = match &rval.layout.ty.sty {
626 ty::Adt(adt, _) => adt
627 .discriminants(self.tcx.tcx)
628 .find(|(_, var)| var.val == real_discr),
629 ty::Generator(def_id, substs, _) => substs
630 .discriminants(*def_id, self.tcx.tcx)
631 .find(|(_, var)| var.val == real_discr),
632 _ => bug!("tagged layout for non-adt non-generator"),
633 }.ok_or_else(|| InterpError::InvalidDiscriminant(raw_discr.erase_tag()))?;
634 (real_discr, index.0)
636 layout::DiscriminantKind::Niche {
641 let variants_start = niche_variants.start().as_u32() as u128;
642 let variants_end = niche_variants.end().as_u32() as u128;
643 let raw_discr = raw_discr.not_undef()
644 .map_err(|_| InterpError::InvalidDiscriminant(ScalarMaybeUndef::Undef))?;
645 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
647 // The niche must be just 0 (which an inbounds pointer value never is)
648 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
649 !self.memory.ptr_may_be_null(ptr);
651 return err!(InvalidDiscriminant(raw_discr.erase_tag().into()));
653 (dataful_variant.as_u32() as u128, dataful_variant)
656 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
657 .wrapping_add(variants_start);
658 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
659 let index = adjusted_discr as usize;
660 assert_eq!(index as u128, adjusted_discr);
661 assert!(index < rval.layout.ty
663 .expect("tagged layout for non adt")
665 (adjusted_discr, VariantIdx::from_usize(index))
667 (dataful_variant.as_u32() as u128, dataful_variant)