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.
4 use std::convert::{TryInto, TryFrom};
7 use rustc::ty::layout::{
8 self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, PrimitiveExt, VariantIdx,
11 use rustc::mir::interpret::{
13 ConstValue, Pointer, Scalar,
14 InterpResult, sign_extend, truncate,
18 MemPlace, MPlaceTy, PlaceTy, Place,
20 pub use rustc::mir::interpret::ScalarMaybeUndef;
21 use rustc_macros::HashStable;
24 /// An `Immediate` represents a single immediate self-contained Rust value.
26 /// For optimization of a few very common cases, there is also a representation for a pair of
27 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
28 /// operations and wide pointers. This idea was taken from rustc's codegen.
29 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
30 /// defined on `Immediate`, and do not have to work with a `Place`.
31 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, Hash)]
32 pub enum Immediate<Tag=(), Id=AllocId> {
33 Scalar(ScalarMaybeUndef<Tag, Id>),
34 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
37 impl<Tag> From<ScalarMaybeUndef<Tag>> for Immediate<Tag> {
39 fn from(val: ScalarMaybeUndef<Tag>) -> Self {
40 Immediate::Scalar(val)
44 impl<Tag> From<Scalar<Tag>> for Immediate<Tag> {
46 fn from(val: Scalar<Tag>) -> Self {
47 Immediate::Scalar(val.into())
51 impl<Tag> From<Pointer<Tag>> for Immediate<Tag> {
53 fn from(val: Pointer<Tag>) -> Self {
54 Immediate::Scalar(Scalar::from(val).into())
58 impl<'tcx, Tag> Immediate<Tag> {
62 cx: &impl HasDataLayout
64 Immediate::ScalarPair(
66 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
70 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
71 Immediate::ScalarPair(val.into(), vtable.into())
75 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
77 Immediate::Scalar(val) => val,
78 Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
83 pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
84 self.to_scalar_or_undef().not_undef()
88 pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
90 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
91 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
96 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
97 // as input for binary and cast operations.
98 #[derive(Copy, Clone, Debug)]
99 pub struct ImmTy<'tcx, Tag=()> {
100 pub(crate) imm: Immediate<Tag>,
101 pub layout: TyLayout<'tcx>,
104 // `Tag: Copy` because some methods on `Scalar` consume them by value
105 impl<Tag: Copy> std::fmt::Display for ImmTy<'tcx, Tag> {
106 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 Immediate::Scalar(ScalarMaybeUndef::Scalar(s)) => match s.to_bits(self.layout.size) {
110 match self.layout.ty.kind {
111 ty::Int(_) => return write!(
113 super::sign_extend(s, self.layout.size) as i128,
115 ty::Uint(_) => return write!(fmt, "{}", s),
116 ty::Bool if s == 0 => return fmt.write_str("false"),
117 ty::Bool if s == 1 => return fmt.write_str("true"),
118 ty::Char => if let Some(c) =
119 u32::try_from(s).ok().and_then(std::char::from_u32) {
120 return write!(fmt, "{}", c);
122 ty::Float(ast::FloatTy::F32) => if let Ok(u) = u32::try_from(s) {
123 return write!(fmt, "{}", f32::from_bits(u));
125 ty::Float(ast::FloatTy::F64) => if let Ok(u) = u64::try_from(s) {
126 return write!(fmt, "{}", f64::from_bits(u));
130 write!(fmt, "{:x}", s)
132 Err(_) => fmt.write_str("{pointer}"),
134 Immediate::Scalar(ScalarMaybeUndef::Undef) => fmt.write_str("{undef}"),
135 Immediate::ScalarPair(..) => fmt.write_str("{wide pointer or tuple}"),
140 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
141 type Target = Immediate<Tag>;
143 fn deref(&self) -> &Immediate<Tag> {
148 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
149 /// or still in memory. The latter is an optimization, to delay reading that chunk of
150 /// memory and to avoid having to store arbitrary-sized data here.
151 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, Hash)]
152 pub enum Operand<Tag=(), Id=AllocId> {
153 Immediate(Immediate<Tag, Id>),
154 Indirect(MemPlace<Tag, Id>),
157 impl<Tag> Operand<Tag> {
159 pub fn assert_mem_place(self) -> MemPlace<Tag>
160 where Tag: ::std::fmt::Debug
163 Operand::Indirect(mplace) => mplace,
164 _ => bug!("assert_mem_place: expected Operand::Indirect, got {:?}", self),
170 pub fn assert_immediate(self) -> Immediate<Tag>
171 where Tag: ::std::fmt::Debug
174 Operand::Immediate(imm) => imm,
175 _ => bug!("assert_immediate: expected Operand::Immediate, got {:?}", self),
181 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
182 pub struct OpTy<'tcx, Tag=()> {
183 op: Operand<Tag>, // Keep this private; it helps enforce invariants.
184 pub layout: TyLayout<'tcx>,
187 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
188 type Target = Operand<Tag>;
190 fn deref(&self) -> &Operand<Tag> {
195 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
197 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
199 op: Operand::Indirect(*mplace),
200 layout: mplace.layout
205 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
207 fn from(val: ImmTy<'tcx, Tag>) -> Self {
209 op: Operand::Immediate(val.imm),
215 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
217 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
218 ImmTy { imm: val.into(), layout }
222 pub fn from_uint(i: impl Into<u128>, layout: TyLayout<'tcx>) -> Self {
223 Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
227 pub fn from_int(i: impl Into<i128>, layout: TyLayout<'tcx>) -> Self {
228 Self::from_scalar(Scalar::from_int(i, layout.size), layout)
232 pub fn to_bits(self) -> InterpResult<'tcx, u128> {
233 self.to_scalar()?.to_bits(self.layout.size)
237 // Use the existing layout if given (but sanity check in debug mode),
238 // or compute the layout.
240 pub(super) fn from_known_layout<'tcx>(
241 layout: Option<TyLayout<'tcx>>,
242 compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
243 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
247 if cfg!(debug_assertions) {
248 let layout2 = compute()?;
249 assert_eq!(layout.details, layout2.details,
250 "mismatch in layout of supposedly equal-layout types {:?} and {:?}",
251 layout.ty, layout2.ty);
258 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
259 /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
260 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
264 op: OpTy<'tcx, M::PointerTag>,
265 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
266 match op.try_as_mplace() {
267 Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
268 Err(imm) => Ok(imm.into()), // Nothing to cast/force
272 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
273 /// Returns `None` if the layout does not permit loading this as a value.
274 fn try_read_immediate_from_mplace(
276 mplace: MPlaceTy<'tcx, M::PointerTag>,
277 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
278 if mplace.layout.is_unsized() {
279 // Don't touch unsized
283 let ptr = match self.check_mplace_access(mplace, None)
284 .expect("places should be checked on creation")
287 None => return Ok(Some(ImmTy { // zero-sized type
288 imm: Scalar::zst().into(),
289 layout: mplace.layout,
293 match mplace.layout.abi {
294 layout::Abi::Scalar(..) => {
295 let scalar = self.memory
296 .get_raw(ptr.alloc_id)?
297 .read_scalar(self, ptr, mplace.layout.size)?;
300 layout: mplace.layout,
303 layout::Abi::ScalarPair(ref a, ref b) => {
304 // We checked `ptr_align` above, so all fields will have the alignment they need.
305 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
306 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
307 let (a, b) = (&a.value, &b.value);
308 let (a_size, b_size) = (a.size(self), b.size(self));
310 let b_offset = a_size.align_to(b.align(self).abi);
311 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
312 let b_ptr = ptr.offset(b_offset, self)?;
313 let a_val = self.memory
314 .get_raw(ptr.alloc_id)?
315 .read_scalar(self, a_ptr, a_size)?;
316 let b_val = self.memory
317 .get_raw(ptr.alloc_id)?
318 .read_scalar(self, b_ptr, b_size)?;
320 imm: Immediate::ScalarPair(a_val, b_val),
321 layout: mplace.layout,
328 /// Try returning an immediate for the operand.
329 /// If the layout does not permit loading this as an immediate, return where in memory
330 /// we can find the data.
331 /// Note that for a given layout, this operation will either always fail or always
332 /// succeed! Whether it succeeds depends on whether the layout can be represented
333 /// in a `Immediate`, not on which data is stored there currently.
334 pub(crate) fn try_read_immediate(
336 src: OpTy<'tcx, M::PointerTag>,
337 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
338 Ok(match src.try_as_mplace() {
340 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
350 /// Read an immediate from a place, asserting that that is possible with the given layout.
352 pub fn read_immediate(
354 op: OpTy<'tcx, M::PointerTag>
355 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
356 if let Ok(imm) = self.try_read_immediate(op)? {
359 bug!("primitive read failed for type: {:?}", op.layout.ty);
363 /// Read a scalar from a place
366 op: OpTy<'tcx, M::PointerTag>
367 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
368 Ok(self.read_immediate(op)?.to_scalar_or_undef())
371 // Turn the wide MPlace into a string (must already be dereferenced!)
374 mplace: MPlaceTy<'tcx, M::PointerTag>,
375 ) -> InterpResult<'tcx, &str> {
376 let len = mplace.len(self)?;
377 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
378 let str = ::std::str::from_utf8(bytes).map_err(|err| {
379 err_unsup!(ValidationFailure(err.to_string()))
384 /// Projection functions
385 pub fn operand_field(
387 op: OpTy<'tcx, M::PointerTag>,
389 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
390 let base = match op.try_as_mplace() {
393 let field = self.mplace_field(mplace, field)?;
394 return Ok(field.into());
399 let field = field.try_into().unwrap();
400 let field_layout = op.layout.field(self, field)?;
401 if field_layout.is_zst() {
402 let immediate = Scalar::zst().into();
403 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
405 let offset = op.layout.fields.offset(field);
406 let immediate = match *base {
407 // the field covers the entire type
408 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
409 // extract fields from types with `ScalarPair` ABI
410 Immediate::ScalarPair(a, b) => {
411 let val = if offset.bytes() == 0 { a } else { b };
414 Immediate::Scalar(val) =>
415 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
417 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
420 pub fn operand_downcast(
422 op: OpTy<'tcx, M::PointerTag>,
424 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
425 // Downcasts only change the layout
426 Ok(match op.try_as_mplace() {
428 self.mplace_downcast(mplace, variant)?.into()
431 let layout = op.layout.for_variant(self, variant);
432 OpTy { layout, ..op }
437 pub fn operand_projection(
439 base: OpTy<'tcx, M::PointerTag>,
440 proj_elem: &mir::PlaceElem<'tcx>,
441 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
442 use rustc::mir::ProjectionElem::*;
443 Ok(match *proj_elem {
444 Field(field, _) => self.operand_field(base, field.index() as u64)?,
445 Downcast(_, variant) => self.operand_downcast(base, variant)?,
446 Deref => self.deref_operand(base)?.into(),
447 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
449 op: Operand::Immediate(Scalar::zst().into()),
450 // the actual index doesn't matter, so we just pick a convenient one like 0
451 layout: base.layout.field(self, 0)?,
454 // The rest should only occur as mplace, we do not use Immediates for types
455 // allowing such operations. This matches place_projection forcing an allocation.
456 let mplace = base.assert_mem_place();
457 self.mplace_projection(mplace, proj_elem)?.into()
462 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
465 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
467 layout: Option<TyLayout<'tcx>>,
468 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
469 assert_ne!(local, mir::RETURN_PLACE);
470 let layout = self.layout_of_local(frame, local, layout)?;
471 let op = if layout.is_zst() {
472 // Do not read from ZST, they might not be initialized
473 Operand::Immediate(Scalar::zst().into())
475 M::access_local(&self, frame, local)?
477 Ok(OpTy { op, layout })
480 /// Every place can be read from, so we can turn them into an operand
484 place: PlaceTy<'tcx, M::PointerTag>
485 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
486 let op = match *place {
487 Place::Ptr(mplace) => {
488 Operand::Indirect(mplace)
490 Place::Local { frame, local } =>
491 *self.access_local(&self.stack[frame], local, None)?
493 Ok(OpTy { op, layout: place.layout })
496 // Evaluate a place with the goal of reading from it. This lets us sometimes
497 // avoid allocations.
498 pub fn eval_place_to_op(
500 place: &mir::Place<'tcx>,
501 layout: Option<TyLayout<'tcx>>,
502 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
503 use rustc::mir::PlaceBase;
505 let base_op = match &place.base {
506 PlaceBase::Local(mir::RETURN_PLACE) =>
507 throw_unsup!(ReadFromReturnPointer),
508 PlaceBase::Local(local) => {
509 // Do not use the layout passed in as argument if the base we are looking at
510 // here is not the entire place.
511 // FIXME use place_projection.is_empty() when is available
512 let layout = if place.projection.is_empty() {
518 self.access_local(self.frame(), *local, layout)?
520 PlaceBase::Static(place_static) => {
521 self.eval_static_to_mplace(&place_static)?.into()
525 let op = place.projection.iter().try_fold(
527 |op, elem| self.operand_projection(op, elem)
530 trace!("eval_place_to_op: got {:?}", *op);
534 /// Evaluate the operand, returning a place where you can then find the data.
535 /// If you already know the layout, you can save two table lookups
536 /// by passing it in here.
539 mir_op: &mir::Operand<'tcx>,
540 layout: Option<TyLayout<'tcx>>,
541 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
542 use rustc::mir::Operand::*;
543 let op = match *mir_op {
544 // FIXME: do some more logic on `move` to invalidate the old location
547 self.eval_place_to_op(place, layout)?,
549 Constant(ref constant) => {
550 let val = self.subst_from_frame_and_normalize_erasing_regions(constant.literal);
551 self.eval_const_to_op(val, layout)?
554 trace!("{:?}: {:?}", mir_op, *op);
558 /// Evaluate a bunch of operands at once
559 pub(super) fn eval_operands(
561 ops: &[mir::Operand<'tcx>],
562 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
564 .map(|op| self.eval_operand(op, None))
568 // Used when the miri-engine runs into a constant and for extracting information from constants
569 // in patterns via the `const_eval` module
570 /// The `val` and `layout` are assumed to already be in our interpreter
571 /// "universe" (param_env).
572 crate fn eval_const_to_op(
574 val: &'tcx ty::Const<'tcx>,
575 layout: Option<TyLayout<'tcx>>,
576 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
577 let tag_scalar = |scalar| match scalar {
578 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
579 Scalar::Raw { data, size } => Scalar::Raw { data, size },
581 // Early-return cases.
582 let val_val = match val.val {
583 ty::ConstKind::Param(_) =>
584 throw_inval!(TooGeneric),
585 ty::ConstKind::Unevaluated(def_id, substs) => {
586 let instance = self.resolve(def_id, substs)?;
587 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
592 ty::ConstKind::Infer(..) |
593 ty::ConstKind::Bound(..) |
594 ty::ConstKind::Placeholder(..) =>
595 bug!("eval_const_to_op: Unexpected ConstKind {:?}", val),
596 ty::ConstKind::Value(val_val) => val_val,
598 // Other cases need layout.
599 let layout = from_known_layout(layout, || {
600 self.layout_of(val.ty)
602 let op = match val_val {
603 ConstValue::ByRef { alloc, offset } => {
604 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
605 // We rely on mutability being set correctly in that allocation to prevent writes
606 // where none should happen.
607 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
608 Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
610 ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x).into()),
611 ConstValue::Slice { data, start, end } => {
612 // We rely on mutability being set correctly in `data` to prevent writes
613 // where none should happen.
614 let ptr = Pointer::new(
615 self.tcx.alloc_map.lock().create_memory_alloc(data),
616 Size::from_bytes(start as u64), // offset: `start`
618 Operand::Immediate(Immediate::new_slice(
619 self.tag_static_base_pointer(ptr).into(),
620 (end - start) as u64, // len: `end - start`
625 Ok(OpTy { op, layout })
628 /// Read discriminant, return the runtime value as well as the variant index.
629 pub fn read_discriminant(
631 rval: OpTy<'tcx, M::PointerTag>,
632 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
633 trace!("read_discriminant_value {:#?}", rval.layout);
635 let (discr_layout, discr_kind, discr_index) = match rval.layout.variants {
636 layout::Variants::Single { index } => {
637 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
638 index.as_u32() as u128,
640 return Ok((discr_val, index));
642 layout::Variants::Multiple {
643 discr: ref discr_layout,
648 (discr_layout, discr_kind, discr_index),
651 // read raw discriminant value
652 let discr_op = self.operand_field(rval, discr_index as u64)?;
653 let discr_val = self.read_immediate(discr_op)?;
654 let raw_discr = discr_val.to_scalar_or_undef();
655 trace!("discr value: {:?}", raw_discr);
657 Ok(match *discr_kind {
658 layout::DiscriminantKind::Tag => {
659 let bits_discr = raw_discr
661 .and_then(|raw_discr| self.force_bits(raw_discr, discr_val.layout.size))
662 .map_err(|_| err_ub!(InvalidDiscriminant(raw_discr.erase_tag())))?;
663 let real_discr = if discr_val.layout.ty.is_signed() {
664 // going from layout tag type to typeck discriminant type
665 // requires first sign extending with the discriminant layout
666 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
667 // and then zeroing with the typeck discriminant type
668 let discr_ty = rval.layout.ty
669 .ty_adt_def().expect("tagged layout corresponds to adt")
672 let size = layout::Integer::from_attr(self, discr_ty).size();
673 let truncatee = sexted as u128;
674 truncate(truncatee, size)
678 // Make sure we catch invalid discriminants
679 let index = match rval.layout.ty.kind {
680 ty::Adt(adt, _) => adt
681 .discriminants(self.tcx.tcx)
682 .find(|(_, var)| var.val == real_discr),
683 ty::Generator(def_id, substs, _) => {
684 let substs = substs.as_generator();
686 .discriminants(def_id, self.tcx.tcx)
687 .find(|(_, var)| var.val == real_discr)
689 _ => bug!("tagged layout for non-adt non-generator"),
692 || err_ub!(InvalidDiscriminant(raw_discr.erase_tag()))
694 (real_discr, index.0)
696 layout::DiscriminantKind::Niche {
701 let variants_start = niche_variants.start().as_u32();
702 let variants_end = niche_variants.end().as_u32();
703 let raw_discr = raw_discr.not_undef().map_err(|_| {
704 err_ub!(InvalidDiscriminant(ScalarMaybeUndef::Undef))
706 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
708 // The niche must be just 0 (which an inbounds pointer value never is)
709 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
710 !self.memory.ptr_may_be_null(ptr);
712 throw_ub!(InvalidDiscriminant(raw_discr.erase_tag().into()))
714 (dataful_variant.as_u32() as u128, dataful_variant)
717 // We need to use machine arithmetic to get the relative variant idx:
718 // variant_index_relative = discr_val - niche_start_val
719 let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
720 let discr_val = ImmTy::from_uint(raw_discr, discr_layout);
721 let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
722 let variant_index_relative_val = self.binary_op(
727 let variant_index_relative = variant_index_relative_val
729 .assert_bits(discr_val.layout.size);
730 // Check if this is in the range that indicates an actual discriminant.
731 if variant_index_relative <= u128::from(variants_end - variants_start) {
732 let variant_index_relative = u32::try_from(variant_index_relative)
733 .expect("we checked that this fits into a u32");
734 // Then computing the absolute variant idx should not overflow any more.
735 let variant_index = variants_start
736 .checked_add(variant_index_relative)
737 .expect("oveflow computing absolute variant idx");
738 assert!((variant_index as usize) < rval.layout.ty
740 .expect("tagged layout for non adt")
742 (u128::from(variant_index), VariantIdx::from_u32(variant_index))
744 (u128::from(dataful_variant.as_u32()), dataful_variant)