]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
Rollup merge of #61926 - scottmcm:vec-vecdeque, r=Mark-Simulacrum
[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::{
8     self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx,
9 };
10
11 use rustc::mir::interpret::{
12     GlobalId, AllocId,
13     ConstValue, Pointer, Scalar,
14     InterpResult, InterpError,
15     sign_extend, truncate,
16 };
17 use super::{
18     InterpCx, Machine,
19     MemPlace, MPlaceTy, PlaceTy, Place,
20 };
21 pub use rustc::mir::interpret::ScalarMaybeUndef;
22
23 /// A `Value` represents a single immediate self-contained Rust value.
24 ///
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>),
34 }
35
36 impl<'tcx, Tag> Immediate<Tag> {
37     #[inline]
38     pub fn from_scalar(val: Scalar<Tag>) -> Self {
39         Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
40     }
41
42     pub fn new_slice(
43         val: Scalar<Tag>,
44         len: u64,
45         cx: &impl HasDataLayout
46     ) -> Self {
47         Immediate::ScalarPair(
48             val.into(),
49             Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
50         )
51     }
52
53     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
54         Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
55     }
56
57     #[inline]
58     pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
59         match self {
60             Immediate::Scalar(val) => val,
61             Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
62         }
63     }
64
65     #[inline]
66     pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
67         self.to_scalar_or_undef().not_undef()
68     }
69
70     #[inline]
71     pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
72         match self {
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()?))
75         }
76     }
77
78     /// Converts the immediate into a pointer (or a pointer-sized integer).
79     /// Throws away the second half of a ScalarPair!
80     #[inline]
81     pub fn to_scalar_ptr(self) -> InterpResult<'tcx, Scalar<Tag>> {
82         match self {
83             Immediate::Scalar(ptr) |
84             Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
85         }
86     }
87
88     /// Converts the value into its metadata.
89     /// Throws away the first half of a ScalarPair!
90     #[inline]
91     pub fn to_meta(self) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
92         Ok(match self {
93             Immediate::Scalar(_) => None,
94             Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
95         })
96     }
97 }
98
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>,
105 }
106
107 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
108     type Target = Immediate<Tag>;
109     #[inline(always)]
110     fn deref(&self) -> &Immediate<Tag> {
111         &self.imm
112     }
113 }
114
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>),
122 }
123
124 impl<Tag> Operand<Tag> {
125     #[inline]
126     pub fn assert_mem_place(self) -> MemPlace<Tag>
127         where Tag: ::std::fmt::Debug
128     {
129         match self {
130             Operand::Indirect(mplace) => mplace,
131             _ => bug!("assert_mem_place: expected Operand::Indirect, got {:?}", self),
132
133         }
134     }
135
136     #[inline]
137     pub fn assert_immediate(self) -> Immediate<Tag>
138         where Tag: ::std::fmt::Debug
139     {
140         match self {
141             Operand::Immediate(imm) => imm,
142             _ => bug!("assert_immediate: expected Operand::Immediate, got {:?}", self),
143
144         }
145     }
146 }
147
148 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
149 pub struct OpTy<'tcx, Tag=()> {
150     op: Operand<Tag>,
151     pub layout: TyLayout<'tcx>,
152 }
153
154 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
155     type Target = Operand<Tag>;
156     #[inline(always)]
157     fn deref(&self) -> &Operand<Tag> {
158         &self.op
159     }
160 }
161
162 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
163     #[inline(always)]
164     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
165         OpTy {
166             op: Operand::Indirect(*mplace),
167             layout: mplace.layout
168         }
169     }
170 }
171
172 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
173     #[inline(always)]
174     fn from(val: ImmTy<'tcx, Tag>) -> Self {
175         OpTy {
176             op: Operand::Immediate(val.imm),
177             layout: val.layout
178         }
179     }
180 }
181
182 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
183 {
184     #[inline]
185     pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
186         ImmTy { imm: Immediate::from_scalar(val), layout }
187     }
188
189     #[inline]
190     pub fn to_bits(self) -> InterpResult<'tcx, u128> {
191         self.to_scalar()?.to_bits(self.layout.size)
192     }
193 }
194
195 // Use the existing layout if given (but sanity check in debug mode),
196 // or compute the layout.
197 #[inline(always)]
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>> {
202     match layout {
203         None => compute(),
204         Some(layout) => {
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);
210             }
211             Ok(layout)
212         }
213     }
214 }
215
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.
219     #[inline]
220     pub fn force_op_ptr(
221         &self,
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
227         }
228     }
229
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(
233         &self,
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
238             return Ok(None);
239         }
240
241         let ptr = match self.check_mplace_access(mplace, None)? {
242             Some(ptr) => ptr,
243             None => return Ok(Some(ImmTy { // zero-sized type
244                 imm: Immediate::Scalar(Scalar::zst().into()),
245                 layout: mplace.layout,
246             })),
247         };
248
249         match mplace.layout.abi {
250             layout::Abi::Scalar(..) => {
251                 let scalar = self.memory
252                     .get(ptr.alloc_id)?
253                     .read_scalar(self, ptr, mplace.layout.size)?;
254                 Ok(Some(ImmTy {
255                     imm: Immediate::Scalar(scalar),
256                     layout: mplace.layout,
257                 }))
258             }
259             layout::Abi::ScalarPair(ref a, ref b) => {
260                 // We checked `ptr_align` above, so all fields will have the alignment they need.
261                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
262                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
263                 let (a, b) = (&a.value, &b.value);
264                 let (a_size, b_size) = (a.size(self), b.size(self));
265                 let a_ptr = ptr;
266                 let b_offset = a_size.align_to(b.align(self).abi);
267                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
268                 let b_ptr = ptr.offset(b_offset, self)?;
269                 let a_val = self.memory
270                     .get(ptr.alloc_id)?
271                     .read_scalar(self, a_ptr, a_size)?;
272                 let b_val = self.memory
273                     .get(ptr.alloc_id)?
274                     .read_scalar(self, b_ptr, b_size)?;
275                 Ok(Some(ImmTy {
276                     imm: Immediate::ScalarPair(a_val, b_val),
277                     layout: mplace.layout,
278                 }))
279             }
280             _ => Ok(None),
281         }
282     }
283
284     /// Try returning an immediate for the operand.
285     /// If the layout does not permit loading this as an immediate, return where in memory
286     /// we can find the data.
287     /// Note that for a given layout, this operation will either always fail or always
288     /// succeed!  Whether it succeeds depends on whether the layout can be represented
289     /// in a `Immediate`, not on which data is stored there currently.
290     pub(crate) fn try_read_immediate(
291         &self,
292         src: OpTy<'tcx, M::PointerTag>,
293     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
294         Ok(match src.try_as_mplace() {
295             Ok(mplace) => {
296                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
297                     Ok(val)
298                 } else {
299                     Err(mplace)
300                 }
301             },
302             Err(val) => Ok(val),
303         })
304     }
305
306     /// Read an immediate from a place, asserting that that is possible with the given layout.
307     #[inline(always)]
308     pub fn read_immediate(
309         &self,
310         op: OpTy<'tcx, M::PointerTag>
311     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
312         if let Ok(imm) = self.try_read_immediate(op)? {
313             Ok(imm)
314         } else {
315             bug!("primitive read failed for type: {:?}", op.layout.ty);
316         }
317     }
318
319     /// Read a scalar from a place
320     pub fn read_scalar(
321         &self,
322         op: OpTy<'tcx, M::PointerTag>
323     ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
324         Ok(self.read_immediate(op)?.to_scalar_or_undef())
325     }
326
327     // Turn the MPlace into a string (must already be dereferenced!)
328     pub fn read_str(
329         &self,
330         mplace: MPlaceTy<'tcx, M::PointerTag>,
331     ) -> InterpResult<'tcx, &str> {
332         let len = mplace.len(self)?;
333         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
334         let str = ::std::str::from_utf8(bytes)
335             .map_err(|err| InterpError::ValidationFailure(err.to_string()))?;
336         Ok(str)
337     }
338
339     /// Projection functions
340     pub fn operand_field(
341         &self,
342         op: OpTy<'tcx, M::PointerTag>,
343         field: u64,
344     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
345         let base = match op.try_as_mplace() {
346             Ok(mplace) => {
347                 // The easy case
348                 let field = self.mplace_field(mplace, field)?;
349                 return Ok(field.into());
350             },
351             Err(value) => value
352         };
353
354         let field = field.try_into().unwrap();
355         let field_layout = op.layout.field(self, field)?;
356         if field_layout.is_zst() {
357             let immediate = Immediate::Scalar(Scalar::zst().into());
358             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
359         }
360         let offset = op.layout.fields.offset(field);
361         let immediate = match *base {
362             // the field covers the entire type
363             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
364             // extract fields from types with `ScalarPair` ABI
365             Immediate::ScalarPair(a, b) => {
366                 let val = if offset.bytes() == 0 { a } else { b };
367                 Immediate::Scalar(val)
368             },
369             Immediate::Scalar(val) =>
370                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
371         };
372         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
373     }
374
375     pub fn operand_downcast(
376         &self,
377         op: OpTy<'tcx, M::PointerTag>,
378         variant: VariantIdx,
379     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
380         // Downcasts only change the layout
381         Ok(match op.try_as_mplace() {
382             Ok(mplace) => {
383                 self.mplace_downcast(mplace, variant)?.into()
384             },
385             Err(..) => {
386                 let layout = op.layout.for_variant(self, variant);
387                 OpTy { layout, ..op }
388             }
389         })
390     }
391
392     pub fn operand_projection(
393         &self,
394         base: OpTy<'tcx, M::PointerTag>,
395         proj_elem: &mir::PlaceElem<'tcx>,
396     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
397         use rustc::mir::ProjectionElem::*;
398         Ok(match *proj_elem {
399             Field(field, _) => self.operand_field(base, field.index() as u64)?,
400             Downcast(_, variant) => self.operand_downcast(base, variant)?,
401             Deref => self.deref_operand(base)?.into(),
402             Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
403                 OpTy {
404                     op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
405                     // the actual index doesn't matter, so we just pick a convenient one like 0
406                     layout: base.layout.field(self, 0)?,
407                 }
408             } else {
409                 // The rest should only occur as mplace, we do not use Immediates for types
410                 // allowing such operations.  This matches place_projection forcing an allocation.
411                 let mplace = base.assert_mem_place();
412                 self.mplace_projection(mplace, proj_elem)?.into()
413             }
414         })
415     }
416
417     /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
418     pub fn access_local(
419         &self,
420         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
421         local: mir::Local,
422         layout: Option<TyLayout<'tcx>>,
423     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
424         assert_ne!(local, mir::RETURN_PLACE);
425         let layout = self.layout_of_local(frame, local, layout)?;
426         let op = if layout.is_zst() {
427             // Do not read from ZST, they might not be initialized
428             Operand::Immediate(Immediate::Scalar(Scalar::zst().into()))
429         } else {
430             frame.locals[local].access()?
431         };
432         Ok(OpTy { op, layout })
433     }
434
435     /// Every place can be read from, so we can turn them into an operand
436     #[inline(always)]
437     pub fn place_to_op(
438         &self,
439         place: PlaceTy<'tcx, M::PointerTag>
440     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
441         let op = match *place {
442             Place::Ptr(mplace) => {
443                 Operand::Indirect(mplace)
444             }
445             Place::Local { frame, local } =>
446                 *self.access_local(&self.stack[frame], local, None)?
447         };
448         Ok(OpTy { op, layout: place.layout })
449     }
450
451     // Evaluate a place with the goal of reading from it.  This lets us sometimes
452     // avoid allocations.
453     pub(super) fn eval_place_to_op(
454         &self,
455         mir_place: &mir::Place<'tcx>,
456         layout: Option<TyLayout<'tcx>>,
457     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
458         use rustc::mir::Place;
459         use rustc::mir::PlaceBase;
460
461         mir_place.iterate(|place_base, place_projection| {
462             let mut op = match place_base {
463                 PlaceBase::Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
464                 PlaceBase::Local(local) => {
465                     // FIXME use place_projection.is_empty() when is available
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                     let layout = if let Place::Base(_) = mir_place {
469                         layout
470                     } else {
471                         None
472                     };
473
474                     self.access_local(self.frame(), *local, layout)?
475                 }
476                 PlaceBase::Static(place_static) => {
477                     self.eval_static_to_mplace(place_static)?.into()
478                 }
479             };
480
481             for proj in place_projection {
482                 op = self.operand_projection(op, &proj.elem)?
483             }
484
485             trace!("eval_place_to_op: got {:?}", *op);
486             Ok(op)
487         })
488     }
489
490     /// Evaluate the operand, returning a place where you can then find the data.
491     /// If you already know the layout, you can save two table lookups
492     /// by passing it in here.
493     pub fn eval_operand(
494         &self,
495         mir_op: &mir::Operand<'tcx>,
496         layout: Option<TyLayout<'tcx>>,
497     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
498         use rustc::mir::Operand::*;
499         let op = match *mir_op {
500             // FIXME: do some more logic on `move` to invalidate the old location
501             Copy(ref place) |
502             Move(ref place) =>
503                 self.eval_place_to_op(place, layout)?,
504
505             Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
506         };
507         trace!("{:?}: {:?}", mir_op, *op);
508         Ok(op)
509     }
510
511     /// Evaluate a bunch of operands at once
512     pub(super) fn eval_operands(
513         &self,
514         ops: &[mir::Operand<'tcx>],
515     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
516         ops.into_iter()
517             .map(|op| self.eval_operand(op, None))
518             .collect()
519     }
520
521     // Used when the miri-engine runs into a constant and for extracting information from constants
522     // in patterns via the `const_eval` module
523     crate fn eval_const_to_op(
524         &self,
525         val: &'tcx ty::Const<'tcx>,
526         layout: Option<TyLayout<'tcx>>,
527     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
528         let tag_scalar = |scalar| match scalar {
529             Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
530             Scalar::Raw { data, size } => Scalar::Raw { data, size },
531         };
532         // Early-return cases.
533         match val.val {
534             ConstValue::Param(_) => return err!(TooGeneric), // FIXME(oli-obk): try to monomorphize
535             ConstValue::Unevaluated(def_id, substs) => {
536                 let instance = self.resolve(def_id, substs)?;
537                 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
538                     instance,
539                     promoted: None,
540                 })?));
541             }
542             _ => {}
543         }
544         // Other cases need layout.
545         let layout = from_known_layout(layout, || {
546             self.layout_of(self.monomorphize(val.ty)?)
547         })?;
548         let op = match val.val {
549             ConstValue::ByRef { offset, align, alloc } => {
550                 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
551                 // We rely on mutability being set correctly in that allocation to prevent writes
552                 // where none should happen.
553                 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
554                 Operand::Indirect(MemPlace::from_ptr(ptr, align))
555             },
556             ConstValue::Scalar(x) =>
557                 Operand::Immediate(Immediate::Scalar(tag_scalar(x).into())),
558             ConstValue::Slice { data, start, end } => {
559                 // We rely on mutability being set correctly in `data` to prevent writes
560                 // where none should happen.
561                 let ptr = Pointer::new(
562                     self.tcx.alloc_map.lock().create_memory_alloc(data),
563                     Size::from_bytes(start as u64), // offset: `start`
564                 );
565                 Operand::Immediate(Immediate::new_slice(
566                     self.tag_static_base_pointer(ptr).into(),
567                     (end - start) as u64, // len: `end - start`
568                     self,
569                 ))
570             }
571             ConstValue::Param(..) |
572             ConstValue::Infer(..) |
573             ConstValue::Placeholder(..) |
574             ConstValue::Unevaluated(..) =>
575                 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
576         };
577         Ok(OpTy { op, layout })
578     }
579
580     /// Read discriminant, return the runtime value as well as the variant index.
581     pub fn read_discriminant(
582         &self,
583         rval: OpTy<'tcx, M::PointerTag>,
584     ) -> InterpResult<'tcx, (u128, VariantIdx)> {
585         trace!("read_discriminant_value {:#?}", rval.layout);
586
587         let (discr_kind, discr_index) = match rval.layout.variants {
588             layout::Variants::Single { index } => {
589                 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
590                     index.as_u32() as u128,
591                     |discr| discr.val);
592                 return Ok((discr_val, index));
593             }
594             layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
595                 (discr_kind, discr_index),
596         };
597
598         // read raw discriminant value
599         let discr_op = self.operand_field(rval, discr_index as u64)?;
600         let discr_val = self.read_immediate(discr_op)?;
601         let raw_discr = discr_val.to_scalar_or_undef();
602         trace!("discr value: {:?}", raw_discr);
603         // post-process
604         Ok(match *discr_kind {
605             layout::DiscriminantKind::Tag => {
606                 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
607                     Ok(raw_discr) => raw_discr,
608                     Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
609                 };
610                 let real_discr = if discr_val.layout.ty.is_signed() {
611                     // going from layout tag type to typeck discriminant type
612                     // requires first sign extending with the layout discriminant
613                     let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
614                     // and then zeroing with the typeck discriminant type
615                     let discr_ty = rval.layout.ty
616                         .ty_adt_def().expect("tagged layout corresponds to adt")
617                         .repr
618                         .discr_type();
619                     let size = layout::Integer::from_attr(self, discr_ty).size();
620                     let truncatee = sexted as u128;
621                     truncate(truncatee, size)
622                 } else {
623                     bits_discr
624                 };
625                 // Make sure we catch invalid discriminants
626                 let index = match &rval.layout.ty.sty {
627                     ty::Adt(adt, _) => adt
628                         .discriminants(self.tcx.tcx)
629                         .find(|(_, var)| var.val == real_discr),
630                     ty::Generator(def_id, substs, _) => substs
631                         .discriminants(*def_id, self.tcx.tcx)
632                         .find(|(_, var)| var.val == real_discr),
633                     _ => bug!("tagged layout for non-adt non-generator"),
634                 }.ok_or_else(|| InterpError::InvalidDiscriminant(raw_discr.erase_tag()))?;
635                 (real_discr, index.0)
636             },
637             layout::DiscriminantKind::Niche {
638                 dataful_variant,
639                 ref niche_variants,
640                 niche_start,
641             } => {
642                 let variants_start = niche_variants.start().as_u32() as u128;
643                 let variants_end = niche_variants.end().as_u32() as u128;
644                 let raw_discr = raw_discr.not_undef()
645                     .map_err(|_| InterpError::InvalidDiscriminant(ScalarMaybeUndef::Undef))?;
646                 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
647                     Err(ptr) => {
648                         // The niche must be just 0 (which an inbounds pointer value never is)
649                         let ptr_valid = niche_start == 0 && variants_start == variants_end &&
650                             !self.memory.ptr_may_be_null(ptr);
651                         if !ptr_valid {
652                             return err!(InvalidDiscriminant(raw_discr.erase_tag().into()));
653                         }
654                         (dataful_variant.as_u32() as u128, dataful_variant)
655                     },
656                     Ok(raw_discr) => {
657                         let adjusted_discr = raw_discr.wrapping_sub(niche_start)
658                             .wrapping_add(variants_start);
659                         if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
660                             let index = adjusted_discr as usize;
661                             assert_eq!(index as u128, adjusted_discr);
662                             assert!(index < rval.layout.ty
663                                 .ty_adt_def()
664                                 .expect("tagged layout for non adt")
665                                 .variants.len());
666                             (adjusted_discr, VariantIdx::from_usize(index))
667                         } else {
668                             (dataful_variant.as_u32() as u128, dataful_variant)
669                         }
670                     },
671                 }
672             }
673         })
674     }
675 }