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