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