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::{
12 self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx, PrimitiveExt
14 use rustc::ty::TypeFoldable;
15 use rustc_macros::HashStable;
18 GlobalId, AllocId, Allocation, Scalar, InterpResult, Pointer, PointerArithmetic,
19 InterpCx, Machine, AllocMap, AllocationExtra,
20 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue,
23 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
24 pub struct MemPlace<Tag=(), Id=AllocId> {
25 /// A place may have an integral pointer for ZSTs, and since it might
26 /// be turned back into a reference before ever being dereferenced.
27 /// However, it may never be undef.
28 pub ptr: Scalar<Tag, Id>,
30 /// Metadata for unsized places. Interpretation is up to the type.
31 /// Must not be present for sized types, but can be missing for unsized types
32 /// (e.g., `extern type`).
33 pub meta: Option<Scalar<Tag, Id>>,
36 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
37 pub enum Place<Tag=(), Id=AllocId> {
38 /// A place referring to a value allocated in the `Memory` system.
39 Ptr(MemPlace<Tag, Id>),
41 /// To support alloc-free locals, we are able to write directly to a local.
42 /// (Without that optimization, we'd just always be a `MemPlace`.)
49 #[derive(Copy, Clone, Debug)]
50 pub struct PlaceTy<'tcx, Tag=()> {
51 place: Place<Tag>, // Keep this private; it helps enforce invariants.
52 pub layout: TyLayout<'tcx>,
55 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
56 type Target = Place<Tag>;
58 fn deref(&self) -> &Place<Tag> {
63 /// A MemPlace with its layout. Constructing it is only possible in this module.
64 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
65 pub struct MPlaceTy<'tcx, Tag=()> {
66 mplace: MemPlace<Tag>,
67 pub layout: TyLayout<'tcx>,
70 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
71 type Target = MemPlace<Tag>;
73 fn deref(&self) -> &MemPlace<Tag> {
78 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
80 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
82 place: Place::Ptr(mplace.mplace),
88 impl<Tag> MemPlace<Tag> {
89 /// Replace ptr tag, maintain vtable tag (if any)
91 pub fn replace_tag(self, new_tag: Tag) -> Self {
93 ptr: self.ptr.erase_tag().with_tag(new_tag),
100 pub fn erase_tag(self) -> MemPlace {
102 ptr: self.ptr.erase_tag(),
104 meta: self.meta.map(Scalar::erase_tag),
109 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
117 /// Produces a Place that will error if attempted to be read from or written to
119 pub fn null(cx: &impl HasDataLayout) -> Self {
120 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
124 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
125 Self::from_scalar_ptr(ptr.into(), align)
128 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
129 /// This is the inverse of `ref_to_mplace`.
131 pub fn to_ref(self) -> Immediate<Tag> {
133 None => Immediate::Scalar(self.ptr.into()),
134 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
141 meta: Option<Scalar<Tag>>,
142 cx: &impl HasDataLayout,
143 ) -> InterpResult<'tcx, Self> {
145 ptr: self.ptr.ptr_offset(offset, cx)?,
146 align: self.align.restrict_for_offset(offset),
152 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
153 /// Produces a MemPlace that works for ZST but nothing else
155 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
157 mplace: MemPlace::from_scalar_ptr(
158 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
165 /// Replace ptr tag, maintain vtable tag (if any)
167 pub fn replace_tag(self, new_tag: Tag) -> Self {
169 mplace: self.mplace.replace_tag(new_tag),
178 meta: Option<Scalar<Tag>>,
179 layout: TyLayout<'tcx>,
180 cx: &impl HasDataLayout,
181 ) -> InterpResult<'tcx, Self> {
183 mplace: self.mplace.offset(offset, meta, cx)?,
189 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
190 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
194 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
195 if self.layout.is_unsized() {
196 // We need to consult `meta` metadata
197 match self.layout.ty.kind {
198 ty::Slice(..) | ty::Str =>
199 return self.mplace.meta.unwrap().to_machine_usize(cx),
200 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
203 // Go through the layout. There are lots of types that support a length,
205 match self.layout.fields {
206 layout::FieldPlacement::Array { count, .. } => Ok(count),
207 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
213 pub(super) fn vtable(self) -> Scalar<Tag> {
214 match self.layout.ty.kind {
215 ty::Dynamic(..) => self.mplace.meta.unwrap(),
216 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
221 // These are defined here because they produce a place.
222 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
224 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
226 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
227 Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
232 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
233 self.try_as_mplace().unwrap()
237 impl<Tag: ::std::fmt::Debug> Place<Tag> {
238 /// Produces a Place that will error if attempted to be read from or written to
240 pub fn null(cx: &impl HasDataLayout) -> Self {
241 Place::Ptr(MemPlace::null(cx))
245 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
246 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
250 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
251 Place::Ptr(MemPlace::from_ptr(ptr, align))
255 pub fn assert_mem_place(self) -> MemPlace<Tag> {
257 Place::Ptr(mplace) => mplace,
258 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
264 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
266 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
267 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
271 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
272 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
274 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
275 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
276 M: Machine<'mir, 'tcx, PointerTag = Tag>,
277 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
278 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
279 M::AllocExtra: AllocationExtra<Tag>,
281 /// Take a value, which represents a (thin or wide) reference, and make it a place.
282 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
284 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
285 /// want to ever use the place for memory access!
286 /// Generally prefer `deref_operand`.
287 pub fn ref_to_mplace(
289 val: ImmTy<'tcx, M::PointerTag>,
290 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
291 let pointee_type = val.layout.ty.builtin_deref(true)
292 .expect("`ref_to_mplace` called on non-ptr type")
294 let layout = self.layout_of(pointee_type)?;
295 let (ptr, meta) = match *val {
296 Immediate::Scalar(ptr) => (ptr.not_undef()?, None),
297 Immediate::ScalarPair(ptr, meta) => (ptr.not_undef()?, Some(meta.not_undef()?)),
300 let mplace = MemPlace {
302 // We could use the run-time alignment here. For now, we do not, because
303 // the point of tracking the alignment here is to make sure that the *static*
304 // alignment information emitted with the loads is correct. The run-time
305 // alignment can only be more restrictive.
306 align: layout.align.abi,
309 Ok(MPlaceTy { mplace, layout })
312 /// Take an operand, representing a pointer, and dereference it to a place -- that
313 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
314 pub fn deref_operand(
316 src: OpTy<'tcx, M::PointerTag>,
317 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
318 let val = self.read_immediate(src)?;
319 trace!("deref to {} on {:?}", val.layout.ty, *val);
320 let place = self.ref_to_mplace(val)?;
321 self.mplace_access_checked(place)
324 /// Check if the given place is good for memory access with the given
325 /// size, falling back to the layout's size if `None` (in the latter case,
326 /// this must be a statically sized type).
328 /// On success, returns `None` for zero-sized accesses (where nothing else is
329 /// left to do) and a `Pointer` to use for the actual access otherwise.
331 pub fn check_mplace_access(
333 place: MPlaceTy<'tcx, M::PointerTag>,
335 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
336 let size = size.unwrap_or_else(|| {
337 assert!(!place.layout.is_unsized());
338 assert!(place.meta.is_none());
341 self.memory.check_ptr_access(place.ptr, size, place.align)
344 /// Return the "access-checked" version of this `MPlace`, where for non-ZST
345 /// this is definitely a `Pointer`.
346 pub fn mplace_access_checked(
348 mut place: MPlaceTy<'tcx, M::PointerTag>,
349 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
350 let (size, align) = self.size_and_align_of_mplace(place)?
351 .unwrap_or((place.layout.size, place.layout.align.abi));
352 assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
353 place.mplace.align = align; // maximally strict checking
354 // When dereferencing a pointer, it must be non-NULL, aligned, and live.
355 if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
356 place.mplace.ptr = ptr.into();
361 /// Force `place.ptr` to a `Pointer`.
362 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
363 pub fn force_mplace_ptr(
365 mut place: MPlaceTy<'tcx, M::PointerTag>,
366 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
367 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
371 /// Offset a pointer to project to a field. Unlike `place_field`, this is always
372 /// possible without allocating, so it can take `&self`. Also return the field's layout.
373 /// This supports both struct and array fields.
377 base: MPlaceTy<'tcx, M::PointerTag>,
379 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
380 // Not using the layout method because we want to compute on u64
381 let offset = match base.layout.fields {
382 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
383 offsets[usize::try_from(field).unwrap()],
384 layout::FieldPlacement::Array { stride, .. } => {
385 let len = base.len(self)?;
387 // This can only be reached in ConstProp and non-rustc-MIR.
388 throw_ub!(BoundsCheckFailed { len, index: field });
392 layout::FieldPlacement::Union(count) => {
393 assert!(field < count as u64,
394 "Tried to access field {} of union {:#?} with {} fields",
395 field, base.layout, count);
396 // Offset is always 0
400 // the only way conversion can fail if is this is an array (otherwise we already panicked
401 // above). In that case, all fields are equal.
402 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
404 // Offset may need adjustment for unsized fields.
405 let (meta, offset) = if field_layout.is_unsized() {
406 // Re-use parent metadata to determine dynamic field layout.
407 // With custom DSTS, this *will* execute user-defined code, but the same
408 // happens at run-time so that's okay.
409 let align = match self.size_and_align_of(base.meta, field_layout)? {
410 Some((_, align)) => align,
411 None if offset == Size::ZERO =>
412 // An extern type at offset 0, we fall back to its static alignment.
413 // FIXME: Once we have made decisions for how to handle size and alignment
414 // of `extern type`, this should be adapted. It is just a temporary hack
415 // to get some code to work that probably ought to work.
416 field_layout.align.abi,
418 bug!("Cannot compute offset for extern type field at non-0 offset"),
420 (base.meta, offset.align_to(align))
422 // base.meta could be present; we might be accessing a sized field of an unsized
427 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
428 // codegen -- mostly to see if we can get away with that
429 base.offset(offset, meta, field_layout, self)
432 // Iterates over all fields of an array. Much more efficient than doing the
433 // same by repeatedly calling `mplace_array`.
434 pub fn mplace_array_fields(
436 base: MPlaceTy<'tcx, Tag>,
437 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
439 let len = base.len(self)?; // also asserts that we have a type where this makes sense
440 let stride = match base.layout.fields {
441 layout::FieldPlacement::Array { stride, .. } => stride,
442 _ => bug!("mplace_array_fields: expected an array layout"),
444 let layout = base.layout.field(self, 0)?;
445 let dl = &self.tcx.data_layout;
446 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
449 pub fn mplace_subslice(
451 base: MPlaceTy<'tcx, M::PointerTag>,
454 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
455 let len = base.len(self)?; // also asserts that we have a type where this makes sense
456 assert!(from <= len - to);
458 // Not using layout method because that works with usize, and does not work with slices
459 // (that have count 0 in their layout).
460 let from_offset = match base.layout.fields {
461 layout::FieldPlacement::Array { stride, .. } =>
463 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
466 // Compute meta and new layout
467 let inner_len = len - to - from;
468 let (meta, ty) = match base.layout.ty.kind {
469 // It is not nice to match on the type, but that seems to be the only way to
471 ty::Array(inner, _) =>
472 (None, self.tcx.mk_array(inner, inner_len)),
474 let len = Scalar::from_uint(inner_len, self.pointer_size());
475 (Some(len), base.layout.ty)
478 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
480 let layout = self.layout_of(ty)?;
481 base.offset(from_offset, meta, layout, self)
484 pub fn mplace_downcast(
486 base: MPlaceTy<'tcx, M::PointerTag>,
488 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
489 // Downcasts only change the layout
490 assert!(base.meta.is_none());
491 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
494 /// Project into an mplace
495 pub fn mplace_projection(
497 base: MPlaceTy<'tcx, M::PointerTag>,
498 proj_elem: &mir::PlaceElem<'tcx>,
499 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
500 use rustc::mir::ProjectionElem::*;
501 Ok(match *proj_elem {
502 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
503 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
504 Deref => self.deref_operand(base.into())?,
507 let layout = self.layout_of(self.tcx.types.usize)?;
508 let n = self.access_local(self.frame(), local, Some(layout))?;
509 let n = self.read_scalar(n)?;
510 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
511 self.mplace_field(base, u64::try_from(n).unwrap())?
519 let n = base.len(self)?;
520 assert!(n >= min_length as u64);
522 let index = if from_end {
523 n - u64::from(offset)
528 self.mplace_field(base, index)?
531 Subslice { from, to } =>
532 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
536 /// Gets the place of a field inside the place, and also the field's type.
537 /// Just a convenience function, but used quite a bit.
538 /// This is the only projection that might have a side-effect: We cannot project
539 /// into the field of a local `ScalarPair`, we have to first allocate it.
542 base: PlaceTy<'tcx, M::PointerTag>,
544 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
545 // FIXME: We could try to be smarter and avoid allocation for fields that span the
547 let mplace = self.force_allocation(base)?;
548 Ok(self.mplace_field(mplace, field)?.into())
551 pub fn place_downcast(
553 base: PlaceTy<'tcx, M::PointerTag>,
555 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
556 // Downcast just changes the layout
557 Ok(match base.place {
558 Place::Ptr(mplace) =>
559 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
560 Place::Local { .. } => {
561 let layout = base.layout.for_variant(self, variant);
562 PlaceTy { layout, ..base }
567 /// Projects into a place.
568 pub fn place_projection(
570 base: PlaceTy<'tcx, M::PointerTag>,
571 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
572 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
573 use rustc::mir::ProjectionElem::*;
574 Ok(match *proj_elem {
575 Field(field, _) => self.place_field(base, field.index() as u64)?,
576 Downcast(_, variant) => self.place_downcast(base, variant)?,
577 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
578 // For the other variants, we have to force an allocation.
579 // This matches `operand_projection`.
580 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
581 let mplace = self.force_allocation(base)?;
582 self.mplace_projection(mplace, proj_elem)?.into()
587 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
588 /// `eval_place` and `eval_place_to_op`.
589 pub(super) fn eval_static_to_mplace(
591 place_static: &mir::Static<'tcx>
592 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
593 use rustc::mir::StaticKind;
595 Ok(match place_static.kind {
596 StaticKind::Promoted(promoted, promoted_substs) => {
597 let substs = self.subst_from_frame_and_normalize_erasing_regions(promoted_substs);
598 let instance = ty::Instance::new(place_static.def_id, substs);
600 // Even after getting `substs` from the frame, this instance may still be
601 // polymorphic because `ConstProp` will try to promote polymorphic MIR.
602 if instance.needs_subst() {
603 throw_inval!(TooGeneric);
606 self.const_eval_raw(GlobalId {
608 promoted: Some(promoted),
612 StaticKind::Static => {
613 let ty = place_static.ty;
614 assert!(!ty.needs_subst());
615 let layout = self.layout_of(ty)?;
616 let instance = ty::Instance::mono(*self.tcx, place_static.def_id);
621 // Just create a lazy reference, so we can support recursive statics.
622 // tcx takes care of assigning every static one and only one unique AllocId.
623 // When the data here is ever actually used, memory will notice,
624 // and it knows how to deal with alloc_id that are present in the
625 // global table but not in its local memory: It calls back into tcx through
626 // a query, triggering the CTFE machinery to actually turn this lazy reference
627 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
628 // this InterpCx uses another Machine (e.g., in miri). This is what we
629 // want! This way, computing statics works consistently between codegen
630 // and miri: They use the same query to eventually obtain a `ty::Const`
631 // and use that for further computation.
633 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
634 // one. Here we make sure that the interpreted program never sees the
635 // resolved ID. Also see the doc comment of `Memory::get_static_alloc`.
636 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
637 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
638 MPlaceTy::from_aligned_ptr(ptr, layout)
643 /// Computes a place. You should only use this if you intend to write into this
644 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
647 place: &mir::Place<'tcx>,
648 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
649 use rustc::mir::PlaceBase;
651 let mut place_ty = match &place.base {
652 PlaceBase::Local(mir::RETURN_PLACE) => {
653 // `return_place` has the *caller* layout, but we want to use our
654 // `layout to verify our assumption. The caller will validate
655 // their layout on return.
657 place: match self.frame().return_place {
659 // Even if we don't have a return place, we sometimes need to
660 // create this place, but any attempt to read from / write to it
661 // (even a ZST read/write) needs to error, so let us make this
664 // FIXME: Ideally we'd make sure that the place projections also
666 None => Place::null(&*self),
668 layout: self.layout_of(
669 self.subst_from_frame_and_normalize_erasing_regions(
670 self.frame().body.return_ty()
675 PlaceBase::Local(local) => PlaceTy {
676 // This works even for dead/uninitialized locals; we check further when writing
677 place: Place::Local {
678 frame: self.cur_frame(),
681 layout: self.layout_of_local(self.frame(), *local, None)?,
683 PlaceBase::Static(place_static) => self.eval_static_to_mplace(&place_static)?.into(),
686 for elem in place.projection.iter() {
687 place_ty = self.place_projection(place_ty, elem)?
690 self.dump_place(place_ty.place);
694 /// Write a scalar to a place
698 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
699 dest: PlaceTy<'tcx, M::PointerTag>,
700 ) -> InterpResult<'tcx> {
701 self.write_immediate(Immediate::Scalar(val.into()), dest)
704 /// Write an immediate to a place
706 pub fn write_immediate(
708 src: Immediate<M::PointerTag>,
709 dest: PlaceTy<'tcx, M::PointerTag>,
710 ) -> InterpResult<'tcx> {
711 self.write_immediate_no_validate(src, dest)?;
713 if M::enforce_validity(self) {
714 // Data got changed, better make sure it matches the type!
715 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
721 /// Write an `Immediate` to memory.
723 pub fn write_immediate_to_mplace(
725 src: Immediate<M::PointerTag>,
726 dest: MPlaceTy<'tcx, M::PointerTag>,
727 ) -> InterpResult<'tcx> {
728 self.write_immediate_to_mplace_no_validate(src, dest)?;
730 if M::enforce_validity(self) {
731 // Data got changed, better make sure it matches the type!
732 self.validate_operand(dest.into(), vec![], None)?;
738 /// Write an immediate to a place.
739 /// If you use this you are responsible for validating that things got copied at the
741 fn write_immediate_no_validate(
743 src: Immediate<M::PointerTag>,
744 dest: PlaceTy<'tcx, M::PointerTag>,
745 ) -> InterpResult<'tcx> {
746 if cfg!(debug_assertions) {
747 // This is a very common path, avoid some checks in release mode
748 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
750 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
751 assert_eq!(self.pointer_size(), dest.layout.size,
752 "Size mismatch when writing pointer"),
753 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
754 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
755 "Size mismatch when writing bits"),
756 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
757 Immediate::ScalarPair(_, _) => {
758 // FIXME: Can we check anything here?
762 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
764 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
765 // but not factored as a separate function.
766 let mplace = match dest.place {
767 Place::Local { frame, local } => {
768 match self.stack[frame].locals[local].access_mut()? {
770 // Local can be updated in-place.
771 *local = LocalValue::Live(Operand::Immediate(src));
775 // The local is in memory, go on below.
780 Place::Ptr(mplace) => mplace, // already referring to memory
782 let dest = MPlaceTy { mplace, layout: dest.layout };
784 // This is already in memory, write there.
785 self.write_immediate_to_mplace_no_validate(src, dest)
788 /// Write an immediate to memory.
789 /// If you use this you are responsible for validating that things got copied at the
791 fn write_immediate_to_mplace_no_validate(
793 value: Immediate<M::PointerTag>,
794 dest: MPlaceTy<'tcx, M::PointerTag>,
795 ) -> InterpResult<'tcx> {
796 // Note that it is really important that the type here is the right one, and matches the
797 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
798 // to handle padding properly, which is only correct if we never look at this data with the
801 // Invalid places are a thing: the return place of a diverging function
802 let ptr = match self.check_mplace_access(dest, None)?
805 None => return Ok(()), // zero-sized access
808 let tcx = &*self.tcx;
809 // FIXME: We should check that there are dest.layout.size many bytes available in
810 // memory. The code below is not sufficient, with enough padding it might not
811 // cover all the bytes!
813 Immediate::Scalar(scalar) => {
814 match dest.layout.abi {
815 layout::Abi::Scalar(_) => {}, // fine
816 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
819 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
820 tcx, ptr, scalar, dest.layout.size
823 Immediate::ScalarPair(a_val, b_val) => {
824 // We checked `ptr_align` above, so all fields will have the alignment they need.
825 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
826 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
827 let (a, b) = match dest.layout.abi {
828 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
829 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
832 let (a_size, b_size) = (a.size(self), b.size(self));
833 let b_offset = a_size.align_to(b.align(self).abi);
834 let b_ptr = ptr.offset(b_offset, self)?;
836 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
837 // but that does not work: We could be a newtype around a pair, then the
838 // fields do not match the `ScalarPair` components.
841 .get_raw_mut(ptr.alloc_id)?
842 .write_scalar(tcx, ptr, a_val, a_size)?;
844 .get_raw_mut(b_ptr.alloc_id)?
845 .write_scalar(tcx, b_ptr, b_val, b_size)
850 /// Copies the data from an operand to a place. This does not support transmuting!
851 /// Use `copy_op_transmute` if the layouts could disagree.
855 src: OpTy<'tcx, M::PointerTag>,
856 dest: PlaceTy<'tcx, M::PointerTag>,
857 ) -> InterpResult<'tcx> {
858 self.copy_op_no_validate(src, dest)?;
860 if M::enforce_validity(self) {
861 // Data got changed, better make sure it matches the type!
862 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
868 /// Copies the data from an operand to a place. This does not support transmuting!
869 /// Use `copy_op_transmute` if the layouts could disagree.
870 /// Also, if you use this you are responsible for validating that things get copied at the
872 fn copy_op_no_validate(
874 src: OpTy<'tcx, M::PointerTag>,
875 dest: PlaceTy<'tcx, M::PointerTag>,
876 ) -> InterpResult<'tcx> {
877 // We do NOT compare the types for equality, because well-typed code can
878 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
879 assert!(src.layout.details == dest.layout.details,
880 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
882 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
883 let src = match self.try_read_immediate(src)? {
885 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
886 // Yay, we got a value that we can write directly.
887 // FIXME: Add a check to make sure that if `src` is indirect,
888 // it does not overlap with `dest`.
889 return self.write_immediate_no_validate(*src_val, dest);
891 Err(mplace) => mplace,
893 // Slow path, this does not fit into an immediate. Just memcpy.
894 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
896 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
897 // is being initialized!
898 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
899 let size = size.unwrap_or_else(|| {
900 assert!(!dest.layout.is_unsized(),
901 "Cannot copy into already initialized unsized place");
904 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
906 let src = self.check_mplace_access(src, Some(size))
907 .expect("places should be checked on creation");
908 let dest = self.check_mplace_access(dest, Some(size))
909 .expect("places should be checked on creation");
910 let (src_ptr, dest_ptr) = match (src, dest) {
911 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
912 (None, None) => return Ok(()), // zero-sized copy
913 _ => bug!("The pointers should both be Some or both None"),
920 /*nonoverlapping*/ true,
924 /// Copies the data from an operand to a place. The layouts may disagree, but they must
925 /// have the same size.
926 pub fn copy_op_transmute(
928 src: OpTy<'tcx, M::PointerTag>,
929 dest: PlaceTy<'tcx, M::PointerTag>,
930 ) -> InterpResult<'tcx> {
931 if src.layout.details == dest.layout.details {
932 // Fast path: Just use normal `copy_op`
933 return self.copy_op(src, dest);
935 // We still require the sizes to match.
936 assert!(src.layout.size == dest.layout.size,
937 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
938 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
939 // to avoid that here.
940 assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
941 "Cannot transmute unsized data");
943 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
944 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
945 // We have to write them to `dest` at the offsets they were *read at*, which is
946 // not necessarily the same as the offsets in `dest.layout`!
947 // Hence we do the copy with the source layout on both sides. We also make sure to write
948 // into memory, because if `dest` is a local we would not even have a way to write
949 // at the `src` offsets; the fact that we came from a different layout would
951 let dest = self.force_allocation(dest)?;
952 self.copy_op_no_validate(
954 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
957 if M::enforce_validity(self) {
958 // Data got changed, better make sure it matches the type!
959 self.validate_operand(dest.into(), vec![], None)?;
965 /// Ensures that a place is in memory, and returns where it is.
966 /// If the place currently refers to a local that doesn't yet have a matching allocation,
967 /// create such an allocation.
968 /// This is essentially `force_to_memplace`.
970 /// This supports unsized types and returns the computed size to avoid some
971 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
973 pub fn force_allocation_maybe_sized(
975 place: PlaceTy<'tcx, M::PointerTag>,
976 meta: Option<Scalar<M::PointerTag>>,
977 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
978 let (mplace, size) = match place.place {
979 Place::Local { frame, local } => {
980 match self.stack[frame].locals[local].access_mut()? {
982 // We need to make an allocation.
983 // FIXME: Consider not doing anything for a ZST, and just returning
984 // a fake pointer? Are we even called for ZST?
986 // We cannot hold on to the reference `local_val` while allocating,
987 // but we can hold on to the value in there.
989 if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
995 // We need the layout of the local. We can NOT use the layout we got,
996 // that might e.g., be an inner field of a struct with `Scalar` layout,
997 // that has different alignment than the outer field.
998 // We also need to support unsized types, and hence cannot use `allocate`.
999 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
1000 let (size, align) = self.size_and_align_of(meta, local_layout)?
1001 .expect("Cannot allocate for non-dyn-sized type");
1002 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
1003 let mplace = MemPlace { ptr: ptr.into(), align, meta };
1004 if let Some(value) = old_val {
1005 // Preserve old value.
1006 // We don't have to validate as we can assume the local
1007 // was already valid for its type.
1008 let mplace = MPlaceTy { mplace, layout: local_layout };
1009 self.write_immediate_to_mplace_no_validate(value, mplace)?;
1011 // Now we can call `access_mut` again, asserting it goes well,
1012 // and actually overwrite things.
1013 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
1014 LocalValue::Live(Operand::Indirect(mplace));
1015 (mplace, Some(size))
1017 Err(mplace) => (mplace, None), // this already was an indirect local
1020 Place::Ptr(mplace) => (mplace, None)
1022 // Return with the original layout, so that the caller can go on
1023 Ok((MPlaceTy { mplace, layout: place.layout }, size))
1027 pub fn force_allocation(
1029 place: PlaceTy<'tcx, M::PointerTag>,
1030 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1031 Ok(self.force_allocation_maybe_sized(place, None)?.0)
1036 layout: TyLayout<'tcx>,
1037 kind: MemoryKind<M::MemoryKinds>,
1038 ) -> MPlaceTy<'tcx, M::PointerTag> {
1039 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1040 MPlaceTy::from_aligned_ptr(ptr, layout)
1043 /// Returns a wide MPlace.
1044 pub fn allocate_str(
1047 kind: MemoryKind<M::MemoryKinds>,
1048 ) -> MPlaceTy<'tcx, M::PointerTag> {
1049 let ptr = self.memory.allocate_static_bytes(str.as_bytes(), kind);
1050 let meta = Scalar::from_uint(str.len() as u128, self.pointer_size());
1051 let mplace = MemPlace {
1053 align: Align::from_bytes(1).unwrap(),
1057 let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1058 MPlaceTy { mplace, layout }
1061 pub fn write_discriminant_index(
1063 variant_index: VariantIdx,
1064 dest: PlaceTy<'tcx, M::PointerTag>,
1065 ) -> InterpResult<'tcx> {
1067 // Layout computation excludes uninhabited variants from consideration
1068 // therefore there's no way to represent those variants in the given layout.
1069 if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1070 throw_ub!(Unreachable);
1073 match dest.layout.variants {
1074 layout::Variants::Single { index } => {
1075 assert_eq!(index, variant_index);
1077 layout::Variants::Multiple {
1078 discr_kind: layout::DiscriminantKind::Tag,
1079 discr: ref discr_layout,
1083 // No need to validate that the discriminant here because the
1084 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1087 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1089 // raw discriminants for enums are isize or bigger during
1090 // their computation, but the in-memory tag is the smallest possible
1092 let size = discr_layout.value.size(self);
1093 let discr_val = truncate(discr_val, size);
1095 let discr_dest = self.place_field(dest, discr_index as u64)?;
1096 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1098 layout::Variants::Multiple {
1099 discr_kind: layout::DiscriminantKind::Niche {
1104 discr: ref discr_layout,
1108 // No need to validate that the discriminant here because the
1109 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1111 if variant_index != dataful_variant {
1112 let variants_start = niche_variants.start().as_u32();
1113 let variant_index_relative = variant_index.as_u32()
1114 .checked_sub(variants_start)
1115 .expect("overflow computing relative variant idx");
1116 // We need to use machine arithmetic when taking into account `niche_start`:
1117 // discr_val = variant_index_relative + niche_start_val
1118 let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1119 let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1120 let variant_index_relative_val =
1121 ImmTy::from_uint(variant_index_relative, discr_layout);
1122 let discr_val = self.binary_op(
1124 variant_index_relative_val,
1128 let niche_dest = self.place_field(dest, discr_index as u64)?;
1129 self.write_immediate(*discr_val, niche_dest)?;
1137 pub fn raw_const_to_mplace(
1139 raw: RawConst<'tcx>,
1140 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1141 // This must be an allocation in `tcx`
1142 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1143 let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1144 let layout = self.layout_of(raw.ty)?;
1145 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1148 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1149 /// Also return some more information so drop doesn't have to run the same code twice.
1150 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1151 -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1152 let vtable = mplace.vtable(); // also sanity checks the type
1153 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1154 let layout = self.layout_of(ty)?;
1156 // More sanity checks
1157 if cfg!(debug_assertions) {
1158 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1159 assert_eq!(size, layout.size);
1160 // only ABI alignment is preserved
1161 assert_eq!(align, layout.align.abi);
1164 let mplace = MPlaceTy {
1165 mplace: MemPlace { meta: None, ..*mplace },
1168 Ok((instance, mplace))