]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/place.rs
Auto merge of #101514 - nvzqz:nvzqz/stabilize-nonzero-bits, r=thomcc
[rust.git] / compiler / rustc_const_eval / src / interpret / place.rs
1 //! Computations on places -- field projections, going from mir::Place, and writing
2 //! into a place.
3 //! All high-level functions to write to memory work on places as destinations.
4
5 use either::{Either, Left, Right};
6
7 use rustc_ast::Mutability;
8 use rustc_middle::mir;
9 use rustc_middle::ty;
10 use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
11 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, TagEncoding, VariantIdx};
12
13 use super::{
14     alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
15     ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemoryKind, OpTy, Operand,
16     Pointer, Provenance, Scalar,
17 };
18
19 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
20 /// Information required for the sound usage of a `MemPlace`.
21 pub enum MemPlaceMeta<Prov: Provenance = AllocId> {
22     /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
23     Meta(Scalar<Prov>),
24     /// `Sized` types or unsized `extern type`
25     None,
26 }
27
28 impl<Prov: Provenance> MemPlaceMeta<Prov> {
29     pub fn unwrap_meta(self) -> Scalar<Prov> {
30         match self {
31             Self::Meta(s) => s,
32             Self::None => {
33                 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
34             }
35         }
36     }
37
38     pub fn has_meta(self) -> bool {
39         match self {
40             Self::Meta(_) => true,
41             Self::None => false,
42         }
43     }
44 }
45
46 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
47 pub struct MemPlace<Prov: Provenance = AllocId> {
48     /// The pointer can be a pure integer, with the `None` provenance.
49     pub ptr: Pointer<Option<Prov>>,
50     /// Metadata for unsized places. Interpretation is up to the type.
51     /// Must not be present for sized types, but can be missing for unsized types
52     /// (e.g., `extern type`).
53     pub meta: MemPlaceMeta<Prov>,
54 }
55
56 /// A MemPlace with its layout. Constructing it is only possible in this module.
57 #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
58 pub struct MPlaceTy<'tcx, Prov: Provenance = AllocId> {
59     mplace: MemPlace<Prov>,
60     pub layout: TyAndLayout<'tcx>,
61     /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
62     /// it needs to have a different alignment than the field type would usually have.
63     /// So we represent this here with a separate field that "overwrites" `layout.align`.
64     /// This means `layout.align` should never be used for a `MPlaceTy`!
65     pub align: Align,
66 }
67
68 #[derive(Copy, Clone, Debug)]
69 pub enum Place<Prov: Provenance = AllocId> {
70     /// A place referring to a value allocated in the `Memory` system.
71     Ptr(MemPlace<Prov>),
72
73     /// To support alloc-free locals, we are able to write directly to a local.
74     /// (Without that optimization, we'd just always be a `MemPlace`.)
75     Local { frame: usize, local: mir::Local },
76 }
77
78 #[derive(Clone, Debug)]
79 pub struct PlaceTy<'tcx, Prov: Provenance = AllocId> {
80     place: Place<Prov>, // Keep this private; it helps enforce invariants.
81     pub layout: TyAndLayout<'tcx>,
82     /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
83     /// it needs to have a different alignment than the field type would usually have.
84     /// So we represent this here with a separate field that "overwrites" `layout.align`.
85     /// This means `layout.align` should never be used for a `PlaceTy`!
86     pub align: Align,
87 }
88
89 impl<'tcx, Prov: Provenance> std::ops::Deref for PlaceTy<'tcx, Prov> {
90     type Target = Place<Prov>;
91     #[inline(always)]
92     fn deref(&self) -> &Place<Prov> {
93         &self.place
94     }
95 }
96
97 impl<'tcx, Prov: Provenance> std::ops::Deref for MPlaceTy<'tcx, Prov> {
98     type Target = MemPlace<Prov>;
99     #[inline(always)]
100     fn deref(&self) -> &MemPlace<Prov> {
101         &self.mplace
102     }
103 }
104
105 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
106     #[inline(always)]
107     fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
108         PlaceTy { place: Place::Ptr(*mplace), layout: mplace.layout, align: mplace.align }
109     }
110 }
111
112 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
113     #[inline(always)]
114     fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
115         PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
116     }
117 }
118
119 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
120     #[inline(always)]
121     fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
122         PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
123     }
124 }
125
126 impl<Prov: Provenance> MemPlace<Prov> {
127     #[inline(always)]
128     pub fn from_ptr(ptr: Pointer<Option<Prov>>) -> Self {
129         MemPlace { ptr, meta: MemPlaceMeta::None }
130     }
131
132     /// Adjust the provenance of the main pointer (metadata is unaffected).
133     pub fn map_provenance(self, f: impl FnOnce(Option<Prov>) -> Option<Prov>) -> Self {
134         MemPlace { ptr: self.ptr.map_provenance(f), ..self }
135     }
136
137     /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
138     /// This is the inverse of `ref_to_mplace`.
139     #[inline(always)]
140     pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
141         match self.meta {
142             MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)),
143             MemPlaceMeta::Meta(meta) => {
144                 Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into())
145             }
146         }
147     }
148
149     #[inline]
150     pub fn offset_with_meta<'tcx>(
151         self,
152         offset: Size,
153         meta: MemPlaceMeta<Prov>,
154         cx: &impl HasDataLayout,
155     ) -> InterpResult<'tcx, Self> {
156         Ok(MemPlace { ptr: self.ptr.offset(offset, cx)?, meta })
157     }
158 }
159
160 impl<Prov: Provenance> Place<Prov> {
161     /// Asserts that this points to some local variable.
162     /// Returns the frame idx and the variable idx.
163     #[inline]
164     #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
165     pub fn assert_local(&self) -> (usize, mir::Local) {
166         match self {
167             Place::Local { frame, local } => (*frame, *local),
168             _ => bug!("assert_local: expected Place::Local, got {:?}", self),
169         }
170     }
171 }
172
173 impl<'tcx, Prov: Provenance> MPlaceTy<'tcx, Prov> {
174     /// Produces a MemPlace that works for ZST but nothing else.
175     /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
176     /// don't need to worry about memory leaks.
177     #[inline]
178     pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
179         assert!(layout.is_zst());
180         let align = layout.align.abi;
181         let ptr = Pointer::from_addr(align.bytes()); // no provenance, absolute address
182         MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None }, layout, align }
183     }
184
185     #[inline]
186     pub fn offset_with_meta(
187         &self,
188         offset: Size,
189         meta: MemPlaceMeta<Prov>,
190         layout: TyAndLayout<'tcx>,
191         cx: &impl HasDataLayout,
192     ) -> InterpResult<'tcx, Self> {
193         Ok(MPlaceTy {
194             mplace: self.mplace.offset_with_meta(offset, meta, cx)?,
195             align: self.align.restrict_for_offset(offset),
196             layout,
197         })
198     }
199
200     pub fn offset(
201         &self,
202         offset: Size,
203         layout: TyAndLayout<'tcx>,
204         cx: &impl HasDataLayout,
205     ) -> InterpResult<'tcx, Self> {
206         assert!(layout.is_sized());
207         self.offset_with_meta(offset, MemPlaceMeta::None, layout, cx)
208     }
209
210     #[inline]
211     pub fn from_aligned_ptr(ptr: Pointer<Option<Prov>>, layout: TyAndLayout<'tcx>) -> Self {
212         MPlaceTy { mplace: MemPlace::from_ptr(ptr), layout, align: layout.align.abi }
213     }
214
215     #[inline]
216     pub fn from_aligned_ptr_with_meta(
217         ptr: Pointer<Option<Prov>>,
218         layout: TyAndLayout<'tcx>,
219         meta: MemPlaceMeta<Prov>,
220     ) -> Self {
221         let mut mplace = MemPlace::from_ptr(ptr);
222         mplace.meta = meta;
223
224         MPlaceTy { mplace, layout, align: layout.align.abi }
225     }
226
227     #[inline]
228     pub(crate) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
229         if self.layout.is_unsized() {
230             // We need to consult `meta` metadata
231             match self.layout.ty.kind() {
232                 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
233                 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
234             }
235         } else {
236             // Go through the layout.  There are lots of types that support a length,
237             // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!)
238             match self.layout.fields {
239                 abi::FieldsShape::Array { count, .. } => Ok(count),
240                 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
241             }
242         }
243     }
244
245     #[inline]
246     pub(super) fn vtable(&self) -> Scalar<Prov> {
247         match self.layout.ty.kind() {
248             ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
249             _ => bug!("vtable not supported on type {:?}", self.layout.ty),
250         }
251     }
252 }
253
254 // These are defined here because they produce a place.
255 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
256     #[inline(always)]
257     pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
258         match **self {
259             Operand::Indirect(mplace) => {
260                 Left(MPlaceTy { mplace, layout: self.layout, align: self.align.unwrap() })
261             }
262             Operand::Immediate(imm) => Right(ImmTy::from_immediate(imm, self.layout)),
263         }
264     }
265
266     #[inline(always)]
267     #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
268     pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
269         self.as_mplace_or_imm().left().unwrap()
270     }
271 }
272
273 impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
274     /// A place is either an mplace or some local.
275     #[inline]
276     pub fn as_mplace_or_local(&self) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local)> {
277         match **self {
278             Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout, align: self.align }),
279             Place::Local { frame, local } => Right((frame, local)),
280         }
281     }
282
283     #[inline(always)]
284     #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
285     pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
286         self.as_mplace_or_local().left().unwrap()
287     }
288 }
289
290 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
291 impl<'mir, 'tcx: 'mir, Prov, M> InterpCx<'mir, 'tcx, M>
292 where
293     Prov: Provenance + 'static,
294     M: Machine<'mir, 'tcx, Provenance = Prov>,
295 {
296     /// Take a value, which represents a (thin or wide) reference, and make it a place.
297     /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
298     ///
299     /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
300     /// want to ever use the place for memory access!
301     /// Generally prefer `deref_operand`.
302     pub fn ref_to_mplace(
303         &self,
304         val: &ImmTy<'tcx, M::Provenance>,
305     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
306         let pointee_type =
307             val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
308         let layout = self.layout_of(pointee_type)?;
309         let (ptr, meta) = match **val {
310             Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None),
311             Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta)),
312             Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
313         };
314
315         let mplace = MemPlace { ptr: ptr.to_pointer(self)?, meta };
316         // When deref'ing a pointer, the *static* alignment given by the type is what matters.
317         let align = layout.align.abi;
318         Ok(MPlaceTy { mplace, layout, align })
319     }
320
321     /// Take an operand, representing a pointer, and dereference it to a place.
322     #[instrument(skip(self), level = "debug")]
323     pub fn deref_operand(
324         &self,
325         src: &OpTy<'tcx, M::Provenance>,
326     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
327         let val = self.read_immediate(src)?;
328         trace!("deref to {} on {:?}", val.layout.ty, *val);
329
330         if val.layout.ty.is_box() {
331             bug!("dereferencing {:?}", val.layout.ty);
332         }
333
334         let mplace = self.ref_to_mplace(&val)?;
335         self.check_mplace(mplace)?;
336         Ok(mplace)
337     }
338
339     #[inline]
340     pub(super) fn get_place_alloc(
341         &self,
342         place: &MPlaceTy<'tcx, M::Provenance>,
343     ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra>>> {
344         assert!(place.layout.is_sized());
345         assert!(!place.meta.has_meta());
346         let size = place.layout.size;
347         self.get_ptr_alloc(place.ptr, size, place.align)
348     }
349
350     #[inline]
351     pub(super) fn get_place_alloc_mut(
352         &mut self,
353         place: &MPlaceTy<'tcx, M::Provenance>,
354     ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra>>> {
355         assert!(place.layout.is_sized());
356         assert!(!place.meta.has_meta());
357         let size = place.layout.size;
358         self.get_ptr_alloc_mut(place.ptr, size, place.align)
359     }
360
361     /// Check if this mplace is dereferenceable and sufficiently aligned.
362     pub fn check_mplace(&self, mplace: MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
363         let (size, align) = self
364             .size_and_align_of_mplace(&mplace)?
365             .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
366         assert!(mplace.align <= align, "dynamic alignment less strict than static one?");
367         let align = M::enforce_alignment(self).then_some(align);
368         self.check_ptr_access_align(
369             mplace.ptr,
370             size,
371             align.unwrap_or(Align::ONE),
372             CheckInAllocMsg::DerefTest,
373         )?;
374         Ok(())
375     }
376
377     /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
378     /// Also returns the number of elements.
379     pub fn mplace_to_simd(
380         &self,
381         mplace: &MPlaceTy<'tcx, M::Provenance>,
382     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
383         // Basically we just transmute this place into an array following simd_size_and_type.
384         // (Transmuting is okay since this is an in-memory place. We also double-check the size
385         // stays the same.)
386         let (len, e_ty) = mplace.layout.ty.simd_size_and_type(*self.tcx);
387         let array = self.tcx.mk_array(e_ty, len);
388         let layout = self.layout_of(array)?;
389         assert_eq!(layout.size, mplace.layout.size);
390         Ok((MPlaceTy { layout, ..*mplace }, len))
391     }
392
393     /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
394     /// Also returns the number of elements.
395     pub fn place_to_simd(
396         &mut self,
397         place: &PlaceTy<'tcx, M::Provenance>,
398     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
399         let mplace = self.force_allocation(place)?;
400         self.mplace_to_simd(&mplace)
401     }
402
403     pub fn local_to_place(
404         &self,
405         frame: usize,
406         local: mir::Local,
407     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
408         let layout = self.layout_of_local(&self.stack()[frame], local, None)?;
409         let place = Place::Local { frame, local };
410         Ok(PlaceTy { place, layout, align: layout.align.abi })
411     }
412
413     /// Computes a place. You should only use this if you intend to write into this
414     /// place; for reading, a more efficient alternative is `eval_place_to_op`.
415     #[instrument(skip(self), level = "debug")]
416     pub fn eval_place(
417         &mut self,
418         mir_place: mir::Place<'tcx>,
419     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
420         let mut place = self.local_to_place(self.frame_idx(), mir_place.local)?;
421         // Using `try_fold` turned out to be bad for performance, hence the loop.
422         for elem in mir_place.projection.iter() {
423             place = self.place_projection(&place, elem)?
424         }
425
426         trace!("{:?}", self.dump_place(place.place));
427         // Sanity-check the type we ended up with.
428         debug_assert!(
429             mir_assign_valid_types(
430                 *self.tcx,
431                 self.param_env,
432                 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
433                     mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
434                 )?)?,
435                 place.layout,
436             ),
437             "eval_place of a MIR place with type {:?} produced an interpreter place with type {:?}",
438             mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
439             place.layout.ty,
440         );
441         Ok(place)
442     }
443
444     /// Write an immediate to a place
445     #[inline(always)]
446     #[instrument(skip(self), level = "debug")]
447     pub fn write_immediate(
448         &mut self,
449         src: Immediate<M::Provenance>,
450         dest: &PlaceTy<'tcx, M::Provenance>,
451     ) -> InterpResult<'tcx> {
452         self.write_immediate_no_validate(src, dest)?;
453
454         if M::enforce_validity(self) {
455             // Data got changed, better make sure it matches the type!
456             self.validate_operand(&self.place_to_op(dest)?)?;
457         }
458
459         Ok(())
460     }
461
462     /// Write a scalar to a place
463     #[inline(always)]
464     pub fn write_scalar(
465         &mut self,
466         val: impl Into<Scalar<M::Provenance>>,
467         dest: &PlaceTy<'tcx, M::Provenance>,
468     ) -> InterpResult<'tcx> {
469         self.write_immediate(Immediate::Scalar(val.into()), dest)
470     }
471
472     /// Write a pointer to a place
473     #[inline(always)]
474     pub fn write_pointer(
475         &mut self,
476         ptr: impl Into<Pointer<Option<M::Provenance>>>,
477         dest: &PlaceTy<'tcx, M::Provenance>,
478     ) -> InterpResult<'tcx> {
479         self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
480     }
481
482     /// Write an immediate to a place.
483     /// If you use this you are responsible for validating that things got copied at the
484     /// right type.
485     fn write_immediate_no_validate(
486         &mut self,
487         src: Immediate<M::Provenance>,
488         dest: &PlaceTy<'tcx, M::Provenance>,
489     ) -> InterpResult<'tcx> {
490         assert!(dest.layout.is_sized(), "Cannot write unsized data");
491         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
492
493         // See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
494         // but not factored as a separate function.
495         let mplace = match dest.place {
496             Place::Local { frame, local } => {
497                 match M::access_local_mut(self, frame, local)? {
498                     Operand::Immediate(local) => {
499                         // Local can be updated in-place.
500                         *local = src;
501                         return Ok(());
502                     }
503                     Operand::Indirect(mplace) => {
504                         // The local is in memory, go on below.
505                         *mplace
506                     }
507                 }
508             }
509             Place::Ptr(mplace) => mplace, // already referring to memory
510         };
511
512         // This is already in memory, write there.
513         self.write_immediate_to_mplace_no_validate(src, dest.layout, dest.align, mplace)
514     }
515
516     /// Write an immediate to memory.
517     /// If you use this you are responsible for validating that things got copied at the
518     /// right layout.
519     fn write_immediate_to_mplace_no_validate(
520         &mut self,
521         value: Immediate<M::Provenance>,
522         layout: TyAndLayout<'tcx>,
523         align: Align,
524         dest: MemPlace<M::Provenance>,
525     ) -> InterpResult<'tcx> {
526         // Note that it is really important that the type here is the right one, and matches the
527         // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
528         // to handle padding properly, which is only correct if we never look at this data with the
529         // wrong type.
530
531         let tcx = *self.tcx;
532         let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else {
533             // zero-sized access
534             return Ok(());
535         };
536
537         match value {
538             Immediate::Scalar(scalar) => {
539                 let Abi::Scalar(s) = layout.abi else { span_bug!(
540                         self.cur_span(),
541                         "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
542                     )
543                 };
544                 let size = s.size(&tcx);
545                 assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
546                 alloc.write_scalar(alloc_range(Size::ZERO, size), scalar)
547             }
548             Immediate::ScalarPair(a_val, b_val) => {
549                 // We checked `ptr_align` above, so all fields will have the alignment they need.
550                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
551                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
552                 let Abi::ScalarPair(a, b) = layout.abi else { span_bug!(
553                         self.cur_span(),
554                         "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
555                         layout
556                     )
557                 };
558                 let (a_size, b_size) = (a.size(&tcx), b.size(&tcx));
559                 let b_offset = a_size.align_to(b.align(&tcx).abi);
560                 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
561
562                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
563                 // but that does not work: We could be a newtype around a pair, then the
564                 // fields do not match the `ScalarPair` components.
565
566                 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
567                 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
568             }
569             Immediate::Uninit => alloc.write_uninit(),
570         }
571     }
572
573     pub fn write_uninit(&mut self, dest: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
574         let mplace = match dest.as_mplace_or_local() {
575             Left(mplace) => mplace,
576             Right((frame, local)) => {
577                 match M::access_local_mut(self, frame, local)? {
578                     Operand::Immediate(local) => {
579                         *local = Immediate::Uninit;
580                         return Ok(());
581                     }
582                     Operand::Indirect(mplace) => {
583                         // The local is in memory, go on below.
584                         MPlaceTy { mplace: *mplace, layout: dest.layout, align: dest.align }
585                     }
586                 }
587             }
588         };
589         let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
590             // Zero-sized access
591             return Ok(());
592         };
593         alloc.write_uninit()?;
594         Ok(())
595     }
596
597     /// Copies the data from an operand to a place.
598     /// `allow_transmute` indicates whether the layouts may disagree.
599     #[inline(always)]
600     #[instrument(skip(self), level = "debug")]
601     pub fn copy_op(
602         &mut self,
603         src: &OpTy<'tcx, M::Provenance>,
604         dest: &PlaceTy<'tcx, M::Provenance>,
605         allow_transmute: bool,
606     ) -> InterpResult<'tcx> {
607         self.copy_op_no_validate(src, dest, allow_transmute)?;
608
609         if M::enforce_validity(self) {
610             // Data got changed, better make sure it matches the type!
611             self.validate_operand(&self.place_to_op(dest)?)?;
612         }
613
614         Ok(())
615     }
616
617     /// Copies the data from an operand to a place.
618     /// `allow_transmute` indicates whether the layouts may disagree.
619     /// Also, if you use this you are responsible for validating that things get copied at the
620     /// right type.
621     #[instrument(skip(self), level = "debug")]
622     fn copy_op_no_validate(
623         &mut self,
624         src: &OpTy<'tcx, M::Provenance>,
625         dest: &PlaceTy<'tcx, M::Provenance>,
626         allow_transmute: bool,
627     ) -> InterpResult<'tcx> {
628         // We do NOT compare the types for equality, because well-typed code can
629         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
630         let layout_compat =
631             mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout);
632         if !allow_transmute && !layout_compat {
633             span_bug!(
634                 self.cur_span(),
635                 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
636                 src.layout.ty,
637                 dest.layout.ty,
638             );
639         }
640
641         // Let us see if the layout is simple so we take a shortcut,
642         // avoid force_allocation.
643         let src = match self.read_immediate_raw(src)? {
644             Right(src_val) => {
645                 // FIXME(const_prop): Const-prop can possibly evaluate an
646                 // unsized copy operation when it thinks that the type is
647                 // actually sized, due to a trivially false where-clause
648                 // predicate like `where Self: Sized` with `Self = dyn Trait`.
649                 // See #102553 for an example of such a predicate.
650                 if src.layout.is_unsized() {
651                     throw_inval!(SizeOfUnsizedType(src.layout.ty));
652                 }
653                 if dest.layout.is_unsized() {
654                     throw_inval!(SizeOfUnsizedType(dest.layout.ty));
655                 }
656                 assert_eq!(src.layout.size, dest.layout.size);
657                 // Yay, we got a value that we can write directly.
658                 return if layout_compat {
659                     self.write_immediate_no_validate(*src_val, dest)
660                 } else {
661                     // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
662                     // loaded using the offsets defined by `src.layout`. When we put this back into
663                     // the destination, we have to use the same offsets! So (a) we make sure we
664                     // write back to memory, and (b) we use `dest` *with the source layout*.
665                     let dest_mem = self.force_allocation(dest)?;
666                     self.write_immediate_to_mplace_no_validate(
667                         *src_val,
668                         src.layout,
669                         dest_mem.align,
670                         *dest_mem,
671                     )
672                 };
673             }
674             Left(mplace) => mplace,
675         };
676         // Slow path, this does not fit into an immediate. Just memcpy.
677         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
678
679         let dest = self.force_allocation(&dest)?;
680         let Some((dest_size, _)) = self.size_and_align_of_mplace(&dest)? else {
681             span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
682         };
683         if cfg!(debug_assertions) {
684             let src_size = self.size_and_align_of_mplace(&src)?.unwrap().0;
685             assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
686         } else {
687             // As a cheap approximation, we compare the fixed parts of the size.
688             assert_eq!(src.layout.size, dest.layout.size);
689         }
690
691         self.mem_copy(
692             src.ptr, src.align, dest.ptr, dest.align, dest_size, /*nonoverlapping*/ false,
693         )
694     }
695
696     /// Ensures that a place is in memory, and returns where it is.
697     /// If the place currently refers to a local that doesn't yet have a matching allocation,
698     /// create such an allocation.
699     /// This is essentially `force_to_memplace`.
700     #[instrument(skip(self), level = "debug")]
701     pub fn force_allocation(
702         &mut self,
703         place: &PlaceTy<'tcx, M::Provenance>,
704     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
705         let mplace = match place.place {
706             Place::Local { frame, local } => {
707                 match M::access_local_mut(self, frame, local)? {
708                     &mut Operand::Immediate(local_val) => {
709                         // We need to make an allocation.
710
711                         // We need the layout of the local.  We can NOT use the layout we got,
712                         // that might e.g., be an inner field of a struct with `Scalar` layout,
713                         // that has different alignment than the outer field.
714                         let local_layout =
715                             self.layout_of_local(&self.stack()[frame], local, None)?;
716                         if local_layout.is_unsized() {
717                             throw_unsup_format!("unsized locals are not supported");
718                         }
719                         let mplace = *self.allocate(local_layout, MemoryKind::Stack)?;
720                         if !matches!(local_val, Immediate::Uninit) {
721                             // Preserve old value. (As an optimization, we can skip this if it was uninit.)
722                             // We don't have to validate as we can assume the local
723                             // was already valid for its type.
724                             self.write_immediate_to_mplace_no_validate(
725                                 local_val,
726                                 local_layout,
727                                 local_layout.align.abi,
728                                 mplace,
729                             )?;
730                         }
731                         // Now we can call `access_mut` again, asserting it goes well,
732                         // and actually overwrite things.
733                         *M::access_local_mut(self, frame, local).unwrap() =
734                             Operand::Indirect(mplace);
735                         mplace
736                     }
737                     &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
738                 }
739             }
740             Place::Ptr(mplace) => mplace,
741         };
742         // Return with the original layout, so that the caller can go on
743         Ok(MPlaceTy { mplace, layout: place.layout, align: place.align })
744     }
745
746     pub fn allocate(
747         &mut self,
748         layout: TyAndLayout<'tcx>,
749         kind: MemoryKind<M::MemoryKind>,
750     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
751         assert!(layout.is_sized());
752         let ptr = self.allocate_ptr(layout.size, layout.align.abi, kind)?;
753         Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
754     }
755
756     /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
757     pub fn allocate_str(
758         &mut self,
759         str: &str,
760         kind: MemoryKind<M::MemoryKind>,
761         mutbl: Mutability,
762     ) -> MPlaceTy<'tcx, M::Provenance> {
763         let ptr = self.allocate_bytes_ptr(str.as_bytes(), Align::ONE, kind, mutbl);
764         let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
765         let mplace = MemPlace { ptr: ptr.into(), meta: MemPlaceMeta::Meta(meta) };
766
767         let ty = self.tcx.mk_ref(
768             self.tcx.lifetimes.re_static,
769             ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
770         );
771         let layout = self.layout_of(ty).unwrap();
772         MPlaceTy { mplace, layout, align: layout.align.abi }
773     }
774
775     /// Writes the discriminant of the given variant.
776     #[instrument(skip(self), level = "debug")]
777     pub fn write_discriminant(
778         &mut self,
779         variant_index: VariantIdx,
780         dest: &PlaceTy<'tcx, M::Provenance>,
781     ) -> InterpResult<'tcx> {
782         // This must be an enum or generator.
783         match dest.layout.ty.kind() {
784             ty::Adt(adt, _) => assert!(adt.is_enum()),
785             ty::Generator(..) => {}
786             _ => span_bug!(
787                 self.cur_span(),
788                 "write_discriminant called on non-variant-type (neither enum nor generator)"
789             ),
790         }
791         // Layout computation excludes uninhabited variants from consideration
792         // therefore there's no way to represent those variants in the given layout.
793         // Essentially, uninhabited variants do not have a tag that corresponds to their
794         // discriminant, so we cannot do anything here.
795         // When evaluating we will always error before even getting here, but ConstProp 'executes'
796         // dead code, so we cannot ICE here.
797         if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
798             throw_ub!(UninhabitedEnumVariantWritten)
799         }
800
801         match dest.layout.variants {
802             abi::Variants::Single { index } => {
803                 assert_eq!(index, variant_index);
804             }
805             abi::Variants::Multiple {
806                 tag_encoding: TagEncoding::Direct,
807                 tag: tag_layout,
808                 tag_field,
809                 ..
810             } => {
811                 // No need to validate that the discriminant here because the
812                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
813
814                 let discr_val =
815                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
816
817                 // raw discriminants for enums are isize or bigger during
818                 // their computation, but the in-memory tag is the smallest possible
819                 // representation
820                 let size = tag_layout.size(self);
821                 let tag_val = size.truncate(discr_val);
822
823                 let tag_dest = self.place_field(dest, tag_field)?;
824                 self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?;
825             }
826             abi::Variants::Multiple {
827                 tag_encoding:
828                     TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start },
829                 tag: tag_layout,
830                 tag_field,
831                 ..
832             } => {
833                 // No need to validate that the discriminant here because the
834                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
835
836                 if variant_index != untagged_variant {
837                     let variants_start = niche_variants.start().as_u32();
838                     let variant_index_relative = variant_index
839                         .as_u32()
840                         .checked_sub(variants_start)
841                         .expect("overflow computing relative variant idx");
842                     // We need to use machine arithmetic when taking into account `niche_start`:
843                     // tag_val = variant_index_relative + niche_start_val
844                     let tag_layout = self.layout_of(tag_layout.primitive().to_int_ty(*self.tcx))?;
845                     let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
846                     let variant_index_relative_val =
847                         ImmTy::from_uint(variant_index_relative, tag_layout);
848                     let tag_val = self.binary_op(
849                         mir::BinOp::Add,
850                         &variant_index_relative_val,
851                         &niche_start_val,
852                     )?;
853                     // Write result.
854                     let niche_dest = self.place_field(dest, tag_field)?;
855                     self.write_immediate(*tag_val, &niche_dest)?;
856                 }
857             }
858         }
859
860         Ok(())
861     }
862
863     pub fn raw_const_to_mplace(
864         &self,
865         raw: ConstAlloc<'tcx>,
866     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
867         // This must be an allocation in `tcx`
868         let _ = self.tcx.global_alloc(raw.alloc_id);
869         let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
870         let layout = self.layout_of(raw.ty)?;
871         Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
872     }
873
874     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
875     pub(super) fn unpack_dyn_trait(
876         &self,
877         mplace: &MPlaceTy<'tcx, M::Provenance>,
878     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
879         let vtable = mplace.vtable().to_pointer(self)?; // also sanity checks the type
880         let (ty, _) = self.get_ptr_vtable(vtable)?;
881         let layout = self.layout_of(ty)?;
882
883         let mplace = MPlaceTy {
884             mplace: MemPlace { meta: MemPlaceMeta::None, ..**mplace },
885             layout,
886             align: layout.align.abi,
887         };
888         Ok(mplace)
889     }
890 }
891
892 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
893 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
894 mod size_asserts {
895     use super::*;
896     use rustc_data_structures::static_assert_size;
897     // tidy-alphabetical-start
898     static_assert_size!(MemPlace, 40);
899     static_assert_size!(MemPlaceMeta, 24);
900     static_assert_size!(MPlaceTy<'_>, 64);
901     static_assert_size!(Place, 40);
902     static_assert_size!(PlaceTy<'_>, 64);
903     // tidy-alphabetical-end
904 }