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