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