1 //! Computations on places -- field projections, going from mir::Place, and writing
3 //! All high-level functions to write to memory work on places as destinations.
7 use rustc_ast::Mutability;
10 use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
11 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, TagEncoding, VariantIdx};
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,
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).
24 /// `Sized` types or unsized `extern type`
28 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
29 rustc_data_structures::static_assert_size!(MemPlaceMeta, 24);
31 impl<Prov: Provenance> MemPlaceMeta<Prov> {
32 pub fn unwrap_meta(self) -> Scalar<Prov> {
36 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
41 pub fn has_meta(self) -> bool {
43 Self::Meta(_) => true,
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>,
59 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
60 rustc_data_structures::static_assert_size!(MemPlace, 40);
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`!
74 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
75 rustc_data_structures::static_assert_size!(MPlaceTy<'_>, 64);
77 #[derive(Copy, Clone, Debug)]
78 pub enum Place<Prov: Provenance = AllocId> {
79 /// A place referring to a value allocated in the `Memory` system.
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 },
87 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
88 rustc_data_structures::static_assert_size!(Place, 48);
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`!
101 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
102 rustc_data_structures::static_assert_size!(PlaceTy<'_>, 72);
104 impl<'tcx, Prov: Provenance> std::ops::Deref for PlaceTy<'tcx, Prov> {
105 type Target = Place<Prov>;
107 fn deref(&self) -> &Place<Prov> {
112 impl<'tcx, Prov: Provenance> std::ops::Deref for MPlaceTy<'tcx, Prov> {
113 type Target = MemPlace<Prov>;
115 fn deref(&self) -> &MemPlace<Prov> {
120 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
122 fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
123 PlaceTy { place: Place::Ptr(*mplace), layout: mplace.layout, align: mplace.align }
127 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
129 fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
130 PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
134 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
136 fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
137 PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
141 impl<Prov: Provenance> MemPlace<Prov> {
143 pub fn from_ptr(ptr: Pointer<Option<Prov>>) -> Self {
144 MemPlace { ptr, meta: MemPlaceMeta::None }
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 }
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`.
155 pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
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())
165 pub fn offset_with_meta<'tcx>(
168 meta: MemPlaceMeta<Prov>,
169 cx: &impl HasDataLayout,
170 ) -> InterpResult<'tcx, Self> {
171 Ok(MemPlace { ptr: self.ptr.offset(offset, cx)?, meta })
175 impl<Prov: Provenance> Place<Prov> {
176 /// Asserts that this points to some local variable.
177 /// Returns the frame idx and the variable idx.
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) {
182 Place::Local { frame, local } => (*frame, *local),
183 _ => bug!("assert_local: expected Place::Local, got {:?}", self),
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.
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 }
201 pub fn offset_with_meta(
204 meta: MemPlaceMeta<Prov>,
205 layout: TyAndLayout<'tcx>,
206 cx: &impl HasDataLayout,
207 ) -> InterpResult<'tcx, Self> {
209 mplace: self.mplace.offset_with_meta(offset, meta, cx)?,
210 align: self.align.restrict_for_offset(offset),
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)
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 }
231 pub fn from_aligned_ptr_with_meta(
232 ptr: Pointer<Option<Prov>>,
233 layout: TyAndLayout<'tcx>,
234 meta: MemPlaceMeta<Prov>,
236 let mut mplace = MemPlace::from_ptr(ptr);
239 MPlaceTy { mplace, layout, align: layout.align.abi }
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),
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),
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),
269 // These are defined here because they produce a place.
270 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
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>> {
276 Operand::Indirect(mplace) => {
277 Ok(MPlaceTy { mplace, layout: self.layout, align: self.align.unwrap() })
279 Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
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()
292 impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
293 /// A place is either an mplace or some local.
295 pub fn try_as_mplace(&self) -> Result<MPlaceTy<'tcx, Prov>, (usize, mir::Local)> {
297 Place::Ptr(mplace) => Ok(MPlaceTy { mplace, layout: self.layout, align: self.align }),
298 Place::Local { frame, local } => Err((frame, local)),
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()
309 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
310 impl<'mir, 'tcx: 'mir, Prov, M> InterpCx<'mir, 'tcx, M>
312 Prov: Provenance + Eq + Hash + 'static,
313 M: Machine<'mir, 'tcx, Provenance = Prov>,
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()`.
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(
323 val: &ImmTy<'tcx, M::Provenance>,
324 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
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)),
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 })
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(
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);
350 if val.layout.ty.is_box() {
351 bug!("dereferencing {:?}", val.layout.ty);
354 let mplace = self.ref_to_mplace(&val)?;
355 self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?;
360 pub(super) fn get_place_alloc(
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)
371 pub(super) fn get_place_alloc_mut(
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)
381 /// Check if this mplace is dereferenceable and sufficiently aligned.
382 fn check_mplace_access(
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)?;
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(
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
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))
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(
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)
422 pub fn local_to_place(
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 })
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")]
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)?
445 trace!("{:?}", self.dump_place(place.place));
446 // Sanity-check the type we ended up with.
448 mir_assign_valid_types(
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
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,
463 /// Write an immediate to a place
465 #[instrument(skip(self), level = "debug")]
466 pub fn write_immediate(
468 src: Immediate<M::Provenance>,
469 dest: &PlaceTy<'tcx, M::Provenance>,
470 ) -> InterpResult<'tcx> {
471 self.write_immediate_no_validate(src, dest)?;
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)?)?;
481 /// Write a scalar to a place
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)
491 /// Write a pointer to a place
493 pub fn write_pointer(
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)
501 /// Write an immediate to a place.
502 /// If you use this you are responsible for validating that things got copied at the
504 fn write_immediate_no_validate(
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);
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.
522 Operand::Indirect(mplace) => {
523 // The local is in memory, go on below.
528 Place::Ptr(mplace) => mplace, // already referring to memory
531 // This is already in memory, write there.
532 self.write_immediate_to_mplace_no_validate(src, dest.layout, dest.align, mplace)
535 /// Write an immediate to memory.
536 /// If you use this you are responsible for validating that things got copied at the
538 fn write_immediate_to_mplace_no_validate(
540 value: Immediate<M::Provenance>,
541 layout: TyAndLayout<'tcx>,
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
551 let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else {
557 Immediate::Scalar(scalar) => {
558 let Abi::Scalar(s) = layout.abi else { span_bug!(
560 "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
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)
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!(
573 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
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
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.
585 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
586 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
588 Immediate::Uninit => alloc.write_uninit(),
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;
601 Operand::Indirect(mplace) => {
602 // The local is in memory, go on below.
603 MPlaceTy { mplace: *mplace, layout: dest.layout, align: dest.align }
608 let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
612 alloc.write_uninit()?;
616 /// Copies the data from an operand to a place.
617 /// `allow_transmute` indicates whether the layouts may disagree.
619 #[instrument(skip(self), level = "debug")]
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)?;
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)?)?;
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
640 #[instrument(skip(self), level = "debug")]
641 fn copy_op_no_validate(
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.
650 mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout);
651 if !allow_transmute && !layout_compat {
654 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
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)? {
664 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
666 !dest.layout.is_unsized(),
667 "the src is sized, so the dest must also be sized"
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)
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(
687 Err(mplace) => mplace,
689 // Slow path, this does not fit into an immediate. Just memcpy.
690 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
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")
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");
700 // As a cheap approximation, we compare the fixed parts of the size.
701 assert_eq!(src.layout.size, dest.layout.size);
705 src.ptr, src.align, dest.ptr, dest.align, dest_size, /*nonoverlapping*/ false,
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(
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.
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.
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");
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(
740 local_layout.align.abi,
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);
750 &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
753 Place::Ptr(mplace) => mplace,
755 // Return with the original layout, so that the caller can go on
756 Ok(MPlaceTy { mplace, layout: place.layout, align: place.align })
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))
769 /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
773 kind: MemoryKind<M::MemoryKind>,
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) };
780 let ty = self.tcx.mk_ref(
781 self.tcx.lifetimes.re_static,
782 ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
784 let layout = self.layout_of(ty).unwrap();
785 MPlaceTy { mplace, layout, align: layout.align.abi }
788 /// Writes the discriminant of the given variant.
789 #[instrument(skip(self), level = "debug")]
790 pub fn write_discriminant(
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(..) => {}
801 "write_discriminant called on non-variant-type (neither enum nor generator)"
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)
814 match dest.layout.variants {
815 abi::Variants::Single { index } => {
816 assert_eq!(index, variant_index);
818 abi::Variants::Multiple {
819 tag_encoding: TagEncoding::Direct,
824 // No need to validate that the discriminant here because the
825 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
828 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
830 // raw discriminants for enums are isize or bigger during
831 // their computation, but the in-memory tag is the smallest possible
833 let size = tag_layout.size(self);
834 let tag_val = size.truncate(discr_val);
836 let tag_dest = self.place_field(dest, tag_field)?;
837 self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?;
839 abi::Variants::Multiple {
841 TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start },
846 // No need to validate that the discriminant here because the
847 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
849 if variant_index != dataful_variant {
850 let variants_start = niche_variants.start().as_u32();
851 let variant_index_relative = variant_index
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(
863 &variant_index_relative_val,
867 let niche_dest = self.place_field(dest, tag_field)?;
868 self.write_immediate(*tag_val, &niche_dest)?;
876 pub fn raw_const_to_mplace(
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))
887 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
888 pub(super) fn unpack_dyn_trait(
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)?;
896 let mplace = MPlaceTy {
897 mplace: MemPlace { meta: MemPlaceMeta::None, ..**mplace },
899 align: layout.align.abi,