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