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 either::{Either, Left, Right};
6 use rustc_hir::def::Namespace;
7 use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
8 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter};
9 use rustc_middle::ty::{ConstInt, Ty, ValTree};
10 use rustc_middle::{mir, ty};
12 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, TagEncoding};
13 use rustc_target::abi::{VariantIdx, Variants};
16 alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, Frame, GlobalId,
17 InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Place, PlaceTy, Pointer,
21 /// An `Immediate` represents a single immediate self-contained Rust value.
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 wide 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)]
29 pub enum Immediate<Prov: Provenance = AllocId> {
30 /// A single scalar value (must have *initialized* `Scalar` ABI).
32 /// A pair of two scalar value (must have `ScalarPair` ABI where both fields are
33 /// `Scalar::Initialized`).
34 ScalarPair(Scalar<Prov>, Scalar<Prov>),
35 /// A value of fully uninitialized memory. Can have and size and layout.
39 impl<Prov: Provenance> From<Scalar<Prov>> for Immediate<Prov> {
41 fn from(val: Scalar<Prov>) -> Self {
42 Immediate::Scalar(val.into())
46 impl<Prov: Provenance> Immediate<Prov> {
47 pub fn from_pointer(p: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
48 Immediate::Scalar(Scalar::from_pointer(p, cx))
51 pub fn from_maybe_pointer(p: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
52 Immediate::Scalar(Scalar::from_maybe_pointer(p, cx))
55 pub fn new_slice(val: Scalar<Prov>, len: u64, cx: &impl HasDataLayout) -> Self {
56 Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
61 vtable: Pointer<Option<Prov>>,
62 cx: &impl HasDataLayout,
64 Immediate::ScalarPair(val.into(), Scalar::from_maybe_pointer(vtable, cx))
68 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
69 pub fn to_scalar(self) -> Scalar<Prov> {
71 Immediate::Scalar(val) => val,
72 Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"),
73 Immediate::Uninit => bug!("Got uninit where a scalar was expected"),
78 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
79 pub fn to_scalar_pair(self) -> (Scalar<Prov>, Scalar<Prov>) {
81 Immediate::ScalarPair(val1, val2) => (val1, val2),
82 Immediate::Scalar(..) => bug!("Got a scalar where a scalar pair was expected"),
83 Immediate::Uninit => bug!("Got uninit where a scalar pair was expected"),
88 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
89 // as input for binary and cast operations.
90 #[derive(Clone, Debug)]
91 pub struct ImmTy<'tcx, Prov: Provenance = AllocId> {
93 pub layout: TyAndLayout<'tcx>,
96 impl<Prov: Provenance> std::fmt::Display for ImmTy<'_, Prov> {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 /// Helper function for printing a scalar to a FmtPrinter
99 fn p<'a, 'tcx, Prov: Provenance>(
100 cx: FmtPrinter<'a, 'tcx>,
103 ) -> Result<FmtPrinter<'a, 'tcx>, std::fmt::Error> {
105 Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true),
106 Scalar::Ptr(ptr, _sz) => {
107 // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
108 // print what is points to, which would fail since it has no access to the local
110 cx.pretty_print_const_pointer(ptr, ty, true)
114 ty::tls::with(|tcx| {
116 Immediate::Scalar(s) => {
117 if let Some(ty) = tcx.lift(self.layout.ty) {
118 let cx = FmtPrinter::new(tcx, Namespace::ValueNS);
119 f.write_str(&p(cx, s, ty)?.into_buffer())?;
122 write!(f, "{:x}: {}", s, self.layout.ty)
124 Immediate::ScalarPair(a, b) => {
125 // FIXME(oli-obk): at least print tuples and slices nicely
126 write!(f, "({:x}, {:x}): {}", a, b, self.layout.ty)
128 Immediate::Uninit => {
129 write!(f, "uninit: {}", self.layout.ty)
136 impl<'tcx, Prov: Provenance> std::ops::Deref for ImmTy<'tcx, Prov> {
137 type Target = Immediate<Prov>;
139 fn deref(&self) -> &Immediate<Prov> {
144 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
145 /// or still in memory. The latter is an optimization, to delay reading that chunk of
146 /// memory and to avoid having to store arbitrary-sized data here.
147 #[derive(Copy, Clone, Debug)]
148 pub enum Operand<Prov: Provenance = AllocId> {
149 Immediate(Immediate<Prov>),
150 Indirect(MemPlace<Prov>),
153 #[derive(Clone, Debug)]
154 pub struct OpTy<'tcx, Prov: Provenance = AllocId> {
155 op: Operand<Prov>, // Keep this private; it helps enforce invariants.
156 pub layout: TyAndLayout<'tcx>,
157 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
158 /// it needs to have a different alignment than the field type would usually have.
159 /// So we represent this here with a separate field that "overwrites" `layout.align`.
160 /// This means `layout.align` should never be used for an `OpTy`!
161 /// `None` means "alignment does not matter since this is a by-value operand"
162 /// (`Operand::Immediate`); this field is only relevant for `Operand::Indirect`.
163 /// Also CTFE ignores alignment anyway, so this is for Miri only.
164 pub align: Option<Align>,
167 impl<'tcx, Prov: Provenance> std::ops::Deref for OpTy<'tcx, Prov> {
168 type Target = Operand<Prov>;
170 fn deref(&self) -> &Operand<Prov> {
175 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
177 fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
178 OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout, align: Some(mplace.align) }
182 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
184 fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
185 OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
189 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
191 fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
192 OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
196 impl<'tcx, Prov: Provenance> From<ImmTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
198 fn from(val: ImmTy<'tcx, Prov>) -> Self {
199 OpTy { op: Operand::Immediate(val.imm), layout: val.layout, align: None }
203 impl<'tcx, Prov: Provenance> ImmTy<'tcx, Prov> {
205 pub fn from_scalar(val: Scalar<Prov>, layout: TyAndLayout<'tcx>) -> Self {
206 ImmTy { imm: val.into(), layout }
210 pub fn from_immediate(imm: Immediate<Prov>, layout: TyAndLayout<'tcx>) -> Self {
211 ImmTy { imm, layout }
215 pub fn uninit(layout: TyAndLayout<'tcx>) -> Self {
216 ImmTy { imm: Immediate::Uninit, layout }
220 pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
221 Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
224 pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
225 Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
229 pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
230 Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
234 pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
235 Self::from_scalar(Scalar::from_int(i, layout.size), layout)
239 pub fn to_const_int(self) -> ConstInt {
240 assert!(self.layout.ty.is_integral());
241 let int = self.to_scalar().assert_int();
242 ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
246 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
247 pub fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
248 if self.layout.is_unsized() {
249 // There are no unsized immediates.
250 self.assert_mem_place().len(cx)
252 match self.layout.fields {
253 abi::FieldsShape::Array { count, .. } => Ok(count),
254 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
259 pub fn offset_with_meta(
262 meta: MemPlaceMeta<Prov>,
263 layout: TyAndLayout<'tcx>,
264 cx: &impl HasDataLayout,
265 ) -> InterpResult<'tcx, Self> {
266 match self.as_mplace_or_imm() {
267 Left(mplace) => Ok(mplace.offset_with_meta(offset, meta, layout, cx)?.into()),
270 matches!(*imm, Immediate::Uninit),
271 "Scalar/ScalarPair cannot be offset into"
273 assert!(!meta.has_meta()); // no place to store metadata here
274 // Every part of an uninit is uninit.
275 Ok(ImmTy::uninit(layout).into())
283 layout: TyAndLayout<'tcx>,
284 cx: &impl HasDataLayout,
285 ) -> InterpResult<'tcx, Self> {
286 assert!(layout.is_sized());
287 self.offset_with_meta(offset, MemPlaceMeta::None, layout, cx)
291 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
292 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
293 /// Returns `None` if the layout does not permit loading this as a value.
295 /// This is an internal function; call `read_immediate` instead.
296 fn read_immediate_from_mplace_raw(
298 mplace: &MPlaceTy<'tcx, M::Provenance>,
299 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
300 if mplace.layout.is_unsized() {
301 // Don't touch unsized
305 let Some(alloc) = self.get_place_alloc(mplace)? else {
306 // zero-sized type can be left uninit
307 return Ok(Some(ImmTy::uninit(mplace.layout)));
310 // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
311 // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
312 // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
313 // case where some of the bytes are initialized and others are not. So, we need an extra
314 // check that walks over the type of `mplace` to make sure it is truly correct to treat this
315 // like a `Scalar` (or `ScalarPair`).
316 Ok(match mplace.layout.abi {
317 Abi::Scalar(abi::Scalar::Initialized { value: s, .. }) => {
318 let size = s.size(self);
319 assert_eq!(size, mplace.layout.size, "abi::Scalar size does not match layout size");
320 let scalar = alloc.read_scalar(
321 alloc_range(Size::ZERO, size),
322 /*read_provenance*/ s.is_ptr(),
324 Some(ImmTy { imm: scalar.into(), layout: mplace.layout })
327 abi::Scalar::Initialized { value: a, .. },
328 abi::Scalar::Initialized { value: b, .. },
330 // We checked `ptr_align` above, so all fields will have the alignment they need.
331 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
332 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
333 let (a_size, b_size) = (a.size(self), b.size(self));
334 let b_offset = a_size.align_to(b.align(self).abi);
335 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
336 let a_val = alloc.read_scalar(
337 alloc_range(Size::ZERO, a_size),
338 /*read_provenance*/ a.is_ptr(),
340 let b_val = alloc.read_scalar(
341 alloc_range(b_offset, b_size),
342 /*read_provenance*/ b.is_ptr(),
345 imm: Immediate::ScalarPair(a_val.into(), b_val.into()),
346 layout: mplace.layout,
350 // Neither a scalar nor scalar pair.
356 /// Try returning an immediate for the operand. If the layout does not permit loading this as an
357 /// immediate, return where in memory we can find the data.
358 /// Note that for a given layout, this operation will either always return Left or Right!
359 /// succeed! Whether it returns Left depends on whether the layout can be represented
360 /// in an `Immediate`, not on which data is stored there currently.
362 /// This is an internal function that should not usually be used; call `read_immediate` instead.
363 /// ConstProp needs it, though.
364 pub fn read_immediate_raw(
366 src: &OpTy<'tcx, M::Provenance>,
367 ) -> InterpResult<'tcx, Either<MPlaceTy<'tcx, M::Provenance>, ImmTy<'tcx, M::Provenance>>> {
368 Ok(match src.as_mplace_or_imm() {
369 Left(ref mplace) => {
370 if let Some(val) = self.read_immediate_from_mplace_raw(mplace)? {
376 Right(val) => Right(val),
380 /// Read an immediate from a place, asserting that that is possible with the given layout.
382 /// If this succeeds, the `ImmTy` is never `Uninit`.
384 pub fn read_immediate(
386 op: &OpTy<'tcx, M::Provenance>,
387 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
390 Abi::Scalar(abi::Scalar::Initialized { .. })
391 | Abi::ScalarPair(abi::Scalar::Initialized { .. }, abi::Scalar::Initialized { .. })
393 span_bug!(self.cur_span(), "primitive read not possible for type: {:?}", op.layout.ty);
395 let imm = self.read_immediate_raw(op)?.right().unwrap();
396 if matches!(*imm, Immediate::Uninit) {
397 throw_ub!(InvalidUninitBytes(None));
402 /// Read a scalar from a place
405 op: &OpTy<'tcx, M::Provenance>,
406 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
407 Ok(self.read_immediate(op)?.to_scalar())
410 /// Read a pointer from a place.
413 op: &OpTy<'tcx, M::Provenance>,
414 ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
415 self.read_scalar(op)?.to_pointer(self)
418 /// Turn the wide MPlace into a string (must already be dereferenced!)
419 pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx, &str> {
420 let len = mplace.len(self)?;
421 let bytes = self.read_bytes_ptr_strip_provenance(mplace.ptr, Size::from_bytes(len))?;
422 let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
426 /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements.
427 /// Also returns the number of elements.
429 /// Can (but does not always) trigger UB if `op` is uninitialized.
430 pub fn operand_to_simd(
432 op: &OpTy<'tcx, M::Provenance>,
433 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
434 // Basically we just transmute this place into an array following simd_size_and_type.
435 // This only works in memory, but repr(simd) types should never be immediates anyway.
436 assert!(op.layout.ty.is_simd());
437 match op.as_mplace_or_imm() {
438 Left(mplace) => self.mplace_to_simd(&mplace),
439 Right(imm) => match *imm {
440 Immediate::Uninit => {
441 throw_ub!(InvalidUninitBytes(None))
443 Immediate::Scalar(..) | Immediate::ScalarPair(..) => {
444 bug!("arrays/slices can never have Scalar/ScalarPair layout")
450 /// Read from a local.
451 /// Will not access memory, instead an indirect `Operand` is returned.
453 /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
454 /// OpTy from a local.
457 frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
459 layout: Option<TyAndLayout<'tcx>>,
460 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
461 let layout = self.layout_of_local(frame, local, layout)?;
462 let op = *frame.locals[local].access()?;
463 Ok(OpTy { op, layout, align: Some(layout.align.abi) })
466 /// Every place can be read from, so we can turn them into an operand.
467 /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
468 /// will never actually read from memory.
472 place: &PlaceTy<'tcx, M::Provenance>,
473 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
474 let op = match **place {
475 Place::Ptr(mplace) => Operand::Indirect(mplace),
476 Place::Local { frame, local } => {
477 *self.local_to_op(&self.stack()[frame], local, None)?
480 Ok(OpTy { op, layout: place.layout, align: Some(place.align) })
483 /// Evaluate a place with the goal of reading from it. This lets us sometimes
484 /// avoid allocations.
485 pub fn eval_place_to_op(
487 mir_place: mir::Place<'tcx>,
488 layout: Option<TyAndLayout<'tcx>>,
489 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
490 // Do not use the layout passed in as argument if the base we are looking at
491 // here is not the entire place.
492 let layout = if mir_place.projection.is_empty() { layout } else { None };
494 let mut op = self.local_to_op(self.frame(), mir_place.local, layout)?;
495 // Using `try_fold` turned out to be bad for performance, hence the loop.
496 for elem in mir_place.projection.iter() {
497 op = self.operand_projection(&op, elem)?
500 trace!("eval_place_to_op: got {:?}", *op);
501 // Sanity-check the type we ended up with.
503 mir_assign_valid_types(
506 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
507 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
511 "eval_place of a MIR place with type {:?} produced an interpreter operand with type {:?}",
512 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
518 /// Evaluate the operand, returning a place where you can then find the data.
519 /// If you already know the layout, you can save two table lookups
520 /// by passing it in here.
524 mir_op: &mir::Operand<'tcx>,
525 layout: Option<TyAndLayout<'tcx>>,
526 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
527 use rustc_middle::mir::Operand::*;
528 let op = match *mir_op {
529 // FIXME: do some more logic on `move` to invalidate the old location
530 Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
532 Constant(ref constant) => {
534 self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?;
536 // This can still fail:
537 // * During ConstProp, with `TooGeneric` or since the `required_consts` were not all
539 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
540 self.eval_mir_constant(&c, Some(constant.span), layout)?
543 trace!("{:?}: {:?}", mir_op, *op);
547 /// Evaluate a bunch of operands at once
548 pub(super) fn eval_operands(
550 ops: &[mir::Operand<'tcx>],
551 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::Provenance>>> {
552 ops.iter().map(|op| self.eval_operand(op, None)).collect()
557 val: ty::Const<'tcx>,
559 ) -> InterpResult<'tcx, ValTree<'tcx>> {
560 Ok(match val.kind() {
561 ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(..) => {
562 throw_inval!(TooGeneric)
564 ty::ConstKind::Error(reported) => {
565 throw_inval!(AlreadyReported(reported))
567 ty::ConstKind::Unevaluated(uv) => {
568 let instance = self.resolve(uv.def, uv.substs)?;
569 let cid = GlobalId { instance, promoted: None };
570 self.ctfe_query(span, |tcx| tcx.eval_to_valtree(self.param_env.and(cid)))?
571 .unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}"))
573 ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => {
574 span_bug!(self.cur_span(), "unexpected ConstKind in ctfe: {val:?}")
576 ty::ConstKind::Value(valtree) => valtree,
580 pub fn eval_mir_constant(
582 val: &mir::ConstantKind<'tcx>,
584 layout: Option<TyAndLayout<'tcx>>,
585 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
586 // FIXME(const_prop): normalization needed b/c const prop lint in
587 // `mir_drops_elaborated_and_const_checked`, which happens before
588 // optimized MIR. Only after optimizing the MIR can we guarantee
589 // that the `RevealAll` pass has happened and that the body's consts
590 // are normalized, so any call to resolve before that needs to be
591 // manually normalized.
592 let val = self.tcx.normalize_erasing_regions(self.param_env, *val);
594 mir::ConstantKind::Ty(ct) => {
596 let valtree = self.eval_ty_constant(ct, span)?;
597 let const_val = self.tcx.valtree_to_const_val((ty, valtree));
598 self.const_val_to_op(const_val, ty, layout)
600 mir::ConstantKind::Val(val, ty) => self.const_val_to_op(val, ty, layout),
601 mir::ConstantKind::Unevaluated(uv, _) => {
602 let instance = self.resolve(uv.def, uv.substs)?;
603 Ok(self.eval_global(GlobalId { instance, promoted: uv.promoted }, span)?.into())
608 pub(super) fn const_val_to_op(
610 val_val: ConstValue<'tcx>,
612 layout: Option<TyAndLayout<'tcx>>,
613 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
614 // Other cases need layout.
615 let adjust_scalar = |scalar| -> InterpResult<'tcx, _> {
617 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
618 Scalar::Int(int) => Scalar::Int(int),
621 let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
622 let op = match val_val {
623 ConstValue::ByRef { alloc, offset } => {
624 let id = self.tcx.create_memory_alloc(alloc);
625 // We rely on mutability being set correctly in that allocation to prevent writes
626 // where none should happen.
627 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
628 Operand::Indirect(MemPlace::from_ptr(ptr.into()))
630 ConstValue::Scalar(x) => Operand::Immediate(adjust_scalar(x)?.into()),
631 ConstValue::ZeroSized => Operand::Immediate(Immediate::Uninit),
632 ConstValue::Slice { data, start, end } => {
633 // We rely on mutability being set correctly in `data` to prevent writes
634 // where none should happen.
635 let ptr = Pointer::new(
636 self.tcx.create_memory_alloc(data),
637 Size::from_bytes(start), // offset: `start`
639 Operand::Immediate(Immediate::new_slice(
640 Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
641 u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
646 Ok(OpTy { op, layout, align: Some(layout.align.abi) })
649 /// Read discriminant, return the runtime value as well as the variant index.
650 /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)!
651 pub fn read_discriminant(
653 op: &OpTy<'tcx, M::Provenance>,
654 ) -> InterpResult<'tcx, (Scalar<M::Provenance>, VariantIdx)> {
655 trace!("read_discriminant_value {:#?}", op.layout);
656 // Get type and layout of the discriminant.
657 let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
658 trace!("discriminant type: {:?}", discr_layout.ty);
660 // We use "discriminant" to refer to the value associated with a particular enum variant.
661 // This is not to be confused with its "variant index", which is just determining its position in the
662 // declared list of variants -- they can differ with explicitly assigned discriminants.
663 // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
664 // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
665 let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
666 Variants::Single { index } => {
667 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
669 // This type actually has discriminants.
670 assert_eq!(discr.ty, discr_layout.ty);
671 Scalar::from_uint(discr.val, discr_layout.size)
674 // On a type without actual discriminants, variant is 0.
675 assert_eq!(index.as_u32(), 0);
676 Scalar::from_uint(index.as_u32(), discr_layout.size)
679 return Ok((discr, index));
681 Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
682 (tag, tag_encoding, tag_field)
686 // There are *three* layouts that come into play here:
687 // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
688 // the `Scalar` we return.
689 // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
690 // and used to interpret the value we read from the tag field.
691 // For the return value, a cast to `discr_layout` is performed.
692 // - The field storing the tag has a layout, which is very similar to `tag_layout` but
693 // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
695 // Get layout for tag.
696 let tag_layout = self.layout_of(tag_scalar_layout.primitive().to_int_ty(*self.tcx))?;
698 // Read tag and sanity-check `tag_layout`.
699 let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
700 assert_eq!(tag_layout.size, tag_val.layout.size);
701 assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
702 trace!("tag value: {}", tag_val);
704 // Figure out which discriminant and variant this corresponds to.
705 Ok(match *tag_encoding {
706 TagEncoding::Direct => {
707 let scalar = tag_val.to_scalar();
708 // Generate a specific error if `tag_val` is not an integer.
709 // (`tag_bits` itself is only used for error messages below.)
710 let tag_bits = scalar
712 .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
713 .assert_bits(tag_layout.size);
714 // Cast bits from tag layout to discriminant layout.
715 // After the checks we did above, this cannot fail, as
716 // discriminants are int-like.
718 self.cast_from_int_like(scalar, tag_val.layout, discr_layout.ty).unwrap();
719 let discr_bits = discr_val.assert_bits(discr_layout.size);
720 // Convert discriminant to variant index, and catch invalid discriminants.
721 let index = match *op.layout.ty.kind() {
723 adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
725 ty::Generator(def_id, substs, _) => {
726 let substs = substs.as_generator();
728 .discriminants(def_id, *self.tcx)
729 .find(|(_, var)| var.val == discr_bits)
731 _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
733 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
734 // Return the cast value, and the index.
737 TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
738 let tag_val = tag_val.to_scalar();
739 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
740 // discriminant (encoded in niche/tag) and variant index are the same.
741 let variants_start = niche_variants.start().as_u32();
742 let variants_end = niche_variants.end().as_u32();
743 let variant = match tag_val.try_to_int() {
745 // So this is a pointer then, and casting to an int failed.
746 // Can only happen during CTFE.
747 // The niche must be just 0, and the ptr not null, then we know this is
748 // okay. Everything else, we conservatively reject.
749 let ptr_valid = niche_start == 0
750 && variants_start == variants_end
751 && !self.scalar_may_be_null(tag_val)?;
753 throw_ub!(InvalidTag(dbg_val))
758 let tag_bits = tag_bits.assert_bits(tag_layout.size);
759 // We need to use machine arithmetic to get the relative variant idx:
760 // variant_index_relative = tag_val - niche_start_val
761 let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
762 let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
763 let variant_index_relative_val =
764 self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
765 let variant_index_relative =
766 variant_index_relative_val.to_scalar().assert_bits(tag_val.layout.size);
767 // Check if this is in the range that indicates an actual discriminant.
768 if variant_index_relative <= u128::from(variants_end - variants_start) {
769 let variant_index_relative = u32::try_from(variant_index_relative)
770 .expect("we checked that this fits into a u32");
771 // Then computing the absolute variant idx should not overflow any more.
772 let variant_index = variants_start
773 .checked_add(variant_index_relative)
774 .expect("overflow computing absolute variant idx");
775 let variants_len = op
779 .expect("tagged layout for non adt")
782 assert!(usize::try_from(variant_index).unwrap() < variants_len);
783 VariantIdx::from_u32(variant_index)
789 // Compute the size of the scalar we need to return.
790 // No need to cast, because the variant index directly serves as discriminant and is
791 // encoded in the tag.
792 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)
798 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
799 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
802 use rustc_data_structures::static_assert_size;
803 // tidy-alphabetical-start
804 static_assert_size!(Immediate, 48);
805 static_assert_size!(ImmTy<'_>, 64);
806 static_assert_size!(Operand, 56);
807 static_assert_size!(OpTy<'_>, 80);
808 // tidy-alphabetical-end