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