]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
use is_uninhabited in more places
[rust.git] / src / librustc_mir / interpret / operand.rs
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.
4 //
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.
10
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.
13
14 use std::hash::{Hash, Hasher};
15 use std::convert::TryInto;
16
17 use rustc::{mir, ty};
18 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt};
19
20 use rustc::mir::interpret::{
21     GlobalId, AllocId,
22     ConstValue, Pointer, Scalar, ScalarMaybeUndef,
23     EvalResult, EvalErrorKind
24 };
25 use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
26
27 /// A `Value` represents a single immediate self-contained Rust value.
28 ///
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>),
38 }
39
40 impl<'tcx> Value {
41     pub fn new_slice(
42         val: Scalar,
43         len: u64,
44         cx: impl HasDataLayout
45     ) -> Self {
46         Value::ScalarPair(val.into(), Scalar::from_uint(len, cx.data_layout().pointer_size).into())
47     }
48
49     pub fn new_dyn_trait(val: Scalar, vtable: Pointer) -> Self {
50         Value::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
51     }
52
53     #[inline]
54     pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef {
55         match self {
56             Value::Scalar(val) => val,
57             Value::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
58         }
59     }
60
61     #[inline]
62     pub fn to_scalar(self) -> EvalResult<'tcx, Scalar> {
63         self.to_scalar_or_undef().not_undef()
64     }
65
66     #[inline]
67     pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar, Scalar)> {
68         match self {
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()?))
71         }
72     }
73
74     /// Convert the value into a pointer (or a pointer-sized integer).
75     /// Throws away the second half of a ScalarPair!
76     #[inline]
77     pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar> {
78         match self {
79             Value::Scalar(ptr) |
80             Value::ScalarPair(ptr, _) => ptr.not_undef(),
81         }
82     }
83 }
84
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> {
89     value: Value,
90     pub layout: TyLayout<'tcx>,
91 }
92
93 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
94     type Target = Value;
95     #[inline(always)]
96     fn deref(&self) -> &Value {
97         &self.value
98     }
99 }
100
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>),
108 }
109
110 impl Operand {
111     #[inline]
112     pub fn to_mem_place(self) -> MemPlace {
113         match self {
114             Operand::Indirect(mplace) => mplace,
115             _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
116
117         }
118     }
119
120     #[inline]
121     pub fn to_immediate(self) -> Value {
122         match self {
123             Operand::Immediate(val) => val,
124             _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
125
126         }
127     }
128 }
129
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>,
134 }
135
136 impl<'tcx> ::std::ops::Deref for OpTy<'tcx> {
137     type Target = Operand;
138     #[inline(always)]
139     fn deref(&self) -> &Operand {
140         &self.op
141     }
142 }
143
144 impl<'tcx> From<MPlaceTy<'tcx>> for OpTy<'tcx> {
145     #[inline(always)]
146     fn from(mplace: MPlaceTy<'tcx>) -> Self {
147         OpTy {
148             op: Operand::Indirect(*mplace),
149             layout: mplace.layout
150         }
151     }
152 }
153
154 impl<'tcx> From<ValTy<'tcx>> for OpTy<'tcx> {
155     #[inline(always)]
156     fn from(val: ValTy<'tcx>) -> Self {
157         OpTy {
158             op: Operand::Immediate(val.value),
159             layout: val.layout
160         }
161     }
162 }
163
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) {
167         self.op.hash(state);
168         self.layout.ty.hash(state);
169     }
170 }
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
174     }
175 }
176 impl<'tcx> Eq for OpTy<'tcx> {}
177
178 // Use the existing layout if given (but sanity check in debug mode),
179 // or compute the layout.
180 #[inline(always)]
181 fn from_known_layout<'tcx>(
182     layout: Option<TyLayout<'tcx>>,
183     compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
184 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
185     match layout {
186         None => compute(),
187         Some(layout) => {
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);
193             }
194             Ok(layout)
195         }
196     }
197 }
198
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(
203         &self,
204         mplace: MPlaceTy<'tcx>,
205     ) -> EvalResult<'tcx, Option<Value>> {
206         if mplace.layout.is_unsized() {
207             // Dont touch unsized
208             return Ok(None);
209         }
210         let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
211
212         if mplace.layout.is_zst() {
213             // Not all ZSTs have a layout we would handle below, so just short-circuit them
214             // all here.
215             self.memory.check_align(ptr, ptr_align)?;
216             return Ok(Some(Value::Scalar(Scalar::zst().into())));
217         }
218
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)))
224             }
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));
228                 let a_ptr = ptr;
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)))
235             }
236             _ => Ok(None),
237         }
238     }
239
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(
247         &self,
248         src: OpTy<'tcx>,
249     ) -> EvalResult<'tcx, Result<Value, MemPlace>> {
250         Ok(match src.try_as_mplace() {
251             Ok(mplace) => {
252                 if let Some(val) = self.try_read_value_from_mplace(mplace)? {
253                     Ok(val)
254                 } else {
255                     Err(*mplace)
256                 }
257             },
258             Err(val) => Ok(val),
259         })
260     }
261
262     /// Read a value from a place, asserting that that is possible with the given layout.
263     #[inline(always)]
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 })
267         } else {
268             bug!("primitive read failed for type: {:?}", op.layout.ty);
269         }
270     }
271
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),
277         }
278     }
279
280     // Turn the MPlace into a string (must already be dereferenced!)
281     pub fn read_str(
282         &self,
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()))?;
289         Ok(str)
290     }
291
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.
295         if layout.is_zst() {
296             return Ok(Operand::Immediate(Value::Scalar(Scalar::zst().into())));
297         }
298
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,
306                 )),
307             _ => {
308                 trace!("Forcing allocation for local of type {:?}", layout.ty);
309                 Operand::Indirect(
310                     *self.allocate(layout, MemoryKind::Stack)?
311                 )
312             }
313         })
314     }
315
316     /// Projection functions
317     pub fn operand_field(
318         &self,
319         op: OpTy<'tcx>,
320         field: u64,
321     ) -> EvalResult<'tcx, OpTy<'tcx>> {
322         let base = match op.try_as_mplace() {
323             Ok(mplace) => {
324                 // The easy case
325                 let field = self.mplace_field(mplace, field)?;
326                 return Ok(field.into());
327             },
328             Err(value) => value
329         };
330
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 });
336         }
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 };
344                 Value::Scalar(val)
345             },
346             Value::Scalar(val) =>
347                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
348         };
349         Ok(OpTy { op: Operand::Immediate(value), layout: field_layout })
350     }
351
352     pub fn operand_downcast(
353         &self,
354         op: OpTy<'tcx>,
355         variant: usize,
356     ) -> EvalResult<'tcx, OpTy<'tcx>> {
357         // Downcasts only change the layout
358         Ok(match op.try_as_mplace() {
359             Ok(mplace) => {
360                 self.mplace_downcast(mplace, variant)?.into()
361             },
362             Err(..) => {
363                 let layout = op.layout.for_variant(self, variant);
364                 OpTy { layout, ..op }
365             }
366         })
367     }
368
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(
372         &self,
373         src: OpTy<'tcx>,
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)?)
378     }
379
380     pub fn operand_projection(
381         &self,
382         base: OpTy<'tcx>,
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() {
391                 OpTy {
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)?,
395                 }
396             } else {
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()
401             }
402         })
403     }
404
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.
408     fn eval_place_to_op(
409         &self,
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),
416             Local(local) => {
417                 let op = *self.frame().locals[local].access()?;
418                 let layout = from_known_layout(layout,
419                     || self.layout_of_local(self.cur_frame(), local))?;
420                 OpTy { op, layout }
421             },
422
423             Projection(ref proj) => {
424                 let op = self.eval_place_to_op(&proj.base, None)?;
425                 self.operand_projection(op, &proj.elem)?
426             }
427
428             _ => self.eval_place_to_mplace(mir_place)?.into(),
429         };
430
431         trace!("eval_place_to_op: got {:?}", *op);
432         Ok(op)
433     }
434
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.
438     pub fn eval_operand(
439         &self,
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
446             Copy(ref place) |
447             Move(ref place) =>
448                 self.eval_place_to_op(place, layout)?,
449
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());
453                     self.layout_of(ty)
454                 })?;
455                 let op = self.const_value_to_op(constant.literal.val)?;
456                 OpTy { op, layout }
457             }
458         };
459         trace!("{:?}: {:?}", mir_op, *op);
460         Ok(op)
461     }
462
463     /// Evaluate a bunch of operands at once
464     pub(super) fn eval_operands(
465         &self,
466         ops: &[mir::Operand<'tcx>],
467     ) -> EvalResult<'tcx, Vec<OpTy<'tcx>>> {
468         ops.into_iter()
469             .map(|op| self.eval_operand(op, None))
470             .collect()
471     }
472
473     // Also used e.g. when miri runs into a constant.
474     pub(super) fn const_value_to_op(
475         &self,
476         val: ConstValue<'tcx>,
477     ) -> EvalResult<'tcx, Operand> {
478         trace!("const_value_to_op: {:?}", val);
479         match val {
480             ConstValue::Unevaluated(def_id, substs) => {
481                 let instance = self.resolve(def_id, substs)?;
482                 self.global_to_op(GlobalId {
483                     instance,
484                     promoted: None,
485                 })
486             }
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)))
491             },
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()))),
496         }
497     }
498     pub fn const_to_op(
499         &self,
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)? })
504     }
505
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)
509     }
510
511     /// Read discriminant, return the runtime value as well as the variant index.
512     pub fn read_discriminant(
513         &self,
514         rval: OpTy<'tcx>,
515     ) -> EvalResult<'tcx, (u128, usize)> {
516         trace!("read_discriminant_value {:#?}", rval.layout);
517         if rval.layout.abi.is_uninhabited() {
518             return err!(Unreachable);
519         }
520
521         match rval.layout.variants {
522             layout::Variants::Single { index } => {
523                 let discr_val = rval.layout.ty.ty_adt_def().map_or(
524                     index as u128,
525                     |def| def.discriminant_for_variant(*self.tcx, index).val);
526                 return Ok((discr_val, index));
527             }
528             layout::Variants::Tagged { .. } |
529             layout::Variants::NicheFilling { .. } => {},
530         }
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);
536         // post-process
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")
549                         .repr
550                         .discr_type();
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
555                 } else {
556                     raw_discr.to_bits(discr_val.layout.size)?
557                 };
558                 // Make sure we catch invalid discriminants
559                 let index = rval.layout.ty
560                     .ty_adt_def()
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))?;
565                 (real_discr, index)
566             },
567             layout::Variants::NicheFilling {
568                 dataful_variant,
569                 ref niche_variants,
570                 niche_start,
571                 ..
572             } => {
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 {
576                     Scalar::Ptr(_) => {
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
581                     },
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 {
587                             discr
588                         } else {
589                             dataful_variant as u128
590                         }
591                     },
592                 };
593                 let index = real_discr as usize;
594                 assert_eq!(index as u128, real_discr);
595                 assert!(index < rval.layout.ty
596                     .ty_adt_def()
597                     .expect("tagged layout for non adt")
598                     .variants.len());
599                 (real_discr, index)
600             }
601         })
602     }
603
604 }