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