]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
Auto merge of #65838 - estebank:resilient-recovery, r=Centril
[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, TryFrom};
5
6 use rustc::{mir, ty};
7 use rustc::ty::layout::{
8     self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, PrimitiveExt, 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 /// An `Immediate` 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, 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(crate) 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, 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, PartialEq)]
157 pub struct OpTy<'tcx, Tag=()> {
158     op: Operand<Tag>, // Keep this private, it helps enforce invariants
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     #[inline]
192     pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
193         ImmTy { imm: val.into(), layout }
194     }
195
196     #[inline]
197     pub fn from_uint(i: impl Into<u128>, layout: TyLayout<'tcx>) -> Self {
198         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
199     }
200
201     #[inline]
202     pub fn from_int(i: impl Into<i128>, layout: TyLayout<'tcx>) -> Self {
203         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
204     }
205
206     #[inline]
207     pub fn to_bits(self) -> InterpResult<'tcx, u128> {
208         self.to_scalar()?.to_bits(self.layout.size)
209     }
210 }
211
212 // Use the existing layout if given (but sanity check in debug mode),
213 // or compute the layout.
214 #[inline(always)]
215 pub(super) fn from_known_layout<'tcx>(
216     layout: Option<TyLayout<'tcx>>,
217     compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
218 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
219     match layout {
220         None => compute(),
221         Some(layout) => {
222             if cfg!(debug_assertions) {
223                 let layout2 = compute()?;
224                 assert_eq!(layout.details, layout2.details,
225                     "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
226                     layout.ty, layout2.ty);
227             }
228             Ok(layout)
229         }
230     }
231 }
232
233 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
234     /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
235     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
236     #[inline]
237     pub fn force_op_ptr(
238         &self,
239         op: OpTy<'tcx, M::PointerTag>,
240     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
241         match op.try_as_mplace() {
242             Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
243             Err(imm) => Ok(imm.into()), // Nothing to cast/force
244         }
245     }
246
247     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
248     /// Returns `None` if the layout does not permit loading this as a value.
249     fn try_read_immediate_from_mplace(
250         &self,
251         mplace: MPlaceTy<'tcx, M::PointerTag>,
252     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
253         if mplace.layout.is_unsized() {
254             // Don't touch unsized
255             return Ok(None);
256         }
257
258         let ptr = match self.check_mplace_access(mplace, None)
259             .expect("places should be checked on creation")
260         {
261             Some(ptr) => ptr,
262             None => return Ok(Some(ImmTy { // zero-sized type
263                 imm: Scalar::zst().into(),
264                 layout: mplace.layout,
265             })),
266         };
267
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(ImmTy {
274                     imm: scalar.into(),
275                     layout: mplace.layout,
276                 }))
277             }
278             layout::Abi::ScalarPair(ref a, ref b) => {
279                 // We checked `ptr_align` above, so all fields will have the alignment they need.
280                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
281                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
282                 let (a, b) = (&a.value, &b.value);
283                 let (a_size, b_size) = (a.size(self), b.size(self));
284                 let a_ptr = ptr;
285                 let b_offset = a_size.align_to(b.align(self).abi);
286                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
287                 let b_ptr = ptr.offset(b_offset, self)?;
288                 let a_val = self.memory
289                     .get(ptr.alloc_id)?
290                     .read_scalar(self, a_ptr, a_size)?;
291                 let b_val = self.memory
292                     .get(ptr.alloc_id)?
293                     .read_scalar(self, b_ptr, b_size)?;
294                 Ok(Some(ImmTy {
295                     imm: Immediate::ScalarPair(a_val, b_val),
296                     layout: mplace.layout,
297                 }))
298             }
299             _ => Ok(None),
300         }
301     }
302
303     /// Try returning an immediate for the operand.
304     /// If the layout does not permit loading this as an immediate, return where in memory
305     /// we can find the data.
306     /// Note that for a given layout, this operation will either always fail or always
307     /// succeed!  Whether it succeeds depends on whether the layout can be represented
308     /// in a `Immediate`, not on which data is stored there currently.
309     pub(crate) fn try_read_immediate(
310         &self,
311         src: OpTy<'tcx, M::PointerTag>,
312     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
313         Ok(match src.try_as_mplace() {
314             Ok(mplace) => {
315                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
316                     Ok(val)
317                 } else {
318                     Err(mplace)
319                 }
320             },
321             Err(val) => Ok(val),
322         })
323     }
324
325     /// Read an immediate from a place, asserting that that is possible with the given layout.
326     #[inline(always)]
327     pub fn read_immediate(
328         &self,
329         op: OpTy<'tcx, M::PointerTag>
330     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
331         if let Ok(imm) = self.try_read_immediate(op)? {
332             Ok(imm)
333         } else {
334             bug!("primitive read failed for type: {:?}", op.layout.ty);
335         }
336     }
337
338     /// Read vector length and element type
339     pub fn read_vector_ty(
340         &self, op: OpTy<'tcx, M::PointerTag>
341     ) -> (u64, &rustc::ty::TyS<'tcx>) {
342         if let layout::Abi::Vector { .. } = op.layout.abi {
343             (op.layout.ty.simd_size(*self.tcx) as _, op.layout.ty.simd_type(*self.tcx))
344         } else {
345             bug!("Type `{}` is not a SIMD vector type", op.layout.ty)
346         }
347     }
348
349     /// Read a scalar from a place
350     pub fn read_scalar(
351         &self,
352         op: OpTy<'tcx, M::PointerTag>
353     ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
354         Ok(self.read_immediate(op)?.to_scalar_or_undef())
355     }
356
357     // Turn the MPlace into a string (must already be dereferenced!)
358     pub fn read_str(
359         &self,
360         mplace: MPlaceTy<'tcx, M::PointerTag>,
361     ) -> InterpResult<'tcx, &str> {
362         let len = mplace.len(self)?;
363         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
364         let str = ::std::str::from_utf8(bytes).map_err(|err| {
365             err_unsup!(ValidationFailure(err.to_string()))
366         })?;
367         Ok(str)
368     }
369
370     /// Projection functions
371     pub fn operand_field(
372         &self,
373         op: OpTy<'tcx, M::PointerTag>,
374         field: u64,
375     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
376         let base = match op.try_as_mplace() {
377             Ok(mplace) => {
378                 // The easy case
379                 let field = self.mplace_field(mplace, field)?;
380                 return Ok(field.into());
381             },
382             Err(value) => value
383         };
384
385         let field = field.try_into().unwrap();
386         let field_layout = op.layout.field(self, field)?;
387         if field_layout.is_zst() {
388             let immediate = Scalar::zst().into();
389             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
390         }
391         let offset = op.layout.fields.offset(field);
392         let immediate = match *base {
393             // the field covers the entire type
394             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
395             // extract fields from types with `ScalarPair` ABI
396             Immediate::ScalarPair(a, b) => {
397                 let val = if offset.bytes() == 0 { a } else { b };
398                 Immediate::from(val)
399             },
400             Immediate::Scalar(val) =>
401                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
402         };
403         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
404     }
405
406     pub fn operand_downcast(
407         &self,
408         op: OpTy<'tcx, M::PointerTag>,
409         variant: VariantIdx,
410     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
411         // Downcasts only change the layout
412         Ok(match op.try_as_mplace() {
413             Ok(mplace) => {
414                 self.mplace_downcast(mplace, variant)?.into()
415             },
416             Err(..) => {
417                 let layout = op.layout.for_variant(self, variant);
418                 OpTy { layout, ..op }
419             }
420         })
421     }
422
423     pub fn operand_projection(
424         &self,
425         base: OpTy<'tcx, M::PointerTag>,
426         proj_elem: &mir::PlaceElem<'tcx>,
427     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
428         use rustc::mir::ProjectionElem::*;
429         Ok(match *proj_elem {
430             Field(field, _) => self.operand_field(base, field.index() as u64)?,
431             Downcast(_, variant) => self.operand_downcast(base, variant)?,
432             Deref => self.deref_operand(base)?.into(),
433             Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
434                 OpTy {
435                     op: Operand::Immediate(Scalar::zst().into()),
436                     // the actual index doesn't matter, so we just pick a convenient one like 0
437                     layout: base.layout.field(self, 0)?,
438                 }
439             } else {
440                 // The rest should only occur as mplace, we do not use Immediates for types
441                 // allowing such operations.  This matches place_projection forcing an allocation.
442                 let mplace = base.assert_mem_place();
443                 self.mplace_projection(mplace, proj_elem)?.into()
444             }
445         })
446     }
447
448     /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
449     pub fn access_local(
450         &self,
451         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
452         local: mir::Local,
453         layout: Option<TyLayout<'tcx>>,
454     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
455         assert_ne!(local, mir::RETURN_PLACE);
456         let layout = self.layout_of_local(frame, local, layout)?;
457         let op = if layout.is_zst() {
458             // Do not read from ZST, they might not be initialized
459             Operand::Immediate(Scalar::zst().into())
460         } else {
461             M::access_local(&self, frame, local)?
462         };
463         Ok(OpTy { op, layout })
464     }
465
466     /// Every place can be read from, so we can turn them into an operand
467     #[inline(always)]
468     pub fn place_to_op(
469         &self,
470         place: PlaceTy<'tcx, M::PointerTag>
471     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
472         let op = match *place {
473             Place::Ptr(mplace) => {
474                 Operand::Indirect(mplace)
475             }
476             Place::Local { frame, local } =>
477                 *self.access_local(&self.stack[frame], local, None)?
478         };
479         Ok(OpTy { op, layout: place.layout })
480     }
481
482     // Evaluate a place with the goal of reading from it.  This lets us sometimes
483     // avoid allocations.
484     pub fn eval_place_to_op(
485         &self,
486         place: &mir::Place<'tcx>,
487         layout: Option<TyLayout<'tcx>>,
488     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
489         use rustc::mir::PlaceBase;
490
491         let base_op = match &place.base {
492             PlaceBase::Local(mir::RETURN_PLACE) =>
493                 throw_unsup!(ReadFromReturnPointer),
494             PlaceBase::Local(local) => {
495                 // Do not use the layout passed in as argument if the base we are looking at
496                 // here is not the entire place.
497                 // FIXME use place_projection.is_empty() when is available
498                 let layout = if place.projection.is_empty() {
499                     layout
500                 } else {
501                     None
502                 };
503
504                 self.access_local(self.frame(), *local, layout)?
505             }
506             PlaceBase::Static(place_static) => {
507                 self.eval_static_to_mplace(&place_static)?.into()
508             }
509         };
510
511         let op = place.projection.iter().try_fold(
512             base_op,
513             |op, elem| self.operand_projection(op, elem)
514         )?;
515
516         trace!("eval_place_to_op: got {:?}", *op);
517         Ok(op)
518     }
519
520     /// Evaluate the operand, returning a place where you can then find the data.
521     /// If you already know the layout, you can save two table lookups
522     /// by passing it in here.
523     pub fn eval_operand(
524         &self,
525         mir_op: &mir::Operand<'tcx>,
526         layout: Option<TyLayout<'tcx>>,
527     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
528         use rustc::mir::Operand::*;
529         let op = match *mir_op {
530             // FIXME: do some more logic on `move` to invalidate the old location
531             Copy(ref place) |
532             Move(ref place) =>
533                 self.eval_place_to_op(place, layout)?,
534
535             Constant(ref constant) => {
536                 let val = self.subst_from_frame_and_normalize_erasing_regions(constant.literal);
537                 self.eval_const_to_op(val, layout)?
538             }
539         };
540         trace!("{:?}: {:?}", mir_op, *op);
541         Ok(op)
542     }
543
544     /// Evaluate a bunch of operands at once
545     pub(super) fn eval_operands(
546         &self,
547         ops: &[mir::Operand<'tcx>],
548     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
549         ops.into_iter()
550             .map(|op| self.eval_operand(op, None))
551             .collect()
552     }
553
554     // Used when the miri-engine runs into a constant and for extracting information from constants
555     // in patterns via the `const_eval` module
556     /// The `val` and `layout` are assumed to already be in our interpreter
557     /// "universe" (param_env).
558     crate fn eval_const_to_op(
559         &self,
560         val: &'tcx ty::Const<'tcx>,
561         layout: Option<TyLayout<'tcx>>,
562     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
563         let tag_scalar = |scalar| match scalar {
564             Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
565             Scalar::Raw { data, size } => Scalar::Raw { data, size },
566         };
567         // Early-return cases.
568         match val.val {
569             ConstValue::Param(_) =>
570                 throw_inval!(TooGeneric),
571             ConstValue::Unevaluated(def_id, substs) => {
572                 let instance = self.resolve(def_id, substs)?;
573                 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
574                     instance,
575                     promoted: None,
576                 })?));
577             }
578             _ => {}
579         }
580         // Other cases need layout.
581         let layout = from_known_layout(layout, || {
582             self.layout_of(val.ty)
583         })?;
584         let op = match val.val {
585             ConstValue::ByRef { alloc, offset } => {
586                 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
587                 // We rely on mutability being set correctly in that allocation to prevent writes
588                 // where none should happen.
589                 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
590                 Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
591             },
592             ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x).into()),
593             ConstValue::Slice { data, start, end } => {
594                 // We rely on mutability being set correctly in `data` to prevent writes
595                 // where none should happen.
596                 let ptr = Pointer::new(
597                     self.tcx.alloc_map.lock().create_memory_alloc(data),
598                     Size::from_bytes(start as u64), // offset: `start`
599                 );
600                 Operand::Immediate(Immediate::new_slice(
601                     self.tag_static_base_pointer(ptr).into(),
602                     (end - start) as u64, // len: `end - start`
603                     self,
604                 ))
605             }
606             ConstValue::Param(..) |
607             ConstValue::Infer(..) |
608             ConstValue::Bound(..) |
609             ConstValue::Placeholder(..) |
610             ConstValue::Unevaluated(..) =>
611                 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
612         };
613         Ok(OpTy { op, layout })
614     }
615
616     /// Read discriminant, return the runtime value as well as the variant index.
617     pub fn read_discriminant(
618         &self,
619         rval: OpTy<'tcx, M::PointerTag>,
620     ) -> InterpResult<'tcx, (u128, VariantIdx)> {
621         trace!("read_discriminant_value {:#?}", rval.layout);
622
623         let (discr_layout, discr_kind, discr_index) = match rval.layout.variants {
624             layout::Variants::Single { index } => {
625                 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
626                     index.as_u32() as u128,
627                     |discr| discr.val);
628                 return Ok((discr_val, index));
629             }
630             layout::Variants::Multiple {
631                 discr: ref discr_layout,
632                 ref discr_kind,
633                 discr_index,
634                 ..
635             } =>
636                 (discr_layout, discr_kind, discr_index),
637         };
638
639         // read raw discriminant value
640         let discr_op = self.operand_field(rval, discr_index as u64)?;
641         let discr_val = self.read_immediate(discr_op)?;
642         let raw_discr = discr_val.to_scalar_or_undef();
643         trace!("discr value: {:?}", raw_discr);
644         // post-process
645         Ok(match *discr_kind {
646             layout::DiscriminantKind::Tag => {
647                 let bits_discr = raw_discr
648                     .not_undef()
649                     .and_then(|raw_discr| self.force_bits(raw_discr, discr_val.layout.size))
650                     .map_err(|_| err_ub!(InvalidDiscriminant(raw_discr.erase_tag())))?;
651                 let real_discr = if discr_val.layout.ty.is_signed() {
652                     // going from layout tag type to typeck discriminant type
653                     // requires first sign extending with the discriminant layout
654                     let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
655                     // and then zeroing with the typeck discriminant type
656                     let discr_ty = rval.layout.ty
657                         .ty_adt_def().expect("tagged layout corresponds to adt")
658                         .repr
659                         .discr_type();
660                     let size = layout::Integer::from_attr(self, discr_ty).size();
661                     let truncatee = sexted as u128;
662                     truncate(truncatee, size)
663                 } else {
664                     bits_discr
665                 };
666                 // Make sure we catch invalid discriminants
667                 let index = match rval.layout.ty.kind {
668                     ty::Adt(adt, _) => adt
669                         .discriminants(self.tcx.tcx)
670                         .find(|(_, var)| var.val == real_discr),
671                     ty::Generator(def_id, substs, _) => {
672                         let substs = substs.as_generator();
673                         substs
674                             .discriminants(def_id, self.tcx.tcx)
675                             .find(|(_, var)| var.val == real_discr)
676                     }
677                     _ => bug!("tagged layout for non-adt non-generator"),
678
679                 }.ok_or_else(
680                     || err_ub!(InvalidDiscriminant(raw_discr.erase_tag()))
681                 )?;
682                 (real_discr, index.0)
683             },
684             layout::DiscriminantKind::Niche {
685                 dataful_variant,
686                 ref niche_variants,
687                 niche_start,
688             } => {
689                 let variants_start = niche_variants.start().as_u32();
690                 let variants_end = niche_variants.end().as_u32();
691                 let raw_discr = raw_discr.not_undef().map_err(|_| {
692                     err_ub!(InvalidDiscriminant(ScalarMaybeUndef::Undef))
693                 })?;
694                 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
695                     Err(ptr) => {
696                         // The niche must be just 0 (which an inbounds pointer value never is)
697                         let ptr_valid = niche_start == 0 && variants_start == variants_end &&
698                             !self.memory.ptr_may_be_null(ptr);
699                         if !ptr_valid {
700                             throw_ub!(InvalidDiscriminant(raw_discr.erase_tag().into()))
701                         }
702                         (dataful_variant.as_u32() as u128, dataful_variant)
703                     },
704                     Ok(raw_discr) => {
705                         // We need to use machine arithmetic to get the relative variant idx:
706                         // variant_index_relative = discr_val - niche_start_val
707                         let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
708                         let discr_val = ImmTy::from_uint(raw_discr, discr_layout);
709                         let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
710                         let variant_index_relative_val = self.binary_op(
711                             mir::BinOp::Sub,
712                             discr_val,
713                             niche_start_val,
714                         )?;
715                         let variant_index_relative = variant_index_relative_val
716                             .to_scalar()?
717                             .assert_bits(discr_val.layout.size);
718                         // Check if this is in the range that indicates an actual discriminant.
719                         if variant_index_relative <= u128::from(variants_end - variants_start) {
720                             let variant_index_relative = u32::try_from(variant_index_relative)
721                                 .expect("we checked that this fits into a u32");
722                             // Then computing the absolute variant idx should not overflow any more.
723                             let variant_index = variants_start
724                                 .checked_add(variant_index_relative)
725                                 .expect("oveflow computing absolute variant idx");
726                             assert!((variant_index as usize) < rval.layout.ty
727                                 .ty_adt_def()
728                                 .expect("tagged layout for non adt")
729                                 .variants.len());
730                             (u128::from(variant_index), VariantIdx::from_u32(variant_index))
731                         } else {
732                             (u128::from(dataful_variant.as_u32()), dataful_variant)
733                         }
734                     },
735                 }
736             }
737         })
738     }
739 }