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