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 // ScalarPair needs a type to interpret, so we often have a value and a type together
86 // as input for binary and cast operations.
87 #[derive(Copy, Clone, Debug)]
88 pub struct ValTy<'tcx> {
90 pub layout: TyLayout<'tcx>,
93 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
96 fn deref(&self) -> &Value {
101 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
102 /// or still in memory. The latter is an optimization, to delay reading that chunk of
103 /// memory and to avoid having to store arbitrary-sized data here.
104 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
105 pub enum Operand<Id=AllocId> {
106 Immediate(Value<Id>),
107 Indirect(MemPlace<Id>),
112 pub fn to_mem_place(self) -> MemPlace {
114 Operand::Indirect(mplace) => mplace,
115 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
121 pub fn to_immediate(self) -> Value {
123 Operand::Immediate(val) => val,
124 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
130 #[derive(Copy, Clone, Debug)]
131 pub struct OpTy<'tcx> {
132 crate op: Operand, // ideally we'd make this private, but const_prop needs this
133 pub layout: TyLayout<'tcx>,
136 impl<'tcx> ::std::ops::Deref for OpTy<'tcx> {
137 type Target = Operand;
139 fn deref(&self) -> &Operand {
144 impl<'tcx> From<MPlaceTy<'tcx>> for OpTy<'tcx> {
146 fn from(mplace: MPlaceTy<'tcx>) -> Self {
148 op: Operand::Indirect(*mplace),
149 layout: mplace.layout
154 impl<'tcx> From<ValTy<'tcx>> for OpTy<'tcx> {
156 fn from(val: ValTy<'tcx>) -> Self {
158 op: Operand::Immediate(val.value),
164 // Validation needs to hash OpTy, but we cannot hash Layout -- so we just hash the type
165 impl<'tcx> Hash for OpTy<'tcx> {
166 fn hash<H: Hasher>(&self, state: &mut H) {
168 self.layout.ty.hash(state);
171 impl<'tcx> PartialEq for OpTy<'tcx> {
172 fn eq(&self, other: &Self) -> bool {
173 self.op == other.op && self.layout.ty == other.layout.ty
176 impl<'tcx> Eq for OpTy<'tcx> {}
178 // Use the existing layout if given (but sanity check in debug mode),
179 // or compute the layout.
181 fn from_known_layout<'tcx>(
182 layout: Option<TyLayout<'tcx>>,
183 compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
184 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
188 if cfg!(debug_assertions) {
189 let layout2 = compute()?;
190 assert_eq!(layout.details, layout2.details,
191 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
192 layout.ty, layout2.ty);
199 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
200 /// Try reading a value in memory; this is interesting particularily for ScalarPair.
201 /// Return None if the layout does not permit loading this as a value.
202 pub(super) fn try_read_value_from_mplace(
204 mplace: MPlaceTy<'tcx>,
205 ) -> EvalResult<'tcx, Option<Value>> {
206 if mplace.layout.is_unsized() {
207 // Dont touch unsized
210 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
212 if mplace.layout.is_zst() {
213 // Not all ZSTs have a layout we would handle below, so just short-circuit them
215 self.memory.check_align(ptr, ptr_align)?;
216 return Ok(Some(Value::Scalar(Scalar::zst().into())));
219 let ptr = ptr.to_ptr()?;
220 match mplace.layout.abi {
221 layout::Abi::Scalar(..) => {
222 let scalar = self.memory.read_scalar(ptr, ptr_align, mplace.layout.size)?;
223 Ok(Some(Value::Scalar(scalar)))
225 layout::Abi::ScalarPair(ref a, ref b) => {
226 let (a, b) = (&a.value, &b.value);
227 let (a_size, b_size) = (a.size(self), b.size(self));
229 let b_offset = a_size.abi_align(b.align(self));
230 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
231 let b_ptr = ptr.offset(b_offset, self)?.into();
232 let a_val = self.memory.read_scalar(a_ptr, ptr_align, a_size)?;
233 let b_val = self.memory.read_scalar(b_ptr, ptr_align, b_size)?;
234 Ok(Some(Value::ScalarPair(a_val, b_val)))
240 /// Try returning an immediate value for the operand.
241 /// If the layout does not permit loading this as a value, return where in memory
242 /// we can find the data.
243 /// Note that for a given layout, this operation will either always fail or always
244 /// succeed! Whether it succeeds depends on whether the layout can be represented
245 /// in a `Value`, not on which data is stored there currently.
246 pub(crate) fn try_read_value(
249 ) -> EvalResult<'tcx, Result<Value, MemPlace>> {
250 Ok(match src.try_as_mplace() {
252 if let Some(val) = self.try_read_value_from_mplace(mplace)? {
262 /// Read a value from a place, asserting that that is possible with the given layout.
264 pub fn read_value(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
265 if let Ok(value) = self.try_read_value(op)? {
266 Ok(ValTy { value, layout: op.layout })
268 bug!("primitive read failed for type: {:?}", op.layout.ty);
272 /// Read a scalar from a place
273 pub fn read_scalar(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ScalarMaybeUndef> {
274 match *self.read_value(op)? {
275 Value::ScalarPair(..) => bug!("got ScalarPair for type: {:?}", op.layout.ty),
276 Value::Scalar(val) => Ok(val),
280 // Turn the MPlace into a string (must already be dereferenced!)
283 mplace: MPlaceTy<'tcx>,
284 ) -> EvalResult<'tcx, &str> {
285 let len = mplace.len(self)?;
286 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
287 let str = ::std::str::from_utf8(bytes)
288 .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
292 pub fn uninit_operand(&mut self, layout: TyLayout<'tcx>) -> EvalResult<'tcx, Operand> {
293 // This decides which types we will use the Immediate optimization for, and hence should
294 // match what `try_read_value` and `eval_place_to_op` support.
296 return Ok(Operand::Immediate(Value::Scalar(Scalar::zst().into())));
299 Ok(match layout.abi {
300 layout::Abi::Scalar(..) =>
301 Operand::Immediate(Value::Scalar(ScalarMaybeUndef::Undef)),
302 layout::Abi::ScalarPair(..) =>
303 Operand::Immediate(Value::ScalarPair(
304 ScalarMaybeUndef::Undef,
305 ScalarMaybeUndef::Undef,
308 trace!("Forcing allocation for local of type {:?}", layout.ty);
310 *self.allocate(layout, MemoryKind::Stack)?
316 /// Projection functions
317 pub fn operand_field(
321 ) -> EvalResult<'tcx, OpTy<'tcx>> {
322 let base = match op.try_as_mplace() {
325 let field = self.mplace_field(mplace, field)?;
326 return Ok(field.into());
331 let field = field.try_into().unwrap();
332 let field_layout = op.layout.field(self, field)?;
333 if field_layout.is_zst() {
334 let val = Value::Scalar(Scalar::zst().into());
335 return Ok(OpTy { op: Operand::Immediate(val), layout: field_layout });
337 let offset = op.layout.fields.offset(field);
338 let value = match base {
339 // the field covers the entire type
340 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
341 // extract fields from types with `ScalarPair` ABI
342 Value::ScalarPair(a, b) => {
343 let val = if offset.bytes() == 0 { a } else { b };
346 Value::Scalar(val) =>
347 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
349 Ok(OpTy { op: Operand::Immediate(value), layout: field_layout })
352 pub fn operand_downcast(
356 ) -> EvalResult<'tcx, OpTy<'tcx>> {
357 // Downcasts only change the layout
358 Ok(match op.try_as_mplace() {
360 self.mplace_downcast(mplace, variant)?.into()
363 let layout = op.layout.for_variant(self, variant);
364 OpTy { layout, ..op }
369 // Take an operand, representing a pointer, and dereference it to a place -- that
370 // will always be a MemPlace.
371 pub(super) fn deref_operand(
374 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
375 let val = self.read_value(src)?;
376 trace!("deref to {} on {:?}", val.layout.ty, *val);
377 Ok(self.ref_to_mplace(val)?)
380 pub fn operand_projection(
383 proj_elem: &mir::PlaceElem<'tcx>,
384 ) -> EvalResult<'tcx, OpTy<'tcx>> {
385 use rustc::mir::ProjectionElem::*;
386 Ok(match *proj_elem {
387 Field(field, _) => self.operand_field(base, field.index() as u64)?,
388 Downcast(_, variant) => self.operand_downcast(base, variant)?,
389 Deref => self.deref_operand(base)?.into(),
390 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
392 op: Operand::Immediate(Value::Scalar(Scalar::zst().into())),
393 // the actual index doesn't matter, so we just pick a convenient one like 0
394 layout: base.layout.field(self, 0)?,
397 // The rest should only occur as mplace, we do not use Immediates for types
398 // allowing such operations. This matches place_projection forcing an allocation.
399 let mplace = base.to_mem_place();
400 self.mplace_projection(mplace, proj_elem)?.into()
405 // Evaluate a place with the goal of reading from it. This lets us sometimes
406 // avoid allocations. If you already know the layout, you can pass it in
407 // to avoid looking it up again.
410 mir_place: &mir::Place<'tcx>,
411 layout: Option<TyLayout<'tcx>>,
412 ) -> EvalResult<'tcx, OpTy<'tcx>> {
413 use rustc::mir::Place::*;
414 let op = match *mir_place {
415 Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
417 let op = *self.frame().locals[local].access()?;
418 let layout = from_known_layout(layout,
419 || self.layout_of_local(self.cur_frame(), local))?;
423 Projection(ref proj) => {
424 let op = self.eval_place_to_op(&proj.base, None)?;
425 self.operand_projection(op, &proj.elem)?
428 _ => self.eval_place_to_mplace(mir_place)?.into(),
431 trace!("eval_place_to_op: got {:?}", *op);
435 /// Evaluate the operand, returning a place where you can then find the data.
436 /// if you already know the layout, you can save two some table lookups
437 /// by passing it in here.
440 mir_op: &mir::Operand<'tcx>,
441 layout: Option<TyLayout<'tcx>>,
442 ) -> EvalResult<'tcx, OpTy<'tcx>> {
443 use rustc::mir::Operand::*;
444 let op = match *mir_op {
445 // FIXME: do some more logic on `move` to invalidate the old location
448 self.eval_place_to_op(place, layout)?,
450 Constant(ref constant) => {
451 let layout = from_known_layout(layout, || {
452 let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
455 let op = self.const_value_to_op(constant.literal.val)?;
459 trace!("{:?}: {:?}", mir_op, *op);
463 /// Evaluate a bunch of operands at once
464 pub(super) fn eval_operands(
466 ops: &[mir::Operand<'tcx>],
467 ) -> EvalResult<'tcx, Vec<OpTy<'tcx>>> {
469 .map(|op| self.eval_operand(op, None))
473 // Also used e.g. when miri runs into a constant.
474 pub(super) fn const_value_to_op(
476 val: ConstValue<'tcx>,
477 ) -> EvalResult<'tcx, Operand> {
478 trace!("const_value_to_op: {:?}", val);
480 ConstValue::Unevaluated(def_id, substs) => {
481 let instance = self.resolve(def_id, substs)?;
482 self.global_to_op(GlobalId {
487 ConstValue::ByRef(id, alloc, offset) => {
488 // We rely on mutability being set correctly in that allocation to prevent writes
489 // where none should happen -- and for `static mut`, we copy on demand anyway.
490 Ok(Operand::Indirect(MemPlace::from_ptr(Pointer::new(id, offset), alloc.align)))
492 ConstValue::ScalarPair(a, b) =>
493 Ok(Operand::Immediate(Value::ScalarPair(a.into(), b))),
494 ConstValue::Scalar(x) =>
495 Ok(Operand::Immediate(Value::Scalar(x.into()))),
500 cnst: &ty::Const<'tcx>,
501 ) -> EvalResult<'tcx, OpTy<'tcx>> {
502 let op = self.const_value_to_op(cnst.val)?;
503 Ok(OpTy { op, layout: self.layout_of(cnst.ty)? })
506 pub(super) fn global_to_op(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, Operand> {
507 let cv = self.const_eval(gid)?;
508 self.const_value_to_op(cv.val)
511 /// Read discriminant, return the runtime value as well as the variant index.
512 pub fn read_discriminant(
515 ) -> EvalResult<'tcx, (u128, usize)> {
516 trace!("read_discriminant_value {:#?}", rval.layout);
517 if rval.layout.abi.is_uninhabited() {
518 return err!(Unreachable);
521 match rval.layout.variants {
522 layout::Variants::Single { index } => {
523 let discr_val = rval.layout.ty.ty_adt_def().map_or(
525 |def| def.discriminant_for_variant(*self.tcx, index).val);
526 return Ok((discr_val, index));
528 layout::Variants::Tagged { .. } |
529 layout::Variants::NicheFilling { .. } => {},
531 // read raw discriminant value
532 let discr_op = self.operand_field(rval, 0)?;
533 let discr_val = self.read_value(discr_op)?;
534 let raw_discr = discr_val.to_scalar()?;
535 trace!("discr value: {:?}", raw_discr);
537 Ok(match rval.layout.variants {
538 layout::Variants::Single { .. } => bug!(),
539 layout::Variants::Tagged { .. } => {
540 let real_discr = if discr_val.layout.ty.is_signed() {
541 let i = raw_discr.to_bits(discr_val.layout.size)? as i128;
542 // going from layout tag type to typeck discriminant type
543 // requires first sign extending with the layout discriminant
544 let shift = 128 - discr_val.layout.size.bits();
545 let sexted = (i << shift) >> shift;
546 // and then zeroing with the typeck discriminant type
547 let discr_ty = rval.layout.ty
548 .ty_adt_def().expect("tagged layout corresponds to adt")
551 let discr_ty = layout::Integer::from_attr(self.tcx.tcx, discr_ty);
552 let shift = 128 - discr_ty.size().bits();
553 let truncatee = sexted as u128;
554 (truncatee << shift) >> shift
556 raw_discr.to_bits(discr_val.layout.size)?
558 // Make sure we catch invalid discriminants
559 let index = rval.layout.ty
561 .expect("tagged layout for non adt")
562 .discriminants(self.tcx.tcx)
563 .position(|var| var.val == real_discr)
564 .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(real_discr))?;
567 layout::Variants::NicheFilling {
573 let variants_start = *niche_variants.start() as u128;
574 let variants_end = *niche_variants.end() as u128;
575 let real_discr = match raw_discr {
577 // The niche must be just 0 (which a pointer value never is)
578 assert!(niche_start == 0);
579 assert!(variants_start == variants_end);
580 dataful_variant as u128
582 Scalar::Bits { bits: raw_discr, size } => {
583 assert_eq!(size as u64, discr_val.layout.size.bytes());
584 let discr = raw_discr.wrapping_sub(niche_start)
585 .wrapping_add(variants_start);
586 if variants_start <= discr && discr <= variants_end {
589 dataful_variant as u128
593 let index = real_discr as usize;
594 assert_eq!(index as u128, real_discr);
595 assert!(index < rval.layout.ty
597 .expect("tagged layout for non adt")