]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/place.rs
nix rustc_target::abi::* reexport in ty::layout
[rust.git] / src / librustc_mir / 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::convert::TryFrom;
6 use std::hash::Hash;
7
8 use rustc_macros::HashStable;
9 use rustc_middle::mir;
10 use rustc_middle::mir::interpret::truncate;
11 use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
12 use rustc_middle::ty::{self, Ty};
13 use rustc_target::abi::{Abi, Align, DiscriminantKind, FieldsShape};
14 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, VariantIdx, Variants};
15
16 use super::{
17     AllocId, AllocMap, Allocation, AllocationExtra, ImmTy, Immediate, InterpCx, InterpResult,
18     LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer, PointerArithmetic, RawConst, Scalar,
19     ScalarMaybeUndef,
20 };
21
22 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
23 /// Information required for the sound usage of a `MemPlace`.
24 pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
25     /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
26     Meta(Scalar<Tag, Id>),
27     /// `Sized` types or unsized `extern type`
28     None,
29     /// The address of this place may not be taken. This protects the `MemPlace` from coming from
30     /// a ZST Operand with a backing allocation and being converted to an integer address. This
31     /// should be impossible, because you can't take the address of an operand, but this is a second
32     /// protection layer ensuring that we don't mess up.
33     Poison,
34 }
35
36 impl<Tag, Id> MemPlaceMeta<Tag, Id> {
37     pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
38         match self {
39             Self::Meta(s) => s,
40             Self::None | Self::Poison => {
41                 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
42             }
43         }
44     }
45     fn has_meta(self) -> bool {
46         match self {
47             Self::Meta(_) => true,
48             Self::None | Self::Poison => false,
49         }
50     }
51 }
52
53 impl<Tag> MemPlaceMeta<Tag> {
54     pub fn erase_tag(self) -> MemPlaceMeta<()> {
55         match self {
56             Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
57             Self::None => MemPlaceMeta::None,
58             Self::Poison => MemPlaceMeta::Poison,
59         }
60     }
61 }
62
63 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
64 pub struct MemPlace<Tag = (), Id = AllocId> {
65     /// A place may have an integral pointer for ZSTs, and since it might
66     /// be turned back into a reference before ever being dereferenced.
67     /// However, it may never be undef.
68     pub ptr: Scalar<Tag, Id>,
69     pub align: Align,
70     /// Metadata for unsized places. Interpretation is up to the type.
71     /// Must not be present for sized types, but can be missing for unsized types
72     /// (e.g., `extern type`).
73     pub meta: MemPlaceMeta<Tag, Id>,
74 }
75
76 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
77 pub enum Place<Tag = (), Id = AllocId> {
78     /// A place referring to a value allocated in the `Memory` system.
79     Ptr(MemPlace<Tag, Id>),
80
81     /// To support alloc-free locals, we are able to write directly to a local.
82     /// (Without that optimization, we'd just always be a `MemPlace`.)
83     Local { frame: usize, local: mir::Local },
84 }
85
86 #[derive(Copy, Clone, Debug)]
87 pub struct PlaceTy<'tcx, Tag = ()> {
88     place: Place<Tag>, // Keep this private; it helps enforce invariants.
89     pub layout: TyAndLayout<'tcx>,
90 }
91
92 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
93     type Target = Place<Tag>;
94     #[inline(always)]
95     fn deref(&self) -> &Place<Tag> {
96         &self.place
97     }
98 }
99
100 /// A MemPlace with its layout. Constructing it is only possible in this module.
101 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
102 pub struct MPlaceTy<'tcx, Tag = ()> {
103     mplace: MemPlace<Tag>,
104     pub layout: TyAndLayout<'tcx>,
105 }
106
107 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
108     type Target = MemPlace<Tag>;
109     #[inline(always)]
110     fn deref(&self) -> &MemPlace<Tag> {
111         &self.mplace
112     }
113 }
114
115 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
116     #[inline(always)]
117     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
118         PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
119     }
120 }
121
122 impl<Tag> MemPlace<Tag> {
123     /// Replace ptr tag, maintain vtable tag (if any)
124     #[inline]
125     pub fn replace_tag(self, new_tag: Tag) -> Self {
126         MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
127     }
128
129     #[inline]
130     pub fn erase_tag(self) -> MemPlace {
131         MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
132     }
133
134     #[inline(always)]
135     fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
136         MemPlace { ptr, align, meta: MemPlaceMeta::None }
137     }
138
139     /// Produces a Place that will error if attempted to be read from or written to
140     #[inline(always)]
141     fn null(cx: &impl HasDataLayout) -> Self {
142         Self::from_scalar_ptr(Scalar::null_ptr(cx), Align::from_bytes(1).unwrap())
143     }
144
145     #[inline(always)]
146     pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
147         Self::from_scalar_ptr(ptr.into(), align)
148     }
149
150     /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
151     /// This is the inverse of `ref_to_mplace`.
152     #[inline(always)]
153     pub fn to_ref(self) -> Immediate<Tag> {
154         match self.meta {
155             MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
156             MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
157             MemPlaceMeta::Poison => bug!(
158                 "MPlaceTy::dangling may never be used to produce a \
159                 place that will have the address of its pointee taken"
160             ),
161         }
162     }
163
164     pub fn offset(
165         self,
166         offset: Size,
167         meta: MemPlaceMeta<Tag>,
168         cx: &impl HasDataLayout,
169     ) -> InterpResult<'tcx, Self> {
170         Ok(MemPlace {
171             ptr: self.ptr.ptr_offset(offset, cx)?,
172             align: self.align.restrict_for_offset(offset),
173             meta,
174         })
175     }
176 }
177
178 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
179     /// Produces a MemPlace that works for ZST but nothing else
180     #[inline]
181     pub fn dangling(layout: TyAndLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
182         let align = layout.align.abi;
183         let ptr = Scalar::from_machine_usize(align.bytes(), cx);
184         // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
185         MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
186     }
187
188     /// Replace ptr tag, maintain vtable tag (if any)
189     #[inline]
190     pub fn replace_tag(self, new_tag: Tag) -> Self {
191         MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
192     }
193
194     #[inline]
195     pub fn offset(
196         self,
197         offset: Size,
198         meta: MemPlaceMeta<Tag>,
199         layout: TyAndLayout<'tcx>,
200         cx: &impl HasDataLayout,
201     ) -> InterpResult<'tcx, Self> {
202         Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
203     }
204
205     #[inline]
206     fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
207         MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
208     }
209
210     #[inline]
211     pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
212         if self.layout.is_unsized() {
213             // We need to consult `meta` metadata
214             match self.layout.ty.kind {
215                 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
216                 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
217             }
218         } else {
219             // Go through the layout.  There are lots of types that support a length,
220             // e.g., SIMD types.
221             match self.layout.fields {
222                 FieldsShape::Array { count, .. } => Ok(count),
223                 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
224             }
225         }
226     }
227
228     #[inline]
229     pub(super) fn vtable(self) -> Scalar<Tag> {
230         match self.layout.ty.kind {
231             ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
232             _ => bug!("vtable not supported on type {:?}", self.layout.ty),
233         }
234     }
235 }
236
237 // These are defined here because they produce a place.
238 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
239     #[inline(always)]
240     /// Note: do not call `as_ref` on the resulting place. This function should only be used to
241     /// read from the resulting mplace, not to get its address back.
242     pub fn try_as_mplace(
243         self,
244         cx: &impl HasDataLayout,
245     ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
246         match *self {
247             Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
248             Operand::Immediate(_) if self.layout.is_zst() => {
249                 Ok(MPlaceTy::dangling(self.layout, cx))
250             }
251             Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
252         }
253     }
254
255     #[inline(always)]
256     /// Note: do not call `as_ref` on the resulting place. This function should only be used to
257     /// read from the resulting mplace, not to get its address back.
258     pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
259         self.try_as_mplace(cx).unwrap()
260     }
261 }
262
263 impl<Tag: ::std::fmt::Debug> Place<Tag> {
264     /// Produces a Place that will error if attempted to be read from or written to
265     #[inline(always)]
266     fn null(cx: &impl HasDataLayout) -> Self {
267         Place::Ptr(MemPlace::null(cx))
268     }
269
270     #[inline]
271     pub fn assert_mem_place(self) -> MemPlace<Tag> {
272         match self {
273             Place::Ptr(mplace) => mplace,
274             _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
275         }
276     }
277 }
278
279 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
280     #[inline]
281     pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
282         MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
283     }
284 }
285
286 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
287 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
288 where
289     // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
290     Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
291     M: Machine<'mir, 'tcx, PointerTag = Tag>,
292     // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
293     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKind>, Allocation<Tag, M::AllocExtra>)>,
294     M::AllocExtra: AllocationExtra<Tag>,
295 {
296     /// Take a value, which represents a (thin or wide) reference, and make it a place.
297     /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
298     ///
299     /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
300     /// want to ever use the place for memory access!
301     /// Generally prefer `deref_operand`.
302     pub fn ref_to_mplace(
303         &self,
304         val: ImmTy<'tcx, M::PointerTag>,
305     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
306         let pointee_type =
307             val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
308         let layout = self.layout_of(pointee_type)?;
309         let (ptr, meta) = match *val {
310             Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
311             Immediate::ScalarPair(ptr, meta) => {
312                 (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
313             }
314         };
315
316         let mplace = MemPlace {
317             ptr,
318             // We could use the run-time alignment here. For now, we do not, because
319             // the point of tracking the alignment here is to make sure that the *static*
320             // alignment information emitted with the loads is correct. The run-time
321             // alignment can only be more restrictive.
322             align: layout.align.abi,
323             meta,
324         };
325         Ok(MPlaceTy { mplace, layout })
326     }
327
328     /// Take an operand, representing a pointer, and dereference it to a place -- that
329     /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
330     pub fn deref_operand(
331         &self,
332         src: OpTy<'tcx, M::PointerTag>,
333     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
334         let val = self.read_immediate(src)?;
335         trace!("deref to {} on {:?}", val.layout.ty, *val);
336         let place = self.ref_to_mplace(val)?;
337         self.mplace_access_checked(place)
338     }
339
340     /// Check if the given place is good for memory access with the given
341     /// size, falling back to the layout's size if `None` (in the latter case,
342     /// this must be a statically sized type).
343     ///
344     /// On success, returns `None` for zero-sized accesses (where nothing else is
345     /// left to do) and a `Pointer` to use for the actual access otherwise.
346     #[inline]
347     pub(super) fn check_mplace_access(
348         &self,
349         place: MPlaceTy<'tcx, M::PointerTag>,
350         size: Option<Size>,
351     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
352         let size = size.unwrap_or_else(|| {
353             assert!(!place.layout.is_unsized());
354             assert!(!place.meta.has_meta());
355             place.layout.size
356         });
357         self.memory.check_ptr_access(place.ptr, size, place.align)
358     }
359
360     /// Return the "access-checked" version of this `MPlace`, where for non-ZST
361     /// this is definitely a `Pointer`.
362     pub fn mplace_access_checked(
363         &self,
364         mut place: MPlaceTy<'tcx, M::PointerTag>,
365     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
366         let (size, align) = self
367             .size_and_align_of_mplace(place)?
368             .unwrap_or((place.layout.size, place.layout.align.abi));
369         assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
370         place.mplace.align = align; // maximally strict checking
371         // When dereferencing a pointer, it must be non-NULL, aligned, and live.
372         if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
373             place.mplace.ptr = ptr.into();
374         }
375         Ok(place)
376     }
377
378     /// Force `place.ptr` to a `Pointer`.
379     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
380     pub(super) fn force_mplace_ptr(
381         &self,
382         mut place: MPlaceTy<'tcx, M::PointerTag>,
383     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
384         place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
385         Ok(place)
386     }
387
388     /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
389     /// always possible without allocating, so it can take `&self`. Also return the field's layout.
390     /// This supports both struct and array fields.
391     ///
392     /// This also works for arrays, but then the `usize` index type is restricting.
393     /// For indexing into arrays, use `mplace_index`.
394     #[inline(always)]
395     pub fn mplace_field(
396         &self,
397         base: MPlaceTy<'tcx, M::PointerTag>,
398         field: usize,
399     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
400         let offset = base.layout.fields.offset(field);
401         let field_layout = base.layout.field(self, field)?;
402
403         // Offset may need adjustment for unsized fields.
404         let (meta, offset) = if field_layout.is_unsized() {
405             // Re-use parent metadata to determine dynamic field layout.
406             // With custom DSTS, this *will* execute user-defined code, but the same
407             // happens at run-time so that's okay.
408             let align = match self.size_and_align_of(base.meta, field_layout)? {
409                 Some((_, align)) => align,
410                 None if offset == Size::ZERO => {
411                     // An extern type at offset 0, we fall back to its static alignment.
412                     // FIXME: Once we have made decisions for how to handle size and alignment
413                     // of `extern type`, this should be adapted.  It is just a temporary hack
414                     // to get some code to work that probably ought to work.
415                     field_layout.align.abi
416                 }
417                 None => bug!("Cannot compute offset for extern type field at non-0 offset"),
418             };
419             (base.meta, offset.align_to(align))
420         } else {
421             // base.meta could be present; we might be accessing a sized field of an unsized
422             // struct.
423             (MemPlaceMeta::None, offset)
424         };
425
426         // We do not look at `base.layout.align` nor `field_layout.align`, unlike
427         // codegen -- mostly to see if we can get away with that
428         base.offset(offset, meta, field_layout, self)
429     }
430
431     /// Index into an array.
432     #[inline(always)]
433     pub fn mplace_index(
434         &self,
435         base: MPlaceTy<'tcx, M::PointerTag>,
436         index: u64,
437     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
438         // Not using the layout method because we want to compute on u64
439         match base.layout.fields {
440             FieldsShape::Array { stride, .. } => {
441                 let len = base.len(self)?;
442                 if index >= len {
443                     // This can only be reached in ConstProp and non-rustc-MIR.
444                     throw_ub!(BoundsCheckFailed { len, index });
445                 }
446                 let offset = stride * index; // `Size` multiplication
447                 // All fields have the same layout.
448                 let field_layout = base.layout.field(self, 0)?;
449
450                 assert!(!field_layout.is_unsized());
451                 base.offset(offset, MemPlaceMeta::None, field_layout, self)
452             }
453             _ => bug!("`mplace_index` called on non-array type {:?}", base.layout.ty),
454         }
455     }
456
457     // Iterates over all fields of an array. Much more efficient than doing the
458     // same by repeatedly calling `mplace_array`.
459     pub(super) fn mplace_array_fields(
460         &self,
461         base: MPlaceTy<'tcx, Tag>,
462     ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
463     {
464         let len = base.len(self)?; // also asserts that we have a type where this makes sense
465         let stride = match base.layout.fields {
466             FieldsShape::Array { stride, .. } => stride,
467             _ => bug!("mplace_array_fields: expected an array layout"),
468         };
469         let layout = base.layout.field(self, 0)?;
470         let dl = &self.tcx.data_layout;
471         // `Size` multiplication
472         Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
473     }
474
475     fn mplace_subslice(
476         &self,
477         base: MPlaceTy<'tcx, M::PointerTag>,
478         from: u64,
479         to: u64,
480         from_end: bool,
481     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
482         let len = base.len(self)?; // also asserts that we have a type where this makes sense
483         let actual_to = if from_end {
484             if from.checked_add(to).map_or(true, |to| to > len) {
485                 // This can only be reached in ConstProp and non-rustc-MIR.
486                 throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
487             }
488             len.checked_sub(to).unwrap()
489         } else {
490             to
491         };
492
493         // Not using layout method because that works with usize, and does not work with slices
494         // (that have count 0 in their layout).
495         let from_offset = match base.layout.fields {
496             FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
497             _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
498         };
499
500         // Compute meta and new layout
501         let inner_len = actual_to.checked_sub(from).unwrap();
502         let (meta, ty) = match base.layout.ty.kind {
503             // It is not nice to match on the type, but that seems to be the only way to
504             // implement this.
505             ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
506             ty::Slice(..) => {
507                 let len = Scalar::from_machine_usize(inner_len, self);
508                 (MemPlaceMeta::Meta(len), base.layout.ty)
509             }
510             _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
511         };
512         let layout = self.layout_of(ty)?;
513         base.offset(from_offset, meta, layout, self)
514     }
515
516     pub(super) fn mplace_downcast(
517         &self,
518         base: MPlaceTy<'tcx, M::PointerTag>,
519         variant: VariantIdx,
520     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
521         // Downcasts only change the layout
522         assert!(!base.meta.has_meta());
523         Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
524     }
525
526     /// Project into an mplace
527     pub(super) fn mplace_projection(
528         &self,
529         base: MPlaceTy<'tcx, M::PointerTag>,
530         proj_elem: &mir::PlaceElem<'tcx>,
531     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
532         use rustc_middle::mir::ProjectionElem::*;
533         Ok(match *proj_elem {
534             Field(field, _) => self.mplace_field(base, field.index())?,
535             Downcast(_, variant) => self.mplace_downcast(base, variant)?,
536             Deref => self.deref_operand(base.into())?,
537
538             Index(local) => {
539                 let layout = self.layout_of(self.tcx.types.usize)?;
540                 let n = self.access_local(self.frame(), local, Some(layout))?;
541                 let n = self.read_scalar(n)?;
542                 let n = u64::try_from(
543                     self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?,
544                 )
545                 .unwrap();
546                 self.mplace_index(base, n)?
547             }
548
549             ConstantIndex { offset, min_length, from_end } => {
550                 let n = base.len(self)?;
551                 if n < u64::from(min_length) {
552                     // This can only be reached in ConstProp and non-rustc-MIR.
553                     throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n.into() });
554                 }
555
556                 let index = if from_end {
557                     assert!(0 < offset && offset <= min_length);
558                     n.checked_sub(u64::from(offset)).unwrap()
559                 } else {
560                     assert!(offset < min_length);
561                     u64::from(offset)
562                 };
563
564                 self.mplace_index(base, index)?
565             }
566
567             Subslice { from, to, from_end } => {
568                 self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
569             }
570         })
571     }
572
573     /// Gets the place of a field inside the place, and also the field's type.
574     /// Just a convenience function, but used quite a bit.
575     /// This is the only projection that might have a side-effect: We cannot project
576     /// into the field of a local `ScalarPair`, we have to first allocate it.
577     pub fn place_field(
578         &mut self,
579         base: PlaceTy<'tcx, M::PointerTag>,
580         field: usize,
581     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
582         // FIXME: We could try to be smarter and avoid allocation for fields that span the
583         // entire place.
584         let mplace = self.force_allocation(base)?;
585         Ok(self.mplace_field(mplace, field)?.into())
586     }
587
588     pub fn place_index(
589         &mut self,
590         base: PlaceTy<'tcx, M::PointerTag>,
591         index: u64,
592     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
593         let mplace = self.force_allocation(base)?;
594         Ok(self.mplace_index(mplace, index)?.into())
595     }
596
597     pub fn place_downcast(
598         &self,
599         base: PlaceTy<'tcx, M::PointerTag>,
600         variant: VariantIdx,
601     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
602         // Downcast just changes the layout
603         Ok(match base.place {
604             Place::Ptr(mplace) => {
605                 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
606             }
607             Place::Local { .. } => {
608                 let layout = base.layout.for_variant(self, variant);
609                 PlaceTy { layout, ..base }
610             }
611         })
612     }
613
614     /// Projects into a place.
615     pub fn place_projection(
616         &mut self,
617         base: PlaceTy<'tcx, M::PointerTag>,
618         proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
619     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
620         use rustc_middle::mir::ProjectionElem::*;
621         Ok(match *proj_elem {
622             Field(field, _) => self.place_field(base, field.index())?,
623             Downcast(_, variant) => self.place_downcast(base, variant)?,
624             Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
625             // For the other variants, we have to force an allocation.
626             // This matches `operand_projection`.
627             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
628                 let mplace = self.force_allocation(base)?;
629                 self.mplace_projection(mplace, proj_elem)?.into()
630             }
631         })
632     }
633
634     /// Computes a place. You should only use this if you intend to write into this
635     /// place; for reading, a more efficient alternative is `eval_place_for_read`.
636     pub fn eval_place(
637         &mut self,
638         place: mir::Place<'tcx>,
639     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
640         let mut place_ty = match place.local {
641             mir::RETURN_PLACE => {
642                 // `return_place` has the *caller* layout, but we want to use our
643                 // `layout to verify our assumption. The caller will validate
644                 // their layout on return.
645                 PlaceTy {
646                     place: match self.frame().return_place {
647                         Some(p) => *p,
648                         // Even if we don't have a return place, we sometimes need to
649                         // create this place, but any attempt to read from / write to it
650                         // (even a ZST read/write) needs to error, so let us make this
651                         // a NULL place.
652                         //
653                         // FIXME: Ideally we'd make sure that the place projections also
654                         // bail out.
655                         None => Place::null(&*self),
656                     },
657                     layout: self.layout_of(
658                         self.subst_from_current_frame_and_normalize_erasing_regions(
659                             self.frame().body.return_ty(),
660                         ),
661                     )?,
662                 }
663             }
664             local => PlaceTy {
665                 // This works even for dead/uninitialized locals; we check further when writing
666                 place: Place::Local { frame: self.cur_frame(), local },
667                 layout: self.layout_of_local(self.frame(), local, None)?,
668             },
669         };
670
671         for elem in place.projection.iter() {
672             place_ty = self.place_projection(place_ty, elem)?
673         }
674
675         self.dump_place(place_ty.place);
676         Ok(place_ty)
677     }
678
679     /// Write a scalar to a place
680     #[inline(always)]
681     pub fn write_scalar(
682         &mut self,
683         val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
684         dest: PlaceTy<'tcx, M::PointerTag>,
685     ) -> InterpResult<'tcx> {
686         self.write_immediate(Immediate::Scalar(val.into()), dest)
687     }
688
689     /// Write an immediate to a place
690     #[inline(always)]
691     pub fn write_immediate(
692         &mut self,
693         src: Immediate<M::PointerTag>,
694         dest: PlaceTy<'tcx, M::PointerTag>,
695     ) -> InterpResult<'tcx> {
696         self.write_immediate_no_validate(src, dest)?;
697
698         if M::enforce_validity(self) {
699             // Data got changed, better make sure it matches the type!
700             self.validate_operand(self.place_to_op(dest)?)?;
701         }
702
703         Ok(())
704     }
705
706     /// Write an `Immediate` to memory.
707     #[inline(always)]
708     pub fn write_immediate_to_mplace(
709         &mut self,
710         src: Immediate<M::PointerTag>,
711         dest: MPlaceTy<'tcx, M::PointerTag>,
712     ) -> InterpResult<'tcx> {
713         self.write_immediate_to_mplace_no_validate(src, dest)?;
714
715         if M::enforce_validity(self) {
716             // Data got changed, better make sure it matches the type!
717             self.validate_operand(dest.into())?;
718         }
719
720         Ok(())
721     }
722
723     /// Write an immediate to a place.
724     /// If you use this you are responsible for validating that things got copied at the
725     /// right type.
726     fn write_immediate_no_validate(
727         &mut self,
728         src: Immediate<M::PointerTag>,
729         dest: PlaceTy<'tcx, M::PointerTag>,
730     ) -> InterpResult<'tcx> {
731         if cfg!(debug_assertions) {
732             // This is a very common path, avoid some checks in release mode
733             assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
734             match src {
735                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
736                     self.pointer_size(),
737                     dest.layout.size,
738                     "Size mismatch when writing pointer"
739                 ),
740                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
741                     assert_eq!(
742                         Size::from_bytes(size),
743                         dest.layout.size,
744                         "Size mismatch when writing bits"
745                     )
746                 }
747                 Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
748                 Immediate::ScalarPair(_, _) => {
749                     // FIXME: Can we check anything here?
750                 }
751             }
752         }
753         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
754
755         // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
756         // but not factored as a separate function.
757         let mplace = match dest.place {
758             Place::Local { frame, local } => {
759                 match self.stack[frame].locals[local].access_mut()? {
760                     Ok(local) => {
761                         // Local can be updated in-place.
762                         *local = LocalValue::Live(Operand::Immediate(src));
763                         return Ok(());
764                     }
765                     Err(mplace) => {
766                         // The local is in memory, go on below.
767                         mplace
768                     }
769                 }
770             }
771             Place::Ptr(mplace) => mplace, // already referring to memory
772         };
773         let dest = MPlaceTy { mplace, layout: dest.layout };
774
775         // This is already in memory, write there.
776         self.write_immediate_to_mplace_no_validate(src, dest)
777     }
778
779     /// Write an immediate to memory.
780     /// If you use this you are responsible for validating that things got copied at the
781     /// right type.
782     fn write_immediate_to_mplace_no_validate(
783         &mut self,
784         value: Immediate<M::PointerTag>,
785         dest: MPlaceTy<'tcx, M::PointerTag>,
786     ) -> InterpResult<'tcx> {
787         // Note that it is really important that the type here is the right one, and matches the
788         // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
789         // to handle padding properly, which is only correct if we never look at this data with the
790         // wrong type.
791
792         // Invalid places are a thing: the return place of a diverging function
793         let ptr = match self.check_mplace_access(dest, None)? {
794             Some(ptr) => ptr,
795             None => return Ok(()), // zero-sized access
796         };
797
798         let tcx = &*self.tcx;
799         // FIXME: We should check that there are dest.layout.size many bytes available in
800         // memory.  The code below is not sufficient, with enough padding it might not
801         // cover all the bytes!
802         match value {
803             Immediate::Scalar(scalar) => {
804                 match dest.layout.abi {
805                     Abi::Scalar(_) => {} // fine
806                     _ => {
807                         bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
808                     }
809                 }
810                 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
811                     tcx,
812                     ptr,
813                     scalar,
814                     dest.layout.size,
815                 )
816             }
817             Immediate::ScalarPair(a_val, b_val) => {
818                 // We checked `ptr_align` above, so all fields will have the alignment they need.
819                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
820                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
821                 let (a, b) = match dest.layout.abi {
822                     Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
823                     _ => bug!(
824                         "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
825                         dest.layout
826                     ),
827                 };
828                 let (a_size, b_size) = (a.size(self), b.size(self));
829                 let b_offset = a_size.align_to(b.align(self).abi);
830                 let b_ptr = ptr.offset(b_offset, self)?;
831
832                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
833                 // but that does not work: We could be a newtype around a pair, then the
834                 // fields do not match the `ScalarPair` components.
835
836                 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
837                 self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
838             }
839         }
840     }
841
842     /// Copies the data from an operand to a place. This does not support transmuting!
843     /// Use `copy_op_transmute` if the layouts could disagree.
844     #[inline(always)]
845     pub fn copy_op(
846         &mut self,
847         src: OpTy<'tcx, M::PointerTag>,
848         dest: PlaceTy<'tcx, M::PointerTag>,
849     ) -> InterpResult<'tcx> {
850         self.copy_op_no_validate(src, dest)?;
851
852         if M::enforce_validity(self) {
853             // Data got changed, better make sure it matches the type!
854             self.validate_operand(self.place_to_op(dest)?)?;
855         }
856
857         Ok(())
858     }
859
860     /// Copies the data from an operand to a place. This does not support transmuting!
861     /// Use `copy_op_transmute` if the layouts could disagree.
862     /// Also, if you use this you are responsible for validating that things get copied at the
863     /// right type.
864     fn copy_op_no_validate(
865         &mut self,
866         src: OpTy<'tcx, M::PointerTag>,
867         dest: PlaceTy<'tcx, M::PointerTag>,
868     ) -> InterpResult<'tcx> {
869         // We do NOT compare the types for equality, because well-typed code can
870         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
871         assert!(
872             src.layout.layout == dest.layout.layout,
873             "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}",
874             src,
875             dest
876         );
877
878         // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
879         let src = match self.try_read_immediate(src)? {
880             Ok(src_val) => {
881                 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
882                 // Yay, we got a value that we can write directly.
883                 // FIXME: Add a check to make sure that if `src` is indirect,
884                 // it does not overlap with `dest`.
885                 return self.write_immediate_no_validate(*src_val, dest);
886             }
887             Err(mplace) => mplace,
888         };
889         // Slow path, this does not fit into an immediate. Just memcpy.
890         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
891
892         // This interprets `src.meta` with the `dest` local's layout, if an unsized local
893         // is being initialized!
894         let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
895         let size = size.unwrap_or_else(|| {
896             assert!(
897                 !dest.layout.is_unsized(),
898                 "Cannot copy into already initialized unsized place"
899             );
900             dest.layout.size
901         });
902         assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
903
904         let src = self
905             .check_mplace_access(src, Some(size))
906             .expect("places should be checked on creation");
907         let dest = self
908             .check_mplace_access(dest, Some(size))
909             .expect("places should be checked on creation");
910         let (src_ptr, dest_ptr) = match (src, dest) {
911             (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
912             (None, None) => return Ok(()), // zero-sized copy
913             _ => bug!("The pointers should both be Some or both None"),
914         };
915
916         self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
917     }
918
919     /// Copies the data from an operand to a place. The layouts may disagree, but they must
920     /// have the same size.
921     pub fn copy_op_transmute(
922         &mut self,
923         src: OpTy<'tcx, M::PointerTag>,
924         dest: PlaceTy<'tcx, M::PointerTag>,
925     ) -> InterpResult<'tcx> {
926         if src.layout.layout == dest.layout.layout {
927             // Fast path: Just use normal `copy_op`
928             return self.copy_op(src, dest);
929         }
930         // We still require the sizes to match.
931         if src.layout.size != dest.layout.size {
932             // FIXME: This should be an assert instead of an error, but if we transmute within an
933             // array length computation, `typeck` may not have yet been run and errored out. In fact
934             // most likey we *are* running `typeck` right now. Investigate whether we can bail out
935             // on `typeck_tables().has_errors` at all const eval entry points.
936             debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
937             self.tcx.sess.delay_span_bug(
938                 self.tcx.span,
939                 "size-changing transmute, should have been caught by transmute checking",
940             );
941             throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
942         }
943         // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
944         // to avoid that here.
945         assert!(
946             !src.layout.is_unsized() && !dest.layout.is_unsized(),
947             "Cannot transmute unsized data"
948         );
949
950         // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
951         // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
952         // We have to write them to `dest` at the offsets they were *read at*, which is
953         // not necessarily the same as the offsets in `dest.layout`!
954         // Hence we do the copy with the source layout on both sides.  We also make sure to write
955         // into memory, because if `dest` is a local we would not even have a way to write
956         // at the `src` offsets; the fact that we came from a different layout would
957         // just be lost.
958         let dest = self.force_allocation(dest)?;
959         self.copy_op_no_validate(
960             src,
961             PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
962         )?;
963
964         if M::enforce_validity(self) {
965             // Data got changed, better make sure it matches the type!
966             self.validate_operand(dest.into())?;
967         }
968
969         Ok(())
970     }
971
972     /// Ensures that a place is in memory, and returns where it is.
973     /// If the place currently refers to a local that doesn't yet have a matching allocation,
974     /// create such an allocation.
975     /// This is essentially `force_to_memplace`.
976     ///
977     /// This supports unsized types and returns the computed size to avoid some
978     /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
979     /// version.
980     pub fn force_allocation_maybe_sized(
981         &mut self,
982         place: PlaceTy<'tcx, M::PointerTag>,
983         meta: MemPlaceMeta<M::PointerTag>,
984     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
985         let (mplace, size) = match place.place {
986             Place::Local { frame, local } => {
987                 match self.stack[frame].locals[local].access_mut()? {
988                     Ok(&mut local_val) => {
989                         // We need to make an allocation.
990
991                         // We need the layout of the local.  We can NOT use the layout we got,
992                         // that might e.g., be an inner field of a struct with `Scalar` layout,
993                         // that has different alignment than the outer field.
994                         let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
995                         // We also need to support unsized types, and hence cannot use `allocate`.
996                         let (size, align) = self
997                             .size_and_align_of(meta, local_layout)?
998                             .expect("Cannot allocate for non-dyn-sized type");
999                         let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
1000                         let mplace = MemPlace { ptr: ptr.into(), align, meta };
1001                         if let LocalValue::Live(Operand::Immediate(value)) = local_val {
1002                             // Preserve old value.
1003                             // We don't have to validate as we can assume the local
1004                             // was already valid for its type.
1005                             let mplace = MPlaceTy { mplace, layout: local_layout };
1006                             self.write_immediate_to_mplace_no_validate(value, mplace)?;
1007                         }
1008                         // Now we can call `access_mut` again, asserting it goes well,
1009                         // and actually overwrite things.
1010                         *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
1011                             LocalValue::Live(Operand::Indirect(mplace));
1012                         (mplace, Some(size))
1013                     }
1014                     Err(mplace) => (mplace, None), // this already was an indirect local
1015                 }
1016             }
1017             Place::Ptr(mplace) => (mplace, None),
1018         };
1019         // Return with the original layout, so that the caller can go on
1020         Ok((MPlaceTy { mplace, layout: place.layout }, size))
1021     }
1022
1023     #[inline(always)]
1024     pub fn force_allocation(
1025         &mut self,
1026         place: PlaceTy<'tcx, M::PointerTag>,
1027     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1028         Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
1029     }
1030
1031     pub fn allocate(
1032         &mut self,
1033         layout: TyAndLayout<'tcx>,
1034         kind: MemoryKind<M::MemoryKind>,
1035     ) -> MPlaceTy<'tcx, M::PointerTag> {
1036         let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1037         MPlaceTy::from_aligned_ptr(ptr, layout)
1038     }
1039
1040     /// Returns a wide MPlace.
1041     pub fn allocate_str(
1042         &mut self,
1043         str: &str,
1044         kind: MemoryKind<M::MemoryKind>,
1045     ) -> MPlaceTy<'tcx, M::PointerTag> {
1046         let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
1047         let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
1048         let mplace = MemPlace {
1049             ptr: ptr.into(),
1050             align: Align::from_bytes(1).unwrap(),
1051             meta: MemPlaceMeta::Meta(meta),
1052         };
1053
1054         let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1055         MPlaceTy { mplace, layout }
1056     }
1057
1058     pub fn write_discriminant_index(
1059         &mut self,
1060         variant_index: VariantIdx,
1061         dest: PlaceTy<'tcx, M::PointerTag>,
1062     ) -> InterpResult<'tcx> {
1063         // Layout computation excludes uninhabited variants from consideration
1064         // therefore there's no way to represent those variants in the given layout.
1065         if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1066             throw_ub!(Unreachable);
1067         }
1068
1069         match dest.layout.variants {
1070             Variants::Single { index } => {
1071                 assert_eq!(index, variant_index);
1072             }
1073             Variants::Multiple {
1074                 discr_kind: DiscriminantKind::Tag,
1075                 discr: ref discr_layout,
1076                 discr_index,
1077                 ..
1078             } => {
1079                 // No need to validate that the discriminant here because the
1080                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1081
1082                 let discr_val =
1083                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1084
1085                 // raw discriminants for enums are isize or bigger during
1086                 // their computation, but the in-memory tag is the smallest possible
1087                 // representation
1088                 let size = discr_layout.value.size(self);
1089                 let discr_val = truncate(discr_val, size);
1090
1091                 let discr_dest = self.place_field(dest, discr_index)?;
1092                 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1093             }
1094             Variants::Multiple {
1095                 discr_kind:
1096                     DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1097                 discr: ref discr_layout,
1098                 discr_index,
1099                 ..
1100             } => {
1101                 // No need to validate that the discriminant here because the
1102                 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1103
1104                 if variant_index != dataful_variant {
1105                     let variants_start = niche_variants.start().as_u32();
1106                     let variant_index_relative = variant_index
1107                         .as_u32()
1108                         .checked_sub(variants_start)
1109                         .expect("overflow computing relative variant idx");
1110                     // We need to use machine arithmetic when taking into account `niche_start`:
1111                     // discr_val = variant_index_relative + niche_start_val
1112                     let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1113                     let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1114                     let variant_index_relative_val =
1115                         ImmTy::from_uint(variant_index_relative, discr_layout);
1116                     let discr_val = self.binary_op(
1117                         mir::BinOp::Add,
1118                         variant_index_relative_val,
1119                         niche_start_val,
1120                     )?;
1121                     // Write result.
1122                     let niche_dest = self.place_field(dest, discr_index)?;
1123                     self.write_immediate(*discr_val, niche_dest)?;
1124                 }
1125             }
1126         }
1127
1128         Ok(())
1129     }
1130
1131     pub fn raw_const_to_mplace(
1132         &self,
1133         raw: RawConst<'tcx>,
1134     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1135         // This must be an allocation in `tcx`
1136         assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1137         let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1138         let layout = self.layout_of(raw.ty)?;
1139         Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1140     }
1141
1142     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1143     /// Also return some more information so drop doesn't have to run the same code twice.
1144     pub(super) fn unpack_dyn_trait(
1145         &self,
1146         mplace: MPlaceTy<'tcx, M::PointerTag>,
1147     ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1148         let vtable = mplace.vtable(); // also sanity checks the type
1149         let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1150         let layout = self.layout_of(ty)?;
1151
1152         // More sanity checks
1153         if cfg!(debug_assertions) {
1154             let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1155             assert_eq!(size, layout.size);
1156             // only ABI alignment is preserved
1157             assert_eq!(align, layout.align.abi);
1158         }
1159
1160         let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1161         Ok((instance, mplace))
1162     }
1163 }