]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/place.rs
Create stable metric to measure long computation in Const Eval
[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), meta)
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     pub fn increment_const_eval_counter(&mut self) {
297         self.const_eval_counter = self.const_eval_counter + 1;
298         if self.const_eval_counter == self.const_eval_limit {
299             let mut warn = self.tcx.sess.struct_warn(format!(
300                 "Const eval counter limit ({}) has been crossed",
301                 self.const_eval_limit
302             ));
303             warn.emit();
304         }
305     }
306
307     /// Take a value, which represents a (thin or wide) reference, and make it a place.
308     /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
309     ///
310     /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
311     /// want to ever use the place for memory access!
312     /// Generally prefer `deref_operand`.
313     pub fn ref_to_mplace(
314         &self,
315         val: &ImmTy<'tcx, M::Provenance>,
316     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
317         let pointee_type =
318             val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
319         let layout = self.layout_of(pointee_type)?;
320         let (ptr, meta) = match **val {
321             Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None),
322             Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta)),
323             Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
324         };
325
326         let mplace = MemPlace { ptr: ptr.to_pointer(self)?, meta };
327         // When deref'ing a pointer, the *static* alignment given by the type is what matters.
328         let align = layout.align.abi;
329         Ok(MPlaceTy { mplace, layout, align })
330     }
331
332     /// Take an operand, representing a pointer, and dereference it to a place.
333     #[instrument(skip(self), level = "debug")]
334     pub fn deref_operand(
335         &self,
336         src: &OpTy<'tcx, M::Provenance>,
337     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
338         let val = self.read_immediate(src)?;
339         trace!("deref to {} on {:?}", val.layout.ty, *val);
340
341         if val.layout.ty.is_box() {
342             bug!("dereferencing {:?}", val.layout.ty);
343         }
344
345         let mplace = self.ref_to_mplace(&val)?;
346         self.check_mplace(mplace)?;
347         Ok(mplace)
348     }
349
350     #[inline]
351     pub(super) fn get_place_alloc(
352         &self,
353         place: &MPlaceTy<'tcx, M::Provenance>,
354     ) -> InterpResult<'tcx, Option<AllocRef<'_, '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(place.ptr, size, place.align)
359     }
360
361     #[inline]
362     pub(super) fn get_place_alloc_mut(
363         &mut self,
364         place: &MPlaceTy<'tcx, M::Provenance>,
365     ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra>>> {
366         assert!(place.layout.is_sized());
367         assert!(!place.meta.has_meta());
368         let size = place.layout.size;
369         self.get_ptr_alloc_mut(place.ptr, size, place.align)
370     }
371
372     /// Check if this mplace is dereferenceable and sufficiently aligned.
373     pub fn check_mplace(&self, mplace: MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
374         let (size, align) = self
375             .size_and_align_of_mplace(&mplace)?
376             .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
377         assert!(mplace.align <= align, "dynamic alignment less strict than static one?");
378         let align = if M::enforce_alignment(self).should_check() { align } else { Align::ONE };
379         self.check_ptr_access_align(mplace.ptr, size, align, CheckInAllocMsg::DerefTest)?;
380         Ok(())
381     }
382
383     /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
384     /// Also returns the number of elements.
385     pub fn mplace_to_simd(
386         &self,
387         mplace: &MPlaceTy<'tcx, M::Provenance>,
388     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
389         // Basically we just transmute this place into an array following simd_size_and_type.
390         // (Transmuting is okay since this is an in-memory place. We also double-check the size
391         // stays the same.)
392         let (len, e_ty) = mplace.layout.ty.simd_size_and_type(*self.tcx);
393         let array = self.tcx.mk_array(e_ty, len);
394         let layout = self.layout_of(array)?;
395         assert_eq!(layout.size, mplace.layout.size);
396         Ok((MPlaceTy { layout, ..*mplace }, len))
397     }
398
399     /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
400     /// Also returns the number of elements.
401     pub fn place_to_simd(
402         &mut self,
403         place: &PlaceTy<'tcx, M::Provenance>,
404     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
405         let mplace = self.force_allocation(place)?;
406         self.mplace_to_simd(&mplace)
407     }
408
409     pub fn local_to_place(
410         &self,
411         frame: usize,
412         local: mir::Local,
413     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
414         let layout = self.layout_of_local(&self.stack()[frame], local, None)?;
415         let place = Place::Local { frame, local };
416         Ok(PlaceTy { place, layout, align: layout.align.abi })
417     }
418
419     /// Computes a place. You should only use this if you intend to write into this
420     /// place; for reading, a more efficient alternative is `eval_place_to_op`.
421     #[instrument(skip(self), level = "debug")]
422     pub fn eval_place(
423         &mut self,
424         mir_place: mir::Place<'tcx>,
425     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
426         let mut place = self.local_to_place(self.frame_idx(), mir_place.local)?;
427         // Using `try_fold` turned out to be bad for performance, hence the loop.
428         for elem in mir_place.projection.iter() {
429             place = self.place_projection(&place, elem)?
430         }
431
432         trace!("{:?}", self.dump_place(place.place));
433         // Sanity-check the type we ended up with.
434         debug_assert!(
435             mir_assign_valid_types(
436                 *self.tcx,
437                 self.param_env,
438                 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
439                     mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
440                 )?)?,
441                 place.layout,
442             ),
443             "eval_place of a MIR place with type {:?} produced an interpreter place with type {:?}",
444             mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
445             place.layout.ty,
446         );
447         Ok(place)
448     }
449
450     /// Write an immediate to a place
451     #[inline(always)]
452     #[instrument(skip(self), level = "debug")]
453     pub fn write_immediate(
454         &mut self,
455         src: Immediate<M::Provenance>,
456         dest: &PlaceTy<'tcx, M::Provenance>,
457     ) -> InterpResult<'tcx> {
458         self.write_immediate_no_validate(src, dest)?;
459
460         if M::enforce_validity(self) {
461             // Data got changed, better make sure it matches the type!
462             self.validate_operand(&self.place_to_op(dest)?)?;
463         }
464
465         Ok(())
466     }
467
468     /// Write a scalar to a place
469     #[inline(always)]
470     pub fn write_scalar(
471         &mut self,
472         val: impl Into<Scalar<M::Provenance>>,
473         dest: &PlaceTy<'tcx, M::Provenance>,
474     ) -> InterpResult<'tcx> {
475         self.write_immediate(Immediate::Scalar(val.into()), dest)
476     }
477
478     /// Write a pointer to a place
479     #[inline(always)]
480     pub fn write_pointer(
481         &mut self,
482         ptr: impl Into<Pointer<Option<M::Provenance>>>,
483         dest: &PlaceTy<'tcx, M::Provenance>,
484     ) -> InterpResult<'tcx> {
485         self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
486     }
487
488     /// Write an immediate to a place.
489     /// If you use this you are responsible for validating that things got copied at the
490     /// right type.
491     fn write_immediate_no_validate(
492         &mut self,
493         src: Immediate<M::Provenance>,
494         dest: &PlaceTy<'tcx, M::Provenance>,
495     ) -> InterpResult<'tcx> {
496         assert!(dest.layout.is_sized(), "Cannot write unsized data");
497         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
498
499         // See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
500         // but not factored as a separate function.
501         let mplace = match dest.place {
502             Place::Local { frame, local } => {
503                 match M::access_local_mut(self, frame, local)? {
504                     Operand::Immediate(local) => {
505                         // Local can be updated in-place.
506                         *local = src;
507                         return Ok(());
508                     }
509                     Operand::Indirect(mplace) => {
510                         // The local is in memory, go on below.
511                         *mplace
512                     }
513                 }
514             }
515             Place::Ptr(mplace) => mplace, // already referring to memory
516         };
517
518         // This is already in memory, write there.
519         self.write_immediate_to_mplace_no_validate(src, dest.layout, dest.align, mplace)
520     }
521
522     /// Write an immediate to memory.
523     /// If you use this you are responsible for validating that things got copied at the
524     /// right layout.
525     fn write_immediate_to_mplace_no_validate(
526         &mut self,
527         value: Immediate<M::Provenance>,
528         layout: TyAndLayout<'tcx>,
529         align: Align,
530         dest: MemPlace<M::Provenance>,
531     ) -> InterpResult<'tcx> {
532         // Note that it is really important that the type here is the right one, and matches the
533         // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
534         // to handle padding properly, which is only correct if we never look at this data with the
535         // wrong type.
536
537         let tcx = *self.tcx;
538         let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else {
539             // zero-sized access
540             return Ok(());
541         };
542
543         match value {
544             Immediate::Scalar(scalar) => {
545                 let Abi::Scalar(s) = layout.abi else { span_bug!(
546                         self.cur_span(),
547                         "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
548                     )
549                 };
550                 let size = s.size(&tcx);
551                 assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
552                 alloc.write_scalar(alloc_range(Size::ZERO, size), scalar)
553             }
554             Immediate::ScalarPair(a_val, b_val) => {
555                 // We checked `ptr_align` above, so all fields will have the alignment they need.
556                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
557                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
558                 let Abi::ScalarPair(a, b) = layout.abi else { span_bug!(
559                         self.cur_span(),
560                         "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
561                         layout
562                     )
563                 };
564                 let (a_size, b_size) = (a.size(&tcx), b.size(&tcx));
565                 let b_offset = a_size.align_to(b.align(&tcx).abi);
566                 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
567
568                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
569                 // but that does not work: We could be a newtype around a pair, then the
570                 // fields do not match the `ScalarPair` components.
571
572                 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
573                 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
574             }
575             Immediate::Uninit => alloc.write_uninit(),
576         }
577     }
578
579     pub fn write_uninit(&mut self, dest: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
580         let mplace = match dest.as_mplace_or_local() {
581             Left(mplace) => mplace,
582             Right((frame, local)) => {
583                 match M::access_local_mut(self, frame, local)? {
584                     Operand::Immediate(local) => {
585                         *local = Immediate::Uninit;
586                         return Ok(());
587                     }
588                     Operand::Indirect(mplace) => {
589                         // The local is in memory, go on below.
590                         MPlaceTy { mplace: *mplace, layout: dest.layout, align: dest.align }
591                     }
592                 }
593             }
594         };
595         let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
596             // Zero-sized access
597             return Ok(());
598         };
599         alloc.write_uninit()?;
600         Ok(())
601     }
602
603     /// Copies the data from an operand to a place.
604     /// `allow_transmute` indicates whether the layouts may disagree.
605     #[inline(always)]
606     #[instrument(skip(self), level = "debug")]
607     pub fn copy_op(
608         &mut self,
609         src: &OpTy<'tcx, M::Provenance>,
610         dest: &PlaceTy<'tcx, M::Provenance>,
611         allow_transmute: bool,
612     ) -> InterpResult<'tcx> {
613         self.copy_op_no_validate(src, dest, allow_transmute)?;
614
615         if M::enforce_validity(self) {
616             // Data got changed, better make sure it matches the type!
617             self.validate_operand(&self.place_to_op(dest)?)?;
618         }
619
620         Ok(())
621     }
622
623     /// Copies the data from an operand to a place.
624     /// `allow_transmute` indicates whether the layouts may disagree.
625     /// Also, if you use this you are responsible for validating that things get copied at the
626     /// right type.
627     #[instrument(skip(self), level = "debug")]
628     fn copy_op_no_validate(
629         &mut self,
630         src: &OpTy<'tcx, M::Provenance>,
631         dest: &PlaceTy<'tcx, M::Provenance>,
632         allow_transmute: bool,
633     ) -> InterpResult<'tcx> {
634         // We do NOT compare the types for equality, because well-typed code can
635         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
636         let layout_compat =
637             mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout);
638         if !allow_transmute && !layout_compat {
639             span_bug!(
640                 self.cur_span(),
641                 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
642                 src.layout.ty,
643                 dest.layout.ty,
644             );
645         }
646
647         // Let us see if the layout is simple so we take a shortcut,
648         // avoid force_allocation.
649         let src = match self.read_immediate_raw(src)? {
650             Right(src_val) => {
651                 // FIXME(const_prop): Const-prop can possibly evaluate an
652                 // unsized copy operation when it thinks that the type is
653                 // actually sized, due to a trivially false where-clause
654                 // predicate like `where Self: Sized` with `Self = dyn Trait`.
655                 // See #102553 for an example of such a predicate.
656                 if src.layout.is_unsized() {
657                     throw_inval!(SizeOfUnsizedType(src.layout.ty));
658                 }
659                 if dest.layout.is_unsized() {
660                     throw_inval!(SizeOfUnsizedType(dest.layout.ty));
661                 }
662                 assert_eq!(src.layout.size, dest.layout.size);
663                 // Yay, we got a value that we can write directly.
664                 return if layout_compat {
665                     self.write_immediate_no_validate(*src_val, dest)
666                 } else {
667                     // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
668                     // loaded using the offsets defined by `src.layout`. When we put this back into
669                     // the destination, we have to use the same offsets! So (a) we make sure we
670                     // write back to memory, and (b) we use `dest` *with the source layout*.
671                     let dest_mem = self.force_allocation(dest)?;
672                     self.write_immediate_to_mplace_no_validate(
673                         *src_val,
674                         src.layout,
675                         dest_mem.align,
676                         *dest_mem,
677                     )
678                 };
679             }
680             Left(mplace) => mplace,
681         };
682         // Slow path, this does not fit into an immediate. Just memcpy.
683         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
684
685         let dest = self.force_allocation(&dest)?;
686         let Some((dest_size, _)) = self.size_and_align_of_mplace(&dest)? else {
687             span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
688         };
689         if cfg!(debug_assertions) {
690             let src_size = self.size_and_align_of_mplace(&src)?.unwrap().0;
691             assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
692         } else {
693             // As a cheap approximation, we compare the fixed parts of the size.
694             assert_eq!(src.layout.size, dest.layout.size);
695         }
696
697         self.mem_copy(
698             src.ptr, src.align, dest.ptr, dest.align, dest_size, /*nonoverlapping*/ false,
699         )
700     }
701
702     /// Ensures that a place is in memory, and returns where it is.
703     /// If the place currently refers to a local that doesn't yet have a matching allocation,
704     /// create such an allocation.
705     /// This is essentially `force_to_memplace`.
706     #[instrument(skip(self), level = "debug")]
707     pub fn force_allocation(
708         &mut self,
709         place: &PlaceTy<'tcx, M::Provenance>,
710     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
711         let mplace = match place.place {
712             Place::Local { frame, local } => {
713                 match M::access_local_mut(self, frame, local)? {
714                     &mut Operand::Immediate(local_val) => {
715                         // We need to make an allocation.
716
717                         // We need the layout of the local. We can NOT use the layout we got,
718                         // that might e.g., be an inner field of a struct with `Scalar` layout,
719                         // that has different alignment than the outer field.
720                         let local_layout =
721                             self.layout_of_local(&self.stack()[frame], local, None)?;
722                         if local_layout.is_unsized() {
723                             throw_unsup_format!("unsized locals are not supported");
724                         }
725                         let mplace = *self.allocate(local_layout, MemoryKind::Stack)?;
726                         if !matches!(local_val, Immediate::Uninit) {
727                             // Preserve old value. (As an optimization, we can skip this if it was uninit.)
728                             // We don't have to validate as we can assume the local
729                             // was already valid for its type.
730                             self.write_immediate_to_mplace_no_validate(
731                                 local_val,
732                                 local_layout,
733                                 local_layout.align.abi,
734                                 mplace,
735                             )?;
736                         }
737                         // Now we can call `access_mut` again, asserting it goes well,
738                         // and actually overwrite things.
739                         *M::access_local_mut(self, frame, local).unwrap() =
740                             Operand::Indirect(mplace);
741                         mplace
742                     }
743                     &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
744                 }
745             }
746             Place::Ptr(mplace) => mplace,
747         };
748         // Return with the original layout, so that the caller can go on
749         Ok(MPlaceTy { mplace, layout: place.layout, align: place.align })
750     }
751
752     pub fn allocate(
753         &mut self,
754         layout: TyAndLayout<'tcx>,
755         kind: MemoryKind<M::MemoryKind>,
756     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
757         assert!(layout.is_sized());
758         let ptr = self.allocate_ptr(layout.size, layout.align.abi, kind)?;
759         Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
760     }
761
762     /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
763     pub fn allocate_str(
764         &mut self,
765         str: &str,
766         kind: MemoryKind<M::MemoryKind>,
767         mutbl: Mutability,
768     ) -> MPlaceTy<'tcx, M::Provenance> {
769         let ptr = self.allocate_bytes_ptr(str.as_bytes(), Align::ONE, kind, mutbl);
770         let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
771         let mplace = MemPlace { ptr: ptr.into(), meta: MemPlaceMeta::Meta(meta) };
772
773         let ty = self.tcx.mk_ref(
774             self.tcx.lifetimes.re_static,
775             ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
776         );
777         let layout = self.layout_of(ty).unwrap();
778         MPlaceTy { mplace, layout, align: layout.align.abi }
779     }
780
781     /// Writes the discriminant of the given variant.
782     #[instrument(skip(self), level = "debug")]
783     pub fn write_discriminant(
784         &mut self,
785         variant_index: VariantIdx,
786         dest: &PlaceTy<'tcx, M::Provenance>,
787     ) -> InterpResult<'tcx> {
788         // This must be an enum or generator.
789         match dest.layout.ty.kind() {
790             ty::Adt(adt, _) => assert!(adt.is_enum()),
791             ty::Generator(..) => {}
792             _ => span_bug!(
793                 self.cur_span(),
794                 "write_discriminant called on non-variant-type (neither enum nor generator)"
795             ),
796         }
797         // Layout computation excludes uninhabited variants from consideration
798         // therefore there's no way to represent those variants in the given layout.
799         // Essentially, uninhabited variants do not have a tag that corresponds to their
800         // discriminant, so we cannot do anything here.
801         // When evaluating we will always error before even getting here, but ConstProp 'executes'
802         // dead code, so we cannot ICE here.
803         if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
804             throw_ub!(UninhabitedEnumVariantWritten)
805         }
806
807         match dest.layout.variants {
808             abi::Variants::Single { index } => {
809                 assert_eq!(index, variant_index);
810             }
811             abi::Variants::Multiple {
812                 tag_encoding: TagEncoding::Direct,
813                 tag: tag_layout,
814                 tag_field,
815                 ..
816             } => {
817                 // No need to validate that the discriminant here because the
818                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
819
820                 let discr_val =
821                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
822
823                 // raw discriminants for enums are isize or bigger during
824                 // their computation, but the in-memory tag is the smallest possible
825                 // representation
826                 let size = tag_layout.size(self);
827                 let tag_val = size.truncate(discr_val);
828
829                 let tag_dest = self.place_field(dest, tag_field)?;
830                 self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?;
831             }
832             abi::Variants::Multiple {
833                 tag_encoding:
834                     TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start },
835                 tag: tag_layout,
836                 tag_field,
837                 ..
838             } => {
839                 // No need to validate that the discriminant here because the
840                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
841
842                 if variant_index != untagged_variant {
843                     let variants_start = niche_variants.start().as_u32();
844                     let variant_index_relative = variant_index
845                         .as_u32()
846                         .checked_sub(variants_start)
847                         .expect("overflow computing relative variant idx");
848                     // We need to use machine arithmetic when taking into account `niche_start`:
849                     // tag_val = variant_index_relative + niche_start_val
850                     let tag_layout = self.layout_of(tag_layout.primitive().to_int_ty(*self.tcx))?;
851                     let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
852                     let variant_index_relative_val =
853                         ImmTy::from_uint(variant_index_relative, tag_layout);
854                     let tag_val = self.binary_op(
855                         mir::BinOp::Add,
856                         &variant_index_relative_val,
857                         &niche_start_val,
858                     )?;
859                     // Write result.
860                     let niche_dest = self.place_field(dest, tag_field)?;
861                     self.write_immediate(*tag_val, &niche_dest)?;
862                 }
863             }
864         }
865
866         Ok(())
867     }
868
869     pub fn raw_const_to_mplace(
870         &self,
871         raw: ConstAlloc<'tcx>,
872     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
873         // This must be an allocation in `tcx`
874         let _ = self.tcx.global_alloc(raw.alloc_id);
875         let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
876         let layout = self.layout_of(raw.ty)?;
877         Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
878     }
879
880     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
881     pub(super) fn unpack_dyn_trait(
882         &self,
883         mplace: &MPlaceTy<'tcx, M::Provenance>,
884     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
885         let vtable = mplace.vtable().to_pointer(self)?; // also sanity checks the type
886         let (ty, _) = self.get_ptr_vtable(vtable)?;
887         let layout = self.layout_of(ty)?;
888
889         let mplace = MPlaceTy {
890             mplace: MemPlace { meta: MemPlaceMeta::None, ..**mplace },
891             layout,
892             align: layout.align.abi,
893         };
894         Ok(mplace)
895     }
896 }
897
898 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
899 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
900 mod size_asserts {
901     use super::*;
902     use rustc_data_structures::static_assert_size;
903     // tidy-alphabetical-start
904     static_assert_size!(MemPlace, 40);
905     static_assert_size!(MemPlaceMeta, 24);
906     static_assert_size!(MPlaceTy<'_>, 64);
907     static_assert_size!(Place, 40);
908     static_assert_size!(PlaceTy<'_>, 64);
909     // tidy-alphabetical-end
910 }