1 //! Computations on places -- field projections, going from mir::Place, and writing
3 //! All high-level functions to write to memory work on places as destinations.
5 use std::convert::TryFrom;
10 use rustc::mir::interpret::truncate;
11 use rustc::ty::{self, Ty};
12 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
13 use rustc::ty::TypeFoldable;
16 GlobalId, AllocId, Allocation, Scalar, EvalResult, Pointer, PointerArithmetic,
17 InterpretCx, Machine, AllocMap, AllocationExtra,
18 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22 pub struct MemPlace<Tag=(), Id=AllocId> {
23 /// A place may have an integral pointer for ZSTs, and since it might
24 /// be turned back into a reference before ever being dereferenced.
25 /// However, it may never be undef.
26 pub ptr: Scalar<Tag, Id>,
28 /// Metadata for unsized places. Interpretation is up to the type.
29 /// Must not be present for sized types, but can be missing for unsized types
30 /// (e.g., `extern type`).
31 pub meta: Option<Scalar<Tag, Id>>,
34 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
35 pub enum Place<Tag=(), Id=AllocId> {
36 /// A place referring to a value allocated in the `Memory` system.
37 Ptr(MemPlace<Tag, Id>),
39 /// To support alloc-free locals, we are able to write directly to a local.
40 /// (Without that optimization, we'd just always be a `MemPlace`.)
47 #[derive(Copy, Clone, Debug)]
48 pub struct PlaceTy<'tcx, Tag=()> {
50 pub layout: TyLayout<'tcx>,
53 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
54 type Target = Place<Tag>;
56 fn deref(&self) -> &Place<Tag> {
61 /// A MemPlace with its layout. Constructing it is only possible in this module.
62 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
63 pub struct MPlaceTy<'tcx, Tag=()> {
64 mplace: MemPlace<Tag>,
65 pub layout: TyLayout<'tcx>,
68 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
69 type Target = MemPlace<Tag>;
71 fn deref(&self) -> &MemPlace<Tag> {
76 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
78 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
80 place: Place::Ptr(mplace.mplace),
86 impl<Tag> MemPlace<Tag> {
87 /// Replace ptr tag, maintain vtable tag (if any)
89 pub fn replace_tag(self, new_tag: Tag) -> Self {
91 ptr: self.ptr.erase_tag().with_tag(new_tag),
98 pub fn erase_tag(self) -> MemPlace {
100 ptr: self.ptr.erase_tag(),
102 meta: self.meta.map(Scalar::erase_tag),
107 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
115 /// Produces a Place that will error if attempted to be read from or written to
117 pub fn null(cx: &impl HasDataLayout) -> Self {
118 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
122 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
123 Self::from_scalar_ptr(ptr.into(), align)
127 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
128 assert!(self.meta.is_none());
129 (self.ptr, self.align)
132 /// metact the ptr part of the mplace
134 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
135 // At this point, we forget about the alignment information --
136 // the place has been turned into a reference, and no matter where it came from,
137 // it now must be aligned.
138 self.to_scalar_ptr_align().0.to_ptr()
141 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
142 /// This is the inverse of `ref_to_mplace`.
144 pub fn to_ref(self) -> Immediate<Tag> {
146 None => Immediate::Scalar(self.ptr.into()),
147 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
154 meta: Option<Scalar<Tag>>,
155 cx: &impl HasDataLayout,
156 ) -> EvalResult<'tcx, Self> {
158 ptr: self.ptr.ptr_offset(offset, cx)?,
159 align: self.align.restrict_for_offset(offset),
165 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
166 /// Produces a MemPlace that works for ZST but nothing else
168 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
170 mplace: MemPlace::from_scalar_ptr(
171 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
178 /// Replace ptr tag, maintain vtable tag (if any)
180 pub fn replace_tag(self, new_tag: Tag) -> Self {
182 mplace: self.mplace.replace_tag(new_tag),
191 meta: Option<Scalar<Tag>>,
192 layout: TyLayout<'tcx>,
193 cx: &impl HasDataLayout,
194 ) -> EvalResult<'tcx, Self> {
196 mplace: self.mplace.offset(offset, meta, cx)?,
202 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
203 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
207 pub(super) fn len(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
208 if self.layout.is_unsized() {
209 // We need to consult `meta` metadata
210 match self.layout.ty.sty {
211 ty::Slice(..) | ty::Str =>
212 return self.mplace.meta.unwrap().to_usize(cx),
213 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
216 // Go through the layout. There are lots of types that support a length,
218 match self.layout.fields {
219 layout::FieldPlacement::Array { count, .. } => Ok(count),
220 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
226 pub(super) fn vtable(self) -> EvalResult<'tcx, Pointer<Tag>> {
227 match self.layout.ty.sty {
228 ty::Dynamic(..) => self.mplace.meta.unwrap().to_ptr(),
229 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
234 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
236 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, Immediate<Tag>> {
238 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
239 Operand::Immediate(imm) => Err(imm),
244 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
245 self.try_as_mplace().unwrap()
249 impl<'tcx, Tag: ::std::fmt::Debug> Place<Tag> {
250 /// Produces a Place that will error if attempted to be read from or written to
252 pub fn null(cx: &impl HasDataLayout) -> Self {
253 Place::Ptr(MemPlace::null(cx))
257 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
258 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
262 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
263 Place::Ptr(MemPlace::from_ptr(ptr, align))
267 pub fn to_mem_place(self) -> MemPlace<Tag> {
269 Place::Ptr(mplace) => mplace,
270 _ => bug!("to_mem_place: expected Place::Ptr, got {:?}", self),
276 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
277 self.to_mem_place().to_scalar_ptr_align()
281 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
282 self.to_mem_place().to_ptr()
286 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
288 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
289 MPlaceTy { mplace: self.place.to_mem_place(), layout: self.layout }
293 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
294 impl<'a, 'mir, 'tcx, Tag, M> InterpretCx<'a, 'mir, 'tcx, M>
296 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
297 Tag: ::std::fmt::Debug+Default+Copy+Eq+Hash+'static,
298 M: Machine<'a, 'mir, 'tcx, PointerTag=Tag>,
299 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
300 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
301 M::AllocExtra: AllocationExtra<Tag>,
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(
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)?;
314 let mplace = MemPlace {
315 ptr: val.to_scalar_ptr()?,
316 // We could use the run-time alignment here. For now, we do not, because
317 // the point of tracking the alignment here is to make sure that the *static*
318 // alignment information emitted with the loads is correct. The run-time
319 // alignment can only be more restrictive.
320 align: layout.align.abi,
321 meta: val.to_meta()?,
323 Ok(MPlaceTy { mplace, layout })
326 // Take an operand, representing a pointer, and dereference it to a place -- that
327 // will always be a MemPlace. Lives in `place.rs` because it creates a place.
328 // This calls the "deref" machine hook, and counts as a deref as far as
329 // Stacked Borrows is concerned.
330 pub fn deref_operand(
332 src: OpTy<'tcx, M::PointerTag>,
333 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
334 let val = self.read_immediate(src)?;
335 trace!("deref to {} on {:?}", val.layout.ty, *val);
336 let mut place = self.ref_to_mplace(val)?;
337 // Pointer tag tracking might want to adjust the tag.
338 let mutbl = match val.layout.ty.sty {
339 // `builtin_deref` considers boxes immutable, that's useless for our purposes
340 ty::Ref(_, _, mutbl) => Some(mutbl),
341 ty::Adt(def, _) if def.is_box() => Some(hir::MutMutable),
342 ty::RawPtr(_) => None,
343 _ => bug!("Unexpected pointer type {}", val.layout.ty),
345 place.mplace.ptr = M::tag_dereference(self, place, mutbl)?;
349 /// Offset a pointer to project to a field. Unlike place_field, this is always
350 /// possible without allocating, so it can take &self. Also return the field's layout.
351 /// This supports both struct and array fields.
355 base: MPlaceTy<'tcx, M::PointerTag>,
357 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
358 // Not using the layout method because we want to compute on u64
359 let offset = match base.layout.fields {
360 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
361 offsets[usize::try_from(field).unwrap()],
362 layout::FieldPlacement::Array { stride, .. } => {
363 let len = base.len(self)?;
364 assert!(field < len, "Tried to access element {} of array/slice with length {}",
368 layout::FieldPlacement::Union(count) => {
369 assert!(field < count as u64,
370 "Tried to access field {} of union with {} fields", field, count);
371 // Offset is always 0
375 // the only way conversion can fail if is this is an array (otherwise we already panicked
376 // above). In that case, all fields are equal.
377 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
379 // Offset may need adjustment for unsized fields.
380 let (meta, offset) = if field_layout.is_unsized() {
381 // Re-use parent metadata to determine dynamic field layout.
382 // With custom DSTS, this *will* execute user-defined code, but the same
383 // happens at run-time so that's okay.
384 let align = match self.size_and_align_of(base.meta, field_layout)? {
385 Some((_, align)) => align,
386 None if offset == Size::ZERO =>
387 // An extern type at offset 0, we fall back to its static alignment.
388 // FIXME: Once we have made decisions for how to handle size and alignment
389 // of `extern type`, this should be adapted. It is just a temporary hack
390 // to get some code to work that probably ought to work.
391 field_layout.align.abi,
393 bug!("Cannot compute offset for extern type field at non-0 offset"),
395 (base.meta, offset.align_to(align))
397 // base.meta could be present; we might be accessing a sized field of an unsized
402 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
403 // codegen -- mostly to see if we can get away with that
404 base.offset(offset, meta, field_layout, self)
407 // Iterates over all fields of an array. Much more efficient than doing the
408 // same by repeatedly calling `mplace_array`.
409 pub fn mplace_array_fields(
411 base: MPlaceTy<'tcx, Tag>,
413 EvalResult<'tcx, impl Iterator<Item=EvalResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
415 let len = base.len(self)?; // also asserts that we have a type where this makes sense
416 let stride = match base.layout.fields {
417 layout::FieldPlacement::Array { stride, .. } => stride,
418 _ => bug!("mplace_array_fields: expected an array layout"),
420 let layout = base.layout.field(self, 0)?;
421 let dl = &self.tcx.data_layout;
422 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
425 pub fn mplace_subslice(
427 base: MPlaceTy<'tcx, M::PointerTag>,
430 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
431 let len = base.len(self)?; // also asserts that we have a type where this makes sense
432 assert!(from <= len - to);
434 // Not using layout method because that works with usize, and does not work with slices
435 // (that have count 0 in their layout).
436 let from_offset = match base.layout.fields {
437 layout::FieldPlacement::Array { stride, .. } =>
439 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
442 // Compute meta and new layout
443 let inner_len = len - to - from;
444 let (meta, ty) = match base.layout.ty.sty {
445 // It is not nice to match on the type, but that seems to be the only way to
447 ty::Array(inner, _) =>
448 (None, self.tcx.mk_array(inner, inner_len)),
450 let len = Scalar::from_uint(inner_len, self.pointer_size());
451 (Some(len), base.layout.ty)
454 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
456 let layout = self.layout_of(ty)?;
457 base.offset(from_offset, meta, layout, self)
460 pub fn mplace_downcast(
462 base: MPlaceTy<'tcx, M::PointerTag>,
464 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
465 // Downcasts only change the layout
466 assert!(base.meta.is_none());
467 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
470 /// Project into an mplace
471 pub fn mplace_projection(
473 base: MPlaceTy<'tcx, M::PointerTag>,
474 proj_elem: &mir::PlaceElem<'tcx>,
475 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
476 use rustc::mir::ProjectionElem::*;
477 Ok(match *proj_elem {
478 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
479 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
480 Deref => self.deref_operand(base.into())?,
483 let layout = self.layout_of(self.tcx.types.usize)?;
484 let n = self.access_local(self.frame(), local, Some(layout))?;
485 let n = self.read_scalar(n)?;
486 let n = n.to_bits(self.tcx.data_layout.pointer_size)?;
487 self.mplace_field(base, u64::try_from(n).unwrap())?
495 let n = base.len(self)?;
496 assert!(n >= min_length as u64);
498 let index = if from_end {
499 n - u64::from(offset)
504 self.mplace_field(base, index)?
507 Subslice { from, to } =>
508 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
512 /// Gets the place of a field inside the place, and also the field's type.
513 /// Just a convenience function, but used quite a bit.
514 /// This is the only projection that might have a side-effect: We cannot project
515 /// into the field of a local `ScalarPair`, we have to first allocate it.
518 base: PlaceTy<'tcx, M::PointerTag>,
520 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
521 // FIXME: We could try to be smarter and avoid allocation for fields that span the
523 let mplace = self.force_allocation(base)?;
524 Ok(self.mplace_field(mplace, field)?.into())
527 pub fn place_downcast(
529 base: PlaceTy<'tcx, M::PointerTag>,
531 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
532 // Downcast just changes the layout
533 Ok(match base.place {
534 Place::Ptr(mplace) =>
535 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
536 Place::Local { .. } => {
537 let layout = base.layout.for_variant(self, variant);
538 PlaceTy { layout, ..base }
543 /// Projects into a place.
544 pub fn place_projection(
546 base: PlaceTy<'tcx, M::PointerTag>,
547 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
548 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
549 use rustc::mir::ProjectionElem::*;
550 Ok(match *proj_elem {
551 Field(field, _) => self.place_field(base, field.index() as u64)?,
552 Downcast(_, variant) => self.place_downcast(base, variant)?,
553 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
554 // For the other variants, we have to force an allocation.
555 // This matches `operand_projection`.
556 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
557 let mplace = self.force_allocation(base)?;
558 self.mplace_projection(mplace, proj_elem)?.into()
563 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
564 /// `eval_place` and `eval_place_to_op`.
565 pub(super) fn eval_place_to_mplace(
567 mir_place: &mir::Place<'tcx>
568 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
569 use rustc::mir::Place::*;
570 use rustc::mir::PlaceBase;
571 use rustc::mir::{Static, StaticKind};
572 Ok(match *mir_place {
573 Base(PlaceBase::Static(box Static { kind: StaticKind::Promoted(promoted), .. })) => {
574 let instance = self.frame().instance;
575 self.const_eval_raw(GlobalId {
577 promoted: Some(promoted),
581 Base(PlaceBase::Static(box Static { kind: StaticKind::Static(def_id), ty })) => {
582 assert!(!ty.needs_subst());
583 let layout = self.layout_of(ty)?;
584 let instance = ty::Instance::mono(*self.tcx, def_id);
589 // Just create a lazy reference, so we can support recursive statics.
590 // tcx takes are of assigning every static one and only one unique AllocId.
591 // When the data here is ever actually used, memory will notice,
592 // and it knows how to deal with alloc_id that are present in the
593 // global table but not in its local memory: It calls back into tcx through
594 // a query, triggering the CTFE machinery to actually turn this lazy reference
595 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
596 // this InterpretCx uses another Machine (e.g., in miri). This is what we
597 // want! This way, computing statics works concistently between codegen
598 // and miri: They use the same query to eventually obtain a `ty::Const`
599 // and use that for further computation.
600 let alloc = self.tcx.alloc_map.lock().intern_static(cid.instance.def_id());
601 MPlaceTy::from_aligned_ptr(Pointer::from(alloc).with_default_tag(), layout)
604 _ => bug!("eval_place_to_mplace called on {:?}", mir_place),
608 /// Computes a place. You should only use this if you intend to write into this
609 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
612 mir_place: &mir::Place<'tcx>
613 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
614 use rustc::mir::Place::*;
615 use rustc::mir::PlaceBase;
616 let place = match *mir_place {
617 Base(PlaceBase::Local(mir::RETURN_PLACE)) => match self.frame().return_place {
618 Some(return_place) =>
619 // We use our layout to verify our assumption; caller will validate
620 // their layout on return.
622 place: *return_place,
623 layout: self.layout_of(self.monomorphize(self.frame().mir.return_ty())?)?,
625 None => return err!(InvalidNullPointerUsage),
627 Base(PlaceBase::Local(local)) => PlaceTy {
628 // This works even for dead/uninitialized locals; we check further when writing
629 place: Place::Local {
630 frame: self.cur_frame(),
633 layout: self.layout_of_local(self.frame(), local, None)?,
636 Projection(ref proj) => {
637 let place = self.eval_place(&proj.base)?;
638 self.place_projection(place, &proj.elem)?
641 _ => self.eval_place_to_mplace(mir_place)?.into(),
644 self.dump_place(place.place);
648 /// Write a scalar to a place
651 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
652 dest: PlaceTy<'tcx, M::PointerTag>,
653 ) -> EvalResult<'tcx> {
654 self.write_immediate(Immediate::Scalar(val.into()), dest)
657 /// Write an immediate to a place
659 pub fn write_immediate(
661 src: Immediate<M::PointerTag>,
662 dest: PlaceTy<'tcx, M::PointerTag>,
663 ) -> EvalResult<'tcx> {
664 self.write_immediate_no_validate(src, dest)?;
666 if M::enforce_validity(self) {
667 // Data got changed, better make sure it matches the type!
668 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
674 /// Write an immediate to a place.
675 /// If you use this you are responsible for validating that things got copied at the
677 fn write_immediate_no_validate(
679 src: Immediate<M::PointerTag>,
680 dest: PlaceTy<'tcx, M::PointerTag>,
681 ) -> EvalResult<'tcx> {
682 if cfg!(debug_assertions) {
683 // This is a very common path, avoid some checks in release mode
684 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
686 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
687 assert_eq!(self.pointer_size(), dest.layout.size,
688 "Size mismatch when writing pointer"),
689 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Bits { size, .. })) =>
690 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
691 "Size mismatch when writing bits"),
692 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
693 Immediate::ScalarPair(_, _) => {
694 // FIXME: Can we check anything here?
698 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
700 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
701 // but not factored as a separate function.
702 let mplace = match dest.place {
703 Place::Local { frame, local } => {
704 match self.stack[frame].locals[local].access_mut()? {
706 // Local can be updated in-place.
707 *local = LocalValue::Live(Operand::Immediate(src));
711 // The local is in memory, go on below.
716 Place::Ptr(mplace) => mplace, // already referring to memory
718 let dest = MPlaceTy { mplace, layout: dest.layout };
720 // This is already in memory, write there.
721 self.write_immediate_to_mplace_no_validate(src, dest)
724 /// Write an immediate to memory.
725 /// If you use this you are responsible for validating that things git copied at the
727 fn write_immediate_to_mplace_no_validate(
729 value: Immediate<M::PointerTag>,
730 dest: MPlaceTy<'tcx, M::PointerTag>,
731 ) -> EvalResult<'tcx> {
732 let (ptr, ptr_align) = dest.to_scalar_ptr_align();
733 // Note that it is really important that the type here is the right one, and matches the
734 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
735 // to handle padding properly, which is only correct if we never look at this data with the
738 // Nothing to do for ZSTs, other than checking alignment
739 if dest.layout.is_zst() {
740 return self.memory.check_align(ptr, ptr_align);
743 // check for integer pointers before alignment to report better errors
744 let ptr = ptr.to_ptr()?;
745 self.memory.check_align(ptr.into(), ptr_align)?;
746 let tcx = &*self.tcx;
747 // FIXME: We should check that there are dest.layout.size many bytes available in
748 // memory. The code below is not sufficient, with enough padding it might not
749 // cover all the bytes!
751 Immediate::Scalar(scalar) => {
752 match dest.layout.abi {
753 layout::Abi::Scalar(_) => {}, // fine
754 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
757 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
758 tcx, ptr, scalar, dest.layout.size
761 Immediate::ScalarPair(a_val, b_val) => {
762 let (a, b) = match dest.layout.abi {
763 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
764 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
767 let (a_size, b_size) = (a.size(self), b.size(self));
768 let b_offset = a_size.align_to(b.align(self).abi);
769 let b_align = ptr_align.restrict_for_offset(b_offset);
770 let b_ptr = ptr.offset(b_offset, self)?;
772 self.memory.check_align(b_ptr.into(), b_align)?;
774 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
775 // but that does not work: We could be a newtype around a pair, then the
776 // fields do not match the `ScalarPair` components.
779 .get_mut(ptr.alloc_id)?
780 .write_scalar(tcx, ptr, a_val, a_size)?;
782 .get_mut(b_ptr.alloc_id)?
783 .write_scalar(tcx, b_ptr, b_val, b_size)
788 /// Copies the data from an operand to a place. This does not support transmuting!
789 /// Use `copy_op_transmute` if the layouts could disagree.
793 src: OpTy<'tcx, M::PointerTag>,
794 dest: PlaceTy<'tcx, M::PointerTag>,
795 ) -> EvalResult<'tcx> {
796 self.copy_op_no_validate(src, dest)?;
798 if M::enforce_validity(self) {
799 // Data got changed, better make sure it matches the type!
800 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
806 /// Copies the data from an operand to a place. This does not support transmuting!
807 /// Use `copy_op_transmute` if the layouts could disagree.
808 /// Also, if you use this you are responsible for validating that things git copied at the
810 fn copy_op_no_validate(
812 src: OpTy<'tcx, M::PointerTag>,
813 dest: PlaceTy<'tcx, M::PointerTag>,
814 ) -> EvalResult<'tcx> {
815 // We do NOT compare the types for equality, because well-typed code can
816 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
817 assert!(src.layout.details == dest.layout.details,
818 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
820 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
821 let src = match self.try_read_immediate(src)? {
823 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
824 // Yay, we got a value that we can write directly.
825 // FIXME: Add a check to make sure that if `src` is indirect,
826 // it does not overlap with `dest`.
827 return self.write_immediate_no_validate(src_val, dest);
829 Err(mplace) => mplace,
831 // Slow path, this does not fit into an immediate. Just memcpy.
832 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
834 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
835 // is being initialized!
836 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
837 let size = size.unwrap_or_else(|| {
838 assert!(!dest.layout.is_unsized(),
839 "Cannot copy into already initialized unsized place");
842 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
845 dest.ptr, dest.align,
847 /*nonoverlapping*/ true,
853 /// Copies the data from an operand to a place. The layouts may disagree, but they must
854 /// have the same size.
855 pub fn copy_op_transmute(
857 src: OpTy<'tcx, M::PointerTag>,
858 dest: PlaceTy<'tcx, M::PointerTag>,
859 ) -> EvalResult<'tcx> {
860 if src.layout.details == dest.layout.details {
861 // Fast path: Just use normal `copy_op`
862 return self.copy_op(src, dest);
864 // We still require the sizes to match.
865 assert!(src.layout.size == dest.layout.size,
866 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
867 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
868 // to avoid that here.
869 assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
870 "Cannot transmute unsized data");
872 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
873 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
874 // We have to write them to `dest` at the offsets they were *read at*, which is
875 // not necessarily the same as the offsets in `dest.layout`!
876 // Hence we do the copy with the source layout on both sides. We also make sure to write
877 // into memory, because if `dest` is a local we would not even have a way to write
878 // at the `src` offsets; the fact that we came from a different layout would
880 let dest = self.force_allocation(dest)?;
881 self.copy_op_no_validate(
883 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
886 if M::enforce_validity(self) {
887 // Data got changed, better make sure it matches the type!
888 self.validate_operand(dest.into(), vec![], None, /*const_mode*/false)?;
894 /// Ensures that a place is in memory, and returns where it is.
895 /// If the place currently refers to a local that doesn't yet have a matching allocation,
896 /// create such an allocation.
897 /// This is essentially `force_to_memplace`.
899 /// This supports unsized types and returns the computed size to avoid some
900 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
902 pub fn force_allocation_maybe_sized(
904 place: PlaceTy<'tcx, M::PointerTag>,
905 meta: Option<Scalar<M::PointerTag>>,
906 ) -> EvalResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
907 let (mplace, size) = match place.place {
908 Place::Local { frame, local } => {
909 match self.stack[frame].locals[local].access_mut()? {
911 // We need to make an allocation.
912 // FIXME: Consider not doing anything for a ZST, and just returning
913 // a fake pointer? Are we even called for ZST?
915 // We cannot hold on to the reference `local_val` while allocating,
916 // but we can hold on to the value in there.
918 if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
924 // We need the layout of the local. We can NOT use the layout we got,
925 // that might e.g., be an inner field of a struct with `Scalar` layout,
926 // that has different alignment than the outer field.
927 // We also need to support unsized types, and hence cannot use `allocate`.
928 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
929 let (size, align) = self.size_and_align_of(meta, local_layout)?
930 .expect("Cannot allocate for non-dyn-sized type");
931 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
932 let mplace = MemPlace { ptr: ptr.into(), align, meta };
933 if let Some(value) = old_val {
934 // Preserve old value.
935 // We don't have to validate as we can assume the local
936 // was already valid for its type.
937 let mplace = MPlaceTy { mplace, layout: local_layout };
938 self.write_immediate_to_mplace_no_validate(value, mplace)?;
940 // Now we can call `access_mut` again, asserting it goes well,
941 // and actually overwrite things.
942 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
943 LocalValue::Live(Operand::Indirect(mplace));
946 Err(mplace) => (mplace, None), // this already was an indirect local
949 Place::Ptr(mplace) => (mplace, None)
951 // Return with the original layout, so that the caller can go on
952 Ok((MPlaceTy { mplace, layout: place.layout }, size))
956 pub fn force_allocation(
958 place: PlaceTy<'tcx, M::PointerTag>,
959 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
960 Ok(self.force_allocation_maybe_sized(place, None)?.0)
965 layout: TyLayout<'tcx>,
966 kind: MemoryKind<M::MemoryKinds>,
967 ) -> MPlaceTy<'tcx, M::PointerTag> {
968 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
969 MPlaceTy::from_aligned_ptr(ptr, layout)
972 pub fn write_discriminant_index(
974 variant_index: VariantIdx,
975 dest: PlaceTy<'tcx, M::PointerTag>,
976 ) -> EvalResult<'tcx> {
977 match dest.layout.variants {
978 layout::Variants::Single { index } => {
979 assert_eq!(index, variant_index);
981 layout::Variants::Multiple {
982 discr_kind: layout::DiscriminantKind::Tag,
987 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
989 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
991 // raw discriminants for enums are isize or bigger during
992 // their computation, but the in-memory tag is the smallest possible
994 let size = discr.value.size(self);
995 let discr_val = truncate(discr_val, size);
997 let discr_dest = self.place_field(dest, discr_index as u64)?;
998 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1000 layout::Variants::Multiple {
1001 discr_kind: layout::DiscriminantKind::Niche {
1010 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1012 if variant_index != dataful_variant {
1014 self.place_field(dest, discr_index as u64)?;
1015 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1016 let niche_value = (niche_value as u128)
1017 .wrapping_add(niche_start);
1019 Scalar::from_uint(niche_value, niche_dest.layout.size),
1029 pub fn raw_const_to_mplace(
1031 raw: RawConst<'tcx>,
1032 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1033 // This must be an allocation in `tcx`
1034 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1035 let layout = self.layout_of(raw.ty)?;
1036 Ok(MPlaceTy::from_aligned_ptr(
1037 Pointer::new(raw.alloc_id, Size::ZERO).with_default_tag(),
1042 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1043 /// Also return some more information so drop doesn't have to run the same code twice.
1044 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1045 -> EvalResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1046 let vtable = mplace.vtable()?; // also sanity checks the type
1047 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1048 let layout = self.layout_of(ty)?;
1050 // More sanity checks
1051 if cfg!(debug_assertions) {
1052 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1053 assert_eq!(size, layout.size);
1054 // only ABI alignment is preserved
1055 assert_eq!(align, layout.align.abi);
1058 let mplace = MPlaceTy {
1059 mplace: MemPlace { meta: None, ..*mplace },
1062 Ok((instance, mplace))