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