]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
Limit the visibility further and expand on a comment
[rust.git] / src / librustc_mir / interpret / operand.rs
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.
3
4 use std::convert::TryInto;
5
6 use rustc::{mir, ty};
7 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
8
9 use rustc::mir::interpret::{
10     GlobalId, AllocId, InboundsCheck,
11     ConstValue, Pointer, Scalar,
12     EvalResult, EvalErrorKind,
13 };
14 use super::{
15     EvalContext, Machine,
16     MemPlace, MPlaceTy, PlaceTy, Place, MemoryKind,
17 };
18 pub use rustc::mir::interpret::ScalarMaybeUndef;
19
20 /// A `Value` represents a single immediate self-contained Rust value.
21 ///
22 /// For optimization of a few very common cases, there is also a representation for a pair of
23 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
24 /// operations and fat pointers. This idea was taken from rustc's codegen.
25 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
26 /// defined on `Immediate`, and do not have to work with a `Place`.
27 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
28 pub enum Immediate<Tag=(), Id=AllocId> {
29     Scalar(ScalarMaybeUndef<Tag, Id>),
30     ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
31 }
32
33 impl Immediate {
34     #[inline]
35     pub fn with_default_tag<Tag>(self) -> Immediate<Tag>
36         where Tag: Default
37     {
38         match self {
39             Immediate::Scalar(x) => Immediate::Scalar(x.with_default_tag()),
40             Immediate::ScalarPair(x, y) =>
41                 Immediate::ScalarPair(x.with_default_tag(), y.with_default_tag()),
42         }
43     }
44 }
45
46 impl<'tcx, Tag> Immediate<Tag> {
47     #[inline]
48     pub fn from_scalar(val: Scalar<Tag>) -> Self {
49         Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
50     }
51
52     #[inline]
53     pub fn erase_tag(self) -> Immediate
54     {
55         match self {
56             Immediate::Scalar(x) => Immediate::Scalar(x.erase_tag()),
57             Immediate::ScalarPair(x, y) =>
58                 Immediate::ScalarPair(x.erase_tag(), y.erase_tag()),
59         }
60     }
61
62     pub fn new_slice(
63         val: Scalar<Tag>,
64         len: u64,
65         cx: &impl HasDataLayout
66     ) -> Self {
67         Immediate::ScalarPair(
68             val.into(),
69             Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
70         )
71     }
72
73     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
74         Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
75     }
76
77     #[inline]
78     pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
79         match self {
80             Immediate::Scalar(val) => val,
81             Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
82         }
83     }
84
85     #[inline]
86     pub fn to_scalar(self) -> EvalResult<'tcx, Scalar<Tag>> {
87         self.to_scalar_or_undef().not_undef()
88     }
89
90     #[inline]
91     pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
92         match self {
93             Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
94             Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
95         }
96     }
97
98     /// Converts the immediate into a pointer (or a pointer-sized integer).
99     /// Throws away the second half of a ScalarPair!
100     #[inline]
101     pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar<Tag>> {
102         match self {
103             Immediate::Scalar(ptr) |
104             Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
105         }
106     }
107
108     /// Converts the value into its metadata.
109     /// Throws away the first half of a ScalarPair!
110     #[inline]
111     pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
112         Ok(match self {
113             Immediate::Scalar(_) => None,
114             Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
115         })
116     }
117 }
118
119 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
120 // as input for binary and cast operations.
121 #[derive(Copy, Clone, Debug)]
122 pub struct ImmTy<'tcx, Tag=()> {
123     pub imm: Immediate<Tag>,
124     pub layout: TyLayout<'tcx>,
125 }
126
127 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
128     type Target = Immediate<Tag>;
129     #[inline(always)]
130     fn deref(&self) -> &Immediate<Tag> {
131         &self.imm
132     }
133 }
134
135 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
136 /// or still in memory. The latter is an optimization, to delay reading that chunk of
137 /// memory and to avoid having to store arbitrary-sized data here.
138 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
139 pub enum Operand<Tag=(), Id=AllocId> {
140     Immediate(Immediate<Tag, Id>),
141     Indirect(MemPlace<Tag, Id>),
142 }
143
144 impl Operand {
145     #[inline]
146     pub fn with_default_tag<Tag>(self) -> Operand<Tag>
147         where Tag: Default
148     {
149         match self {
150             Operand::Immediate(x) => Operand::Immediate(x.with_default_tag()),
151             Operand::Indirect(x) => Operand::Indirect(x.with_default_tag()),
152         }
153     }
154 }
155
156 impl<Tag> Operand<Tag> {
157     #[inline]
158     pub fn erase_tag(self) -> Operand
159     {
160         match self {
161             Operand::Immediate(x) => Operand::Immediate(x.erase_tag()),
162             Operand::Indirect(x) => Operand::Indirect(x.erase_tag()),
163         }
164     }
165
166     #[inline]
167     pub fn to_mem_place(self) -> MemPlace<Tag>
168         where Tag: ::std::fmt::Debug
169     {
170         match self {
171             Operand::Indirect(mplace) => mplace,
172             _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
173
174         }
175     }
176
177     #[inline]
178     pub fn to_immediate(self) -> Immediate<Tag>
179         where Tag: ::std::fmt::Debug
180     {
181         match self {
182             Operand::Immediate(imm) => imm,
183             _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
184
185         }
186     }
187 }
188
189 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
190 pub struct OpTy<'tcx, Tag=()> {
191     op: Operand<Tag>,
192     pub layout: TyLayout<'tcx>,
193 }
194
195 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
196     type Target = Operand<Tag>;
197     #[inline(always)]
198     fn deref(&self) -> &Operand<Tag> {
199         &self.op
200     }
201 }
202
203 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
204     #[inline(always)]
205     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
206         OpTy {
207             op: Operand::Indirect(*mplace),
208             layout: mplace.layout
209         }
210     }
211 }
212
213 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
214     #[inline(always)]
215     fn from(val: ImmTy<'tcx, Tag>) -> Self {
216         OpTy {
217             op: Operand::Immediate(val.imm),
218             layout: val.layout
219         }
220     }
221 }
222
223 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
224 {
225     #[inline]
226     pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
227         ImmTy { imm: Immediate::from_scalar(val), layout }
228     }
229
230     #[inline]
231     pub fn to_bits(self) -> EvalResult<'tcx, u128> {
232         self.to_scalar()?.to_bits(self.layout.size)
233     }
234 }
235
236 impl<'tcx, Tag> OpTy<'tcx, Tag>
237 {
238     #[inline]
239     pub fn erase_tag(self) -> OpTy<'tcx>
240     {
241         OpTy {
242             op: self.op.erase_tag(),
243             layout: self.layout,
244         }
245     }
246 }
247
248 // Use the existing layout if given (but sanity check in debug mode),
249 // or compute the layout.
250 #[inline(always)]
251 pub(super) fn from_known_layout<'tcx>(
252     layout: Option<TyLayout<'tcx>>,
253     compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
254 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
255     match layout {
256         None => compute(),
257         Some(layout) => {
258             if cfg!(debug_assertions) {
259                 let layout2 = compute()?;
260                 assert_eq!(layout.details, layout2.details,
261                     "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
262                     layout.ty, layout2.ty);
263             }
264             Ok(layout)
265         }
266     }
267 }
268
269 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
270     /// Try reading an immediate in memory; this is interesting particularly for ScalarPair.
271     /// Returns `None` if the layout does not permit loading this as a value.
272     fn try_read_immediate_from_mplace(
273         &self,
274         mplace: MPlaceTy<'tcx, M::PointerTag>,
275     ) -> EvalResult<'tcx, Option<Immediate<M::PointerTag>>> {
276         if mplace.layout.is_unsized() {
277             // Don't touch unsized
278             return Ok(None);
279         }
280         let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
281
282         if mplace.layout.is_zst() {
283             // Not all ZSTs have a layout we would handle below, so just short-circuit them
284             // all here.
285             self.memory.check_align(ptr, ptr_align)?;
286             return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
287         }
288
289         // check for integer pointers before alignment to report better errors
290         let ptr = ptr.to_ptr()?;
291         self.memory.check_align(ptr.into(), ptr_align)?;
292         match mplace.layout.abi {
293             layout::Abi::Scalar(..) => {
294                 let scalar = self.memory
295                     .get(ptr.alloc_id)?
296                     .read_scalar(self, ptr, mplace.layout.size)?;
297                 Ok(Some(Immediate::Scalar(scalar)))
298             }
299             layout::Abi::ScalarPair(ref a, ref b) => {
300                 let (a, b) = (&a.value, &b.value);
301                 let (a_size, b_size) = (a.size(self), b.size(self));
302                 let a_ptr = ptr;
303                 let b_offset = a_size.align_to(b.align(self).abi);
304                 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
305                 let b_ptr = ptr.offset(b_offset, self)?;
306                 let a_val = self.memory
307                     .get(ptr.alloc_id)?
308                     .read_scalar(self, a_ptr, a_size)?;
309                 let b_align = ptr_align.restrict_for_offset(b_offset);
310                 self.memory.check_align(b_ptr.into(), b_align)?;
311                 let b_val = self.memory
312                     .get(ptr.alloc_id)?
313                     .read_scalar(self, b_ptr, b_size)?;
314                 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
315             }
316             _ => Ok(None),
317         }
318     }
319
320     /// Try returning an immediate for the operand.
321     /// If the layout does not permit loading this as an immediate, return where in memory
322     /// we can find the data.
323     /// Note that for a given layout, this operation will either always fail or always
324     /// succeed!  Whether it succeeds depends on whether the layout can be represented
325     /// in a `Immediate`, not on which data is stored there currently.
326     pub(super) fn try_read_immediate(
327         &self,
328         src: OpTy<'tcx, M::PointerTag>,
329     ) -> EvalResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
330         Ok(match src.try_as_mplace() {
331             Ok(mplace) => {
332                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
333                     Ok(val)
334                 } else {
335                     Err(*mplace)
336                 }
337             },
338             Err(val) => Ok(val),
339         })
340     }
341
342     /// Read an immediate from a place, asserting that that is possible with the given layout.
343     #[inline(always)]
344     pub fn read_immediate(
345         &self,
346         op: OpTy<'tcx, M::PointerTag>
347     ) -> EvalResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
348         if let Ok(imm) = self.try_read_immediate(op)? {
349             Ok(ImmTy { imm, layout: op.layout })
350         } else {
351             bug!("primitive read failed for type: {:?}", op.layout.ty);
352         }
353     }
354
355     /// Read a scalar from a place
356     pub fn read_scalar(
357         &self,
358         op: OpTy<'tcx, M::PointerTag>
359     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
360         Ok(self.read_immediate(op)?.to_scalar_or_undef())
361     }
362
363     // Turn the MPlace into a string (must already be dereferenced!)
364     pub fn read_str(
365         &self,
366         mplace: MPlaceTy<'tcx, M::PointerTag>,
367     ) -> EvalResult<'tcx, &str> {
368         let len = mplace.len(self)?;
369         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
370         let str = ::std::str::from_utf8(bytes)
371             .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
372         Ok(str)
373     }
374
375     pub fn uninit_operand(
376         &mut self,
377         layout: TyLayout<'tcx>
378     ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
379         // This decides which types we will use the Immediate optimization for, and hence should
380         // match what `try_read_immediate` and `eval_place_to_op` support.
381         if layout.is_zst() {
382             return Ok(Operand::Immediate(Immediate::Scalar(Scalar::zst().into())));
383         }
384
385         Ok(match layout.abi {
386             layout::Abi::Scalar(..) =>
387                 Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)),
388             layout::Abi::ScalarPair(..) =>
389                 Operand::Immediate(Immediate::ScalarPair(
390                     ScalarMaybeUndef::Undef,
391                     ScalarMaybeUndef::Undef,
392                 )),
393             _ => {
394                 trace!("Forcing allocation for local of type {:?}", layout.ty);
395                 Operand::Indirect(
396                     *self.allocate(layout, MemoryKind::Stack)
397                 )
398             }
399         })
400     }
401
402     /// Projection functions
403     pub fn operand_field(
404         &self,
405         op: OpTy<'tcx, M::PointerTag>,
406         field: u64,
407     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
408         let base = match op.try_as_mplace() {
409             Ok(mplace) => {
410                 // The easy case
411                 let field = self.mplace_field(mplace, field)?;
412                 return Ok(field.into());
413             },
414             Err(value) => value
415         };
416
417         let field = field.try_into().unwrap();
418         let field_layout = op.layout.field(self, field)?;
419         if field_layout.is_zst() {
420             let immediate = Immediate::Scalar(Scalar::zst().into());
421             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
422         }
423         let offset = op.layout.fields.offset(field);
424         let immediate = match base {
425             // the field covers the entire type
426             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
427             // extract fields from types with `ScalarPair` ABI
428             Immediate::ScalarPair(a, b) => {
429                 let val = if offset.bytes() == 0 { a } else { b };
430                 Immediate::Scalar(val)
431             },
432             Immediate::Scalar(val) =>
433                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
434         };
435         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
436     }
437
438     pub fn operand_downcast(
439         &self,
440         op: OpTy<'tcx, M::PointerTag>,
441         variant: VariantIdx,
442     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
443         // Downcasts only change the layout
444         Ok(match op.try_as_mplace() {
445             Ok(mplace) => {
446                 self.mplace_downcast(mplace, variant)?.into()
447             },
448             Err(..) => {
449                 let layout = op.layout.for_variant(self, variant);
450                 OpTy { layout, ..op }
451             }
452         })
453     }
454
455     pub fn operand_projection(
456         &self,
457         base: OpTy<'tcx, M::PointerTag>,
458         proj_elem: &mir::PlaceElem<'tcx>,
459     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
460         use rustc::mir::ProjectionElem::*;
461         Ok(match *proj_elem {
462             Field(field, _) => self.operand_field(base, field.index() as u64)?,
463             Downcast(_, variant) => self.operand_downcast(base, variant)?,
464             Deref => self.deref_operand(base)?.into(),
465             Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
466                 OpTy {
467                     op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
468                     // the actual index doesn't matter, so we just pick a convenient one like 0
469                     layout: base.layout.field(self, 0)?,
470                 }
471             } else {
472                 // The rest should only occur as mplace, we do not use Immediates for types
473                 // allowing such operations.  This matches place_projection forcing an allocation.
474                 let mplace = base.to_mem_place();
475                 self.mplace_projection(mplace, proj_elem)?.into()
476             }
477         })
478     }
479
480     /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
481     pub fn access_local(
482         &self,
483         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
484         local: mir::Local,
485         layout: Option<TyLayout<'tcx>>,
486     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
487         assert_ne!(local, mir::RETURN_PLACE);
488         let op = *frame.locals[local].access()?;
489         let layout = self.layout_of_local(frame, local, layout)?;
490         Ok(OpTy { op, layout })
491     }
492
493     /// Every place can be read from, so we can turm them into an operand
494     #[inline(always)]
495     pub fn place_to_op(
496         &self,
497         place: PlaceTy<'tcx, M::PointerTag>
498     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
499         let op = match *place {
500             Place::Ptr(mplace) => {
501                 Operand::Indirect(mplace)
502             }
503             Place::Local { frame, local } =>
504                 *self.stack[frame].locals[local].access()?
505         };
506         Ok(OpTy { op, layout: place.layout })
507     }
508
509     // Evaluate a place with the goal of reading from it.  This lets us sometimes
510     // avoid allocations.
511     pub(super) fn eval_place_to_op(
512         &self,
513         mir_place: &mir::Place<'tcx>,
514         layout: Option<TyLayout<'tcx>>,
515     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
516         use rustc::mir::Place::*;
517         let op = match *mir_place {
518             Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
519             Local(local) => self.access_local(self.frame(), local, layout)?,
520
521             Projection(ref proj) => {
522                 let op = self.eval_place_to_op(&proj.base, None)?;
523                 self.operand_projection(op, &proj.elem)?
524             }
525
526             _ => self.eval_place_to_mplace(mir_place)?.into(),
527         };
528
529         trace!("eval_place_to_op: got {:?}", *op);
530         Ok(op)
531     }
532
533     /// Evaluate the operand, returning a place where you can then find the data.
534     /// if you already know the layout, you can save two some table lookups
535     /// by passing it in here.
536     pub fn eval_operand(
537         &self,
538         mir_op: &mir::Operand<'tcx>,
539         layout: Option<TyLayout<'tcx>>,
540     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
541         use rustc::mir::Operand::*;
542         let op = match *mir_op {
543             // FIXME: do some more logic on `move` to invalidate the old location
544             Copy(ref place) |
545             Move(ref place) =>
546                 self.eval_place_to_op(place, layout)?,
547
548             Constant(ref constant) => self.eval_lazy_const_to_op(*constant.literal, layout)?,
549         };
550         trace!("{:?}: {:?}", mir_op, *op);
551         Ok(op)
552     }
553
554     /// Evaluate a bunch of operands at once
555     pub(super) fn eval_operands(
556         &self,
557         ops: &[mir::Operand<'tcx>],
558     ) -> EvalResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
559         ops.into_iter()
560             .map(|op| self.eval_operand(op, None))
561             .collect()
562     }
563
564     // Used when Miri runs into a constant, and by const propagation.
565     crate fn eval_lazy_const_to_op(
566         &self,
567         val: ty::LazyConst<'tcx>,
568         layout: Option<TyLayout<'tcx>>,
569     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
570         trace!("const_to_op: {:?}", val);
571         match val {
572             ty::LazyConst::Unevaluated(def_id, substs) => {
573                 let instance = self.resolve(def_id, substs)?;
574                 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
575                     instance,
576                     promoted: None,
577                 })?));
578             },
579             ty::LazyConst::Evaluated(c) => self.const_to_op(c, layout),
580         }
581     }
582
583     // Used when the miri-engine runs into a constant and for extracting information from constants
584     // in patterns via the `const_eval` module
585     crate fn const_to_op(
586         &self,
587         val: ty::Const<'tcx>,
588         layout: Option<TyLayout<'tcx>>,
589     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
590         let layout = from_known_layout(layout, || {
591             let ty = self.monomorphize(val.ty)?;
592             self.layout_of(ty)
593         })?;
594         let op = match val.val {
595             ConstValue::ByRef(ptr, alloc) => {
596                 // We rely on mutability being set correctly in that allocation to prevent writes
597                 // where none should happen -- and for `static mut`, we copy on demand anyway.
598                 Operand::Indirect(
599                     MemPlace::from_ptr(ptr, alloc.align)
600                 ).with_default_tag()
601             },
602             ConstValue::Slice(a, b) =>
603                 Operand::Immediate(Immediate::ScalarPair(
604                     a.into(),
605                     Scalar::from_uint(b, self.tcx.data_layout.pointer_size).into(),
606                 )).with_default_tag(),
607             ConstValue::Scalar(x) =>
608                 Operand::Immediate(Immediate::Scalar(x.into())).with_default_tag(),
609         };
610         Ok(OpTy {
611             op,
612             layout,
613         })
614     }
615
616     /// Read discriminant, return the runtime value as well as the variant index.
617     pub fn read_discriminant(
618         &self,
619         rval: OpTy<'tcx, M::PointerTag>,
620     ) -> EvalResult<'tcx, (u128, VariantIdx)> {
621         trace!("read_discriminant_value {:#?}", rval.layout);
622
623         match rval.layout.variants {
624             layout::Variants::Single { index } => {
625                 let discr_val = rval.layout.ty.ty_adt_def().map_or(
626                     index.as_u32() as u128,
627                     |def| def.discriminant_for_variant(*self.tcx, index).val);
628                 return Ok((discr_val, index));
629             }
630             layout::Variants::Tagged { .. } |
631             layout::Variants::NicheFilling { .. } => {},
632         }
633         // read raw discriminant value
634         let discr_op = self.operand_field(rval, 0)?;
635         let discr_val = self.read_immediate(discr_op)?;
636         let raw_discr = discr_val.to_scalar_or_undef();
637         trace!("discr value: {:?}", raw_discr);
638         // post-process
639         Ok(match rval.layout.variants {
640             layout::Variants::Single { .. } => bug!(),
641             layout::Variants::Tagged { .. } => {
642                 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
643                     Ok(raw_discr) => raw_discr,
644                     Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
645                 };
646                 let real_discr = if discr_val.layout.ty.is_signed() {
647                     let i = bits_discr as i128;
648                     // going from layout tag type to typeck discriminant type
649                     // requires first sign extending with the layout discriminant
650                     let shift = 128 - discr_val.layout.size.bits();
651                     let sexted = (i << shift) >> shift;
652                     // and then zeroing with the typeck discriminant type
653                     let discr_ty = rval.layout.ty
654                         .ty_adt_def().expect("tagged layout corresponds to adt")
655                         .repr
656                         .discr_type();
657                     let discr_ty = layout::Integer::from_attr(self, discr_ty);
658                     let shift = 128 - discr_ty.size().bits();
659                     let truncatee = sexted as u128;
660                     (truncatee << shift) >> shift
661                 } else {
662                     bits_discr
663                 };
664                 // Make sure we catch invalid discriminants
665                 let index = rval.layout.ty
666                     .ty_adt_def()
667                     .expect("tagged layout for non adt")
668                     .discriminants(self.tcx.tcx)
669                     .find(|(_, var)| var.val == real_discr)
670                     .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(raw_discr.erase_tag()))?;
671                 (real_discr, index.0)
672             },
673             layout::Variants::NicheFilling {
674                 dataful_variant,
675                 ref niche_variants,
676                 niche_start,
677                 ..
678             } => {
679                 let variants_start = niche_variants.start().as_u32() as u128;
680                 let variants_end = niche_variants.end().as_u32() as u128;
681                 match raw_discr {
682                     ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) => {
683                         // The niche must be just 0 (which an inbounds pointer value never is)
684                         let ptr_valid = niche_start == 0 && variants_start == variants_end &&
685                             self.memory.check_bounds_ptr(ptr, InboundsCheck::MaybeDead).is_ok();
686                         if !ptr_valid {
687                             return err!(InvalidDiscriminant(raw_discr.erase_tag()));
688                         }
689                         (dataful_variant.as_u32() as u128, dataful_variant)
690                     },
691                     ScalarMaybeUndef::Scalar(Scalar::Bits { bits: raw_discr, size }) => {
692                         assert_eq!(size as u64, discr_val.layout.size.bytes());
693                         let adjusted_discr = raw_discr.wrapping_sub(niche_start)
694                             .wrapping_add(variants_start);
695                         if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
696                             let index = adjusted_discr as usize;
697                             assert_eq!(index as u128, adjusted_discr);
698                             assert!(index < rval.layout.ty
699                                 .ty_adt_def()
700                                 .expect("tagged layout for non adt")
701                                 .variants.len());
702                             (adjusted_discr, VariantIdx::from_usize(index))
703                         } else {
704                             (dataful_variant.as_u32() as u128, dataful_variant)
705                         }
706                     },
707                     ScalarMaybeUndef::Undef =>
708                         return err!(InvalidDiscriminant(ScalarMaybeUndef::Undef)),
709                 }
710             }
711         })
712     }
713 }