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