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)
242 .expect("places should be checked on creation")
245 None => return Ok(Some(ImmTy { // zero-sized type
246 imm: Immediate::Scalar(Scalar::zst().into()),
247 layout: mplace.layout,
251 match mplace.layout.abi {
252 layout::Abi::Scalar(..) => {
253 let scalar = self.memory
255 .read_scalar(self, ptr, mplace.layout.size)?;
257 imm: Immediate::Scalar(scalar),
258 layout: mplace.layout,
261 layout::Abi::ScalarPair(ref a, ref b) => {
262 // We checked `ptr_align` above, so all fields will have the alignment they need.
263 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
264 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
265 let (a, b) = (&a.value, &b.value);
266 let (a_size, b_size) = (a.size(self), b.size(self));
268 let b_offset = a_size.align_to(b.align(self).abi);
269 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
270 let b_ptr = ptr.offset(b_offset, self)?;
271 let a_val = self.memory
273 .read_scalar(self, a_ptr, a_size)?;
274 let b_val = self.memory
276 .read_scalar(self, b_ptr, b_size)?;
278 imm: Immediate::ScalarPair(a_val, b_val),
279 layout: mplace.layout,
286 /// Try returning an immediate for the operand.
287 /// If the layout does not permit loading this as an immediate, return where in memory
288 /// we can find the data.
289 /// Note that for a given layout, this operation will either always fail or always
290 /// succeed! Whether it succeeds depends on whether the layout can be represented
291 /// in a `Immediate`, not on which data is stored there currently.
292 pub(crate) fn try_read_immediate(
294 src: OpTy<'tcx, M::PointerTag>,
295 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
296 Ok(match src.try_as_mplace() {
298 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
308 /// Read an immediate from a place, asserting that that is possible with the given layout.
310 pub fn read_immediate(
312 op: OpTy<'tcx, M::PointerTag>
313 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
314 if let Ok(imm) = self.try_read_immediate(op)? {
317 bug!("primitive read failed for type: {:?}", op.layout.ty);
321 /// Read a scalar from a place
324 op: OpTy<'tcx, M::PointerTag>
325 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
326 Ok(self.read_immediate(op)?.to_scalar_or_undef())
329 // Turn the MPlace into a string (must already be dereferenced!)
332 mplace: MPlaceTy<'tcx, M::PointerTag>,
333 ) -> InterpResult<'tcx, &str> {
334 let len = mplace.len(self)?;
335 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
336 let str = ::std::str::from_utf8(bytes)
337 .map_err(|err| InterpError::ValidationFailure(err.to_string()))?;
341 /// Projection functions
342 pub fn operand_field(
344 op: OpTy<'tcx, M::PointerTag>,
346 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
347 let base = match op.try_as_mplace() {
350 let field = self.mplace_field(mplace, field)?;
351 return Ok(field.into());
356 let field = field.try_into().unwrap();
357 let field_layout = op.layout.field(self, field)?;
358 if field_layout.is_zst() {
359 let immediate = Immediate::Scalar(Scalar::zst().into());
360 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
362 let offset = op.layout.fields.offset(field);
363 let immediate = match *base {
364 // the field covers the entire type
365 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
366 // extract fields from types with `ScalarPair` ABI
367 Immediate::ScalarPair(a, b) => {
368 let val = if offset.bytes() == 0 { a } else { b };
369 Immediate::Scalar(val)
371 Immediate::Scalar(val) =>
372 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
374 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
377 pub fn operand_downcast(
379 op: OpTy<'tcx, M::PointerTag>,
381 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
382 // Downcasts only change the layout
383 Ok(match op.try_as_mplace() {
385 self.mplace_downcast(mplace, variant)?.into()
388 let layout = op.layout.for_variant(self, variant);
389 OpTy { layout, ..op }
394 pub fn operand_projection(
396 base: OpTy<'tcx, M::PointerTag>,
397 proj_elem: &mir::PlaceElem<'tcx>,
398 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
399 use rustc::mir::ProjectionElem::*;
400 Ok(match *proj_elem {
401 Field(field, _) => self.operand_field(base, field.index() as u64)?,
402 Downcast(_, variant) => self.operand_downcast(base, variant)?,
403 Deref => self.deref_operand(base)?.into(),
404 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
406 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
407 // the actual index doesn't matter, so we just pick a convenient one like 0
408 layout: base.layout.field(self, 0)?,
411 // The rest should only occur as mplace, we do not use Immediates for types
412 // allowing such operations. This matches place_projection forcing an allocation.
413 let mplace = base.assert_mem_place();
414 self.mplace_projection(mplace, proj_elem)?.into()
419 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
422 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
424 layout: Option<TyLayout<'tcx>>,
425 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
426 assert_ne!(local, mir::RETURN_PLACE);
427 let layout = self.layout_of_local(frame, local, layout)?;
428 let op = if layout.is_zst() {
429 // Do not read from ZST, they might not be initialized
430 Operand::Immediate(Immediate::Scalar(Scalar::zst().into()))
432 frame.locals[local].access()?
434 Ok(OpTy { op, layout })
437 /// Every place can be read from, so we can turn them into an operand
441 place: PlaceTy<'tcx, M::PointerTag>
442 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
443 let op = match *place {
444 Place::Ptr(mplace) => {
445 Operand::Indirect(mplace)
447 Place::Local { frame, local } =>
448 *self.access_local(&self.stack[frame], local, None)?
450 Ok(OpTy { op, layout: place.layout })
453 // Evaluate a place with the goal of reading from it. This lets us sometimes
454 // avoid allocations.
455 pub(super) fn eval_place_to_op(
457 mir_place: &mir::Place<'tcx>,
458 layout: Option<TyLayout<'tcx>>,
459 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
460 use rustc::mir::PlaceBase;
462 mir_place.iterate(|place_base, place_projection| {
463 let mut op = match place_base {
464 PlaceBase::Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
465 PlaceBase::Local(local) => {
466 // Do not use the layout passed in as argument if the base we are looking at
467 // here is not the entire place.
468 // FIXME use place_projection.is_empty() when is available
469 let layout = if mir_place.projection.is_none() {
475 self.access_local(self.frame(), *local, layout)?
477 PlaceBase::Static(place_static) => {
478 self.eval_static_to_mplace(place_static)?.into()
482 for proj in place_projection {
483 op = self.operand_projection(op, &proj.elem)?
486 trace!("eval_place_to_op: got {:?}", *op);
491 /// Evaluate the operand, returning a place where you can then find the data.
492 /// If you already know the layout, you can save two table lookups
493 /// by passing it in here.
496 mir_op: &mir::Operand<'tcx>,
497 layout: Option<TyLayout<'tcx>>,
498 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
499 use rustc::mir::Operand::*;
500 let op = match *mir_op {
501 // FIXME: do some more logic on `move` to invalidate the old location
504 self.eval_place_to_op(place, layout)?,
506 Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
508 trace!("{:?}: {:?}", mir_op, *op);
512 /// Evaluate a bunch of operands at once
513 pub(super) fn eval_operands(
515 ops: &[mir::Operand<'tcx>],
516 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
518 .map(|op| self.eval_operand(op, None))
522 // Used when the miri-engine runs into a constant and for extracting information from constants
523 // in patterns via the `const_eval` module
524 crate fn eval_const_to_op(
526 val: &'tcx ty::Const<'tcx>,
527 layout: Option<TyLayout<'tcx>>,
528 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
529 let tag_scalar = |scalar| match scalar {
530 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
531 Scalar::Raw { data, size } => Scalar::Raw { data, size },
533 // Early-return cases.
535 ConstValue::Param(_) => return err!(TooGeneric), // FIXME(oli-obk): try to monomorphize
536 ConstValue::Unevaluated(def_id, substs) => {
537 let instance = self.resolve(def_id, substs)?;
538 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
545 // Other cases need layout.
546 let layout = from_known_layout(layout, || {
547 self.layout_of(self.monomorphize(val.ty)?)
549 let op = match val.val {
550 ConstValue::ByRef { offset, align, alloc } => {
551 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
552 // We rely on mutability being set correctly in that allocation to prevent writes
553 // where none should happen.
554 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
555 Operand::Indirect(MemPlace::from_ptr(ptr, align))
557 ConstValue::Scalar(x) =>
558 Operand::Immediate(Immediate::Scalar(tag_scalar(x).into())),
559 ConstValue::Slice { data, start, end } => {
560 // We rely on mutability being set correctly in `data` to prevent writes
561 // where none should happen.
562 let ptr = Pointer::new(
563 self.tcx.alloc_map.lock().create_memory_alloc(data),
564 Size::from_bytes(start as u64), // offset: `start`
566 Operand::Immediate(Immediate::new_slice(
567 self.tag_static_base_pointer(ptr).into(),
568 (end - start) as u64, // len: `end - start`
572 ConstValue::Param(..) |
573 ConstValue::Infer(..) |
574 ConstValue::Placeholder(..) |
575 ConstValue::Unevaluated(..) =>
576 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
578 Ok(OpTy { op, layout })
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 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
586 trace!("read_discriminant_value {:#?}", rval.layout);
588 let (discr_kind, discr_index) = match rval.layout.variants {
589 layout::Variants::Single { index } => {
590 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
591 index.as_u32() as u128,
593 return Ok((discr_val, index));
595 layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
596 (discr_kind, discr_index),
599 // read raw discriminant value
600 let discr_op = self.operand_field(rval, discr_index as u64)?;
601 let discr_val = self.read_immediate(discr_op)?;
602 let raw_discr = discr_val.to_scalar_or_undef();
603 trace!("discr value: {:?}", raw_discr);
605 Ok(match *discr_kind {
606 layout::DiscriminantKind::Tag => {
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 // going from layout tag type to typeck discriminant type
613 // requires first sign extending with the layout discriminant
614 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
615 // and then zeroing with the typeck discriminant type
616 let discr_ty = rval.layout.ty
617 .ty_adt_def().expect("tagged layout corresponds to adt")
620 let size = layout::Integer::from_attr(self, discr_ty).size();
621 let truncatee = sexted as u128;
622 truncate(truncatee, size)
626 // Make sure we catch invalid discriminants
627 let index = match &rval.layout.ty.sty {
628 ty::Adt(adt, _) => adt
629 .discriminants(self.tcx.tcx)
630 .find(|(_, var)| var.val == real_discr),
631 ty::Generator(def_id, substs, _) => substs
632 .discriminants(*def_id, self.tcx.tcx)
633 .find(|(_, var)| var.val == real_discr),
634 _ => bug!("tagged layout for non-adt non-generator"),
635 }.ok_or_else(|| InterpError::InvalidDiscriminant(raw_discr.erase_tag()))?;
636 (real_discr, index.0)
638 layout::DiscriminantKind::Niche {
643 let variants_start = niche_variants.start().as_u32() as u128;
644 let variants_end = niche_variants.end().as_u32() as u128;
645 let raw_discr = raw_discr.not_undef()
646 .map_err(|_| InterpError::InvalidDiscriminant(ScalarMaybeUndef::Undef))?;
647 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
649 // The niche must be just 0 (which an inbounds pointer value never is)
650 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
651 !self.memory.ptr_may_be_null(ptr);
653 return err!(InvalidDiscriminant(raw_discr.erase_tag().into()));
655 (dataful_variant.as_u32() as u128, dataful_variant)
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)