1 //! Computations on places -- field projections, going from mir::Place, and writing
3 //! All high-level functions to write to memory work on places as destinations.
5 use std::convert::TryFrom;
9 use rustc::mir::interpret::truncate;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
12 use rustc::ty::TypeFoldable;
15 GlobalId, AllocId, Allocation, Scalar, InterpResult, Pointer, PointerArithmetic,
16 InterpCx, Machine, AllocMap, AllocationExtra,
17 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue,
20 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
21 pub struct MemPlace<Tag=(), Id=AllocId> {
22 /// A place may have an integral pointer for ZSTs, and since it might
23 /// be turned back into a reference before ever being dereferenced.
24 /// However, it may never be undef.
25 pub ptr: Scalar<Tag, Id>,
27 /// Metadata for unsized places. Interpretation is up to the type.
28 /// Must not be present for sized types, but can be missing for unsized types
29 /// (e.g., `extern type`).
30 pub meta: Option<Scalar<Tag, Id>>,
33 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
34 pub enum Place<Tag=(), Id=AllocId> {
35 /// A place referring to a value allocated in the `Memory` system.
36 Ptr(MemPlace<Tag, Id>),
38 /// To support alloc-free locals, we are able to write directly to a local.
39 /// (Without that optimization, we'd just always be a `MemPlace`.)
46 #[derive(Copy, Clone, Debug)]
47 pub struct PlaceTy<'tcx, Tag=()> {
49 pub layout: TyLayout<'tcx>,
52 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
53 type Target = Place<Tag>;
55 fn deref(&self) -> &Place<Tag> {
60 /// A MemPlace with its layout. Constructing it is only possible in this module.
61 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
62 pub struct MPlaceTy<'tcx, Tag=()> {
63 mplace: MemPlace<Tag>,
64 pub layout: TyLayout<'tcx>,
67 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
68 type Target = MemPlace<Tag>;
70 fn deref(&self) -> &MemPlace<Tag> {
75 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
77 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
79 place: Place::Ptr(mplace.mplace),
85 impl<Tag> MemPlace<Tag> {
86 /// Replace ptr tag, maintain vtable tag (if any)
88 pub fn replace_tag(self, new_tag: Tag) -> Self {
90 ptr: self.ptr.erase_tag().with_tag(new_tag),
97 pub fn erase_tag(self) -> MemPlace {
99 ptr: self.ptr.erase_tag(),
101 meta: self.meta.map(Scalar::erase_tag),
106 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
114 /// Produces a Place that will error if attempted to be read from or written to
116 pub fn null(cx: &impl HasDataLayout) -> Self {
117 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
121 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
122 Self::from_scalar_ptr(ptr.into(), align)
125 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
126 /// This is the inverse of `ref_to_mplace`.
128 pub fn to_ref(self) -> Immediate<Tag> {
130 None => Immediate::Scalar(self.ptr.into()),
131 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
138 meta: Option<Scalar<Tag>>,
139 cx: &impl HasDataLayout,
140 ) -> InterpResult<'tcx, Self> {
142 ptr: self.ptr.ptr_offset(offset, cx)?,
143 align: self.align.restrict_for_offset(offset),
149 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
150 /// Produces a MemPlace that works for ZST but nothing else
152 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
154 mplace: MemPlace::from_scalar_ptr(
155 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
162 /// Replace ptr tag, maintain vtable tag (if any)
164 pub fn replace_tag(self, new_tag: Tag) -> Self {
166 mplace: self.mplace.replace_tag(new_tag),
175 meta: Option<Scalar<Tag>>,
176 layout: TyLayout<'tcx>,
177 cx: &impl HasDataLayout,
178 ) -> InterpResult<'tcx, Self> {
180 mplace: self.mplace.offset(offset, meta, cx)?,
186 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
187 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
191 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
192 if self.layout.is_unsized() {
193 // We need to consult `meta` metadata
194 match self.layout.ty.sty {
195 ty::Slice(..) | ty::Str =>
196 return self.mplace.meta.unwrap().to_usize(cx),
197 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
200 // Go through the layout. There are lots of types that support a length,
202 match self.layout.fields {
203 layout::FieldPlacement::Array { count, .. } => Ok(count),
204 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
210 pub(super) fn vtable(self) -> Scalar<Tag> {
211 match self.layout.ty.sty {
212 ty::Dynamic(..) => self.mplace.meta.unwrap(),
213 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
218 // These are defined here because they produce a place.
219 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
221 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
223 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
224 Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
229 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
230 self.try_as_mplace().unwrap()
234 impl<Tag: ::std::fmt::Debug> Place<Tag> {
235 /// Produces a Place that will error if attempted to be read from or written to
237 pub fn null(cx: &impl HasDataLayout) -> Self {
238 Place::Ptr(MemPlace::null(cx))
242 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
243 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
247 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
248 Place::Ptr(MemPlace::from_ptr(ptr, align))
252 pub fn assert_mem_place(self) -> MemPlace<Tag> {
254 Place::Ptr(mplace) => mplace,
255 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
261 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
263 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
264 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
268 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
269 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
271 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
272 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
273 M: Machine<'mir, 'tcx, PointerTag = Tag>,
274 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
275 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
276 M::AllocExtra: AllocationExtra<Tag>,
278 /// Take a value, which represents a (thin or fat) reference, and make it a place.
279 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
280 pub fn ref_to_mplace(
282 val: ImmTy<'tcx, M::PointerTag>,
283 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
284 let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
285 let layout = self.layout_of(pointee_type)?;
287 let mplace = MemPlace {
288 ptr: val.to_scalar_ptr()?,
289 // We could use the run-time alignment here. For now, we do not, because
290 // the point of tracking the alignment here is to make sure that the *static*
291 // alignment information emitted with the loads is correct. The run-time
292 // alignment can only be more restrictive.
293 align: layout.align.abi,
294 meta: val.to_meta()?,
296 Ok(MPlaceTy { mplace, layout })
299 /// Take an operand, representing a pointer, and dereference it to a place -- that
300 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
301 pub fn deref_operand(
303 src: OpTy<'tcx, M::PointerTag>,
304 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
305 let val = self.read_immediate(src)?;
306 trace!("deref to {} on {:?}", val.layout.ty, *val);
307 self.ref_to_mplace(val)
310 /// Check if the given place is good for memory access with the given
311 /// size, falling back to the layout's size if `None` (in the latter case,
312 /// this must be a statically sized type).
314 /// On success, returns `None` for zero-sized accesses (where nothing else is
315 /// left to do) and a `Pointer` to use for the actual access otherwise.
317 pub fn check_mplace_access(
319 place: MPlaceTy<'tcx, M::PointerTag>,
321 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
322 let size = size.unwrap_or_else(|| {
323 assert!(!place.layout.is_unsized());
324 assert!(place.meta.is_none());
327 self.memory.check_ptr_access(place.ptr, size, place.align)
330 /// Force `place.ptr` to a `Pointer`.
331 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
332 pub fn force_mplace_ptr(
334 mut place: MPlaceTy<'tcx, M::PointerTag>,
335 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
336 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
340 /// Offset a pointer to project to a field. Unlike `place_field`, this is always
341 /// possible without allocating, so it can take `&self`. Also return the field's layout.
342 /// This supports both struct and array fields.
346 base: MPlaceTy<'tcx, M::PointerTag>,
348 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
349 // Not using the layout method because we want to compute on u64
350 let offset = match base.layout.fields {
351 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
352 offsets[usize::try_from(field).unwrap()],
353 layout::FieldPlacement::Array { stride, .. } => {
354 let len = base.len(self)?;
356 // This can be violated because this runs during promotion on code where the
357 // type system has not yet ensured that such things don't happen.
358 debug!("tried to access element {} of array/slice with length {}", field, len);
359 throw_panic!(BoundsCheck { len, index: field });
363 layout::FieldPlacement::Union(count) => {
364 assert!(field < count as u64,
365 "Tried to access field {} of union with {} fields", field, count);
366 // Offset is always 0
370 // the only way conversion can fail if is this is an array (otherwise we already panicked
371 // above). In that case, all fields are equal.
372 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
374 // Offset may need adjustment for unsized fields.
375 let (meta, offset) = if field_layout.is_unsized() {
376 // Re-use parent metadata to determine dynamic field layout.
377 // With custom DSTS, this *will* execute user-defined code, but the same
378 // happens at run-time so that's okay.
379 let align = match self.size_and_align_of(base.meta, field_layout)? {
380 Some((_, align)) => align,
381 None if offset == Size::ZERO =>
382 // An extern type at offset 0, we fall back to its static alignment.
383 // FIXME: Once we have made decisions for how to handle size and alignment
384 // of `extern type`, this should be adapted. It is just a temporary hack
385 // to get some code to work that probably ought to work.
386 field_layout.align.abi,
388 bug!("Cannot compute offset for extern type field at non-0 offset"),
390 (base.meta, offset.align_to(align))
392 // base.meta could be present; we might be accessing a sized field of an unsized
397 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
398 // codegen -- mostly to see if we can get away with that
399 base.offset(offset, meta, field_layout, self)
402 // Iterates over all fields of an array. Much more efficient than doing the
403 // same by repeatedly calling `mplace_array`.
404 pub fn mplace_array_fields(
406 base: MPlaceTy<'tcx, Tag>,
407 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
409 let len = base.len(self)?; // also asserts that we have a type where this makes sense
410 let stride = match base.layout.fields {
411 layout::FieldPlacement::Array { stride, .. } => stride,
412 _ => bug!("mplace_array_fields: expected an array layout"),
414 let layout = base.layout.field(self, 0)?;
415 let dl = &self.tcx.data_layout;
416 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
419 pub fn mplace_subslice(
421 base: MPlaceTy<'tcx, M::PointerTag>,
424 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
425 let len = base.len(self)?; // also asserts that we have a type where this makes sense
426 assert!(from <= len - to);
428 // Not using layout method because that works with usize, and does not work with slices
429 // (that have count 0 in their layout).
430 let from_offset = match base.layout.fields {
431 layout::FieldPlacement::Array { stride, .. } =>
433 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
436 // Compute meta and new layout
437 let inner_len = len - to - from;
438 let (meta, ty) = match base.layout.ty.sty {
439 // It is not nice to match on the type, but that seems to be the only way to
441 ty::Array(inner, _) =>
442 (None, self.tcx.mk_array(inner, inner_len)),
444 let len = Scalar::from_uint(inner_len, self.pointer_size());
445 (Some(len), base.layout.ty)
448 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
450 let layout = self.layout_of(ty)?;
451 base.offset(from_offset, meta, layout, self)
454 pub fn mplace_downcast(
456 base: MPlaceTy<'tcx, M::PointerTag>,
458 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
459 // Downcasts only change the layout
460 assert!(base.meta.is_none());
461 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
464 /// Project into an mplace
465 pub fn mplace_projection(
467 base: MPlaceTy<'tcx, M::PointerTag>,
468 proj_elem: &mir::PlaceElem<'tcx>,
469 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
470 use rustc::mir::ProjectionElem::*;
471 Ok(match *proj_elem {
472 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
473 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
474 Deref => self.deref_operand(base.into())?,
477 let layout = self.layout_of(self.tcx.types.usize)?;
478 let n = self.access_local(self.frame(), local, Some(layout))?;
479 let n = self.read_scalar(n)?;
480 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
481 self.mplace_field(base, u64::try_from(n).unwrap())?
489 let n = base.len(self)?;
490 assert!(n >= min_length as u64);
492 let index = if from_end {
493 n - u64::from(offset)
498 self.mplace_field(base, index)?
501 Subslice { from, to } =>
502 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
506 /// Gets the place of a field inside the place, and also the field's type.
507 /// Just a convenience function, but used quite a bit.
508 /// This is the only projection that might have a side-effect: We cannot project
509 /// into the field of a local `ScalarPair`, we have to first allocate it.
512 base: PlaceTy<'tcx, M::PointerTag>,
514 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
515 // FIXME: We could try to be smarter and avoid allocation for fields that span the
517 let mplace = self.force_allocation(base)?;
518 Ok(self.mplace_field(mplace, field)?.into())
521 pub fn place_downcast(
523 base: PlaceTy<'tcx, M::PointerTag>,
525 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
526 // Downcast just changes the layout
527 Ok(match base.place {
528 Place::Ptr(mplace) =>
529 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
530 Place::Local { .. } => {
531 let layout = base.layout.for_variant(self, variant);
532 PlaceTy { layout, ..base }
537 /// Projects into a place.
538 pub fn place_projection(
540 base: PlaceTy<'tcx, M::PointerTag>,
541 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
542 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
543 use rustc::mir::ProjectionElem::*;
544 Ok(match *proj_elem {
545 Field(field, _) => self.place_field(base, field.index() as u64)?,
546 Downcast(_, variant) => self.place_downcast(base, variant)?,
547 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
548 // For the other variants, we have to force an allocation.
549 // This matches `operand_projection`.
550 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
551 let mplace = self.force_allocation(base)?;
552 self.mplace_projection(mplace, proj_elem)?.into()
557 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
558 /// `eval_place` and `eval_place_to_op`.
559 pub(super) fn eval_static_to_mplace(
561 place_static: &mir::Static<'tcx>
562 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
563 use rustc::mir::StaticKind;
565 Ok(match place_static.kind {
566 StaticKind::Promoted(promoted) => {
567 let instance = self.frame().instance;
568 self.const_eval_raw(GlobalId {
570 promoted: Some(promoted),
574 StaticKind::Static(def_id) => {
575 let ty = place_static.ty;
576 assert!(!ty.needs_subst());
577 let layout = self.layout_of(ty)?;
578 let instance = ty::Instance::mono(*self.tcx, def_id);
583 // Just create a lazy reference, so we can support recursive statics.
584 // tcx takes care of assigning every static one and only one unique AllocId.
585 // When the data here is ever actually used, memory will notice,
586 // and it knows how to deal with alloc_id that are present in the
587 // global table but not in its local memory: It calls back into tcx through
588 // a query, triggering the CTFE machinery to actually turn this lazy reference
589 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
590 // this InterpCx uses another Machine (e.g., in miri). This is what we
591 // want! This way, computing statics works consistently between codegen
592 // and miri: They use the same query to eventually obtain a `ty::Const`
593 // and use that for further computation.
595 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
596 // one. Here we make sure that the interpreted program never sees the
597 // resolved ID. Also see the doc comment of `Memory::get_static_alloc`.
598 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
599 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
600 MPlaceTy::from_aligned_ptr(ptr, layout)
605 /// Computes a place. You should only use this if you intend to write into this
606 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
609 mir_place: &mir::Place<'tcx>,
610 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
611 use rustc::mir::PlaceBase;
613 mir_place.iterate(|place_base, place_projection| {
614 let mut place = match place_base {
615 PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
616 Some(return_place) => {
617 // We use our layout to verify our assumption; caller will validate
618 // their layout on return.
620 place: *return_place,
622 .layout_of(self.monomorphize(self.frame().body.return_ty())?)?,
625 None => throw_unsup!(InvalidNullPointerUsage),
627 PlaceBase::Local(local) => PlaceTy {
628 // This works even for dead/uninitialized locals; we check further when writing
629 place: Place::Local {
630 frame: self.cur_frame(),
633 layout: self.layout_of_local(self.frame(), *local, None)?,
635 PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
638 for proj in place_projection {
639 place = self.place_projection(place, &proj.elem)?
642 self.dump_place(place.place);
647 /// Write a scalar to a place
650 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
651 dest: PlaceTy<'tcx, M::PointerTag>,
652 ) -> InterpResult<'tcx> {
653 self.write_immediate(Immediate::Scalar(val.into()), dest)
656 /// Write an immediate to a place
658 pub fn write_immediate(
660 src: Immediate<M::PointerTag>,
661 dest: PlaceTy<'tcx, M::PointerTag>,
662 ) -> InterpResult<'tcx> {
663 self.write_immediate_no_validate(src, dest)?;
665 if M::enforce_validity(self) {
666 // Data got changed, better make sure it matches the type!
667 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
673 /// Write an `Immediate` to memory.
675 pub fn write_immediate_to_mplace(
677 src: Immediate<M::PointerTag>,
678 dest: MPlaceTy<'tcx, M::PointerTag>,
679 ) -> InterpResult<'tcx> {
680 self.write_immediate_to_mplace_no_validate(src, dest)?;
682 if M::enforce_validity(self) {
683 // Data got changed, better make sure it matches the type!
684 self.validate_operand(dest.into(), vec![], None)?;
690 /// Write an immediate to a place.
691 /// If you use this you are responsible for validating that things got copied at the
693 fn write_immediate_no_validate(
695 src: Immediate<M::PointerTag>,
696 dest: PlaceTy<'tcx, M::PointerTag>,
697 ) -> InterpResult<'tcx> {
698 if cfg!(debug_assertions) {
699 // This is a very common path, avoid some checks in release mode
700 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
702 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
703 assert_eq!(self.pointer_size(), dest.layout.size,
704 "Size mismatch when writing pointer"),
705 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
706 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
707 "Size mismatch when writing bits"),
708 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
709 Immediate::ScalarPair(_, _) => {
710 // FIXME: Can we check anything here?
714 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
716 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
717 // but not factored as a separate function.
718 let mplace = match dest.place {
719 Place::Local { frame, local } => {
720 match self.stack[frame].locals[local].access_mut()? {
722 // Local can be updated in-place.
723 *local = LocalValue::Live(Operand::Immediate(src));
727 // The local is in memory, go on below.
732 Place::Ptr(mplace) => mplace, // already referring to memory
734 let dest = MPlaceTy { mplace, layout: dest.layout };
736 // This is already in memory, write there.
737 self.write_immediate_to_mplace_no_validate(src, dest)
740 /// Write an immediate to memory.
741 /// If you use this you are responsible for validating that things got copied at the
743 fn write_immediate_to_mplace_no_validate(
745 value: Immediate<M::PointerTag>,
746 dest: MPlaceTy<'tcx, M::PointerTag>,
747 ) -> InterpResult<'tcx> {
748 // Note that it is really important that the type here is the right one, and matches the
749 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
750 // to handle padding properly, which is only correct if we never look at this data with the
753 let ptr = match self.check_mplace_access(dest, None)? {
755 None => return Ok(()), // zero-sized access
758 let tcx = &*self.tcx;
759 // FIXME: We should check that there are dest.layout.size many bytes available in
760 // memory. The code below is not sufficient, with enough padding it might not
761 // cover all the bytes!
763 Immediate::Scalar(scalar) => {
764 match dest.layout.abi {
765 layout::Abi::Scalar(_) => {}, // fine
766 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
769 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
770 tcx, ptr, scalar, dest.layout.size
773 Immediate::ScalarPair(a_val, b_val) => {
774 // We checked `ptr_align` above, so all fields will have the alignment they need.
775 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
776 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
777 let (a, b) = match dest.layout.abi {
778 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
779 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
782 let (a_size, b_size) = (a.size(self), b.size(self));
783 let b_offset = a_size.align_to(b.align(self).abi);
784 let b_ptr = ptr.offset(b_offset, self)?;
786 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
787 // but that does not work: We could be a newtype around a pair, then the
788 // fields do not match the `ScalarPair` components.
791 .get_mut(ptr.alloc_id)?
792 .write_scalar(tcx, ptr, a_val, a_size)?;
794 .get_mut(b_ptr.alloc_id)?
795 .write_scalar(tcx, b_ptr, b_val, b_size)
800 /// Copies the data from an operand to a place. This does not support transmuting!
801 /// Use `copy_op_transmute` if the layouts could disagree.
805 src: OpTy<'tcx, M::PointerTag>,
806 dest: PlaceTy<'tcx, M::PointerTag>,
807 ) -> InterpResult<'tcx> {
808 self.copy_op_no_validate(src, dest)?;
810 if M::enforce_validity(self) {
811 // Data got changed, better make sure it matches the type!
812 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
818 /// Copies the data from an operand to a place. This does not support transmuting!
819 /// Use `copy_op_transmute` if the layouts could disagree.
820 /// Also, if you use this you are responsible for validating that things get copied at the
822 fn copy_op_no_validate(
824 src: OpTy<'tcx, M::PointerTag>,
825 dest: PlaceTy<'tcx, M::PointerTag>,
826 ) -> InterpResult<'tcx> {
827 // We do NOT compare the types for equality, because well-typed code can
828 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
829 assert!(src.layout.details == dest.layout.details,
830 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
832 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
833 let src = match self.try_read_immediate(src)? {
835 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
836 // Yay, we got a value that we can write directly.
837 // FIXME: Add a check to make sure that if `src` is indirect,
838 // it does not overlap with `dest`.
839 return self.write_immediate_no_validate(*src_val, dest);
841 Err(mplace) => mplace,
843 // Slow path, this does not fit into an immediate. Just memcpy.
844 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
846 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
847 // is being initialized!
848 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
849 let size = size.unwrap_or_else(|| {
850 assert!(!dest.layout.is_unsized(),
851 "Cannot copy into already initialized unsized place");
854 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
856 let src = self.check_mplace_access(src, Some(size))?;
857 let dest = self.check_mplace_access(dest, Some(size))?;
858 let (src_ptr, dest_ptr) = match (src, dest) {
859 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
860 (None, None) => return Ok(()), // zero-sized copy
861 _ => bug!("The pointers should both be Some or both None"),
868 /*nonoverlapping*/ true,
872 /// Copies the data from an operand to a place. The layouts may disagree, but they must
873 /// have the same size.
874 pub fn copy_op_transmute(
876 src: OpTy<'tcx, M::PointerTag>,
877 dest: PlaceTy<'tcx, M::PointerTag>,
878 ) -> InterpResult<'tcx> {
879 if src.layout.details == dest.layout.details {
880 // Fast path: Just use normal `copy_op`
881 return self.copy_op(src, dest);
883 // We still require the sizes to match.
884 assert!(src.layout.size == dest.layout.size,
885 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
886 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
887 // to avoid that here.
888 assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
889 "Cannot transmute unsized data");
891 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
892 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
893 // We have to write them to `dest` at the offsets they were *read at*, which is
894 // not necessarily the same as the offsets in `dest.layout`!
895 // Hence we do the copy with the source layout on both sides. We also make sure to write
896 // into memory, because if `dest` is a local we would not even have a way to write
897 // at the `src` offsets; the fact that we came from a different layout would
899 let dest = self.force_allocation(dest)?;
900 self.copy_op_no_validate(
902 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
905 if M::enforce_validity(self) {
906 // Data got changed, better make sure it matches the type!
907 self.validate_operand(dest.into(), vec![], None)?;
913 /// Ensures that a place is in memory, and returns where it is.
914 /// If the place currently refers to a local that doesn't yet have a matching allocation,
915 /// create such an allocation.
916 /// This is essentially `force_to_memplace`.
918 /// This supports unsized types and returns the computed size to avoid some
919 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
921 pub fn force_allocation_maybe_sized(
923 place: PlaceTy<'tcx, M::PointerTag>,
924 meta: Option<Scalar<M::PointerTag>>,
925 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
926 let (mplace, size) = match place.place {
927 Place::Local { frame, local } => {
928 match self.stack[frame].locals[local].access_mut()? {
930 // We need to make an allocation.
931 // FIXME: Consider not doing anything for a ZST, and just returning
932 // a fake pointer? Are we even called for ZST?
934 // We cannot hold on to the reference `local_val` while allocating,
935 // but we can hold on to the value in there.
937 if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
943 // We need the layout of the local. We can NOT use the layout we got,
944 // that might e.g., be an inner field of a struct with `Scalar` layout,
945 // that has different alignment than the outer field.
946 // We also need to support unsized types, and hence cannot use `allocate`.
947 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
948 let (size, align) = self.size_and_align_of(meta, local_layout)?
949 .expect("Cannot allocate for non-dyn-sized type");
950 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
951 let mplace = MemPlace { ptr: ptr.into(), align, meta };
952 if let Some(value) = old_val {
953 // Preserve old value.
954 // We don't have to validate as we can assume the local
955 // was already valid for its type.
956 let mplace = MPlaceTy { mplace, layout: local_layout };
957 self.write_immediate_to_mplace_no_validate(value, mplace)?;
959 // Now we can call `access_mut` again, asserting it goes well,
960 // and actually overwrite things.
961 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
962 LocalValue::Live(Operand::Indirect(mplace));
965 Err(mplace) => (mplace, None), // this already was an indirect local
968 Place::Ptr(mplace) => (mplace, None)
970 // Return with the original layout, so that the caller can go on
971 Ok((MPlaceTy { mplace, layout: place.layout }, size))
975 pub fn force_allocation(
977 place: PlaceTy<'tcx, M::PointerTag>,
978 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
979 Ok(self.force_allocation_maybe_sized(place, None)?.0)
984 layout: TyLayout<'tcx>,
985 kind: MemoryKind<M::MemoryKinds>,
986 ) -> MPlaceTy<'tcx, M::PointerTag> {
987 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
988 MPlaceTy::from_aligned_ptr(ptr, layout)
991 pub fn write_discriminant_index(
993 variant_index: VariantIdx,
994 dest: PlaceTy<'tcx, M::PointerTag>,
995 ) -> InterpResult<'tcx> {
996 match dest.layout.variants {
997 layout::Variants::Single { index } => {
998 assert_eq!(index, variant_index);
1000 layout::Variants::Multiple {
1001 discr_kind: layout::DiscriminantKind::Tag,
1006 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
1008 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1010 // raw discriminants for enums are isize or bigger during
1011 // their computation, but the in-memory tag is the smallest possible
1013 let size = discr.value.size(self);
1014 let discr_val = truncate(discr_val, size);
1016 let discr_dest = self.place_field(dest, discr_index as u64)?;
1017 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1019 layout::Variants::Multiple {
1020 discr_kind: layout::DiscriminantKind::Niche {
1029 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1031 if variant_index != dataful_variant {
1033 self.place_field(dest, discr_index as u64)?;
1034 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1035 let niche_value = (niche_value as u128)
1036 .wrapping_add(niche_start);
1038 Scalar::from_uint(niche_value, niche_dest.layout.size),
1048 pub fn raw_const_to_mplace(
1050 raw: RawConst<'tcx>,
1051 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1052 // This must be an allocation in `tcx`
1053 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1054 let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1055 let layout = self.layout_of(raw.ty)?;
1056 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1059 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1060 /// Also return some more information so drop doesn't have to run the same code twice.
1061 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1062 -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1063 let vtable = mplace.vtable(); // also sanity checks the type
1064 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1065 let layout = self.layout_of(ty)?;
1067 // More sanity checks
1068 if cfg!(debug_assertions) {
1069 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1070 assert_eq!(size, layout.size);
1071 // only ABI alignment is preserved
1072 assert_eq!(align, layout.align.abi);
1075 let mplace = MPlaceTy {
1076 mplace: MemPlace { meta: None, ..*mplace },
1079 Ok((instance, mplace))