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 EvalContext, Machine, AllocMap, AllocationExtra,
18 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind
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),
88 pub fn with_default_tag<Tag>(self) -> MemPlace<Tag>
92 ptr: self.ptr.with_default_tag(),
94 meta: self.meta.map(Scalar::with_default_tag),
99 impl<Tag> MemPlace<Tag> {
101 pub fn erase_tag(self) -> MemPlace
104 ptr: self.ptr.erase_tag(),
106 meta: self.meta.map(Scalar::erase_tag),
111 pub fn with_tag(self, new_tag: Tag) -> Self
114 ptr: self.ptr.with_tag(new_tag),
121 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
129 /// Produces a Place that will error if attempted to be read from or written to
131 pub fn null(cx: &impl HasDataLayout) -> Self {
132 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
136 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
137 Self::from_scalar_ptr(ptr.into(), align)
141 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
142 assert!(self.meta.is_none());
143 (self.ptr, self.align)
146 /// metact the ptr part of the mplace
148 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
149 // At this point, we forget about the alignment information --
150 // the place has been turned into a reference, and no matter where it came from,
151 // it now must be aligned.
152 self.to_scalar_ptr_align().0.to_ptr()
155 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
156 /// This is the inverse of `ref_to_mplace`.
158 pub fn to_ref(self) -> Immediate<Tag> {
160 None => Immediate::Scalar(self.ptr.into()),
161 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
168 meta: Option<Scalar<Tag>>,
169 cx: &impl HasDataLayout,
170 ) -> EvalResult<'tcx, Self> {
172 ptr: self.ptr.ptr_offset(offset, cx)?,
173 align: self.align.restrict_for_offset(offset),
179 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
180 /// Produces a MemPlace that works for ZST but nothing else
182 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
184 mplace: MemPlace::from_scalar_ptr(
185 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
193 pub fn with_tag(self, new_tag: Tag) -> Self
196 mplace: self.mplace.with_tag(new_tag),
205 meta: Option<Scalar<Tag>>,
206 layout: TyLayout<'tcx>,
207 cx: &impl HasDataLayout,
208 ) -> EvalResult<'tcx, Self> {
210 mplace: self.mplace.offset(offset, meta, cx)?,
216 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
217 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
221 pub(super) fn len(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
222 if self.layout.is_unsized() {
223 // We need to consult `meta` metadata
224 match self.layout.ty.sty {
225 ty::Slice(..) | ty::Str =>
226 return self.mplace.meta.unwrap().to_usize(cx),
227 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
230 // Go through the layout. There are lots of types that support a length,
232 match self.layout.fields {
233 layout::FieldPlacement::Array { count, .. } => Ok(count),
234 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
240 pub(super) fn vtable(self) -> EvalResult<'tcx, Pointer<Tag>> {
241 match self.layout.ty.sty {
242 ty::Dynamic(..) => self.mplace.meta.unwrap().to_ptr(),
243 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
248 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
250 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, Immediate<Tag>> {
252 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
253 Operand::Immediate(imm) => Err(imm),
258 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
259 self.try_as_mplace().unwrap()
263 impl<'tcx, Tag: ::std::fmt::Debug> Place<Tag> {
264 /// Produces a Place that will error if attempted to be read from or written to
266 pub fn null(cx: &impl HasDataLayout) -> Self {
267 Place::Ptr(MemPlace::null(cx))
271 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
272 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
276 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
277 Place::Ptr(MemPlace::from_ptr(ptr, align))
281 pub fn to_mem_place(self) -> MemPlace<Tag> {
283 Place::Ptr(mplace) => mplace,
284 _ => bug!("to_mem_place: expected Place::Ptr, got {:?}", self),
290 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
291 self.to_mem_place().to_scalar_ptr_align()
295 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
296 self.to_mem_place().to_ptr()
300 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
302 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
303 MPlaceTy { mplace: self.place.to_mem_place(), layout: self.layout }
307 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
308 impl<'a, 'mir, 'tcx, Tag, M> EvalContext<'a, 'mir, 'tcx, M>
310 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
311 Tag: ::std::fmt::Debug+Default+Copy+Eq+Hash+'static,
312 M: Machine<'a, 'mir, 'tcx, PointerTag=Tag>,
313 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
314 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
315 M::AllocExtra: AllocationExtra<Tag, M::MemoryExtra>,
317 /// Take a value, which represents a (thin or fat) reference, and make it a place.
318 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
319 /// This does NOT call the "deref" machine hook, so it does NOT count as a
320 /// deref as far as Stacked Borrows is concerned. Use `deref_operand` for that!
321 pub fn ref_to_mplace(
323 val: ImmTy<'tcx, M::PointerTag>,
324 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
325 let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
326 let layout = self.layout_of(pointee_type)?;
328 let mplace = MemPlace {
329 ptr: val.to_scalar_ptr()?,
330 // We could use the run-time alignment here. For now, we do not, because
331 // the point of tracking the alignment here is to make sure that the *static*
332 // alignment information emitted with the loads is correct. The run-time
333 // alignment can only be more restrictive.
334 align: layout.align.abi,
335 meta: val.to_meta()?,
337 Ok(MPlaceTy { mplace, layout })
340 // Take an operand, representing a pointer, and dereference it to a place -- that
341 // will always be a MemPlace. Lives in `place.rs` because it creates a place.
342 // This calls the "deref" machine hook, and counts as a deref as far as
343 // Stacked Borrows is concerned.
344 pub fn deref_operand(
346 src: OpTy<'tcx, M::PointerTag>,
347 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
348 let val = self.read_immediate(src)?;
349 trace!("deref to {} on {:?}", val.layout.ty, *val);
350 let mut place = self.ref_to_mplace(val)?;
351 // Pointer tag tracking might want to adjust the tag.
352 let mutbl = match val.layout.ty.sty {
353 // `builtin_deref` considers boxes immutable, that's useless for our purposes
354 ty::Ref(_, _, mutbl) => Some(mutbl),
355 ty::Adt(def, _) if def.is_box() => Some(hir::MutMutable),
356 ty::RawPtr(_) => None,
357 _ => bug!("Unexpected pointer type {}", val.layout.ty),
359 place.mplace.ptr = M::tag_dereference(self, place, mutbl)?;
363 /// Offset a pointer to project to a field. Unlike place_field, this is always
364 /// possible without allocating, so it can take &self. Also return the field's layout.
365 /// This supports both struct and array fields.
369 base: MPlaceTy<'tcx, M::PointerTag>,
371 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
372 // Not using the layout method because we want to compute on u64
373 let offset = match base.layout.fields {
374 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
375 offsets[usize::try_from(field).unwrap()],
376 layout::FieldPlacement::Array { stride, .. } => {
377 let len = base.len(self)?;
378 assert!(field < len, "Tried to access element {} of array/slice with length {}",
382 layout::FieldPlacement::Union(count) => {
383 assert!(field < count as u64,
384 "Tried to access field {} of union with {} fields", field, count);
385 // Offset is always 0
389 // the only way conversion can fail if is this is an array (otherwise we already panicked
390 // above). In that case, all fields are equal.
391 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
393 // Offset may need adjustment for unsized fields.
394 let (meta, offset) = if field_layout.is_unsized() {
395 // Re-use parent metadata to determine dynamic field layout.
396 // With custom DSTS, this *will* execute user-defined code, but the same
397 // happens at run-time so that's okay.
398 let align = match self.size_and_align_of(base.meta, field_layout)? {
399 Some((_, align)) => align,
400 None if offset == Size::ZERO =>
401 // An extern type at offset 0, we fall back to its static alignment.
402 // FIXME: Once we have made decisions for how to handle size and alignment
403 // of `extern type`, this should be adapted. It is just a temporary hack
404 // to get some code to work that probably ought to work.
405 field_layout.align.abi,
407 bug!("Cannot compute offset for extern type field at non-0 offset"),
409 (base.meta, offset.align_to(align))
411 // base.meta could be present; we might be accessing a sized field of an unsized
416 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
417 // codegen -- mostly to see if we can get away with that
418 base.offset(offset, meta, field_layout, self)
421 // Iterates over all fields of an array. Much more efficient than doing the
422 // same by repeatedly calling `mplace_array`.
423 pub fn mplace_array_fields(
425 base: MPlaceTy<'tcx, Tag>,
427 EvalResult<'tcx, impl Iterator<Item=EvalResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
429 let len = base.len(self)?; // also asserts that we have a type where this makes sense
430 let stride = match base.layout.fields {
431 layout::FieldPlacement::Array { stride, .. } => stride,
432 _ => bug!("mplace_array_fields: expected an array layout"),
434 let layout = base.layout.field(self, 0)?;
435 let dl = &self.tcx.data_layout;
436 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
439 pub fn mplace_subslice(
441 base: MPlaceTy<'tcx, M::PointerTag>,
444 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
445 let len = base.len(self)?; // also asserts that we have a type where this makes sense
446 assert!(from <= len - to);
448 // Not using layout method because that works with usize, and does not work with slices
449 // (that have count 0 in their layout).
450 let from_offset = match base.layout.fields {
451 layout::FieldPlacement::Array { stride, .. } =>
453 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
456 // Compute meta and new layout
457 let inner_len = len - to - from;
458 let (meta, ty) = match base.layout.ty.sty {
459 // It is not nice to match on the type, but that seems to be the only way to
461 ty::Array(inner, _) =>
462 (None, self.tcx.mk_array(inner, inner_len)),
464 let len = Scalar::from_uint(inner_len, self.pointer_size());
465 (Some(len), base.layout.ty)
468 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
470 let layout = self.layout_of(ty)?;
471 base.offset(from_offset, meta, layout, self)
474 pub fn mplace_downcast(
476 base: MPlaceTy<'tcx, M::PointerTag>,
478 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
479 // Downcasts only change the layout
480 assert!(base.meta.is_none());
481 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
484 /// Project into an mplace
485 pub fn mplace_projection(
487 base: MPlaceTy<'tcx, M::PointerTag>,
488 proj_elem: &mir::PlaceElem<'tcx>,
489 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
490 use rustc::mir::ProjectionElem::*;
491 Ok(match *proj_elem {
492 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
493 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
494 Deref => self.deref_operand(base.into())?,
497 let layout = self.layout_of(self.tcx.types.usize)?;
498 let n = self.access_local(self.frame(), local, Some(layout))?;
499 let n = self.read_scalar(n)?;
500 let n = n.to_bits(self.tcx.data_layout.pointer_size)?;
501 self.mplace_field(base, u64::try_from(n).unwrap())?
509 let n = base.len(self)?;
510 assert!(n >= min_length as u64);
512 let index = if from_end {
513 n - u64::from(offset)
518 self.mplace_field(base, index)?
521 Subslice { from, to } =>
522 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
526 /// Gets the place of a field inside the place, and also the field's type.
527 /// Just a convenience function, but used quite a bit.
528 /// This is the only projection that might have a side-effect: We cannot project
529 /// into the field of a local `ScalarPair`, we have to first allocate it.
532 base: PlaceTy<'tcx, M::PointerTag>,
534 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
535 // FIXME: We could try to be smarter and avoid allocation for fields that span the
537 let mplace = self.force_allocation(base)?;
538 Ok(self.mplace_field(mplace, field)?.into())
541 pub fn place_downcast(
543 base: PlaceTy<'tcx, M::PointerTag>,
545 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
546 // Downcast just changes the layout
547 Ok(match base.place {
548 Place::Ptr(mplace) =>
549 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
550 Place::Local { .. } => {
551 let layout = base.layout.for_variant(self, variant);
552 PlaceTy { layout, ..base }
557 /// Projects into a place.
558 pub fn place_projection(
560 base: PlaceTy<'tcx, M::PointerTag>,
561 proj_elem: &mir::ProjectionElem<'tcx, mir::Local, Ty<'tcx>>,
562 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
563 use rustc::mir::ProjectionElem::*;
564 Ok(match *proj_elem {
565 Field(field, _) => self.place_field(base, field.index() as u64)?,
566 Downcast(_, variant) => self.place_downcast(base, variant)?,
567 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
568 // For the other variants, we have to force an allocation.
569 // This matches `operand_projection`.
570 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
571 let mplace = self.force_allocation(base)?;
572 self.mplace_projection(mplace, proj_elem)?.into()
577 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
578 /// `eval_place` and `eval_place_to_op`.
579 pub(super) fn eval_place_to_mplace(
581 mir_place: &mir::Place<'tcx>
582 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
583 use rustc::mir::Place::*;
584 use rustc::mir::PlaceBase;
585 use rustc::mir::{Static, StaticKind};
586 Ok(match *mir_place {
587 Base(PlaceBase::Static(box Static { kind: StaticKind::Promoted(promoted), .. })) => {
588 let instance = self.frame().instance;
589 self.const_eval_raw(GlobalId {
591 promoted: Some(promoted),
595 Base(PlaceBase::Static(box Static { kind: StaticKind::Static(def_id), ty })) => {
596 assert!(!ty.needs_subst());
597 let layout = self.layout_of(ty)?;
598 let instance = ty::Instance::mono(*self.tcx, def_id);
603 // Just create a lazy reference, so we can support recursive statics.
604 // tcx takes are of assigning every static one and only one unique AllocId.
605 // When the data here is ever actually used, memory will notice,
606 // and it knows how to deal with alloc_id that are present in the
607 // global table but not in its local memory: It calls back into tcx through
608 // a query, triggering the CTFE machinery to actually turn this lazy reference
609 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
610 // this EvalContext uses another Machine (e.g., in miri). This is what we
611 // want! This way, computing statics works concistently between codegen
612 // and miri: They use the same query to eventually obtain a `ty::Const`
613 // and use that for further computation.
614 let alloc = self.tcx.alloc_map.lock().intern_static(cid.instance.def_id());
615 MPlaceTy::from_aligned_ptr(Pointer::from(alloc).with_default_tag(), layout)
618 _ => bug!("eval_place_to_mplace called on {:?}", mir_place),
622 /// Computes a place. You should only use this if you intend to write into this
623 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
626 mir_place: &mir::Place<'tcx>
627 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
628 use rustc::mir::Place::*;
629 use rustc::mir::PlaceBase;
630 let place = match *mir_place {
631 Base(PlaceBase::Local(mir::RETURN_PLACE)) => match self.frame().return_place {
632 Some(return_place) =>
633 // We use our layout to verify our assumption; caller will validate
634 // their layout on return.
636 place: *return_place,
637 layout: self.layout_of(self.monomorphize(self.frame().mir.return_ty())?)?,
639 None => return err!(InvalidNullPointerUsage),
641 Base(PlaceBase::Local(local)) => PlaceTy {
642 place: Place::Local {
643 frame: self.cur_frame(),
646 layout: self.layout_of_local(self.frame(), local, None)?,
649 Projection(ref proj) => {
650 let place = self.eval_place(&proj.base)?;
651 self.place_projection(place, &proj.elem)?
654 _ => self.eval_place_to_mplace(mir_place)?.into(),
657 self.dump_place(place.place);
661 /// Write a scalar to a place
664 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
665 dest: PlaceTy<'tcx, M::PointerTag>,
666 ) -> EvalResult<'tcx> {
667 self.write_immediate(Immediate::Scalar(val.into()), dest)
670 /// Write an immediate to a place
672 pub fn write_immediate(
674 src: Immediate<M::PointerTag>,
675 dest: PlaceTy<'tcx, M::PointerTag>,
676 ) -> EvalResult<'tcx> {
677 self.write_immediate_no_validate(src, dest)?;
679 if M::enforce_validity(self) {
680 // Data got changed, better make sure it matches the type!
681 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
687 /// Write an immediate to a place.
688 /// If you use this you are responsible for validating that things got copied at the
690 fn write_immediate_no_validate(
692 src: Immediate<M::PointerTag>,
693 dest: PlaceTy<'tcx, M::PointerTag>,
694 ) -> EvalResult<'tcx> {
695 if cfg!(debug_assertions) {
696 // This is a very common path, avoid some checks in release mode
697 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
699 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
700 assert_eq!(self.pointer_size(), dest.layout.size,
701 "Size mismatch when writing pointer"),
702 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Bits { size, .. })) =>
703 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
704 "Size mismatch when writing bits"),
705 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
706 Immediate::ScalarPair(_, _) => {
707 // FIXME: Can we check anything here?
711 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
713 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
714 // but not factored as a separate function.
715 let mplace = match dest.place {
716 Place::Local { frame, local } => {
717 match *self.stack[frame].locals[local].access_mut()? {
718 Operand::Immediate(ref mut dest_val) => {
719 // Yay, we can just change the local directly.
723 Operand::Indirect(mplace) => mplace, // already in memory
726 Place::Ptr(mplace) => mplace, // already in memory
728 let dest = MPlaceTy { mplace, layout: dest.layout };
730 // This is already in memory, write there.
731 self.write_immediate_to_mplace_no_validate(src, dest)
734 /// Write an immediate to memory.
735 /// If you use this you are responsible for validating that things git copied at the
737 fn write_immediate_to_mplace_no_validate(
739 value: Immediate<M::PointerTag>,
740 dest: MPlaceTy<'tcx, M::PointerTag>,
741 ) -> EvalResult<'tcx> {
742 let (ptr, ptr_align) = dest.to_scalar_ptr_align();
743 // Note that it is really important that the type here is the right one, and matches the
744 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
745 // to handle padding properly, which is only correct if we never look at this data with the
748 // Nothing to do for ZSTs, other than checking alignment
749 if dest.layout.is_zst() {
750 return self.memory.check_align(ptr, ptr_align);
753 // check for integer pointers before alignment to report better errors
754 let ptr = ptr.to_ptr()?;
755 self.memory.check_align(ptr.into(), ptr_align)?;
756 let tcx = &*self.tcx;
757 // FIXME: We should check that there are dest.layout.size many bytes available in
758 // memory. The code below is not sufficient, with enough padding it might not
759 // cover all the bytes!
761 Immediate::Scalar(scalar) => {
762 match dest.layout.abi {
763 layout::Abi::Scalar(_) => {}, // fine
764 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
767 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
768 tcx, ptr, scalar, dest.layout.size
771 Immediate::ScalarPair(a_val, b_val) => {
772 let (a, b) = match dest.layout.abi {
773 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
774 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
777 let (a_size, b_size) = (a.size(self), b.size(self));
778 let b_offset = a_size.align_to(b.align(self).abi);
779 let b_align = ptr_align.restrict_for_offset(b_offset);
780 let b_ptr = ptr.offset(b_offset, self)?;
782 self.memory.check_align(b_ptr.into(), b_align)?;
784 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
785 // but that does not work: We could be a newtype around a pair, then the
786 // fields do not match the `ScalarPair` components.
789 .get_mut(ptr.alloc_id)?
790 .write_scalar(tcx, ptr, a_val, a_size)?;
792 .get_mut(b_ptr.alloc_id)?
793 .write_scalar(tcx, b_ptr, b_val, b_size)
798 /// Copies the data from an operand to a place. This does not support transmuting!
799 /// Use `copy_op_transmute` if the layouts could disagree.
803 src: OpTy<'tcx, M::PointerTag>,
804 dest: PlaceTy<'tcx, M::PointerTag>,
805 ) -> EvalResult<'tcx> {
806 self.copy_op_no_validate(src, dest)?;
808 if M::enforce_validity(self) {
809 // Data got changed, better make sure it matches the type!
810 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
816 /// Copies the data from an operand to a place. This does not support transmuting!
817 /// Use `copy_op_transmute` if the layouts could disagree.
818 /// Also, if you use this you are responsible for validating that things git copied at the
820 fn copy_op_no_validate(
822 src: OpTy<'tcx, M::PointerTag>,
823 dest: PlaceTy<'tcx, M::PointerTag>,
824 ) -> EvalResult<'tcx> {
825 debug_assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
826 "Cannot copy unsized data");
827 // We do NOT compare the types for equality, because well-typed code can
828 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
829 assert!(src.layout.details == dest.layout.details,
830 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
832 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
833 let src = match self.try_read_immediate(src)? {
835 // Yay, we got a value that we can write directly.
836 // FIXME: Add a check to make sure that if `src` is indirect,
837 // it does not overlap with `dest`.
838 return self.write_immediate_no_validate(src_val, dest);
840 Err(mplace) => mplace,
842 // Slow path, this does not fit into an immediate. Just memcpy.
843 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
845 let dest = self.force_allocation(dest)?;
846 let (src_ptr, src_align) = src.to_scalar_ptr_align();
847 let (dest_ptr, dest_align) = dest.to_scalar_ptr_align();
850 dest_ptr, dest_align,
852 /*nonoverlapping*/ true,
858 /// Copies the data from an operand to a place. The layouts may disagree, but they must
859 /// have the same size.
860 pub fn copy_op_transmute(
862 src: OpTy<'tcx, M::PointerTag>,
863 dest: PlaceTy<'tcx, M::PointerTag>,
864 ) -> EvalResult<'tcx> {
865 if src.layout.details == dest.layout.details {
866 // Fast path: Just use normal `copy_op`
867 return self.copy_op(src, dest);
869 // We still require the sizes to match
870 debug_assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
871 "Cannot copy unsized data");
872 assert!(src.layout.size == dest.layout.size,
873 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
875 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
876 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
877 // We have to write them to `dest` at the offsets they were *read at*, which is
878 // not necessarily the same as the offsets in `dest.layout`!
879 // Hence we do the copy with the source layout on both sides. We also make sure to write
880 // into memory, because if `dest` is a local we would not even have a way to write
881 // at the `src` offsets; the fact that we came from a different layout would
883 let dest = self.force_allocation(dest)?;
884 self.copy_op_no_validate(
886 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
889 if M::enforce_validity(self) {
890 // Data got changed, better make sure it matches the type!
891 self.validate_operand(dest.into(), vec![], None, /*const_mode*/false)?;
897 /// Ensures that a place is in memory, and returns where it is.
898 /// If the place currently refers to a local that doesn't yet have a matching allocation,
899 /// create such an allocation.
900 /// This is essentially `force_to_memplace`.
901 pub fn force_allocation(
903 place: PlaceTy<'tcx, M::PointerTag>,
904 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
905 let mplace = match place.place {
906 Place::Local { frame, local } => {
907 match *self.stack[frame].locals[local].access()? {
908 Operand::Indirect(mplace) => mplace,
909 Operand::Immediate(value) => {
910 // We need to make an allocation.
911 // FIXME: Consider not doing anything for a ZST, and just returning
912 // a fake pointer? Are we even called for ZST?
914 // We need the layout of the local. We can NOT use the layout we got,
915 // that might e.g., be an inner field of a struct with `Scalar` layout,
916 // that has different alignment than the outer field.
917 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
918 let ptr = self.allocate(local_layout, MemoryKind::Stack);
919 // We don't have to validate as we can assume the local
920 // was already valid for its type.
921 self.write_immediate_to_mplace_no_validate(value, ptr)?;
922 let mplace = ptr.mplace;
924 *self.stack[frame].locals[local].access_mut()? =
925 Operand::Indirect(mplace);
930 Place::Ptr(mplace) => mplace
932 // Return with the original layout, so that the caller can go on
933 Ok(MPlaceTy { mplace, layout: place.layout })
938 layout: TyLayout<'tcx>,
939 kind: MemoryKind<M::MemoryKinds>,
940 ) -> MPlaceTy<'tcx, M::PointerTag> {
941 if layout.is_unsized() {
942 assert!(self.tcx.features().unsized_locals, "cannot alloc memory for unsized type");
943 // FIXME: What should we do here? We should definitely also tag!
944 MPlaceTy::dangling(layout, self)
946 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
947 let ptr = M::tag_new_allocation(self, ptr, kind);
948 MPlaceTy::from_aligned_ptr(ptr, layout)
952 pub fn write_discriminant_index(
954 variant_index: VariantIdx,
955 dest: PlaceTy<'tcx, M::PointerTag>,
956 ) -> EvalResult<'tcx> {
957 match dest.layout.variants {
958 layout::Variants::Single { index } => {
959 assert_eq!(index, variant_index);
961 layout::Variants::Tagged { ref tag, .. } => {
962 let adt_def = dest.layout.ty.ty_adt_def().unwrap();
963 assert!(variant_index.as_usize() < adt_def.variants.len());
964 let discr_val = adt_def
965 .discriminant_for_variant(*self.tcx, variant_index)
968 // raw discriminants for enums are isize or bigger during
969 // their computation, but the in-memory tag is the smallest possible
971 let size = tag.value.size(self);
972 let discr_val = truncate(discr_val, size);
974 let discr_dest = self.place_field(dest, 0)?;
975 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
977 layout::Variants::NicheFilling {
984 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
986 if variant_index != dataful_variant {
988 self.place_field(dest, 0)?;
989 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
990 let niche_value = (niche_value as u128)
991 .wrapping_add(niche_start);
993 Scalar::from_uint(niche_value, niche_dest.layout.size),
1003 pub fn raw_const_to_mplace(
1005 raw: RawConst<'tcx>,
1006 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1007 // This must be an allocation in `tcx`
1008 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1009 let layout = self.layout_of(raw.ty)?;
1010 Ok(MPlaceTy::from_aligned_ptr(
1011 Pointer::new(raw.alloc_id, Size::ZERO).with_default_tag(),
1016 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1017 /// Also return some more information so drop doesn't have to run the same code twice.
1018 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1019 -> EvalResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1020 let vtable = mplace.vtable()?; // also sanity checks the type
1021 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1022 let layout = self.layout_of(ty)?;
1024 // More sanity checks
1025 if cfg!(debug_assertions) {
1026 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1027 assert_eq!(size, layout.size);
1028 // only ABI alignment is preserved
1029 assert_eq!(align, layout.align.abi);
1032 let mplace = MPlaceTy {
1033 mplace: MemPlace { meta: None, ..*mplace },
1036 Ok((instance, mplace))