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