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