]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/operand.rs
CTFE/Miri engine Pointer type overhaul: make Scalar-to-Pointer conversion infallible
[rust.git] / compiler / rustc_mir / src / 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::TryFrom;
5 use std::fmt::Write;
6
7 use rustc_errors::ErrorReported;
8 use rustc_hir::def::Namespace;
9 use rustc_macros::HashStable;
10 use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
11 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Printer};
12 use rustc_middle::ty::{ConstInt, Ty};
13 use rustc_middle::{mir, ty};
14 use rustc_target::abi::{Abi, HasDataLayout, LayoutOf, Size, TagEncoding};
15 use rustc_target::abi::{VariantIdx, Variants};
16
17 use super::{
18     alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, GlobalId,
19     InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, Place, PlaceTy, Pointer, Provenance,
20     Scalar, ScalarMaybeUninit,
21 };
22
23 /// An `Immediate` represents a single immediate self-contained Rust value.
24 ///
25 /// For optimization of a few very common cases, there is also a representation for a pair of
26 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
27 /// operations and wide pointers. This idea was taken from rustc's codegen.
28 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
29 /// defined on `Immediate`, and do not have to work with a `Place`.
30 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash)]
31 pub enum Immediate<Tag = AllocId> {
32     Scalar(ScalarMaybeUninit<Tag>),
33     ScalarPair(ScalarMaybeUninit<Tag>, ScalarMaybeUninit<Tag>),
34 }
35
36 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
37 //FIXME rustc_data_structures::static_assert_size!(Immediate, 56);
38
39 impl<Tag: Provenance> std::fmt::Debug for Immediate<Tag> {
40     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41         use Immediate::*;
42         match self {
43             Scalar(s) => f.debug_tuple("Scalar").field(s).finish(),
44             ScalarPair(s1, s2) => f.debug_tuple("ScalarPair").field(s1).field(s2).finish(),
45         }
46     }
47 }
48
49 impl<Tag> From<ScalarMaybeUninit<Tag>> for Immediate<Tag> {
50     #[inline(always)]
51     fn from(val: ScalarMaybeUninit<Tag>) -> Self {
52         Immediate::Scalar(val)
53     }
54 }
55
56 impl<Tag> From<Scalar<Tag>> for Immediate<Tag> {
57     #[inline(always)]
58     fn from(val: Scalar<Tag>) -> Self {
59         Immediate::Scalar(val.into())
60     }
61 }
62
63 impl<Tag> From<Pointer<Tag>> for Immediate<Tag> {
64     #[inline(always)]
65     fn from(val: Pointer<Tag>) -> Self {
66         Immediate::Scalar(Scalar::from(val).into())
67     }
68 }
69
70 impl<'tcx, Tag> Immediate<Tag> {
71     pub fn new_slice(val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout) -> Self {
72         Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
73     }
74
75     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
76         Immediate::ScalarPair(val.into(), vtable.into())
77     }
78
79     #[inline]
80     pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit<Tag> {
81         match self {
82             Immediate::Scalar(val) => val,
83             Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
84         }
85     }
86
87     #[inline]
88     pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
89         self.to_scalar_or_uninit().check_init()
90     }
91 }
92
93 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
94 // as input for binary and cast operations.
95 #[derive(Copy, Clone)]
96 pub struct ImmTy<'tcx, Tag = AllocId> {
97     imm: Immediate<Tag>,
98     pub layout: TyAndLayout<'tcx>,
99 }
100
101 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
102 //FIXME rustc_data_structures::static_assert_size!(ImmTy<'_>, 72);
103
104 impl<'tcx, Tag: Provenance> std::fmt::Debug for ImmTy<'tcx, Tag> {
105     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106         let ImmTy { imm, layout } = self;
107         f.debug_struct("ImmTy").field("imm", imm).field("layout", layout).finish()
108     }
109 }
110
111 impl<Tag: Provenance> std::fmt::Display for ImmTy<'tcx, Tag> {
112     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113         /// Helper function for printing a scalar to a FmtPrinter
114         fn p<'a, 'tcx, F: std::fmt::Write, Tag: Provenance>(
115             cx: FmtPrinter<'a, 'tcx, F>,
116             s: ScalarMaybeUninit<Tag>,
117             ty: Ty<'tcx>,
118         ) -> Result<FmtPrinter<'a, 'tcx, F>, std::fmt::Error> {
119             match s {
120                 ScalarMaybeUninit::Scalar(s) => {
121                     cx.pretty_print_const_scalar(s.erase_for_fmt(), ty, true)
122                 }
123                 ScalarMaybeUninit::Uninit => cx.typed_value(
124                     |mut this| {
125                         this.write_str("uninit ")?;
126                         Ok(this)
127                     },
128                     |this| this.print_type(ty),
129                     " ",
130                 ),
131             }
132         }
133         ty::tls::with(|tcx| {
134             match self.imm {
135                 Immediate::Scalar(s) => {
136                     if let Some(ty) = tcx.lift(self.layout.ty) {
137                         let cx = FmtPrinter::new(tcx, f, Namespace::ValueNS);
138                         p(cx, s, ty)?;
139                         return Ok(());
140                     }
141                     write!(f, "{}: {}", s.erase_for_fmt(), self.layout.ty)
142                 }
143                 Immediate::ScalarPair(a, b) => {
144                     // FIXME(oli-obk): at least print tuples and slices nicely
145                     write!(f, "({}, {}): {}", a.erase_for_fmt(), b.erase_for_fmt(), self.layout.ty,)
146                 }
147             }
148         })
149     }
150 }
151
152 impl<'tcx, Tag> std::ops::Deref for ImmTy<'tcx, Tag> {
153     type Target = Immediate<Tag>;
154     #[inline(always)]
155     fn deref(&self) -> &Immediate<Tag> {
156         &self.imm
157     }
158 }
159
160 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
161 /// or still in memory. The latter is an optimization, to delay reading that chunk of
162 /// memory and to avoid having to store arbitrary-sized data here.
163 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash)]
164 pub enum Operand<Tag = AllocId> {
165     Immediate(Immediate<Tag>),
166     Indirect(MemPlace<Tag>),
167 }
168
169 impl<Tag: Provenance> std::fmt::Debug for Operand<Tag> {
170     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171         use Operand::*;
172         match self {
173             Immediate(i) => f.debug_tuple("Immediate").field(i).finish(),
174             Indirect(p) => f.debug_tuple("Indirect").field(p).finish(),
175         }
176     }
177 }
178
179 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
180 pub struct OpTy<'tcx, Tag = AllocId> {
181     op: Operand<Tag>, // Keep this private; it helps enforce invariants.
182     pub layout: TyAndLayout<'tcx>,
183 }
184
185 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
186 rustc_data_structures::static_assert_size!(OpTy<'_, ()>, 80);
187
188 impl<'tcx, Tag: Provenance> std::fmt::Debug for OpTy<'tcx, Tag> {
189     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190         let OpTy { op, layout } = self;
191         f.debug_struct("OpTy").field("op", op).field("layout", layout).finish()
192     }
193 }
194
195 impl<'tcx, Tag> std::ops::Deref for OpTy<'tcx, Tag> {
196     type Target = Operand<Tag>;
197     #[inline(always)]
198     fn deref(&self) -> &Operand<Tag> {
199         &self.op
200     }
201 }
202
203 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
204     #[inline(always)]
205     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
206         OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout }
207     }
208 }
209
210 impl<'tcx, Tag: Copy> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
211     #[inline(always)]
212     fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self {
213         OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout }
214     }
215 }
216
217 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
218     #[inline(always)]
219     fn from(val: ImmTy<'tcx, Tag>) -> Self {
220         OpTy { op: Operand::Immediate(val.imm), layout: val.layout }
221     }
222 }
223
224 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
225     #[inline]
226     pub fn from_scalar(val: Scalar<Tag>, layout: TyAndLayout<'tcx>) -> Self {
227         ImmTy { imm: val.into(), layout }
228     }
229
230     #[inline]
231     pub fn from_immediate(imm: Immediate<Tag>, layout: TyAndLayout<'tcx>) -> Self {
232         ImmTy { imm, layout }
233     }
234
235     #[inline]
236     pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
237         Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
238     }
239     #[inline]
240     pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
241         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
242     }
243
244     #[inline]
245     pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
246         Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
247     }
248
249     #[inline]
250     pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
251         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
252     }
253
254     #[inline]
255     pub fn to_const_int(self) -> ConstInt {
256         assert!(self.layout.ty.is_integral());
257         let int = self.to_scalar().expect("to_const_int doesn't work on scalar pairs").assert_int();
258         ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
259     }
260 }
261
262 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
263     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
264     /// Returns `None` if the layout does not permit loading this as a value.
265     fn try_read_immediate_from_mplace(
266         &self,
267         mplace: &MPlaceTy<'tcx, M::PointerTag>,
268     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
269         if mplace.layout.is_unsized() {
270             // Don't touch unsized
271             return Ok(None);
272         }
273
274         let alloc = match self.get_alloc(mplace)? {
275             Some(ptr) => ptr,
276             None => {
277                 return Ok(Some(ImmTy {
278                     // zero-sized type
279                     imm: Scalar::ZST.into(),
280                     layout: mplace.layout,
281                 }));
282             }
283         };
284
285         match mplace.layout.abi {
286             Abi::Scalar(..) => {
287                 let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?;
288                 Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout }))
289             }
290             Abi::ScalarPair(ref a, ref b) => {
291                 // We checked `ptr_align` above, so all fields will have the alignment they need.
292                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
293                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
294                 let (a, b) = (&a.value, &b.value);
295                 let (a_size, b_size) = (a.size(self), b.size(self));
296                 let b_offset = a_size.align_to(b.align(self).abi);
297                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
298                 let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?;
299                 let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?;
300                 Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }))
301             }
302             _ => Ok(None),
303         }
304     }
305
306     /// Try returning an immediate for the operand.
307     /// If the layout does not permit loading this as an immediate, return where in memory
308     /// we can find the data.
309     /// Note that for a given layout, this operation will either always fail or always
310     /// succeed!  Whether it succeeds depends on whether the layout can be represented
311     /// in a `Immediate`, not on which data is stored there currently.
312     pub(crate) fn try_read_immediate(
313         &self,
314         src: &OpTy<'tcx, M::PointerTag>,
315     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
316         Ok(match src.try_as_mplace() {
317             Ok(ref mplace) => {
318                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
319                     Ok(val)
320                 } else {
321                     Err(*mplace)
322                 }
323             }
324             Err(val) => Ok(val),
325         })
326     }
327
328     /// Read an immediate from a place, asserting that that is possible with the given layout.
329     #[inline(always)]
330     pub fn read_immediate(
331         &self,
332         op: &OpTy<'tcx, M::PointerTag>,
333     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
334         if let Ok(imm) = self.try_read_immediate(op)? {
335             Ok(imm)
336         } else {
337             span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty);
338         }
339     }
340
341     /// Read a scalar from a place
342     pub fn read_scalar(
343         &self,
344         op: &OpTy<'tcx, M::PointerTag>,
345     ) -> InterpResult<'tcx, ScalarMaybeUninit<M::PointerTag>> {
346         Ok(self.read_immediate(op)?.to_scalar_or_uninit())
347     }
348
349     /// Read a pointer from a place.
350     pub fn read_pointer(
351         &self,
352         op: &OpTy<'tcx, M::PointerTag>,
353     ) -> InterpResult<'tcx, Pointer<Option<M::PointerTag>>> {
354         Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?))
355     }
356
357     // Turn the wide MPlace into a string (must already be dereferenced!)
358     pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> {
359         let len = mplace.len(self)?;
360         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?;
361         let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
362         Ok(str)
363     }
364
365     /// Projection functions
366     pub fn operand_field(
367         &self,
368         op: &OpTy<'tcx, M::PointerTag>,
369         field: usize,
370     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
371         let base = match op.try_as_mplace() {
372             Ok(ref mplace) => {
373                 // We can reuse the mplace field computation logic for indirect operands.
374                 let field = self.mplace_field(mplace, field)?;
375                 return Ok(field.into());
376             }
377             Err(value) => value,
378         };
379
380         let field_layout = op.layout.field(self, field)?;
381         if field_layout.is_zst() {
382             let immediate = Scalar::ZST.into();
383             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
384         }
385         let offset = op.layout.fields.offset(field);
386         let immediate = match *base {
387             // the field covers the entire type
388             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
389             // extract fields from types with `ScalarPair` ABI
390             Immediate::ScalarPair(a, b) => {
391                 let val = if offset.bytes() == 0 { a } else { b };
392                 Immediate::from(val)
393             }
394             Immediate::Scalar(val) => span_bug!(
395                 self.cur_span(),
396                 "field access on non aggregate {:#?}, {:#?}",
397                 val,
398                 op.layout
399             ),
400         };
401         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
402     }
403
404     pub fn operand_index(
405         &self,
406         op: &OpTy<'tcx, M::PointerTag>,
407         index: u64,
408     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
409         if let Ok(index) = usize::try_from(index) {
410             // We can just treat this as a field.
411             self.operand_field(op, index)
412         } else {
413             // Indexing into a big array. This must be an mplace.
414             let mplace = op.assert_mem_place();
415             Ok(self.mplace_index(&mplace, index)?.into())
416         }
417     }
418
419     pub fn operand_downcast(
420         &self,
421         op: &OpTy<'tcx, M::PointerTag>,
422         variant: VariantIdx,
423     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
424         // Downcasts only change the layout
425         Ok(match op.try_as_mplace() {
426             Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(),
427             Err(..) => {
428                 let layout = op.layout.for_variant(self, variant);
429                 OpTy { layout, ..*op }
430             }
431         })
432     }
433
434     pub fn operand_projection(
435         &self,
436         base: &OpTy<'tcx, M::PointerTag>,
437         proj_elem: mir::PlaceElem<'tcx>,
438     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
439         use rustc_middle::mir::ProjectionElem::*;
440         Ok(match proj_elem {
441             Field(field, _) => self.operand_field(base, field.index())?,
442             Downcast(_, variant) => self.operand_downcast(base, variant)?,
443             Deref => self.deref_operand(base)?.into(),
444             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
445                 // The rest should only occur as mplace, we do not use Immediates for types
446                 // allowing such operations.  This matches place_projection forcing an allocation.
447                 let mplace = base.assert_mem_place();
448                 self.mplace_projection(&mplace, proj_elem)?.into()
449             }
450         })
451     }
452
453     /// Read from a local. Will not actually access the local if reading from a ZST.
454     /// Will not access memory, instead an indirect `Operand` is returned.
455     ///
456     /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
457     /// OpTy from a local
458     pub fn access_local(
459         &self,
460         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
461         local: mir::Local,
462         layout: Option<TyAndLayout<'tcx>>,
463     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
464         let layout = self.layout_of_local(frame, local, layout)?;
465         let op = if layout.is_zst() {
466             // Do not read from ZST, they might not be initialized
467             Operand::Immediate(Scalar::ZST.into())
468         } else {
469             M::access_local(&self, frame, local)?
470         };
471         Ok(OpTy { op, layout })
472     }
473
474     /// Every place can be read from, so we can turn them into an operand.
475     /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
476     /// will never actually read from memory.
477     #[inline(always)]
478     pub fn place_to_op(
479         &self,
480         place: &PlaceTy<'tcx, M::PointerTag>,
481     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
482         let op = match **place {
483             Place::Ptr(mplace) => Operand::Indirect(mplace),
484             Place::Local { frame, local } => {
485                 *self.access_local(&self.stack()[frame], local, None)?
486             }
487         };
488         Ok(OpTy { op, layout: place.layout })
489     }
490
491     // Evaluate a place with the goal of reading from it.  This lets us sometimes
492     // avoid allocations.
493     pub fn eval_place_to_op(
494         &self,
495         place: mir::Place<'tcx>,
496         layout: Option<TyAndLayout<'tcx>>,
497     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
498         // Do not use the layout passed in as argument if the base we are looking at
499         // here is not the entire place.
500         let layout = if place.projection.is_empty() { layout } else { None };
501
502         let base_op = self.access_local(self.frame(), place.local, layout)?;
503
504         let op = place
505             .projection
506             .iter()
507             .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?;
508
509         trace!("eval_place_to_op: got {:?}", *op);
510         // Sanity-check the type we ended up with.
511         debug_assert!(mir_assign_valid_types(
512             *self.tcx,
513             self.param_env,
514             self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
515                 place.ty(&self.frame().body.local_decls, *self.tcx).ty
516             ))?,
517             op.layout,
518         ));
519         Ok(op)
520     }
521
522     /// Evaluate the operand, returning a place where you can then find the data.
523     /// If you already know the layout, you can save two table lookups
524     /// by passing it in here.
525     #[inline]
526     pub fn eval_operand(
527         &self,
528         mir_op: &mir::Operand<'tcx>,
529         layout: Option<TyAndLayout<'tcx>>,
530     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
531         use rustc_middle::mir::Operand::*;
532         let op = match *mir_op {
533             // FIXME: do some more logic on `move` to invalidate the old location
534             Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
535
536             Constant(ref constant) => {
537                 let val =
538                     self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal);
539                 // This can still fail:
540                 // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all
541                 //   checked yet.
542                 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
543
544                 self.mir_const_to_op(&val, layout)?
545             }
546         };
547         trace!("{:?}: {:?}", mir_op, *op);
548         Ok(op)
549     }
550
551     /// Evaluate a bunch of operands at once
552     pub(super) fn eval_operands(
553         &self,
554         ops: &[mir::Operand<'tcx>],
555     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
556         ops.iter().map(|op| self.eval_operand(op, None)).collect()
557     }
558
559     // Used when the miri-engine runs into a constant and for extracting information from constants
560     // in patterns via the `const_eval` module
561     /// The `val` and `layout` are assumed to already be in our interpreter
562     /// "universe" (param_env).
563     crate fn const_to_op(
564         &self,
565         val: &ty::Const<'tcx>,
566         layout: Option<TyAndLayout<'tcx>>,
567     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
568         match val.val {
569             ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric),
570             ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)),
571             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
572                 let instance = self.resolve(def, substs)?;
573                 Ok(self.eval_to_allocation(GlobalId { instance, promoted })?.into())
574             }
575             ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => {
576                 span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val)
577             }
578             ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout),
579         }
580     }
581
582     crate fn mir_const_to_op(
583         &self,
584         val: &mir::ConstantKind<'tcx>,
585         layout: Option<TyAndLayout<'tcx>>,
586     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
587         match val {
588             mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout),
589             mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout),
590         }
591     }
592
593     crate fn const_val_to_op(
594         &self,
595         val_val: ConstValue<'tcx>,
596         ty: Ty<'tcx>,
597         layout: Option<TyAndLayout<'tcx>>,
598     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
599         // Other cases need layout.
600         let tag_scalar = |scalar| -> InterpResult<'tcx, _> {
601             Ok(match scalar {
602                 Scalar::Ptr(ptr) => Scalar::Ptr(self.global_base_pointer(ptr)?),
603                 Scalar::Int(int) => Scalar::Int(int),
604             })
605         };
606         let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
607         let op = match val_val {
608             ConstValue::ByRef { alloc, offset } => {
609                 let id = self.tcx.create_memory_alloc(alloc);
610                 // We rely on mutability being set correctly in that allocation to prevent writes
611                 // where none should happen.
612                 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
613                 Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi))
614             }
615             ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x.into())?.into()),
616             ConstValue::Slice { data, start, end } => {
617                 // We rely on mutability being set correctly in `data` to prevent writes
618                 // where none should happen.
619                 let ptr = Pointer::new(
620                     self.tcx.create_memory_alloc(data),
621                     Size::from_bytes(start), // offset: `start`
622                 );
623                 Operand::Immediate(Immediate::new_slice(
624                     self.global_base_pointer(ptr)?.into(),
625                     u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
626                     self,
627                 ))
628             }
629         };
630         Ok(OpTy { op, layout })
631     }
632
633     /// Read discriminant, return the runtime value as well as the variant index.
634     pub fn read_discriminant(
635         &self,
636         op: &OpTy<'tcx, M::PointerTag>,
637     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, VariantIdx)> {
638         trace!("read_discriminant_value {:#?}", op.layout);
639         // Get type and layout of the discriminant.
640         let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
641         trace!("discriminant type: {:?}", discr_layout.ty);
642
643         // We use "discriminant" to refer to the value associated with a particular enum variant.
644         // This is not to be confused with its "variant index", which is just determining its position in the
645         // declared list of variants -- they can differ with explicitly assigned discriminants.
646         // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
647         // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
648         let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
649             Variants::Single { index } => {
650                 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
651                     Some(discr) => {
652                         // This type actually has discriminants.
653                         assert_eq!(discr.ty, discr_layout.ty);
654                         Scalar::from_uint(discr.val, discr_layout.size)
655                     }
656                     None => {
657                         // On a type without actual discriminants, variant is 0.
658                         assert_eq!(index.as_u32(), 0);
659                         Scalar::from_uint(index.as_u32(), discr_layout.size)
660                     }
661                 };
662                 return Ok((discr, index));
663             }
664             Variants::Multiple { ref tag, ref tag_encoding, tag_field, .. } => {
665                 (tag, tag_encoding, tag_field)
666             }
667         };
668
669         // There are *three* layouts that come into play here:
670         // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
671         //   the `Scalar` we return.
672         // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
673         //   and used to interpret the value we read from the tag field.
674         //   For the return value, a cast to `discr_layout` is performed.
675         // - The field storing the tag has a layout, which is very similar to `tag_layout` but
676         //   may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
677
678         // Get layout for tag.
679         let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?;
680
681         // Read tag and sanity-check `tag_layout`.
682         let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
683         assert_eq!(tag_layout.size, tag_val.layout.size);
684         assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
685         let tag_val = tag_val.to_scalar()?;
686         trace!("tag value: {:?}", tag_val);
687
688         // Figure out which discriminant and variant this corresponds to.
689         Ok(match *tag_encoding {
690             TagEncoding::Direct => {
691                 let tag_bits = tag_val
692                     .to_bits(tag_layout.size)
693                     .map_err(|_| err_ub!(InvalidTag(tag_val.erase_for_fmt())))?;
694                 // Cast bits from tag layout to discriminant layout.
695                 let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty);
696                 let discr_bits = discr_val.assert_bits(discr_layout.size);
697                 // Convert discriminant to variant index, and catch invalid discriminants.
698                 let index = match *op.layout.ty.kind() {
699                     ty::Adt(adt, _) => {
700                         adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
701                     }
702                     ty::Generator(def_id, substs, _) => {
703                         let substs = substs.as_generator();
704                         substs
705                             .discriminants(def_id, *self.tcx)
706                             .find(|(_, var)| var.val == discr_bits)
707                     }
708                     _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
709                 }
710                 .ok_or_else(|| err_ub!(InvalidTag(tag_val.erase_for_fmt())))?;
711                 // Return the cast value, and the index.
712                 (discr_val, index.0)
713             }
714             TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => {
715                 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
716                 // discriminant (encoded in niche/tag) and variant index are the same.
717                 let variants_start = niche_variants.start().as_u32();
718                 let variants_end = niche_variants.end().as_u32();
719                 let variant = match tag_val.to_bits_or_ptr(tag_layout.size, self) {
720                     Err(ptr) => {
721                         // The niche must be just 0 (which an inbounds pointer value never is)
722                         let ptr_valid = niche_start == 0
723                             && variants_start == variants_end
724                             && !self.memory.ptr_may_be_null(ptr.into());
725                         if !ptr_valid {
726                             throw_ub!(InvalidTag(tag_val.erase_for_fmt()))
727                         }
728                         dataful_variant
729                     }
730                     Ok(tag_bits) => {
731                         // We need to use machine arithmetic to get the relative variant idx:
732                         // variant_index_relative = tag_val - niche_start_val
733                         let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
734                         let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
735                         let variant_index_relative_val =
736                             self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
737                         let variant_index_relative = variant_index_relative_val
738                             .to_scalar()?
739                             .assert_bits(tag_val.layout.size);
740                         // Check if this is in the range that indicates an actual discriminant.
741                         if variant_index_relative <= u128::from(variants_end - variants_start) {
742                             let variant_index_relative = u32::try_from(variant_index_relative)
743                                 .expect("we checked that this fits into a u32");
744                             // Then computing the absolute variant idx should not overflow any more.
745                             let variant_index = variants_start
746                                 .checked_add(variant_index_relative)
747                                 .expect("overflow computing absolute variant idx");
748                             let variants_len = op
749                                 .layout
750                                 .ty
751                                 .ty_adt_def()
752                                 .expect("tagged layout for non adt")
753                                 .variants
754                                 .len();
755                             assert!(usize::try_from(variant_index).unwrap() < variants_len);
756                             VariantIdx::from_u32(variant_index)
757                         } else {
758                             dataful_variant
759                         }
760                     }
761                 };
762                 // Compute the size of the scalar we need to return.
763                 // No need to cast, because the variant index directly serves as discriminant and is
764                 // encoded in the tag.
765                 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)
766             }
767         })
768     }
769 }