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, ScalarMaybeUninit,
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
22 /// Information required for the sound usage of a `MemPlace`.
23 pub enum MemPlaceMeta<Tag = ()> {
24 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
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> MemPlaceMeta<Tag> {
36 pub fn unwrap_meta(self) -> Scalar<Tag> {
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,
51 pub fn erase_tag(self) -> MemPlaceMeta<()> {
53 Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
54 Self::None => MemPlaceMeta::None,
55 Self::Poison => MemPlaceMeta::Poison,
60 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
61 pub struct MemPlace<Tag = ()> {
62 /// A place may have an integral pointer for ZSTs, and since it might
63 /// be turned back into a reference before ever being dereferenced.
64 /// However, it may never be undef.
67 /// Metadata for unsized places. Interpretation is up to the type.
68 /// Must not be present for sized types, but can be missing for unsized types
69 /// (e.g., `extern type`).
70 pub meta: MemPlaceMeta<Tag>,
73 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
74 pub enum Place<Tag = ()> {
75 /// A place referring to a value allocated in the `Memory` system.
78 /// To support alloc-free locals, we are able to write directly to a local.
79 /// (Without that optimization, we'd just always be a `MemPlace`.)
80 Local { frame: usize, local: mir::Local },
83 #[derive(Copy, Clone, Debug)]
84 pub struct PlaceTy<'tcx, Tag = ()> {
85 place: Place<Tag>, // Keep this private; it helps enforce invariants.
86 pub layout: TyAndLayout<'tcx>,
89 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
90 type Target = Place<Tag>;
92 fn deref(&self) -> &Place<Tag> {
97 /// A MemPlace with its layout. Constructing it is only possible in this module.
98 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
99 pub struct MPlaceTy<'tcx, Tag = ()> {
100 mplace: MemPlace<Tag>,
101 pub layout: TyAndLayout<'tcx>,
104 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
105 type Target = MemPlace<Tag>;
107 fn deref(&self) -> &MemPlace<Tag> {
112 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
114 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
115 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
119 impl<Tag> MemPlace<Tag> {
120 /// Replace ptr tag, maintain vtable tag (if any)
122 pub fn replace_tag(self, new_tag: Tag) -> Self {
123 MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
127 pub fn erase_tag(self) -> MemPlace {
128 MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
132 fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
133 MemPlace { ptr, align, meta: MemPlaceMeta::None }
137 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
138 Self::from_scalar_ptr(ptr.into(), align)
141 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
142 /// This is the inverse of `ref_to_mplace`.
144 pub fn to_ref(self) -> Immediate<Tag> {
146 MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
147 MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
148 MemPlaceMeta::Poison => bug!(
149 "MPlaceTy::dangling may never be used to produce a \
150 place that will have the address of its pointee taken"
158 meta: MemPlaceMeta<Tag>,
159 cx: &impl HasDataLayout,
160 ) -> InterpResult<'tcx, Self> {
162 ptr: self.ptr.ptr_offset(offset, cx)?,
163 align: self.align.restrict_for_offset(offset),
169 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
170 /// Produces a MemPlace that works for ZST but nothing else
172 pub fn dangling(layout: TyAndLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
173 let align = layout.align.abi;
174 let ptr = Scalar::from_machine_usize(align.bytes(), cx);
175 // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
176 MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
179 /// Replace ptr tag, maintain vtable tag (if any)
181 pub fn replace_tag(self, new_tag: Tag) -> Self {
182 MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
189 meta: MemPlaceMeta<Tag>,
190 layout: TyAndLayout<'tcx>,
191 cx: &impl HasDataLayout,
192 ) -> InterpResult<'tcx, Self> {
193 Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
197 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
198 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
202 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
203 if self.layout.is_unsized() {
204 // We need to consult `meta` metadata
205 match self.layout.ty.kind {
206 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
207 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
210 // Go through the layout. There are lots of types that support a length,
212 match self.layout.fields {
213 FieldsShape::Array { count, .. } => Ok(count),
214 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
220 pub(super) fn vtable(self) -> Scalar<Tag> {
221 match self.layout.ty.kind {
222 ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
223 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
228 // These are defined here because they produce a place.
229 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
231 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
232 /// read from the resulting mplace, not to get its address back.
233 pub fn try_as_mplace(
235 cx: &impl HasDataLayout,
236 ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
238 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
239 Operand::Immediate(_) if self.layout.is_zst() => {
240 Ok(MPlaceTy::dangling(self.layout, cx))
242 Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
247 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
248 /// read from the resulting mplace, not to get its address back.
249 pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
250 self.try_as_mplace(cx).unwrap()
254 impl<Tag: ::std::fmt::Debug> Place<Tag> {
256 pub fn assert_mem_place(self) -> MemPlace<Tag> {
258 Place::Ptr(mplace) => mplace,
259 _ => 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: 'mir, 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::MemoryKind>, 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>> {
292 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
293 let layout = self.layout_of(pointee_type)?;
294 let (ptr, meta) = match *val {
295 Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
296 Immediate::ScalarPair(ptr, meta) => {
297 (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
301 let mplace = MemPlace {
303 // We could use the run-time alignment here. For now, we do not, because
304 // the point of tracking the alignment here is to make sure that the *static*
305 // alignment information emitted with the loads is correct. The run-time
306 // alignment can only be more restrictive.
307 align: layout.align.abi,
310 Ok(MPlaceTy { mplace, layout })
313 /// Take an operand, representing a pointer, and dereference it to a place -- that
314 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
315 pub fn deref_operand(
317 src: OpTy<'tcx, M::PointerTag>,
318 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
319 let val = self.read_immediate(src)?;
320 trace!("deref to {} on {:?}", val.layout.ty, *val);
321 let place = self.ref_to_mplace(val)?;
322 self.mplace_access_checked(place, None)
325 /// Check if the given place is good for memory access with the given
326 /// size, falling back to the layout's size if `None` (in the latter case,
327 /// this must be a statically sized type).
329 /// On success, returns `None` for zero-sized accesses (where nothing else is
330 /// left to do) and a `Pointer` to use for the actual access otherwise.
332 pub(super) fn check_mplace_access(
334 place: MPlaceTy<'tcx, M::PointerTag>,
336 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
337 let size = size.unwrap_or_else(|| {
338 assert!(!place.layout.is_unsized());
339 assert!(!place.meta.has_meta());
342 self.memory.check_ptr_access(place.ptr, size, place.align)
345 /// Return the "access-checked" version of this `MPlace`, where for non-ZST
346 /// this is definitely a `Pointer`.
348 /// `force_align` must only be used when correct alignment does not matter,
349 /// like in Stacked Borrows.
350 pub fn mplace_access_checked(
352 mut place: MPlaceTy<'tcx, M::PointerTag>,
353 force_align: Option<Align>,
354 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
355 let (size, align) = self
356 .size_and_align_of_mplace(place)?
357 .unwrap_or((place.layout.size, place.layout.align.abi));
358 assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
359 // Check (stricter) dynamic alignment, unless forced otherwise.
360 place.mplace.align = force_align.unwrap_or(align);
361 // When dereferencing a pointer, it must be non-NULL, aligned, and live.
362 if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
363 place.mplace.ptr = ptr.into();
368 /// Force `place.ptr` to a `Pointer`.
369 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
370 pub(super) fn force_mplace_ptr(
372 mut place: MPlaceTy<'tcx, M::PointerTag>,
373 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
374 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
378 /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
379 /// always possible without allocating, so it can take `&self`. Also return the field's layout.
380 /// This supports both struct and array fields.
382 /// This also works for arrays, but then the `usize` index type is restricting.
383 /// For indexing into arrays, use `mplace_index`.
387 base: MPlaceTy<'tcx, M::PointerTag>,
389 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
390 let offset = base.layout.fields.offset(field);
391 let field_layout = base.layout.field(self, field)?;
393 // Offset may need adjustment for unsized fields.
394 let (meta, offset) = if field_layout.is_unsized() {
395 // Re-use parent metadata to determine dynamic field layout.
396 // With custom DSTS, this *will* execute user-defined code, but the same
397 // happens at run-time so that's okay.
398 let align = match self.size_and_align_of(base.meta, field_layout)? {
399 Some((_, align)) => align,
400 None if offset == Size::ZERO => {
401 // An extern type at offset 0, we fall back to its static alignment.
402 // FIXME: Once we have made decisions for how to handle size and alignment
403 // of `extern type`, this should be adapted. It is just a temporary hack
404 // to get some code to work that probably ought to work.
405 field_layout.align.abi
407 None => bug!("Cannot compute offset for extern type field at non-0 offset"),
409 (base.meta, offset.align_to(align))
411 // base.meta could be present; we might be accessing a sized field of an unsized
413 (MemPlaceMeta::None, offset)
416 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
417 // codegen -- mostly to see if we can get away with that
418 base.offset(offset, meta, field_layout, self)
421 /// Index into an array.
425 base: MPlaceTy<'tcx, M::PointerTag>,
427 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
428 // Not using the layout method because we want to compute on u64
429 match base.layout.fields {
430 FieldsShape::Array { stride, .. } => {
431 let len = base.len(self)?;
433 // This can only be reached in ConstProp and non-rustc-MIR.
434 throw_ub!(BoundsCheckFailed { len, index });
436 let offset = stride * index; // `Size` multiplication
437 // All fields have the same layout.
438 let field_layout = base.layout.field(self, 0)?;
440 assert!(!field_layout.is_unsized());
441 base.offset(offset, MemPlaceMeta::None, field_layout, self)
443 _ => bug!("`mplace_index` called on non-array type {:?}", base.layout.ty),
447 // Iterates over all fields of an array. Much more efficient than doing the
448 // same by repeatedly calling `mplace_array`.
449 pub(super) fn mplace_array_fields(
451 base: MPlaceTy<'tcx, Tag>,
452 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
454 let len = base.len(self)?; // also asserts that we have a type where this makes sense
455 let stride = match base.layout.fields {
456 FieldsShape::Array { stride, .. } => stride,
457 _ => bug!("mplace_array_fields: expected an array layout"),
459 let layout = base.layout.field(self, 0)?;
460 let dl = &self.tcx.data_layout;
461 // `Size` multiplication
462 Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
467 base: MPlaceTy<'tcx, M::PointerTag>,
471 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
472 let len = base.len(self)?; // also asserts that we have a type where this makes sense
473 let actual_to = if from_end {
474 if from.checked_add(to).map_or(true, |to| to > len) {
475 // This can only be reached in ConstProp and non-rustc-MIR.
476 throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
478 len.checked_sub(to).unwrap()
483 // Not using layout method because that works with usize, and does not work with slices
484 // (that have count 0 in their layout).
485 let from_offset = match base.layout.fields {
486 FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
487 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
490 // Compute meta and new layout
491 let inner_len = actual_to.checked_sub(from).unwrap();
492 let (meta, ty) = match base.layout.ty.kind {
493 // It is not nice to match on the type, but that seems to be the only way to
495 ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
497 let len = Scalar::from_machine_usize(inner_len, self);
498 (MemPlaceMeta::Meta(len), base.layout.ty)
500 _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
502 let layout = self.layout_of(ty)?;
503 base.offset(from_offset, meta, layout, self)
506 pub(super) fn mplace_downcast(
508 base: MPlaceTy<'tcx, M::PointerTag>,
510 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
511 // Downcasts only change the layout
512 assert!(!base.meta.has_meta());
513 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
516 /// Project into an mplace
517 pub(super) fn mplace_projection(
519 base: MPlaceTy<'tcx, M::PointerTag>,
520 proj_elem: &mir::PlaceElem<'tcx>,
521 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
522 use rustc_middle::mir::ProjectionElem::*;
523 Ok(match *proj_elem {
524 Field(field, _) => self.mplace_field(base, field.index())?,
525 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
526 Deref => self.deref_operand(base.into())?,
529 let layout = self.layout_of(self.tcx.types.usize)?;
530 let n = self.access_local(self.frame(), local, Some(layout))?;
531 let n = self.read_scalar(n)?;
532 let n = u64::try_from(
533 self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?,
536 self.mplace_index(base, n)?
539 ConstantIndex { offset, min_length, from_end } => {
540 let n = base.len(self)?;
541 if n < u64::from(min_length) {
542 // This can only be reached in ConstProp and non-rustc-MIR.
543 throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n });
546 let index = if from_end {
547 assert!(0 < offset && offset <= min_length);
548 n.checked_sub(u64::from(offset)).unwrap()
550 assert!(offset < min_length);
554 self.mplace_index(base, index)?
557 Subslice { from, to, from_end } => {
558 self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
563 /// Gets the place of a field inside the place, and also the field's type.
564 /// Just a convenience function, but used quite a bit.
565 /// This is the only projection that might have a side-effect: We cannot project
566 /// into the field of a local `ScalarPair`, we have to first allocate it.
569 base: PlaceTy<'tcx, M::PointerTag>,
571 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
572 // FIXME: We could try to be smarter and avoid allocation for fields that span the
574 let mplace = self.force_allocation(base)?;
575 Ok(self.mplace_field(mplace, field)?.into())
580 base: PlaceTy<'tcx, M::PointerTag>,
582 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
583 let mplace = self.force_allocation(base)?;
584 Ok(self.mplace_index(mplace, index)?.into())
587 pub fn place_downcast(
589 base: PlaceTy<'tcx, M::PointerTag>,
591 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
592 // Downcast just changes the layout
593 Ok(match base.place {
594 Place::Ptr(mplace) => {
595 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
597 Place::Local { .. } => {
598 let layout = base.layout.for_variant(self, variant);
599 PlaceTy { layout, ..base }
604 /// Projects into a place.
605 pub fn place_projection(
607 base: PlaceTy<'tcx, M::PointerTag>,
608 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
609 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
610 use rustc_middle::mir::ProjectionElem::*;
611 Ok(match *proj_elem {
612 Field(field, _) => self.place_field(base, field.index())?,
613 Downcast(_, variant) => self.place_downcast(base, variant)?,
614 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
615 // For the other variants, we have to force an allocation.
616 // This matches `operand_projection`.
617 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
618 let mplace = self.force_allocation(base)?;
619 self.mplace_projection(mplace, proj_elem)?.into()
624 /// Computes a place. You should only use this if you intend to write into this
625 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
628 place: mir::Place<'tcx>,
629 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
630 let mut place_ty = PlaceTy {
631 // This works even for dead/uninitialized locals; we check further when writing
632 place: Place::Local { frame: self.frame_idx(), local: place.local },
633 layout: self.layout_of_local(self.frame(), place.local, None)?,
636 for elem in place.projection.iter() {
637 place_ty = self.place_projection(place_ty, elem)?
640 self.dump_place(place_ty.place);
644 /// Write a scalar to a place
648 val: impl Into<ScalarMaybeUninit<M::PointerTag>>,
649 dest: PlaceTy<'tcx, M::PointerTag>,
650 ) -> InterpResult<'tcx> {
651 self.write_immediate(Immediate::Scalar(val.into()), dest)
654 /// Write an immediate to a place
656 pub fn write_immediate(
658 src: Immediate<M::PointerTag>,
659 dest: PlaceTy<'tcx, M::PointerTag>,
660 ) -> InterpResult<'tcx> {
661 self.write_immediate_no_validate(src, dest)?;
663 if M::enforce_validity(self) {
664 // Data got changed, better make sure it matches the type!
665 self.validate_operand(self.place_to_op(dest)?)?;
671 /// Write an `Immediate` to memory.
673 pub fn write_immediate_to_mplace(
675 src: Immediate<M::PointerTag>,
676 dest: MPlaceTy<'tcx, M::PointerTag>,
677 ) -> InterpResult<'tcx> {
678 self.write_immediate_to_mplace_no_validate(src, dest)?;
680 if M::enforce_validity(self) {
681 // Data got changed, better make sure it matches the type!
682 self.validate_operand(dest.into())?;
688 /// Write an immediate to a place.
689 /// If you use this you are responsible for validating that things got copied at the
691 fn write_immediate_no_validate(
693 src: Immediate<M::PointerTag>,
694 dest: PlaceTy<'tcx, M::PointerTag>,
695 ) -> InterpResult<'tcx> {
696 if cfg!(debug_assertions) {
697 // This is a very common path, avoid some checks in release mode
698 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
700 Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Ptr(_))) => assert_eq!(
703 "Size mismatch when writing pointer"
705 Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Raw { size, .. })) => {
707 Size::from_bytes(size),
709 "Size mismatch when writing bits"
712 Immediate::Scalar(ScalarMaybeUninit::Uninit) => {} // undef can have any size
713 Immediate::ScalarPair(_, _) => {
714 // FIXME: Can we check anything here?
718 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
720 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
721 // but not factored as a separate function.
722 let mplace = match dest.place {
723 Place::Local { frame, local } => {
724 match self.stack_mut()[frame].locals[local].access_mut()? {
726 // Local can be updated in-place.
727 *local = LocalValue::Live(Operand::Immediate(src));
731 // The local is in memory, go on below.
736 Place::Ptr(mplace) => mplace, // already referring to memory
738 let dest = MPlaceTy { mplace, layout: dest.layout };
740 // This is already in memory, write there.
741 self.write_immediate_to_mplace_no_validate(src, dest)
744 /// Write an immediate to memory.
745 /// If you use this you are responsible for validating that things got copied at the
747 fn write_immediate_to_mplace_no_validate(
749 value: Immediate<M::PointerTag>,
750 dest: MPlaceTy<'tcx, M::PointerTag>,
751 ) -> InterpResult<'tcx> {
752 // Note that it is really important that the type here is the right one, and matches the
753 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
754 // to handle padding properly, which is only correct if we never look at this data with the
757 // Invalid places are a thing: the return place of a diverging function
758 let ptr = match self.check_mplace_access(dest, None)? {
760 None => return Ok(()), // zero-sized access
763 let tcx = &*self.tcx;
764 // FIXME: We should check that there are dest.layout.size many bytes available in
765 // memory. The code below is not sufficient, with enough padding it might not
766 // cover all the bytes!
768 Immediate::Scalar(scalar) => {
769 match dest.layout.abi {
770 Abi::Scalar(_) => {} // fine
772 bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
775 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
782 Immediate::ScalarPair(a_val, b_val) => {
783 // We checked `ptr_align` above, so all fields will have the alignment they need.
784 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
785 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
786 let (a, b) = match dest.layout.abi {
787 Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
789 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
793 let (a_size, b_size) = (a.size(self), b.size(self));
794 let b_offset = a_size.align_to(b.align(self).abi);
795 let b_ptr = ptr.offset(b_offset, self)?;
797 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
798 // but that does not work: We could be a newtype around a pair, then the
799 // fields do not match the `ScalarPair` components.
801 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
802 self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
807 /// Copies the data from an operand to a place. This does not support transmuting!
808 /// Use `copy_op_transmute` if the layouts could disagree.
812 src: OpTy<'tcx, M::PointerTag>,
813 dest: PlaceTy<'tcx, M::PointerTag>,
814 ) -> InterpResult<'tcx> {
815 self.copy_op_no_validate(src, dest)?;
817 if M::enforce_validity(self) {
818 // Data got changed, better make sure it matches the type!
819 self.validate_operand(self.place_to_op(dest)?)?;
825 /// Copies the data from an operand to a place. This does not support transmuting!
826 /// Use `copy_op_transmute` if the layouts could disagree.
827 /// Also, if you use this you are responsible for validating that things get copied at the
829 fn copy_op_no_validate(
831 src: OpTy<'tcx, M::PointerTag>,
832 dest: PlaceTy<'tcx, M::PointerTag>,
833 ) -> InterpResult<'tcx> {
834 // We do NOT compare the types for equality, because well-typed code can
835 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
836 if !mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
839 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
845 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
846 let src = match self.try_read_immediate(src)? {
848 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
849 // Yay, we got a value that we can write directly.
850 // FIXME: Add a check to make sure that if `src` is indirect,
851 // it does not overlap with `dest`.
852 return self.write_immediate_no_validate(*src_val, dest);
854 Err(mplace) => mplace,
856 // Slow path, this does not fit into an immediate. Just memcpy.
857 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
859 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
860 // is being initialized!
861 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
862 let size = size.unwrap_or_else(|| {
864 !dest.layout.is_unsized(),
865 "Cannot copy into already initialized unsized place"
869 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
872 .check_mplace_access(src, Some(size))
873 .expect("places should be checked on creation");
875 .check_mplace_access(dest, Some(size))
876 .expect("places should be checked on creation");
877 let (src_ptr, dest_ptr) = match (src, dest) {
878 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
879 (None, None) => return Ok(()), // zero-sized copy
880 _ => bug!("The pointers should both be Some or both None"),
883 self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
886 /// Copies the data from an operand to a place. The layouts may disagree, but they must
887 /// have the same size.
888 pub fn copy_op_transmute(
890 src: OpTy<'tcx, M::PointerTag>,
891 dest: PlaceTy<'tcx, M::PointerTag>,
892 ) -> InterpResult<'tcx> {
893 if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
894 // Fast path: Just use normal `copy_op`
895 return self.copy_op(src, dest);
897 // We still require the sizes to match.
898 if src.layout.size != dest.layout.size {
899 // FIXME: This should be an assert instead of an error, but if we transmute within an
900 // array length computation, `typeck` may not have yet been run and errored out. In fact
901 // most likey we *are* running `typeck` right now. Investigate whether we can bail out
902 // on `typeck_tables().has_errors` at all const eval entry points.
903 debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
904 self.tcx.sess.delay_span_bug(
906 "size-changing transmute, should have been caught by transmute checking",
908 throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
910 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
911 // to avoid that here.
913 !src.layout.is_unsized() && !dest.layout.is_unsized(),
914 "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())?;
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: MemPlaceMeta<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_mut()[frame].locals[local].access_mut()? {
955 Ok(&mut local_val) => {
956 // We need to make an allocation.
958 // We need the layout of the local. We can NOT use the layout we got,
959 // that might e.g., be an inner field of a struct with `Scalar` layout,
960 // that has different alignment than the outer field.
962 self.layout_of_local(&self.stack()[frame], local, None)?;
963 // We also need to support unsized types, and hence cannot use `allocate`.
964 let (size, align) = self
965 .size_and_align_of(meta, local_layout)?
966 .expect("Cannot allocate for non-dyn-sized type");
967 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
968 let mplace = MemPlace { ptr: ptr.into(), align, meta };
969 if let LocalValue::Live(Operand::Immediate(value)) = local_val {
970 // Preserve old value.
971 // We don't have to validate as we can assume the local
972 // was already valid for its type.
973 let mplace = MPlaceTy { mplace, layout: local_layout };
974 self.write_immediate_to_mplace_no_validate(value, mplace)?;
976 // Now we can call `access_mut` again, asserting it goes well,
977 // and actually overwrite things.
978 *self.stack_mut()[frame].locals[local].access_mut().unwrap().unwrap() =
979 LocalValue::Live(Operand::Indirect(mplace));
982 Err(mplace) => (mplace, None), // this already was an indirect local
985 Place::Ptr(mplace) => (mplace, None),
987 // Return with the original layout, so that the caller can go on
988 Ok((MPlaceTy { mplace, layout: place.layout }, size))
992 pub fn force_allocation(
994 place: PlaceTy<'tcx, M::PointerTag>,
995 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
996 Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
1001 layout: TyAndLayout<'tcx>,
1002 kind: MemoryKind<M::MemoryKind>,
1003 ) -> MPlaceTy<'tcx, M::PointerTag> {
1004 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1005 MPlaceTy::from_aligned_ptr(ptr, layout)
1008 /// Returns a wide MPlace.
1009 pub fn allocate_str(
1012 kind: MemoryKind<M::MemoryKind>,
1013 ) -> MPlaceTy<'tcx, M::PointerTag> {
1014 let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
1015 let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
1016 let mplace = MemPlace {
1018 align: Align::from_bytes(1).unwrap(),
1019 meta: MemPlaceMeta::Meta(meta),
1022 let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1023 MPlaceTy { mplace, layout }
1026 pub fn write_discriminant_index(
1028 variant_index: VariantIdx,
1029 dest: PlaceTy<'tcx, M::PointerTag>,
1030 ) -> InterpResult<'tcx> {
1031 // Layout computation excludes uninhabited variants from consideration
1032 // therefore there's no way to represent those variants in the given layout.
1033 if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1034 throw_ub!(Unreachable);
1037 match dest.layout.variants {
1038 Variants::Single { index } => {
1039 assert_eq!(index, variant_index);
1041 Variants::Multiple {
1042 discr_kind: DiscriminantKind::Tag,
1043 discr: ref discr_layout,
1047 // No need to validate that the discriminant here because the
1048 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1051 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1053 // raw discriminants for enums are isize or bigger during
1054 // their computation, but the in-memory tag is the smallest possible
1056 let size = discr_layout.value.size(self);
1057 let discr_val = truncate(discr_val, size);
1059 let discr_dest = self.place_field(dest, discr_index)?;
1060 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1062 Variants::Multiple {
1064 DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1065 discr: ref discr_layout,
1069 // No need to validate that the discriminant here because the
1070 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1072 if variant_index != dataful_variant {
1073 let variants_start = niche_variants.start().as_u32();
1074 let variant_index_relative = variant_index
1076 .checked_sub(variants_start)
1077 .expect("overflow computing relative variant idx");
1078 // We need to use machine arithmetic when taking into account `niche_start`:
1079 // discr_val = variant_index_relative + niche_start_val
1080 let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1081 let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1082 let variant_index_relative_val =
1083 ImmTy::from_uint(variant_index_relative, discr_layout);
1084 let discr_val = self.binary_op(
1086 variant_index_relative_val,
1090 let niche_dest = self.place_field(dest, discr_index)?;
1091 self.write_immediate(*discr_val, niche_dest)?;
1099 pub fn raw_const_to_mplace(
1101 raw: RawConst<'tcx>,
1102 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1103 // This must be an allocation in `tcx`
1104 let _ = self.tcx.global_alloc(raw.alloc_id);
1105 let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1106 let layout = self.layout_of(raw.ty)?;
1107 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1110 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1111 /// Also return some more information so drop doesn't have to run the same code twice.
1112 pub(super) fn unpack_dyn_trait(
1114 mplace: MPlaceTy<'tcx, M::PointerTag>,
1115 ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1116 let vtable = mplace.vtable(); // also sanity checks the type
1117 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1118 let layout = self.layout_of(ty)?;
1120 // More sanity checks
1121 if cfg!(debug_assertions) {
1122 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1123 assert_eq!(size, layout.size);
1124 // only ABI alignment is preserved
1125 assert_eq!(align, layout.align.abi);
1128 let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1129 Ok((instance, mplace))