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;
8 use rustc_macros::HashStable;
10 use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_target::abi::{Abi, Align, DiscriminantKind, FieldsShape};
13 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, VariantIdx, Variants};
16 mir_assign_valid_types, truncate, AllocId, AllocMap, Allocation, AllocationExtra, ImmTy,
17 Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer,
18 PointerArithmetic, RawConst, Scalar, ScalarMaybeUndef,
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
22 /// Information required for the sound usage of a `MemPlace`.
23 pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
24 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
25 Meta(Scalar<Tag, Id>),
26 /// `Sized` types or unsized `extern type`
28 /// The address of this place may not be taken. This protects the `MemPlace` from coming from
29 /// a ZST Operand without a backing allocation and being converted to an integer address. This
30 /// should be impossible, because you can't take the address of an operand, but this is a second
31 /// protection layer ensuring that we don't mess up.
35 impl<Tag, Id> MemPlaceMeta<Tag, Id> {
36 pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
39 Self::None | Self::Poison => {
40 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
44 fn has_meta(self) -> bool {
46 Self::Meta(_) => true,
47 Self::None | Self::Poison => false,
52 impl<Tag> MemPlaceMeta<Tag> {
53 pub fn erase_tag(self) -> MemPlaceMeta<()> {
55 Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
56 Self::None => MemPlaceMeta::None,
57 Self::Poison => MemPlaceMeta::Poison,
62 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
63 pub struct MemPlace<Tag = (), Id = AllocId> {
64 /// A place may have an integral pointer for ZSTs, and since it might
65 /// be turned back into a reference before ever being dereferenced.
66 /// However, it may never be undef.
67 pub ptr: Scalar<Tag, Id>,
69 /// Metadata for unsized places. Interpretation is up to the type.
70 /// Must not be present for sized types, but can be missing for unsized types
71 /// (e.g., `extern type`).
72 pub meta: MemPlaceMeta<Tag, Id>,
75 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
76 pub enum Place<Tag = (), Id = AllocId> {
77 /// A place referring to a value allocated in the `Memory` system.
78 Ptr(MemPlace<Tag, Id>),
80 /// To support alloc-free locals, we are able to write directly to a local.
81 /// (Without that optimization, we'd just always be a `MemPlace`.)
82 Local { frame: usize, local: mir::Local },
85 #[derive(Copy, Clone, Debug)]
86 pub struct PlaceTy<'tcx, Tag = ()> {
87 place: Place<Tag>, // Keep this private; it helps enforce invariants.
88 pub layout: TyAndLayout<'tcx>,
91 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
92 type Target = Place<Tag>;
94 fn deref(&self) -> &Place<Tag> {
99 /// A MemPlace with its layout. Constructing it is only possible in this module.
100 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
101 pub struct MPlaceTy<'tcx, Tag = ()> {
102 mplace: MemPlace<Tag>,
103 pub layout: TyAndLayout<'tcx>,
106 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
107 type Target = MemPlace<Tag>;
109 fn deref(&self) -> &MemPlace<Tag> {
114 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
116 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
117 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
121 impl<Tag> MemPlace<Tag> {
122 /// Replace ptr tag, maintain vtable tag (if any)
124 pub fn replace_tag(self, new_tag: Tag) -> Self {
125 MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
129 pub fn erase_tag(self) -> MemPlace {
130 MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
134 fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
135 MemPlace { ptr, align, meta: MemPlaceMeta::None }
138 /// Produces a Place that will error if attempted to be read from or written to
140 fn null(cx: &impl HasDataLayout) -> Self {
141 Self::from_scalar_ptr(Scalar::null_ptr(cx), Align::from_bytes(1).unwrap())
145 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
146 Self::from_scalar_ptr(ptr.into(), align)
149 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
150 /// This is the inverse of `ref_to_mplace`.
152 pub fn to_ref(self) -> Immediate<Tag> {
154 MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
155 MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
156 MemPlaceMeta::Poison => bug!(
157 "MPlaceTy::dangling may never be used to produce a \
158 place that will have the address of its pointee taken"
166 meta: MemPlaceMeta<Tag>,
167 cx: &impl HasDataLayout,
168 ) -> InterpResult<'tcx, Self> {
170 ptr: self.ptr.ptr_offset(offset, cx)?,
171 align: self.align.restrict_for_offset(offset),
177 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
178 /// Produces a MemPlace that works for ZST but nothing else
180 pub fn dangling(layout: TyAndLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
181 let align = layout.align.abi;
182 let ptr = Scalar::from_machine_usize(align.bytes(), cx);
183 // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
184 MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
187 /// Replace ptr tag, maintain vtable tag (if any)
189 pub fn replace_tag(self, new_tag: Tag) -> Self {
190 MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
197 meta: MemPlaceMeta<Tag>,
198 layout: TyAndLayout<'tcx>,
199 cx: &impl HasDataLayout,
200 ) -> InterpResult<'tcx, Self> {
201 Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
205 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
206 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
210 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
211 if self.layout.is_unsized() {
212 // We need to consult `meta` metadata
213 match self.layout.ty.kind {
214 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
215 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
218 // Go through the layout. There are lots of types that support a length,
220 match self.layout.fields {
221 FieldsShape::Array { count, .. } => Ok(count),
222 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
228 pub(super) fn vtable(self) -> Scalar<Tag> {
229 match self.layout.ty.kind {
230 ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
231 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
236 // These are defined here because they produce a place.
237 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
239 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
240 /// read from the resulting mplace, not to get its address back.
241 pub fn try_as_mplace(
243 cx: &impl HasDataLayout,
244 ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
246 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
247 Operand::Immediate(_) if self.layout.is_zst() => {
248 Ok(MPlaceTy::dangling(self.layout, cx))
250 Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
255 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
256 /// read from the resulting mplace, not to get its address back.
257 pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
258 self.try_as_mplace(cx).unwrap()
262 impl<Tag: ::std::fmt::Debug> Place<Tag> {
263 /// Produces a Place that will error if attempted to be read from or written to
265 fn null(cx: &impl HasDataLayout) -> Self {
266 Place::Ptr(MemPlace::null(cx))
270 pub fn assert_mem_place(self) -> MemPlace<Tag> {
272 Place::Ptr(mplace) => mplace,
273 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
278 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
279 pub fn null(cx: &impl HasDataLayout, layout: TyAndLayout<'tcx>) -> Self {
280 Self { place: Place::null(cx), layout }
284 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
285 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
289 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
290 impl<'mir, 'tcx: 'mir, Tag, M> InterpCx<'mir, 'tcx, M>
292 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
293 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
294 M: Machine<'mir, 'tcx, PointerTag = Tag>,
295 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
296 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKind>, Allocation<Tag, M::AllocExtra>)>,
297 M::AllocExtra: AllocationExtra<Tag>,
299 /// Take a value, which represents a (thin or wide) reference, and make it a place.
300 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
302 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
303 /// want to ever use the place for memory access!
304 /// Generally prefer `deref_operand`.
305 pub fn ref_to_mplace(
307 val: ImmTy<'tcx, M::PointerTag>,
308 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
310 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
311 let layout = self.layout_of(pointee_type)?;
312 let (ptr, meta) = match *val {
313 Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
314 Immediate::ScalarPair(ptr, meta) => {
315 (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
319 let mplace = MemPlace {
321 // We could use the run-time alignment here. For now, we do not, because
322 // the point of tracking the alignment here is to make sure that the *static*
323 // alignment information emitted with the loads is correct. The run-time
324 // alignment can only be more restrictive.
325 align: layout.align.abi,
328 Ok(MPlaceTy { mplace, layout })
331 /// Take an operand, representing a pointer, and dereference it to a place -- that
332 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
333 pub fn deref_operand(
335 src: OpTy<'tcx, M::PointerTag>,
336 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
337 let val = self.read_immediate(src)?;
338 trace!("deref to {} on {:?}", val.layout.ty, *val);
339 let place = self.ref_to_mplace(val)?;
340 self.mplace_access_checked(place)
343 /// Check if the given place is good for memory access with the given
344 /// size, falling back to the layout's size if `None` (in the latter case,
345 /// this must be a statically sized type).
347 /// On success, returns `None` for zero-sized accesses (where nothing else is
348 /// left to do) and a `Pointer` to use for the actual access otherwise.
350 pub(super) fn check_mplace_access(
352 place: MPlaceTy<'tcx, M::PointerTag>,
354 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
355 let size = size.unwrap_or_else(|| {
356 assert!(!place.layout.is_unsized());
357 assert!(!place.meta.has_meta());
360 self.memory.check_ptr_access(place.ptr, size, place.align)
363 /// Return the "access-checked" version of this `MPlace`, where for non-ZST
364 /// this is definitely a `Pointer`.
365 pub fn mplace_access_checked(
367 mut place: MPlaceTy<'tcx, M::PointerTag>,
368 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
369 let (size, align) = self
370 .size_and_align_of_mplace(place)?
371 .unwrap_or((place.layout.size, place.layout.align.abi));
372 assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
373 place.mplace.align = align; // maximally strict checking
374 // When dereferencing a pointer, it must be non-NULL, aligned, and live.
375 if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
376 place.mplace.ptr = ptr.into();
381 /// Force `place.ptr` to a `Pointer`.
382 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
383 pub(super) fn force_mplace_ptr(
385 mut place: MPlaceTy<'tcx, M::PointerTag>,
386 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
387 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
391 /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
392 /// always possible without allocating, so it can take `&self`. Also return the field's layout.
393 /// This supports both struct and array fields.
395 /// This also works for arrays, but then the `usize` index type is restricting.
396 /// For indexing into arrays, use `mplace_index`.
400 base: MPlaceTy<'tcx, M::PointerTag>,
402 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
403 let offset = base.layout.fields.offset(field);
404 let field_layout = base.layout.field(self, field)?;
406 // Offset may need adjustment for unsized fields.
407 let (meta, offset) = if field_layout.is_unsized() {
408 // Re-use parent metadata to determine dynamic field layout.
409 // With custom DSTS, this *will* execute user-defined code, but the same
410 // happens at run-time so that's okay.
411 let align = match self.size_and_align_of(base.meta, field_layout)? {
412 Some((_, align)) => align,
413 None if offset == Size::ZERO => {
414 // An extern type at offset 0, we fall back to its static alignment.
415 // FIXME: Once we have made decisions for how to handle size and alignment
416 // of `extern type`, this should be adapted. It is just a temporary hack
417 // to get some code to work that probably ought to work.
418 field_layout.align.abi
420 None => bug!("Cannot compute offset for extern type field at non-0 offset"),
422 (base.meta, offset.align_to(align))
424 // base.meta could be present; we might be accessing a sized field of an unsized
426 (MemPlaceMeta::None, offset)
429 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
430 // codegen -- mostly to see if we can get away with that
431 base.offset(offset, meta, field_layout, self)
434 /// Index into an array.
438 base: MPlaceTy<'tcx, M::PointerTag>,
440 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
441 // Not using the layout method because we want to compute on u64
442 match base.layout.fields {
443 FieldsShape::Array { stride, .. } => {
444 let len = base.len(self)?;
446 // This can only be reached in ConstProp and non-rustc-MIR.
447 throw_ub!(BoundsCheckFailed { len, index });
449 let offset = stride * index; // `Size` multiplication
450 // All fields have the same layout.
451 let field_layout = base.layout.field(self, 0)?;
453 assert!(!field_layout.is_unsized());
454 base.offset(offset, MemPlaceMeta::None, field_layout, self)
456 _ => bug!("`mplace_index` called on non-array type {:?}", base.layout.ty),
460 // Iterates over all fields of an array. Much more efficient than doing the
461 // same by repeatedly calling `mplace_array`.
462 pub(super) fn mplace_array_fields(
464 base: MPlaceTy<'tcx, Tag>,
465 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
467 let len = base.len(self)?; // also asserts that we have a type where this makes sense
468 let stride = match base.layout.fields {
469 FieldsShape::Array { stride, .. } => stride,
470 _ => bug!("mplace_array_fields: expected an array layout"),
472 let layout = base.layout.field(self, 0)?;
473 let dl = &self.tcx.data_layout;
474 // `Size` multiplication
475 Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
480 base: MPlaceTy<'tcx, M::PointerTag>,
484 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
485 let len = base.len(self)?; // also asserts that we have a type where this makes sense
486 let actual_to = if from_end {
487 if from.checked_add(to).map_or(true, |to| to > len) {
488 // This can only be reached in ConstProp and non-rustc-MIR.
489 throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
491 len.checked_sub(to).unwrap()
496 // Not using layout method because that works with usize, and does not work with slices
497 // (that have count 0 in their layout).
498 let from_offset = match base.layout.fields {
499 FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
500 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
503 // Compute meta and new layout
504 let inner_len = actual_to.checked_sub(from).unwrap();
505 let (meta, ty) = match base.layout.ty.kind {
506 // It is not nice to match on the type, but that seems to be the only way to
508 ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
510 let len = Scalar::from_machine_usize(inner_len, self);
511 (MemPlaceMeta::Meta(len), base.layout.ty)
513 _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
515 let layout = self.layout_of(ty)?;
516 base.offset(from_offset, meta, layout, self)
519 pub(super) fn mplace_downcast(
521 base: MPlaceTy<'tcx, M::PointerTag>,
523 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
524 // Downcasts only change the layout
525 assert!(!base.meta.has_meta());
526 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
529 /// Project into an mplace
530 pub(super) fn mplace_projection(
532 base: MPlaceTy<'tcx, M::PointerTag>,
533 proj_elem: &mir::PlaceElem<'tcx>,
534 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
535 use rustc_middle::mir::ProjectionElem::*;
536 Ok(match *proj_elem {
537 Field(field, _) => self.mplace_field(base, field.index())?,
538 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
539 Deref => self.deref_operand(base.into())?,
542 let layout = self.layout_of(self.tcx.types.usize)?;
543 let n = self.access_local(self.frame(), local, Some(layout))?;
544 let n = self.read_scalar(n)?;
545 let n = u64::try_from(
546 self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?,
549 self.mplace_index(base, n)?
552 ConstantIndex { offset, min_length, from_end } => {
553 let n = base.len(self)?;
554 if n < u64::from(min_length) {
555 // This can only be reached in ConstProp and non-rustc-MIR.
556 throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n });
559 let index = if from_end {
560 assert!(0 < offset && offset <= min_length);
561 n.checked_sub(u64::from(offset)).unwrap()
563 assert!(offset < min_length);
567 self.mplace_index(base, index)?
570 Subslice { from, to, from_end } => {
571 self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
576 /// Gets the place of a field inside the place, and also the field's type.
577 /// Just a convenience function, but used quite a bit.
578 /// This is the only projection that might have a side-effect: We cannot project
579 /// into the field of a local `ScalarPair`, we have to first allocate it.
582 base: PlaceTy<'tcx, M::PointerTag>,
584 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
585 // FIXME: We could try to be smarter and avoid allocation for fields that span the
587 let mplace = self.force_allocation(base)?;
588 Ok(self.mplace_field(mplace, field)?.into())
593 base: PlaceTy<'tcx, M::PointerTag>,
595 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
596 let mplace = self.force_allocation(base)?;
597 Ok(self.mplace_index(mplace, index)?.into())
600 pub fn place_downcast(
602 base: PlaceTy<'tcx, M::PointerTag>,
604 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
605 // Downcast just changes the layout
606 Ok(match base.place {
607 Place::Ptr(mplace) => {
608 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
610 Place::Local { .. } => {
611 let layout = base.layout.for_variant(self, variant);
612 PlaceTy { layout, ..base }
617 /// Projects into a place.
618 pub fn place_projection(
620 base: PlaceTy<'tcx, M::PointerTag>,
621 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
622 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
623 use rustc_middle::mir::ProjectionElem::*;
624 Ok(match *proj_elem {
625 Field(field, _) => self.place_field(base, field.index())?,
626 Downcast(_, variant) => self.place_downcast(base, variant)?,
627 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
628 // For the other variants, we have to force an allocation.
629 // This matches `operand_projection`.
630 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
631 let mplace = self.force_allocation(base)?;
632 self.mplace_projection(mplace, proj_elem)?.into()
637 /// Computes a place. You should only use this if you intend to write into this
638 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
641 place: mir::Place<'tcx>,
642 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
643 let mut place_ty = PlaceTy {
644 // This works even for dead/uninitialized locals; we check further when writing
645 place: Place::Local { frame: self.frame_idx(), local: place.local },
646 layout: self.layout_of_local(self.frame(), place.local, None)?,
649 for elem in place.projection.iter() {
650 place_ty = self.place_projection(place_ty, elem)?
653 self.dump_place(place_ty.place);
657 /// Write a scalar to a place
661 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
662 dest: PlaceTy<'tcx, M::PointerTag>,
663 ) -> InterpResult<'tcx> {
664 self.write_immediate(Immediate::Scalar(val.into()), dest)
667 /// Write an immediate to a place
669 pub fn write_immediate(
671 src: Immediate<M::PointerTag>,
672 dest: PlaceTy<'tcx, M::PointerTag>,
673 ) -> InterpResult<'tcx> {
674 self.write_immediate_no_validate(src, dest)?;
676 if M::enforce_validity(self) {
677 // Data got changed, better make sure it matches the type!
678 self.validate_operand(self.place_to_op(dest)?)?;
684 /// Write an `Immediate` to memory.
686 pub fn write_immediate_to_mplace(
688 src: Immediate<M::PointerTag>,
689 dest: MPlaceTy<'tcx, M::PointerTag>,
690 ) -> InterpResult<'tcx> {
691 self.write_immediate_to_mplace_no_validate(src, dest)?;
693 if M::enforce_validity(self) {
694 // Data got changed, better make sure it matches the type!
695 self.validate_operand(dest.into())?;
701 /// Write an immediate to a place.
702 /// If you use this you are responsible for validating that things got copied at the
704 fn write_immediate_no_validate(
706 src: Immediate<M::PointerTag>,
707 dest: PlaceTy<'tcx, M::PointerTag>,
708 ) -> InterpResult<'tcx> {
709 if cfg!(debug_assertions) {
710 // This is a very common path, avoid some checks in release mode
711 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
713 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
716 "Size mismatch when writing pointer"
718 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
720 Size::from_bytes(size),
722 "Size mismatch when writing bits"
725 Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
726 Immediate::ScalarPair(_, _) => {
727 // FIXME: Can we check anything here?
731 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
733 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
734 // but not factored as a separate function.
735 let mplace = match dest.place {
736 Place::Local { frame, local } => {
737 match self.stack_mut()[frame].locals[local].access_mut()? {
739 // Local can be updated in-place.
740 *local = LocalValue::Live(Operand::Immediate(src));
744 // The local is in memory, go on below.
749 Place::Ptr(mplace) => mplace, // already referring to memory
751 let dest = MPlaceTy { mplace, layout: dest.layout };
753 // This is already in memory, write there.
754 self.write_immediate_to_mplace_no_validate(src, dest)
757 /// Write an immediate to memory.
758 /// If you use this you are responsible for validating that things got copied at the
760 fn write_immediate_to_mplace_no_validate(
762 value: Immediate<M::PointerTag>,
763 dest: MPlaceTy<'tcx, M::PointerTag>,
764 ) -> InterpResult<'tcx> {
765 // Note that it is really important that the type here is the right one, and matches the
766 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
767 // to handle padding properly, which is only correct if we never look at this data with the
770 // Invalid places are a thing: the return place of a diverging function
771 let ptr = match self.check_mplace_access(dest, None)? {
773 None => return Ok(()), // zero-sized access
776 let tcx = &*self.tcx;
777 // FIXME: We should check that there are dest.layout.size many bytes available in
778 // memory. The code below is not sufficient, with enough padding it might not
779 // cover all the bytes!
781 Immediate::Scalar(scalar) => {
782 match dest.layout.abi {
783 Abi::Scalar(_) => {} // fine
785 bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
788 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
795 Immediate::ScalarPair(a_val, b_val) => {
796 // We checked `ptr_align` above, so all fields will have the alignment they need.
797 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
798 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
799 let (a, b) = match dest.layout.abi {
800 Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
802 "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.
814 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
815 self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
820 /// Copies the data from an operand to a place. This does not support transmuting!
821 /// Use `copy_op_transmute` if the layouts could disagree.
825 src: OpTy<'tcx, M::PointerTag>,
826 dest: PlaceTy<'tcx, M::PointerTag>,
827 ) -> InterpResult<'tcx> {
828 self.copy_op_no_validate(src, dest)?;
830 if M::enforce_validity(self) {
831 // Data got changed, better make sure it matches the type!
832 self.validate_operand(self.place_to_op(dest)?)?;
838 /// Copies the data from an operand to a place. This does not support transmuting!
839 /// Use `copy_op_transmute` if the layouts could disagree.
840 /// Also, if you use this you are responsible for validating that things get copied at the
842 fn copy_op_no_validate(
844 src: OpTy<'tcx, M::PointerTag>,
845 dest: PlaceTy<'tcx, M::PointerTag>,
846 ) -> InterpResult<'tcx> {
847 // We do NOT compare the types for equality, because well-typed code can
848 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
849 if !mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
852 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
858 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
859 let src = match self.try_read_immediate(src)? {
861 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
862 // Yay, we got a value that we can write directly.
863 // FIXME: Add a check to make sure that if `src` is indirect,
864 // it does not overlap with `dest`.
865 return self.write_immediate_no_validate(*src_val, dest);
867 Err(mplace) => mplace,
869 // Slow path, this does not fit into an immediate. Just memcpy.
870 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
872 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
873 // is being initialized!
874 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
875 let size = size.unwrap_or_else(|| {
877 !dest.layout.is_unsized(),
878 "Cannot copy into already initialized unsized place"
882 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
885 .check_mplace_access(src, Some(size))
886 .expect("places should be checked on creation");
888 .check_mplace_access(dest, Some(size))
889 .expect("places should be checked on creation");
890 let (src_ptr, dest_ptr) = match (src, dest) {
891 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
892 (None, None) => return Ok(()), // zero-sized copy
893 _ => bug!("The pointers should both be Some or both None"),
896 self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
899 /// Copies the data from an operand to a place. The layouts may disagree, but they must
900 /// have the same size.
901 pub fn copy_op_transmute(
903 src: OpTy<'tcx, M::PointerTag>,
904 dest: PlaceTy<'tcx, M::PointerTag>,
905 ) -> InterpResult<'tcx> {
906 if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
907 // Fast path: Just use normal `copy_op`
908 return self.copy_op(src, dest);
910 // We still require the sizes to match.
911 if src.layout.size != dest.layout.size {
912 // FIXME: This should be an assert instead of an error, but if we transmute within an
913 // array length computation, `typeck` may not have yet been run and errored out. In fact
914 // most likey we *are* running `typeck` right now. Investigate whether we can bail out
915 // on `typeck_tables().has_errors` at all const eval entry points.
916 debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
917 self.tcx.sess.delay_span_bug(
919 "size-changing transmute, should have been caught by transmute checking",
921 throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
923 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
924 // to avoid that here.
926 !src.layout.is_unsized() && !dest.layout.is_unsized(),
927 "Cannot transmute unsized data"
930 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
931 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
932 // We have to write them to `dest` at the offsets they were *read at*, which is
933 // not necessarily the same as the offsets in `dest.layout`!
934 // Hence we do the copy with the source layout on both sides. We also make sure to write
935 // into memory, because if `dest` is a local we would not even have a way to write
936 // at the `src` offsets; the fact that we came from a different layout would
938 let dest = self.force_allocation(dest)?;
939 self.copy_op_no_validate(
941 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
944 if M::enforce_validity(self) {
945 // Data got changed, better make sure it matches the type!
946 self.validate_operand(dest.into())?;
952 /// Ensures that a place is in memory, and returns where it is.
953 /// If the place currently refers to a local that doesn't yet have a matching allocation,
954 /// create such an allocation.
955 /// This is essentially `force_to_memplace`.
957 /// This supports unsized types and returns the computed size to avoid some
958 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
960 pub fn force_allocation_maybe_sized(
962 place: PlaceTy<'tcx, M::PointerTag>,
963 meta: MemPlaceMeta<M::PointerTag>,
964 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
965 let (mplace, size) = match place.place {
966 Place::Local { frame, local } => {
967 match self.stack_mut()[frame].locals[local].access_mut()? {
968 Ok(&mut local_val) => {
969 // We need to make an allocation.
971 // We need the layout of the local. We can NOT use the layout we got,
972 // that might e.g., be an inner field of a struct with `Scalar` layout,
973 // that has different alignment than the outer field.
975 self.layout_of_local(&self.stack()[frame], local, None)?;
976 // We also need to support unsized types, and hence cannot use `allocate`.
977 let (size, align) = self
978 .size_and_align_of(meta, local_layout)?
979 .expect("Cannot allocate for non-dyn-sized type");
980 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
981 let mplace = MemPlace { ptr: ptr.into(), align, meta };
982 if let LocalValue::Live(Operand::Immediate(value)) = local_val {
983 // Preserve old value.
984 // We don't have to validate as we can assume the local
985 // was already valid for its type.
986 let mplace = MPlaceTy { mplace, layout: local_layout };
987 self.write_immediate_to_mplace_no_validate(value, mplace)?;
989 // Now we can call `access_mut` again, asserting it goes well,
990 // and actually overwrite things.
991 *self.stack_mut()[frame].locals[local].access_mut().unwrap().unwrap() =
992 LocalValue::Live(Operand::Indirect(mplace));
995 Err(mplace) => (mplace, None), // this already was an indirect local
998 Place::Ptr(mplace) => (mplace, None),
1000 // Return with the original layout, so that the caller can go on
1001 Ok((MPlaceTy { mplace, layout: place.layout }, size))
1005 pub fn force_allocation(
1007 place: PlaceTy<'tcx, M::PointerTag>,
1008 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1009 Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
1014 layout: TyAndLayout<'tcx>,
1015 kind: MemoryKind<M::MemoryKind>,
1016 ) -> MPlaceTy<'tcx, M::PointerTag> {
1017 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1018 MPlaceTy::from_aligned_ptr(ptr, layout)
1021 /// Returns a wide MPlace.
1022 pub fn allocate_str(
1025 kind: MemoryKind<M::MemoryKind>,
1026 ) -> MPlaceTy<'tcx, M::PointerTag> {
1027 let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
1028 let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
1029 let mplace = MemPlace {
1031 align: Align::from_bytes(1).unwrap(),
1032 meta: MemPlaceMeta::Meta(meta),
1035 let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1036 MPlaceTy { mplace, layout }
1039 pub fn write_discriminant_index(
1041 variant_index: VariantIdx,
1042 dest: PlaceTy<'tcx, M::PointerTag>,
1043 ) -> InterpResult<'tcx> {
1044 // Layout computation excludes uninhabited variants from consideration
1045 // therefore there's no way to represent those variants in the given layout.
1046 if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1047 throw_ub!(Unreachable);
1050 match dest.layout.variants {
1051 Variants::Single { index } => {
1052 assert_eq!(index, variant_index);
1054 Variants::Multiple {
1055 discr_kind: DiscriminantKind::Tag,
1056 discr: ref discr_layout,
1060 // No need to validate that the discriminant here because the
1061 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1064 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1066 // raw discriminants for enums are isize or bigger during
1067 // their computation, but the in-memory tag is the smallest possible
1069 let size = discr_layout.value.size(self);
1070 let discr_val = truncate(discr_val, size);
1072 let discr_dest = self.place_field(dest, discr_index)?;
1073 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1075 Variants::Multiple {
1077 DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1078 discr: ref discr_layout,
1082 // No need to validate that the discriminant here because the
1083 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1085 if variant_index != dataful_variant {
1086 let variants_start = niche_variants.start().as_u32();
1087 let variant_index_relative = variant_index
1089 .checked_sub(variants_start)
1090 .expect("overflow computing relative variant idx");
1091 // We need to use machine arithmetic when taking into account `niche_start`:
1092 // discr_val = variant_index_relative + niche_start_val
1093 let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1094 let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1095 let variant_index_relative_val =
1096 ImmTy::from_uint(variant_index_relative, discr_layout);
1097 let discr_val = self.binary_op(
1099 variant_index_relative_val,
1103 let niche_dest = self.place_field(dest, discr_index)?;
1104 self.write_immediate(*discr_val, niche_dest)?;
1112 pub fn raw_const_to_mplace(
1114 raw: RawConst<'tcx>,
1115 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1116 // This must be an allocation in `tcx`
1117 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1118 let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1119 let layout = self.layout_of(raw.ty)?;
1120 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1123 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1124 /// Also return some more information so drop doesn't have to run the same code twice.
1125 pub(super) fn unpack_dyn_trait(
1127 mplace: MPlaceTy<'tcx, M::PointerTag>,
1128 ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1129 let vtable = mplace.vtable(); // also sanity checks the type
1130 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1131 let layout = self.layout_of(ty)?;
1133 // More sanity checks
1134 if cfg!(debug_assertions) {
1135 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1136 assert_eq!(size, layout.size);
1137 // only ABI alignment is preserved
1138 assert_eq!(align, layout.align.abi);
1141 let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1142 Ok((instance, mplace))