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;
9 use rustc::mir::interpret::truncate;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
12 use rustc::ty::TypeFoldable;
15 GlobalId, AllocId, Allocation, Scalar, InterpResult, Pointer, PointerArithmetic,
16 InterpCx, Machine, AllocMap, AllocationExtra,
17 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue,
20 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
21 pub struct MemPlace<Tag=(), Id=AllocId> {
22 /// A place may have an integral pointer for ZSTs, and since it might
23 /// be turned back into a reference before ever being dereferenced.
24 /// However, it may never be undef.
25 pub ptr: Scalar<Tag, Id>,
27 /// Metadata for unsized places. Interpretation is up to the type.
28 /// Must not be present for sized types, but can be missing for unsized types
29 /// (e.g., `extern type`).
30 pub meta: Option<Scalar<Tag, Id>>,
33 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
34 pub enum Place<Tag=(), Id=AllocId> {
35 /// A place referring to a value allocated in the `Memory` system.
36 Ptr(MemPlace<Tag, Id>),
38 /// To support alloc-free locals, we are able to write directly to a local.
39 /// (Without that optimization, we'd just always be a `MemPlace`.)
46 #[derive(Copy, Clone, Debug)]
47 pub struct PlaceTy<'tcx, Tag=()> {
48 place: Place<Tag>, // Keep this private, it helps enforce invariants
49 pub layout: TyLayout<'tcx>,
52 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
53 type Target = Place<Tag>;
55 fn deref(&self) -> &Place<Tag> {
60 /// A MemPlace with its layout. Constructing it is only possible in this module.
61 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
62 pub struct MPlaceTy<'tcx, Tag=()> {
63 mplace: MemPlace<Tag>,
64 pub layout: TyLayout<'tcx>,
67 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
68 type Target = MemPlace<Tag>;
70 fn deref(&self) -> &MemPlace<Tag> {
75 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
77 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
79 place: Place::Ptr(mplace.mplace),
85 impl<Tag> MemPlace<Tag> {
86 /// Replace ptr tag, maintain vtable tag (if any)
88 pub fn replace_tag(self, new_tag: Tag) -> Self {
90 ptr: self.ptr.erase_tag().with_tag(new_tag),
97 pub fn erase_tag(self) -> MemPlace {
99 ptr: self.ptr.erase_tag(),
101 meta: self.meta.map(Scalar::erase_tag),
106 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
114 /// Produces a Place that will error if attempted to be read from or written to
116 pub fn null(cx: &impl HasDataLayout) -> Self {
117 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
121 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
122 Self::from_scalar_ptr(ptr.into(), align)
125 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
126 /// This is the inverse of `ref_to_mplace`.
128 pub fn to_ref(self) -> Immediate<Tag> {
130 None => Immediate::Scalar(self.ptr.into()),
131 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
138 meta: Option<Scalar<Tag>>,
139 cx: &impl HasDataLayout,
140 ) -> InterpResult<'tcx, Self> {
142 ptr: self.ptr.ptr_offset(offset, cx)?,
143 align: self.align.restrict_for_offset(offset),
149 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
150 /// Produces a MemPlace that works for ZST but nothing else
152 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
154 mplace: MemPlace::from_scalar_ptr(
155 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
162 /// Replace ptr tag, maintain vtable tag (if any)
164 pub fn replace_tag(self, new_tag: Tag) -> Self {
166 mplace: self.mplace.replace_tag(new_tag),
175 meta: Option<Scalar<Tag>>,
176 layout: TyLayout<'tcx>,
177 cx: &impl HasDataLayout,
178 ) -> InterpResult<'tcx, Self> {
180 mplace: self.mplace.offset(offset, meta, cx)?,
186 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
187 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
191 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
192 if self.layout.is_unsized() {
193 // We need to consult `meta` metadata
194 match self.layout.ty.sty {
195 ty::Slice(..) | ty::Str =>
196 return self.mplace.meta.unwrap().to_usize(cx),
197 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
200 // Go through the layout. There are lots of types that support a length,
202 match self.layout.fields {
203 layout::FieldPlacement::Array { count, .. } => Ok(count),
204 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
210 pub(super) fn vtable(self) -> Scalar<Tag> {
211 match self.layout.ty.sty {
212 ty::Dynamic(..) => self.mplace.meta.unwrap(),
213 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
218 // These are defined here because they produce a place.
219 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
221 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
223 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
224 Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
229 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
230 self.try_as_mplace().unwrap()
234 impl<Tag: ::std::fmt::Debug> Place<Tag> {
235 /// Produces a Place that will error if attempted to be read from or written to
237 pub fn null(cx: &impl HasDataLayout) -> Self {
238 Place::Ptr(MemPlace::null(cx))
242 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
243 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
247 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
248 Place::Ptr(MemPlace::from_ptr(ptr, align))
252 pub fn assert_mem_place(self) -> MemPlace<Tag> {
254 Place::Ptr(mplace) => mplace,
255 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
261 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
263 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
264 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
268 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
269 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
271 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
272 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
273 M: Machine<'mir, 'tcx, PointerTag = Tag>,
274 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
275 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
276 M::AllocExtra: AllocationExtra<Tag>,
278 /// Take a value, which represents a (thin or fat) reference, and make it a place.
279 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
281 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
282 /// want to ever use the place for memory access!
283 /// Generally prefer `deref_operand`.
284 pub fn ref_to_mplace(
286 val: ImmTy<'tcx, M::PointerTag>,
287 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
288 let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
289 let layout = self.layout_of(pointee_type)?;
291 let mplace = MemPlace {
292 ptr: val.to_scalar_ptr()?,
293 // We could use the run-time alignment here. For now, we do not, because
294 // the point of tracking the alignment here is to make sure that the *static*
295 // alignment information emitted with the loads is correct. The run-time
296 // alignment can only be more restrictive.
297 align: layout.align.abi,
298 meta: val.to_meta()?,
300 Ok(MPlaceTy { mplace, layout })
303 /// Take an operand, representing a pointer, and dereference it to a place -- that
304 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
305 pub fn deref_operand(
307 src: OpTy<'tcx, M::PointerTag>,
308 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
309 let val = self.read_immediate(src)?;
310 trace!("deref to {} on {:?}", val.layout.ty, *val);
311 let place = self.ref_to_mplace(val)?;
312 self.mplace_access_checked(place)
315 /// Check if the given place is good for memory access with the given
316 /// size, falling back to the layout's size if `None` (in the latter case,
317 /// this must be a statically sized type).
319 /// On success, returns `None` for zero-sized accesses (where nothing else is
320 /// left to do) and a `Pointer` to use for the actual access otherwise.
322 pub fn check_mplace_access(
324 place: MPlaceTy<'tcx, M::PointerTag>,
326 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
327 let size = size.unwrap_or_else(|| {
328 assert!(!place.layout.is_unsized());
329 assert!(place.meta.is_none());
332 self.memory.check_ptr_access(place.ptr, size, place.align)
335 /// Return the "access-checked" version of this `MPlace`, where for non-ZST
336 /// this is definitely a `Pointer`.
337 pub fn mplace_access_checked(
339 mut place: MPlaceTy<'tcx, M::PointerTag>,
340 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
341 let (size, align) = self.size_and_align_of_mplace(place)?
342 .unwrap_or((place.layout.size, place.layout.align.abi));
343 assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
344 place.mplace.align = align; // maximally strict checking
345 // When dereferencing a pointer, it must be non-NULL, aligned, and live.
346 if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
347 place.mplace.ptr = ptr.into();
352 /// Force `place.ptr` to a `Pointer`.
353 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
354 pub fn force_mplace_ptr(
356 mut place: MPlaceTy<'tcx, M::PointerTag>,
357 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
358 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
362 /// Offset a pointer to project to a field. Unlike `place_field`, this is always
363 /// possible without allocating, so it can take `&self`. Also return the field's layout.
364 /// This supports both struct and array fields.
368 base: MPlaceTy<'tcx, M::PointerTag>,
370 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
371 // Not using the layout method because we want to compute on u64
372 let offset = match base.layout.fields {
373 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
374 offsets[usize::try_from(field).unwrap()],
375 layout::FieldPlacement::Array { stride, .. } => {
376 let len = base.len(self)?;
378 // This can be violated because this runs during promotion on code where the
379 // type system has not yet ensured that such things don't happen.
380 debug!("tried to access element {} of array/slice with length {}", field, len);
381 throw_panic!(BoundsCheck { len, index: field });
385 layout::FieldPlacement::Union(count) => {
386 assert!(field < count as u64,
387 "Tried to access field {} of union with {} fields", field, count);
388 // Offset is always 0
392 // the only way conversion can fail if is this is an array (otherwise we already panicked
393 // above). In that case, all fields are equal.
394 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
396 // Offset may need adjustment for unsized fields.
397 let (meta, offset) = if field_layout.is_unsized() {
398 // Re-use parent metadata to determine dynamic field layout.
399 // With custom DSTS, this *will* execute user-defined code, but the same
400 // happens at run-time so that's okay.
401 let align = match self.size_and_align_of(base.meta, field_layout)? {
402 Some((_, align)) => align,
403 None if offset == Size::ZERO =>
404 // An extern type at offset 0, we fall back to its static alignment.
405 // FIXME: Once we have made decisions for how to handle size and alignment
406 // of `extern type`, this should be adapted. It is just a temporary hack
407 // to get some code to work that probably ought to work.
408 field_layout.align.abi,
410 bug!("Cannot compute offset for extern type field at non-0 offset"),
412 (base.meta, offset.align_to(align))
414 // base.meta could be present; we might be accessing a sized field of an unsized
419 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
420 // codegen -- mostly to see if we can get away with that
421 base.offset(offset, meta, field_layout, self)
424 // Iterates over all fields of an array. Much more efficient than doing the
425 // same by repeatedly calling `mplace_array`.
426 pub fn mplace_array_fields(
428 base: MPlaceTy<'tcx, Tag>,
429 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
431 let len = base.len(self)?; // also asserts that we have a type where this makes sense
432 let stride = match base.layout.fields {
433 layout::FieldPlacement::Array { stride, .. } => stride,
434 _ => bug!("mplace_array_fields: expected an array layout"),
436 let layout = base.layout.field(self, 0)?;
437 let dl = &self.tcx.data_layout;
438 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
441 pub fn mplace_subslice(
443 base: MPlaceTy<'tcx, M::PointerTag>,
446 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
447 let len = base.len(self)?; // also asserts that we have a type where this makes sense
448 assert!(from <= len - to);
450 // Not using layout method because that works with usize, and does not work with slices
451 // (that have count 0 in their layout).
452 let from_offset = match base.layout.fields {
453 layout::FieldPlacement::Array { stride, .. } =>
455 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
458 // Compute meta and new layout
459 let inner_len = len - to - from;
460 let (meta, ty) = match base.layout.ty.sty {
461 // It is not nice to match on the type, but that seems to be the only way to
463 ty::Array(inner, _) =>
464 (None, self.tcx.mk_array(inner, inner_len)),
466 let len = Scalar::from_uint(inner_len, self.pointer_size());
467 (Some(len), base.layout.ty)
470 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
472 let layout = self.layout_of(ty)?;
473 base.offset(from_offset, meta, layout, self)
476 pub fn mplace_downcast(
478 base: MPlaceTy<'tcx, M::PointerTag>,
480 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
481 // Downcasts only change the layout
482 assert!(base.meta.is_none());
483 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
486 /// Project into an mplace
487 pub fn mplace_projection(
489 base: MPlaceTy<'tcx, M::PointerTag>,
490 proj_elem: &mir::PlaceElem<'tcx>,
491 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
492 use rustc::mir::ProjectionElem::*;
493 Ok(match *proj_elem {
494 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
495 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
496 Deref => self.deref_operand(base.into())?,
499 let layout = self.layout_of(self.tcx.types.usize)?;
500 let n = self.access_local(self.frame(), local, Some(layout))?;
501 let n = self.read_scalar(n)?;
502 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
503 self.mplace_field(base, u64::try_from(n).unwrap())?
511 let n = base.len(self)?;
512 assert!(n >= min_length as u64);
514 let index = if from_end {
515 n - u64::from(offset)
520 self.mplace_field(base, index)?
523 Subslice { from, to } =>
524 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
528 /// Gets the place of a field inside the place, and also the field's type.
529 /// Just a convenience function, but used quite a bit.
530 /// This is the only projection that might have a side-effect: We cannot project
531 /// into the field of a local `ScalarPair`, we have to first allocate it.
534 base: PlaceTy<'tcx, M::PointerTag>,
536 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
537 // FIXME: We could try to be smarter and avoid allocation for fields that span the
539 let mplace = self.force_allocation(base)?;
540 Ok(self.mplace_field(mplace, field)?.into())
543 pub fn place_downcast(
545 base: PlaceTy<'tcx, M::PointerTag>,
547 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
548 // Downcast just changes the layout
549 Ok(match base.place {
550 Place::Ptr(mplace) =>
551 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
552 Place::Local { .. } => {
553 let layout = base.layout.for_variant(self, variant);
554 PlaceTy { layout, ..base }
559 /// Projects into a place.
560 pub fn place_projection(
562 base: PlaceTy<'tcx, M::PointerTag>,
563 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
564 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
565 use rustc::mir::ProjectionElem::*;
566 Ok(match *proj_elem {
567 Field(field, _) => self.place_field(base, field.index() as u64)?,
568 Downcast(_, variant) => self.place_downcast(base, variant)?,
569 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
570 // For the other variants, we have to force an allocation.
571 // This matches `operand_projection`.
572 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
573 let mplace = self.force_allocation(base)?;
574 self.mplace_projection(mplace, proj_elem)?.into()
579 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
580 /// `eval_place` and `eval_place_to_op`.
581 pub(super) fn eval_static_to_mplace(
583 place_static: &mir::Static<'tcx>
584 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
585 use rustc::mir::StaticKind;
587 Ok(match place_static.kind {
588 StaticKind::Promoted(promoted) => {
589 let instance = self.frame().instance;
590 self.const_eval_raw(GlobalId {
592 promoted: Some(promoted),
596 StaticKind::Static(def_id) => {
597 let ty = place_static.ty;
598 assert!(!ty.needs_subst());
599 let layout = self.layout_of(ty)?;
600 let instance = ty::Instance::mono(*self.tcx, def_id);
605 // Just create a lazy reference, so we can support recursive statics.
606 // tcx takes care of assigning every static one and only one unique AllocId.
607 // When the data here is ever actually used, memory will notice,
608 // and it knows how to deal with alloc_id that are present in the
609 // global table but not in its local memory: It calls back into tcx through
610 // a query, triggering the CTFE machinery to actually turn this lazy reference
611 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
612 // this InterpCx uses another Machine (e.g., in miri). This is what we
613 // want! This way, computing statics works consistently between codegen
614 // and miri: They use the same query to eventually obtain a `ty::Const`
615 // and use that for further computation.
617 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
618 // one. Here we make sure that the interpreted program never sees the
619 // resolved ID. Also see the doc comment of `Memory::get_static_alloc`.
620 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
621 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
622 MPlaceTy::from_aligned_ptr(ptr, layout)
627 /// Computes a place. You should only use this if you intend to write into this
628 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
631 mir_place: &mir::Place<'tcx>,
632 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
633 use rustc::mir::PlaceBase;
635 mir_place.iterate(|place_base, place_projection| {
636 let mut place = match place_base {
637 PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
638 Some(return_place) => {
639 // We use our layout to verify our assumption; caller will validate
640 // their layout on return.
642 place: *return_place,
644 .layout_of(self.monomorphize(self.frame().body.return_ty())?)?,
647 None => throw_unsup!(InvalidNullPointerUsage),
649 PlaceBase::Local(local) => PlaceTy {
650 // This works even for dead/uninitialized locals; we check further when writing
651 place: Place::Local {
652 frame: self.cur_frame(),
655 layout: self.layout_of_local(self.frame(), *local, None)?,
657 PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
660 for proj in place_projection {
661 place = self.place_projection(place, &proj.elem)?
664 self.dump_place(place.place);
669 /// Write a scalar to a place
672 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
673 dest: PlaceTy<'tcx, M::PointerTag>,
674 ) -> InterpResult<'tcx> {
675 self.write_immediate(Immediate::Scalar(val.into()), dest)
678 /// Write an immediate to a place
680 pub fn write_immediate(
682 src: Immediate<M::PointerTag>,
683 dest: PlaceTy<'tcx, M::PointerTag>,
684 ) -> InterpResult<'tcx> {
685 self.write_immediate_no_validate(src, dest)?;
687 if M::enforce_validity(self) {
688 // Data got changed, better make sure it matches the type!
689 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
695 /// Write an `Immediate` to memory.
697 pub fn write_immediate_to_mplace(
699 src: Immediate<M::PointerTag>,
700 dest: MPlaceTy<'tcx, M::PointerTag>,
701 ) -> InterpResult<'tcx> {
702 self.write_immediate_to_mplace_no_validate(src, dest)?;
704 if M::enforce_validity(self) {
705 // Data got changed, better make sure it matches the type!
706 self.validate_operand(dest.into(), vec![], None)?;
712 /// Write an immediate to a place.
713 /// If you use this you are responsible for validating that things got copied at the
715 fn write_immediate_no_validate(
717 src: Immediate<M::PointerTag>,
718 dest: PlaceTy<'tcx, M::PointerTag>,
719 ) -> InterpResult<'tcx> {
720 if cfg!(debug_assertions) {
721 // This is a very common path, avoid some checks in release mode
722 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
724 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
725 assert_eq!(self.pointer_size(), dest.layout.size,
726 "Size mismatch when writing pointer"),
727 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
728 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
729 "Size mismatch when writing bits"),
730 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
731 Immediate::ScalarPair(_, _) => {
732 // FIXME: Can we check anything here?
736 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
738 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
739 // but not factored as a separate function.
740 let mplace = match dest.place {
741 Place::Local { frame, local } => {
742 match self.stack[frame].locals[local].access_mut()? {
744 // Local can be updated in-place.
745 *local = LocalValue::Live(Operand::Immediate(src));
749 // The local is in memory, go on below.
754 Place::Ptr(mplace) => mplace, // already referring to memory
756 let dest = MPlaceTy { mplace, layout: dest.layout };
758 // This is already in memory, write there.
759 self.write_immediate_to_mplace_no_validate(src, dest)
762 /// Write an immediate to memory.
763 /// If you use this you are responsible for validating that things got copied at the
765 fn write_immediate_to_mplace_no_validate(
767 value: Immediate<M::PointerTag>,
768 dest: MPlaceTy<'tcx, M::PointerTag>,
769 ) -> InterpResult<'tcx> {
770 // Note that it is really important that the type here is the right one, and matches the
771 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
772 // to handle padding properly, which is only correct if we never look at this data with the
775 let ptr = match self.check_mplace_access(dest, None)
776 .expect("places should be checked on creation")
779 None => return Ok(()), // zero-sized access
782 let tcx = &*self.tcx;
783 // FIXME: We should check that there are dest.layout.size many bytes available in
784 // memory. The code below is not sufficient, with enough padding it might not
785 // cover all the bytes!
787 Immediate::Scalar(scalar) => {
788 match dest.layout.abi {
789 layout::Abi::Scalar(_) => {}, // fine
790 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
793 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
794 tcx, ptr, scalar, dest.layout.size
797 Immediate::ScalarPair(a_val, b_val) => {
798 // We checked `ptr_align` above, so all fields will have the alignment they need.
799 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
800 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
801 let (a, b) = match dest.layout.abi {
802 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
803 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
806 let (a_size, b_size) = (a.size(self), b.size(self));
807 let b_offset = a_size.align_to(b.align(self).abi);
808 let b_ptr = ptr.offset(b_offset, self)?;
810 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
811 // but that does not work: We could be a newtype around a pair, then the
812 // fields do not match the `ScalarPair` components.
815 .get_mut(ptr.alloc_id)?
816 .write_scalar(tcx, ptr, a_val, a_size)?;
818 .get_mut(b_ptr.alloc_id)?
819 .write_scalar(tcx, b_ptr, b_val, b_size)
824 /// Copies the data from an operand to a place. This does not support transmuting!
825 /// Use `copy_op_transmute` if the layouts could disagree.
829 src: OpTy<'tcx, M::PointerTag>,
830 dest: PlaceTy<'tcx, M::PointerTag>,
831 ) -> InterpResult<'tcx> {
832 self.copy_op_no_validate(src, dest)?;
834 if M::enforce_validity(self) {
835 // Data got changed, better make sure it matches the type!
836 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
842 /// Copies the data from an operand to a place. This does not support transmuting!
843 /// Use `copy_op_transmute` if the layouts could disagree.
844 /// Also, if you use this you are responsible for validating that things get copied at the
846 fn copy_op_no_validate(
848 src: OpTy<'tcx, M::PointerTag>,
849 dest: PlaceTy<'tcx, M::PointerTag>,
850 ) -> InterpResult<'tcx> {
851 // We do NOT compare the types for equality, because well-typed code can
852 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
853 assert!(src.layout.details == dest.layout.details,
854 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
856 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
857 let src = match self.try_read_immediate(src)? {
859 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
860 // Yay, we got a value that we can write directly.
861 // FIXME: Add a check to make sure that if `src` is indirect,
862 // it does not overlap with `dest`.
863 return self.write_immediate_no_validate(*src_val, dest);
865 Err(mplace) => mplace,
867 // Slow path, this does not fit into an immediate. Just memcpy.
868 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
870 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
871 // is being initialized!
872 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
873 let size = size.unwrap_or_else(|| {
874 assert!(!dest.layout.is_unsized(),
875 "Cannot copy into already initialized unsized place");
878 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
880 let src = self.check_mplace_access(src, Some(size))
881 .expect("places should be checked on creation");
882 let dest = self.check_mplace_access(dest, Some(size))
883 .expect("places should be checked on creation");
884 let (src_ptr, dest_ptr) = match (src, dest) {
885 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
886 (None, None) => return Ok(()), // zero-sized copy
887 _ => bug!("The pointers should both be Some or both None"),
894 /*nonoverlapping*/ true,
898 /// Copies the data from an operand to a place. The layouts may disagree, but they must
899 /// have the same size.
900 pub fn copy_op_transmute(
902 src: OpTy<'tcx, M::PointerTag>,
903 dest: PlaceTy<'tcx, M::PointerTag>,
904 ) -> InterpResult<'tcx> {
905 if src.layout.details == dest.layout.details {
906 // Fast path: Just use normal `copy_op`
907 return self.copy_op(src, dest);
909 // We still require the sizes to match.
910 assert!(src.layout.size == dest.layout.size,
911 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
912 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
913 // to avoid that here.
914 assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
915 "Cannot transmute unsized data");
917 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
918 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
919 // We have to write them to `dest` at the offsets they were *read at*, which is
920 // not necessarily the same as the offsets in `dest.layout`!
921 // Hence we do the copy with the source layout on both sides. We also make sure to write
922 // into memory, because if `dest` is a local we would not even have a way to write
923 // at the `src` offsets; the fact that we came from a different layout would
925 let dest = self.force_allocation(dest)?;
926 self.copy_op_no_validate(
928 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
931 if M::enforce_validity(self) {
932 // Data got changed, better make sure it matches the type!
933 self.validate_operand(dest.into(), vec![], None)?;
939 /// Ensures that a place is in memory, and returns where it is.
940 /// If the place currently refers to a local that doesn't yet have a matching allocation,
941 /// create such an allocation.
942 /// This is essentially `force_to_memplace`.
944 /// This supports unsized types and returns the computed size to avoid some
945 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
947 pub fn force_allocation_maybe_sized(
949 place: PlaceTy<'tcx, M::PointerTag>,
950 meta: Option<Scalar<M::PointerTag>>,
951 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
952 let (mplace, size) = match place.place {
953 Place::Local { frame, local } => {
954 match self.stack[frame].locals[local].access_mut()? {
956 // We need to make an allocation.
957 // FIXME: Consider not doing anything for a ZST, and just returning
958 // a fake pointer? Are we even called for ZST?
960 // We cannot hold on to the reference `local_val` while allocating,
961 // but we can hold on to the value in there.
963 if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
969 // We need the layout of the local. We can NOT use the layout we got,
970 // that might e.g., be an inner field of a struct with `Scalar` layout,
971 // that has different alignment than the outer field.
972 // We also need to support unsized types, and hence cannot use `allocate`.
973 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
974 let (size, align) = self.size_and_align_of(meta, local_layout)?
975 .expect("Cannot allocate for non-dyn-sized type");
976 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
977 let mplace = MemPlace { ptr: ptr.into(), align, meta };
978 if let Some(value) = old_val {
979 // Preserve old value.
980 // We don't have to validate as we can assume the local
981 // was already valid for its type.
982 let mplace = MPlaceTy { mplace, layout: local_layout };
983 self.write_immediate_to_mplace_no_validate(value, mplace)?;
985 // Now we can call `access_mut` again, asserting it goes well,
986 // and actually overwrite things.
987 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
988 LocalValue::Live(Operand::Indirect(mplace));
991 Err(mplace) => (mplace, None), // this already was an indirect local
994 Place::Ptr(mplace) => (mplace, None)
996 // Return with the original layout, so that the caller can go on
997 Ok((MPlaceTy { mplace, layout: place.layout }, size))
1001 pub fn force_allocation(
1003 place: PlaceTy<'tcx, M::PointerTag>,
1004 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1005 Ok(self.force_allocation_maybe_sized(place, None)?.0)
1010 layout: TyLayout<'tcx>,
1011 kind: MemoryKind<M::MemoryKinds>,
1012 ) -> MPlaceTy<'tcx, M::PointerTag> {
1013 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1014 MPlaceTy::from_aligned_ptr(ptr, layout)
1017 pub fn write_discriminant_index(
1019 variant_index: VariantIdx,
1020 dest: PlaceTy<'tcx, M::PointerTag>,
1021 ) -> InterpResult<'tcx> {
1022 match dest.layout.variants {
1023 layout::Variants::Single { index } => {
1024 assert_eq!(index, variant_index);
1026 layout::Variants::Multiple {
1027 discr_kind: layout::DiscriminantKind::Tag,
1032 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
1034 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1036 // raw discriminants for enums are isize or bigger during
1037 // their computation, but the in-memory tag is the smallest possible
1039 let size = discr.value.size(self);
1040 let discr_val = truncate(discr_val, size);
1042 let discr_dest = self.place_field(dest, discr_index as u64)?;
1043 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1045 layout::Variants::Multiple {
1046 discr_kind: layout::DiscriminantKind::Niche {
1055 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1057 if variant_index != dataful_variant {
1059 self.place_field(dest, discr_index as u64)?;
1060 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1061 let niche_value = (niche_value as u128)
1062 .wrapping_add(niche_start);
1064 Scalar::from_uint(niche_value, niche_dest.layout.size),
1074 pub fn raw_const_to_mplace(
1076 raw: RawConst<'tcx>,
1077 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1078 // This must be an allocation in `tcx`
1079 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1080 let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1081 let layout = self.layout_of(raw.ty)?;
1082 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1085 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1086 /// Also return some more information so drop doesn't have to run the same code twice.
1087 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1088 -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1089 let vtable = mplace.vtable(); // also sanity checks the type
1090 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1091 let layout = self.layout_of(ty)?;
1093 // More sanity checks
1094 if cfg!(debug_assertions) {
1095 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1096 assert_eq!(size, layout.size);
1097 // only ABI alignment is preserved
1098 assert_eq!(align, layout.align.abi);
1101 let mplace = MPlaceTy {
1102 mplace: MemPlace { meta: None, ..*mplace },
1105 Ok((instance, mplace))