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::hash::{Hash, Hasher};
15 use std::convert::TryInto;
18 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt};
20 use rustc::mir::interpret::{
22 ConstValue, Pointer, Scalar, ScalarMaybeUndef,
23 EvalResult, EvalErrorKind
25 use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
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 `Value`, and do not have to work with a `Place`.
34 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
35 pub enum Value<Id=AllocId> {
36 Scalar(ScalarMaybeUndef<Id>),
37 ScalarPair(ScalarMaybeUndef<Id>, ScalarMaybeUndef<Id>),
44 cx: impl HasDataLayout
46 Value::ScalarPair(val.into(), Scalar::from_uint(len, cx.data_layout().pointer_size).into())
49 pub fn new_dyn_trait(val: Scalar, vtable: Pointer) -> Self {
50 Value::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
54 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef {
56 Value::Scalar(val) => val,
57 Value::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
62 pub fn to_scalar(self) -> EvalResult<'tcx, Scalar> {
63 self.to_scalar_or_undef().not_undef()
67 pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar, Scalar)> {
69 Value::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
70 Value::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
74 /// Convert the value into a pointer (or a pointer-sized integer).
75 /// Throws away the second half of a ScalarPair!
77 pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar> {
80 Value::ScalarPair(ptr, _) => ptr.not_undef(),
85 impl_stable_hash_for!(enum ::interpret::Value {
90 // ScalarPair needs a type to interpret, so we often have a value and a type together
91 // as input for binary and cast operations.
92 #[derive(Copy, Clone, Debug)]
93 pub struct ValTy<'tcx> {
95 pub layout: TyLayout<'tcx>,
98 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
101 fn deref(&self) -> &Value {
106 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
107 /// or still in memory. The latter is an optimization, to delay reading that chunk of
108 /// memory and to avoid having to store arbitrary-sized data here.
109 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
110 pub enum Operand<Id=AllocId> {
111 Immediate(Value<Id>),
112 Indirect(MemPlace<Id>),
117 pub fn to_mem_place(self) -> MemPlace {
119 Operand::Indirect(mplace) => mplace,
120 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
126 pub fn to_immediate(self) -> Value {
128 Operand::Immediate(val) => val,
129 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
135 impl_stable_hash_for!(enum ::interpret::Operand {
140 #[derive(Copy, Clone, Debug)]
141 pub struct OpTy<'tcx> {
142 crate op: Operand, // ideally we'd make this private, but const_prop needs this
143 pub layout: TyLayout<'tcx>,
146 impl<'tcx> ::std::ops::Deref for OpTy<'tcx> {
147 type Target = Operand;
149 fn deref(&self) -> &Operand {
154 impl<'tcx> From<MPlaceTy<'tcx>> for OpTy<'tcx> {
156 fn from(mplace: MPlaceTy<'tcx>) -> Self {
158 op: Operand::Indirect(*mplace),
159 layout: mplace.layout
164 impl<'tcx> From<ValTy<'tcx>> for OpTy<'tcx> {
166 fn from(val: ValTy<'tcx>) -> Self {
168 op: Operand::Immediate(val.value),
174 // Validation needs to hash OpTy, but we cannot hash Layout -- so we just hash the type
175 impl<'tcx> Hash for OpTy<'tcx> {
176 fn hash<H: Hasher>(&self, state: &mut H) {
178 self.layout.ty.hash(state);
181 impl<'tcx> PartialEq for OpTy<'tcx> {
182 fn eq(&self, other: &Self) -> bool {
183 self.op == other.op && self.layout.ty == other.layout.ty
186 impl<'tcx> Eq for OpTy<'tcx> {}
188 // Use the existing layout if given (but sanity check in debug mode),
189 // or compute the layout.
191 fn from_known_layout<'tcx>(
192 layout: Option<TyLayout<'tcx>>,
193 compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
194 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
198 if cfg!(debug_assertions) {
199 let layout2 = compute()?;
200 assert_eq!(layout.details, layout2.details,
201 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
202 layout.ty, layout2.ty);
209 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
210 /// Try reading a value in memory; this is interesting particularily for ScalarPair.
211 /// Return None if the layout does not permit loading this as a value.
212 pub(super) fn try_read_value_from_mplace(
214 mplace: MPlaceTy<'tcx>,
215 ) -> EvalResult<'tcx, Option<Value>> {
216 if mplace.layout.is_unsized() {
217 // Dont touch unsized
220 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
222 if mplace.layout.is_zst() {
223 // Not all ZSTs have a layout we would handle below, so just short-circuit them
225 self.memory.check_align(ptr, ptr_align)?;
226 return Ok(Some(Value::Scalar(Scalar::zst().into())));
229 let ptr = ptr.to_ptr()?;
230 match mplace.layout.abi {
231 layout::Abi::Scalar(..) => {
232 let scalar = self.memory.read_scalar(ptr, ptr_align, mplace.layout.size)?;
233 Ok(Some(Value::Scalar(scalar)))
235 layout::Abi::ScalarPair(ref a, ref b) => {
236 let (a, b) = (&a.value, &b.value);
237 let (a_size, b_size) = (a.size(self), b.size(self));
239 let b_offset = a_size.abi_align(b.align(self));
240 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
241 let b_ptr = ptr.offset(b_offset, self)?.into();
242 let a_val = self.memory.read_scalar(a_ptr, ptr_align, a_size)?;
243 let b_val = self.memory.read_scalar(b_ptr, ptr_align, b_size)?;
244 Ok(Some(Value::ScalarPair(a_val, b_val)))
250 /// Try returning an immediate value for the operand.
251 /// If the layout does not permit loading this as a value, return where in memory
252 /// we can find the data.
253 /// Note that for a given layout, this operation will either always fail or always
254 /// succeed! Whether it succeeds depends on whether the layout can be represented
255 /// in a `Value`, not on which data is stored there currently.
256 pub(crate) fn try_read_value(
259 ) -> EvalResult<'tcx, Result<Value, MemPlace>> {
260 Ok(match src.try_as_mplace() {
262 if let Some(val) = self.try_read_value_from_mplace(mplace)? {
272 /// Read a value from a place, asserting that that is possible with the given layout.
274 pub fn read_value(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
275 if let Ok(value) = self.try_read_value(op)? {
276 Ok(ValTy { value, layout: op.layout })
278 bug!("primitive read failed for type: {:?}", op.layout.ty);
282 /// Read a scalar from a place
283 pub fn read_scalar(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ScalarMaybeUndef> {
284 match *self.read_value(op)? {
285 Value::ScalarPair(..) => bug!("got ScalarPair for type: {:?}", op.layout.ty),
286 Value::Scalar(val) => Ok(val),
290 // Turn the MPlace into a string (must already be dereferenced!)
293 mplace: MPlaceTy<'tcx>,
294 ) -> EvalResult<'tcx, &str> {
295 let len = mplace.len(self)?;
296 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
297 let str = ::std::str::from_utf8(bytes)
298 .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
302 pub fn uninit_operand(&mut self, layout: TyLayout<'tcx>) -> EvalResult<'tcx, Operand> {
303 // This decides which types we will use the Immediate optimization for, and hence should
304 // match what `try_read_value` and `eval_place_to_op` support.
306 return Ok(Operand::Immediate(Value::Scalar(Scalar::zst().into())));
309 Ok(match layout.abi {
310 layout::Abi::Scalar(..) =>
311 Operand::Immediate(Value::Scalar(ScalarMaybeUndef::Undef)),
312 layout::Abi::ScalarPair(..) =>
313 Operand::Immediate(Value::ScalarPair(
314 ScalarMaybeUndef::Undef,
315 ScalarMaybeUndef::Undef,
318 trace!("Forcing allocation for local of type {:?}", layout.ty);
320 *self.allocate(layout, MemoryKind::Stack)?
326 /// Projection functions
327 pub fn operand_field(
331 ) -> EvalResult<'tcx, OpTy<'tcx>> {
332 let base = match op.try_as_mplace() {
335 let field = self.mplace_field(mplace, field)?;
336 return Ok(field.into());
341 let field = field.try_into().unwrap();
342 let field_layout = op.layout.field(self, field)?;
343 if field_layout.is_zst() {
344 let val = Value::Scalar(Scalar::zst().into());
345 return Ok(OpTy { op: Operand::Immediate(val), layout: field_layout });
347 let offset = op.layout.fields.offset(field);
348 let value = match base {
349 // the field covers the entire type
350 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
351 // extract fields from types with `ScalarPair` ABI
352 Value::ScalarPair(a, b) => {
353 let val = if offset.bytes() == 0 { a } else { b };
356 Value::Scalar(val) =>
357 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
359 Ok(OpTy { op: Operand::Immediate(value), layout: field_layout })
362 pub fn operand_downcast(
366 ) -> EvalResult<'tcx, OpTy<'tcx>> {
367 // Downcasts only change the layout
368 Ok(match op.try_as_mplace() {
370 self.mplace_downcast(mplace, variant)?.into()
373 let layout = op.layout.for_variant(self, variant);
374 OpTy { layout, ..op }
379 // Take an operand, representing a pointer, and dereference it to a place -- that
380 // will always be a MemPlace.
381 pub(super) fn deref_operand(
384 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
385 let val = self.read_value(src)?;
386 trace!("deref to {} on {:?}", val.layout.ty, *val);
387 Ok(self.ref_to_mplace(val)?)
390 pub fn operand_projection(
393 proj_elem: &mir::PlaceElem<'tcx>,
394 ) -> EvalResult<'tcx, OpTy<'tcx>> {
395 use rustc::mir::ProjectionElem::*;
396 Ok(match *proj_elem {
397 Field(field, _) => self.operand_field(base, field.index() as u64)?,
398 Downcast(_, variant) => self.operand_downcast(base, variant)?,
399 Deref => self.deref_operand(base)?.into(),
400 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
402 op: Operand::Immediate(Value::Scalar(Scalar::zst().into())),
403 // the actual index doesn't matter, so we just pick a convenient one like 0
404 layout: base.layout.field(self, 0)?,
407 // The rest should only occur as mplace, we do not use Immediates for types
408 // allowing such operations. This matches place_projection forcing an allocation.
409 let mplace = base.to_mem_place();
410 self.mplace_projection(mplace, proj_elem)?.into()
415 // Evaluate a place with the goal of reading from it. This lets us sometimes
416 // avoid allocations. If you already know the layout, you can pass it in
417 // to avoid looking it up again.
420 mir_place: &mir::Place<'tcx>,
421 layout: Option<TyLayout<'tcx>>,
422 ) -> EvalResult<'tcx, OpTy<'tcx>> {
423 use rustc::mir::Place::*;
424 let op = match *mir_place {
425 Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
427 let op = *self.frame().locals[local].access()?;
428 let layout = from_known_layout(layout,
429 || self.layout_of_local(self.cur_frame(), local))?;
433 Projection(ref proj) => {
434 let op = self.eval_place_to_op(&proj.base, None)?;
435 self.operand_projection(op, &proj.elem)?
438 _ => self.eval_place_to_mplace(mir_place)?.into(),
441 trace!("eval_place_to_op: got {:?}", *op);
445 /// Evaluate the operand, returning a place where you can then find the data.
446 /// if you already know the layout, you can save two some table lookups
447 /// by passing it in here.
450 mir_op: &mir::Operand<'tcx>,
451 layout: Option<TyLayout<'tcx>>,
452 ) -> EvalResult<'tcx, OpTy<'tcx>> {
453 use rustc::mir::Operand::*;
454 let op = match *mir_op {
455 // FIXME: do some more logic on `move` to invalidate the old location
458 self.eval_place_to_op(place, layout)?,
460 Constant(ref constant) => {
461 let layout = from_known_layout(layout, || {
462 let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
465 let op = self.const_value_to_op(constant.literal.val)?;
469 trace!("{:?}: {:?}", mir_op, *op);
473 /// Evaluate a bunch of operands at once
474 pub(super) fn eval_operands(
476 ops: &[mir::Operand<'tcx>],
477 ) -> EvalResult<'tcx, Vec<OpTy<'tcx>>> {
479 .map(|op| self.eval_operand(op, None))
483 // Also used e.g. when miri runs into a constant.
484 pub(super) fn const_value_to_op(
486 val: ConstValue<'tcx>,
487 ) -> EvalResult<'tcx, Operand> {
488 trace!("const_value_to_op: {:?}", val);
490 ConstValue::Unevaluated(def_id, substs) => {
491 let instance = self.resolve(def_id, substs)?;
492 self.global_to_op(GlobalId {
497 ConstValue::ByRef(id, alloc, offset) => {
498 // We rely on mutability being set correctly in that allocation to prevent writes
499 // where none should happen -- and for `static mut`, we copy on demand anyway.
500 Ok(Operand::Indirect(MemPlace::from_ptr(Pointer::new(id, offset), alloc.align)))
502 ConstValue::ScalarPair(a, b) =>
503 Ok(Operand::Immediate(Value::ScalarPair(a.into(), b))),
504 ConstValue::Scalar(x) =>
505 Ok(Operand::Immediate(Value::Scalar(x.into()))),
510 cnst: &ty::Const<'tcx>,
511 ) -> EvalResult<'tcx, OpTy<'tcx>> {
512 let op = self.const_value_to_op(cnst.val)?;
513 Ok(OpTy { op, layout: self.layout_of(cnst.ty)? })
516 pub(super) fn global_to_op(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, Operand> {
517 let cv = self.const_eval(gid)?;
518 self.const_value_to_op(cv.val)
521 /// Read discriminant, return the runtime value as well as the variant index.
522 pub fn read_discriminant(
525 ) -> EvalResult<'tcx, (u128, usize)> {
526 trace!("read_discriminant_value {:#?}", rval.layout);
527 if rval.layout.abi == layout::Abi::Uninhabited {
528 return err!(Unreachable);
531 match rval.layout.variants {
532 layout::Variants::Single { index } => {
533 let discr_val = rval.layout.ty.ty_adt_def().map_or(
535 |def| def.discriminant_for_variant(*self.tcx, index).val);
536 return Ok((discr_val, index));
538 layout::Variants::Tagged { .. } |
539 layout::Variants::NicheFilling { .. } => {},
541 // read raw discriminant value
542 let discr_op = self.operand_field(rval, 0)?;
543 let discr_val = self.read_value(discr_op)?;
544 let raw_discr = discr_val.to_scalar()?;
545 trace!("discr value: {:?}", raw_discr);
547 Ok(match rval.layout.variants {
548 layout::Variants::Single { .. } => bug!(),
549 layout::Variants::Tagged { .. } => {
550 let real_discr = if discr_val.layout.ty.is_signed() {
551 let i = raw_discr.to_bits(discr_val.layout.size)? as i128;
552 // going from layout tag type to typeck discriminant type
553 // requires first sign extending with the layout discriminant
554 let shift = 128 - discr_val.layout.size.bits();
555 let sexted = (i << shift) >> shift;
556 // and then zeroing with the typeck discriminant type
557 let discr_ty = rval.layout.ty
558 .ty_adt_def().expect("tagged layout corresponds to adt")
561 let discr_ty = layout::Integer::from_attr(self.tcx.tcx, discr_ty);
562 let shift = 128 - discr_ty.size().bits();
563 let truncatee = sexted as u128;
564 (truncatee << shift) >> shift
566 raw_discr.to_bits(discr_val.layout.size)?
568 // Make sure we catch invalid discriminants
569 let index = rval.layout.ty
571 .expect("tagged layout for non adt")
572 .discriminants(self.tcx.tcx)
573 .position(|var| var.val == real_discr)
574 .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(real_discr))?;
577 layout::Variants::NicheFilling {
583 let variants_start = *niche_variants.start() as u128;
584 let variants_end = *niche_variants.end() as u128;
585 let real_discr = match raw_discr {
587 // The niche must be just 0 (which a pointer value never is)
588 assert!(niche_start == 0);
589 assert!(variants_start == variants_end);
590 dataful_variant as u128
592 Scalar::Bits { bits: raw_discr, size } => {
593 assert_eq!(size as u64, discr_val.layout.size.bytes());
594 let discr = raw_discr.wrapping_sub(niche_start)
595 .wrapping_add(variants_start);
596 if variants_start <= discr && discr <= variants_end {
599 dataful_variant as u128
603 let index = real_discr as usize;
604 assert_eq!(index as u128, real_discr);
605 assert!(index < rval.layout.ty
607 .expect("tagged layout for non adt")