place.rs 46.6 KB
Newer Older
R
Ralf Jung 已提交
1 2 3 4 5
//! Computations on places -- field projections, going from mir::Place, and writing
//! into a place.
//! All high-level functions to write to memory work on places as destinations.

use std::convert::TryFrom;
6
use std::hash::Hash;
R
Ralf Jung 已提交
7

8
use rustc::mir;
9
use rustc::mir::interpret::truncate;
10
use rustc::ty::layout::{
M
Mark Rousskov 已提交
11
    self, Align, HasDataLayout, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
12
};
M
Mark Rousskov 已提交
13
use rustc::ty::{self, Ty};
14
use rustc_macros::HashStable;
O
Oliver Schneider 已提交
15

16
use super::{
S
Santiago Pastorino 已提交
17 18 19
    AllocId, AllocMap, Allocation, AllocationExtra, ImmTy, Immediate, InterpCx, InterpResult,
    LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer, PointerArithmetic, RawConst, Scalar,
    ScalarMaybeUndef,
R
Ralf Jung 已提交
20 21
};

22
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
O
Oliver Scherer 已提交
23
/// Information required for the sound usage of a `MemPlace`.
24
pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
O
Oliver Scherer 已提交
25
    /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
O
Oliver Scherer 已提交
26
    Meta(Scalar<Tag, Id>),
27 28 29 30 31 32 33 34 35 36
    /// `Sized` types or unsized `extern type`
    None,
    /// The address of this place may not be taken. This protects the `MemPlace` from coming from
    /// a ZST Operand with a backing allocation and being converted to an integer address. This
    /// should be impossible, because you can't take the address of an operand, but this is a second
    /// protection layer ensuring that we don't mess up.
    Poison,
}

impl<Tag, Id> MemPlaceMeta<Tag, Id> {
O
Oliver Scherer 已提交
37
    pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
38
        match self {
O
Oliver Scherer 已提交
39
            Self::Meta(s) => s,
40 41 42 43 44
            Self::None | Self::Poison => {
                bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
            }
        }
    }
O
Oliver Scherer 已提交
45
    fn has_meta(self) -> bool {
46
        match self {
O
Oliver Scherer 已提交
47
            Self::Meta(_) => true,
48 49 50 51 52 53 54 55
            Self::None | Self::Poison => false,
        }
    }
}

impl<Tag> MemPlaceMeta<Tag> {
    pub fn erase_tag(self) -> MemPlaceMeta<()> {
        match self {
O
Oliver Scherer 已提交
56
            Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
57 58 59 60 61 62
            Self::None => MemPlaceMeta::None,
            Self::Poison => MemPlaceMeta::Poison,
        }
    }
}

63
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
M
Mark Rousskov 已提交
64
pub struct MemPlace<Tag = (), Id = AllocId> {
R
Ralf Jung 已提交
65 66 67
    /// A place may have an integral pointer for ZSTs, and since it might
    /// be turned back into a reference before ever being dereferenced.
    /// However, it may never be undef.
68
    pub ptr: Scalar<Tag, Id>,
69
    pub align: Align,
A
Alexander Regueiro 已提交
70
    /// Metadata for unsized places. Interpretation is up to the type.
R
Ralf Jung 已提交
71
    /// Must not be present for sized types, but can be missing for unsized types
72
    /// (e.g., `extern type`).
73
    pub meta: MemPlaceMeta<Tag, Id>,
R
Ralf Jung 已提交
74
}
O
Oliver Schneider 已提交
75

76
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
M
Mark Rousskov 已提交
77
pub enum Place<Tag = (), Id = AllocId> {
78
    /// A place referring to a value allocated in the `Memory` system.
79
    Ptr(MemPlace<Tag, Id>),
O
Oliver Schneider 已提交
80

R
Ralf Jung 已提交
81 82
    /// To support alloc-free locals, we are able to write directly to a local.
    /// (Without that optimization, we'd just always be a `MemPlace`.)
M
Mark Rousskov 已提交
83
    Local { frame: usize, local: mir::Local },
O
Oliver Schneider 已提交
84 85
}

R
Ralf Jung 已提交
86
#[derive(Copy, Clone, Debug)]
M
Mark Rousskov 已提交
87
pub struct PlaceTy<'tcx, Tag = ()> {
88
    place: Place<Tag>, // Keep this private; it helps enforce invariants.
R
Ralf Jung 已提交
89 90 91
    pub layout: TyLayout<'tcx>,
}

92 93
impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
    type Target = Place<Tag>;
94
    #[inline(always)]
95
    fn deref(&self) -> &Place<Tag> {
R
Ralf Jung 已提交
96 97 98 99 100
        &self.place
    }
}

/// A MemPlace with its layout. Constructing it is only possible in this module.
101
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
M
Mark Rousskov 已提交
102
pub struct MPlaceTy<'tcx, Tag = ()> {
103
    mplace: MemPlace<Tag>,
R
Ralf Jung 已提交
104 105 106
    pub layout: TyLayout<'tcx>,
}

107 108
impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
    type Target = MemPlace<Tag>;
109
    #[inline(always)]
110
    fn deref(&self) -> &MemPlace<Tag> {
R
Ralf Jung 已提交
111
        &self.mplace
O
Oliver Schneider 已提交
112
    }
R
Ralf Jung 已提交
113 114
}

115
impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
116
    #[inline(always)]
117
    fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
M
Mark Rousskov 已提交
118
        PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
R
Ralf Jung 已提交
119 120
    }
}
O
Oliver Schneider 已提交
121

122 123
impl<Tag> MemPlace<Tag> {
    /// Replace ptr tag, maintain vtable tag (if any)
124
    #[inline]
125
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
126
        MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
127 128 129
    }

    #[inline]
130
    pub fn erase_tag(self) -> MemPlace {
131
        MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
132 133
    }

R
Ralf Jung 已提交
134
    #[inline(always)]
135
    fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
136
        MemPlace { ptr, align, meta: MemPlaceMeta::None }
O
Oliver Schneider 已提交
137 138
    }

139 140
    /// Produces a Place that will error if attempted to be read from or written to
    #[inline(always)]
141
    fn null(cx: &impl HasDataLayout) -> Self {
142
        Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
143 144
    }

R
Ralf Jung 已提交
145
    #[inline(always)]
146
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
147 148 149
        Self::from_scalar_ptr(ptr.into(), align)
    }

R
Ralf Jung 已提交
150
    /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
151 152 153 154
    /// This is the inverse of `ref_to_mplace`.
    #[inline(always)]
    pub fn to_ref(self) -> Immediate<Tag> {
        match self.meta {
155
            MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
O
Oliver Scherer 已提交
156
            MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
157 158 159 160
            MemPlaceMeta::Poison => bug!(
                "MPlaceTy::dangling may never be used to produce a \
                place that will have the address of its pointee taken"
            ),
161 162
        }
    }
163 164 165 166

    pub fn offset(
        self,
        offset: Size,
167
        meta: MemPlaceMeta<Tag>,
168
        cx: &impl HasDataLayout,
169
    ) -> InterpResult<'tcx, Self> {
170 171 172 173 174 175
        Ok(MemPlace {
            ptr: self.ptr.ptr_offset(offset, cx)?,
            align: self.align.restrict_for_offset(offset),
            meta,
        })
    }
R
Ralf Jung 已提交
176 177
}

178
impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
179 180
    /// Produces a MemPlace that works for ZST but nothing else
    #[inline]
181
    pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
O
Oliver Scherer 已提交
182 183
        let align = layout.align.abi;
        let ptr = Scalar::from_uint(align.bytes(), cx.pointer_size());
184
        // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
O
Oliver Scherer 已提交
185
        MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
R
Ralf Jung 已提交
186 187
    }

188
    /// Replace ptr tag, maintain vtable tag (if any)
189
    #[inline]
190
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
191
        MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
192 193 194
    }

    #[inline]
195 196 197
    pub fn offset(
        self,
        offset: Size,
198
        meta: MemPlaceMeta<Tag>,
199 200
        layout: TyLayout<'tcx>,
        cx: &impl HasDataLayout,
201
    ) -> InterpResult<'tcx, Self> {
M
Mark Rousskov 已提交
202
        Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
203 204
    }

R
Ralf Jung 已提交
205
    #[inline]
206
    fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
207
        MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
R
Ralf Jung 已提交
208 209 210
    }

    #[inline]
211
    pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
212
        if self.layout.is_unsized() {
R
Ralf Jung 已提交
213
            // We need to consult `meta` metadata
V
varkor 已提交
214
            match self.layout.ty.kind {
215
                ty::Slice(..) | ty::Str => {
O
Oliver Scherer 已提交
216
                    return self.mplace.meta.unwrap_meta().to_machine_usize(cx);
217
                }
218
                _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
219
            }
220 221
        } else {
            // Go through the layout.  There are lots of types that support a length,
222
            // e.g., SIMD types.
223 224 225
            match self.layout.fields {
                layout::FieldPlacement::Array { count, .. } => Ok(count),
                _ => bug!("len not supported on sized type {:?}", self.layout.ty),
226 227 228 229 230
            }
        }
    }

    #[inline]
231
    pub(super) fn vtable(self) -> Scalar<Tag> {
V
varkor 已提交
232
        match self.layout.ty.kind {
O
Oliver Scherer 已提交
233
            ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
234
            _ => bug!("vtable not supported on type {:?}", self.layout.ty),
R
Ralf Jung 已提交
235 236 237 238
        }
    }
}

239
// These are defined here because they produce a place.
240
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
241
    #[inline(always)]
242 243
    /// Note: do not call `as_ref` on the resulting place. This function should only be used to
    /// read from the resulting mplace, not to get its address back.
244 245 246 247
    pub fn try_as_mplace(
        self,
        cx: &impl HasDataLayout,
    ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
248
        match *self {
R
Ralf Jung 已提交
249
            Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
250 251 252
            Operand::Immediate(_) if self.layout.is_zst() => {
                Ok(MPlaceTy::dangling(self.layout, cx))
            }
253
            Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
R
Ralf Jung 已提交
254 255 256
        }
    }

257
    #[inline(always)]
258 259
    /// Note: do not call `as_ref` on the resulting place. This function should only be used to
    /// read from the resulting mplace, not to get its address back.
260 261
    pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
        self.try_as_mplace(cx).unwrap()
R
Ralf Jung 已提交
262 263 264
    }
}

R
Ralf Jung 已提交
265
impl<Tag: ::std::fmt::Debug> Place<Tag> {
R
Ralf Jung 已提交
266
    /// Produces a Place that will error if attempted to be read from or written to
267
    #[inline(always)]
268
    fn null(cx: &impl HasDataLayout) -> Self {
269
        Place::Ptr(MemPlace::null(cx))
R
Ralf Jung 已提交
270 271 272
    }

    #[inline]
273
    pub fn assert_mem_place(self) -> MemPlace<Tag> {
O
Oliver Schneider 已提交
274
        match self {
R
Ralf Jung 已提交
275
            Place::Ptr(mplace) => mplace,
276
            _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
O
Oliver Schneider 已提交
277 278
        }
    }
R
Ralf Jung 已提交
279
}
O
Oliver Schneider 已提交
280

281
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
282
    #[inline]
283 284
    pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
        MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
O
Oliver Schneider 已提交
285 286 287
    }
}

288
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
R
Ralf Jung 已提交
289
impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
290
where
R
Ralf Jung 已提交
291
    // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
292
    Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
293
    M: Machine<'mir, 'tcx, PointerTag = Tag>,
R
Ralf Jung 已提交
294
    // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
295
    M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
296
    M::AllocExtra: AllocationExtra<Tag>,
297
{
R
Ralf Jung 已提交
298
    /// Take a value, which represents a (thin or wide) reference, and make it a place.
299
    /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
R
Ralf Jung 已提交
300 301 302 303
    ///
    /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
    /// want to ever use the place for memory access!
    /// Generally prefer `deref_operand`.
R
Ralf Jung 已提交
304
    pub fn ref_to_mplace(
305
        &self,
306
        val: ImmTy<'tcx, M::PointerTag>,
307
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
308 309
        let pointee_type =
            val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
310
        let layout = self.layout_of(pointee_type)?;
311
        let (ptr, meta) = match *val {
312 313
            Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
            Immediate::ScalarPair(ptr, meta) => {
O
Oliver Scherer 已提交
314
                (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
315
            }
316
        };
317

318
        let mplace = MemPlace {
319
            ptr,
320 321 322 323
            // We could use the run-time alignment here. For now, we do not, because
            // the point of tracking the alignment here is to make sure that the *static*
            // alignment information emitted with the loads is correct. The run-time
            // alignment can only be more restrictive.
324
            align: layout.align.abi,
325
            meta,
326 327
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
328 329
    }

330 331
    /// Take an operand, representing a pointer, and dereference it to a place -- that
    /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
332 333 334
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
335
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
336 337
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
338 339
        let place = self.ref_to_mplace(val)?;
        self.mplace_access_checked(place)
340 341
    }

342 343 344 345 346 347 348
    /// Check if the given place is good for memory access with the given
    /// size, falling back to the layout's size if `None` (in the latter case,
    /// this must be a statically sized type).
    ///
    /// On success, returns `None` for zero-sized accesses (where nothing else is
    /// left to do) and a `Pointer` to use for the actual access otherwise.
    #[inline]
349
    pub(super) fn check_mplace_access(
350 351 352 353 354 355
        &self,
        place: MPlaceTy<'tcx, M::PointerTag>,
        size: Option<Size>,
    ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
        let size = size.unwrap_or_else(|| {
            assert!(!place.layout.is_unsized());
O
Oliver Scherer 已提交
356
            assert!(!place.meta.has_meta());
357 358 359 360 361
            place.layout.size
        });
        self.memory.check_ptr_access(place.ptr, size, place.align)
    }

362 363 364 365 366 367
    /// Return the "access-checked" version of this `MPlace`, where for non-ZST
    /// this is definitely a `Pointer`.
    pub fn mplace_access_checked(
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
368 369
        let (size, align) = self
            .size_and_align_of_mplace(place)?
370 371 372 373 374 375 376 377 378 379
            .unwrap_or((place.layout.size, place.layout.align.abi));
        assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
        place.mplace.align = align; // maximally strict checking
        // When dereferencing a pointer, it must be non-NULL, aligned, and live.
        if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
            place.mplace.ptr = ptr.into();
        }
        Ok(place)
    }

R
Ralf Jung 已提交
380
    /// Force `place.ptr` to a `Pointer`.
381
    /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
382
    pub(super) fn force_mplace_ptr(
383 384 385
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
386
        place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
387 388 389
        Ok(place)
    }

390 391
    /// Offset a pointer to project to a field. Unlike `place_field`, this is always
    /// possible without allocating, so it can take `&self`. Also return the field's layout.
R
Ralf Jung 已提交
392 393 394
    /// This supports both struct and array fields.
    #[inline(always)]
    pub fn mplace_field(
O
Oliver Schneider 已提交
395
        &self,
396
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
397
        field: u64,
398
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
399 400
        // Not using the layout method because we want to compute on u64
        let offset = match base.layout.fields {
M
Mark Rousskov 已提交
401 402 403
            layout::FieldPlacement::Arbitrary { ref offsets, .. } => {
                offsets[usize::try_from(field).unwrap()]
            }
R
Ralf Jung 已提交
404
            layout::FieldPlacement::Array { stride, .. } => {
405
                let len = base.len(self)?;
406
                if field >= len {
407 408
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len, index: field });
409
                }
R
Ralf Jung 已提交
410 411
                stride * field
            }
412
            layout::FieldPlacement::Union(count) => {
M
Mark Rousskov 已提交
413 414 415 416 417 418 419
                assert!(
                    field < count as u64,
                    "Tried to access field {} of union {:#?} with {} fields",
                    field,
                    base.layout,
                    count
                );
420 421 422
                // Offset is always 0
                Size::from_bytes(0)
            }
R
Ralf Jung 已提交
423 424 425
        };
        // the only way conversion can fail if is this is an array (otherwise we already panicked
        // above). In that case, all fields are equal.
R
Ralf Jung 已提交
426
        let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
R
Ralf Jung 已提交
427

428
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
429
        let (meta, offset) = if field_layout.is_unsized() {
430 431 432
            // Re-use parent metadata to determine dynamic field layout.
            // With custom DSTS, this *will* execute user-defined code, but the same
            // happens at run-time so that's okay.
433 434 435
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
                None if offset == Size::ZERO =>
M
Mark Rousskov 已提交
436 437 438 439 440 441 442 443
                // An extern type at offset 0, we fall back to its static alignment.
                // FIXME: Once we have made decisions for how to handle size and alignment
                // of `extern type`, this should be adapted.  It is just a temporary hack
                // to get some code to work that probably ought to work.
                {
                    field_layout.align.abi
                }
                None => bug!("Cannot compute offset for extern type field at non-0 offset"),
444
            };
445
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
446
        } else {
R
Ralf Jung 已提交
447
            // base.meta could be present; we might be accessing a sized field of an unsized
448
            // struct.
449
            (MemPlaceMeta::None, offset)
R
Ralf Jung 已提交
450 451
        };

452 453 454
        // We do not look at `base.layout.align` nor `field_layout.align`, unlike
        // codegen -- mostly to see if we can get away with that
        base.offset(offset, meta, field_layout, self)
O
Oliver Schneider 已提交
455 456
    }

457 458
    // Iterates over all fields of an array. Much more efficient than doing the
    // same by repeatedly calling `mplace_array`.
459
    pub(super) fn mplace_array_fields(
460
        &self,
461
        base: MPlaceTy<'tcx, Tag>,
462
    ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
463
    {
464
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
465 466 467 468 469 470
        let stride = match base.layout.fields {
            layout::FieldPlacement::Array { stride, .. } => stride,
            _ => bug!("mplace_array_fields: expected an array layout"),
        };
        let layout = base.layout.field(self, 0)?;
        let dl = &self.tcx.data_layout;
471
        Ok((0..len).map(move |i| base.offset(i * stride, MemPlaceMeta::None, layout, dl)))
472 473
    }

474
    fn mplace_subslice(
O
Oliver Schneider 已提交
475
        &self,
476
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
477 478
        from: u64,
        to: u64,
479
        from_end: bool,
480
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
481
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
482
        let actual_to = if from_end {
483 484 485 486
            if from + to > len {
                // This can only be reached in ConstProp and non-rustc-MIR.
                throw_ub!(BoundsCheckFailed { len: len as u64, index: from as u64 + to as u64 });
            }
487 488 489 490
            len - to
        } else {
            to
        };
R
Ralf Jung 已提交
491 492 493 494

        // Not using layout method because that works with usize, and does not work with slices
        // (that have count 0 in their layout).
        let from_offset = match base.layout.fields {
M
Mark Rousskov 已提交
495
            layout::FieldPlacement::Array { stride, .. } => stride * from,
R
Ralf Jung 已提交
496
            _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
O
Oliver Schneider 已提交
497
        };
R
Ralf Jung 已提交
498

R
Ralf Jung 已提交
499
        // Compute meta and new layout
500
        let inner_len = actual_to - from;
V
varkor 已提交
501
        let (meta, ty) = match base.layout.ty.kind {
R
Ralf Jung 已提交
502 503
            // It is not nice to match on the type, but that seems to be the only way to
            // implement this.
504
            ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
505
            ty::Slice(..) => {
506
                let len = Scalar::from_uint(inner_len, self.pointer_size());
O
Oliver Scherer 已提交
507
                (MemPlaceMeta::Meta(len), base.layout.ty)
508
            }
M
Mark Rousskov 已提交
509
            _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
R
Ralf Jung 已提交
510 511
        };
        let layout = self.layout_of(ty)?;
512
        base.offset(from_offset, meta, layout, self)
R
Ralf Jung 已提交
513 514
    }

515
    pub(super) fn mplace_downcast(
R
Ralf Jung 已提交
516
        &self,
517
        base: MPlaceTy<'tcx, M::PointerTag>,
518
        variant: VariantIdx,
519
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
520
        // Downcasts only change the layout
O
Oliver Scherer 已提交
521
        assert!(!base.meta.has_meta());
R
Ralf Jung 已提交
522
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
523 524
    }

R
Ralf Jung 已提交
525
    /// Project into an mplace
526
    pub(super) fn mplace_projection(
O
Oliver Schneider 已提交
527
        &self,
528
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
529
        proj_elem: &mir::PlaceElem<'tcx>,
530
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
531
        use rustc::mir::ProjectionElem::*;
R
Ralf Jung 已提交
532 533 534 535 536 537
        Ok(match *proj_elem {
            Field(field, _) => self.mplace_field(base, field.index() as u64)?,
            Downcast(_, variant) => self.mplace_downcast(base, variant)?,
            Deref => self.deref_operand(base.into())?,

            Index(local) => {
R
Ralf Jung 已提交
538
                let layout = self.layout_of(self.tcx.types.usize)?;
539 540
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
541
                let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
R
Ralf Jung 已提交
542 543 544
                self.mplace_field(base, u64::try_from(n).unwrap())?
            }

M
Mark Rousskov 已提交
545
            ConstantIndex { offset, min_length, from_end } => {
546
                let n = base.len(self)?;
547 548 549 550
                if n < min_length as u64 {
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len: min_length as u64, index: n as u64 });
                }
R
Ralf Jung 已提交
551 552

                let index = if from_end {
553
                    assert!(0 < offset && offset - 1 < min_length);
R
Ralf Jung 已提交
554 555
                    n - u64::from(offset)
                } else {
O
Oliver Scherer 已提交
556
                    assert!(offset < min_length);
R
Ralf Jung 已提交
557 558 559 560 561 562
                    u64::from(offset)
                };

                self.mplace_field(base, index)?
            }

M
Mark Rousskov 已提交
563 564 565
            Subslice { from, to, from_end } => {
                self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
            }
R
Ralf Jung 已提交
566
        })
O
Oliver Schneider 已提交
567 568
    }

A
Alexander Regueiro 已提交
569
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
570
    /// Just a convenience function, but used quite a bit.
571 572
    /// This is the only projection that might have a side-effect: We cannot project
    /// into the field of a local `ScalarPair`, we have to first allocate it.
R
Ralf Jung 已提交
573
    pub fn place_field(
O
Oliver Schneider 已提交
574
        &mut self,
575
        base: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
576
        field: u64,
577
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
578 579 580 581
        // FIXME: We could try to be smarter and avoid allocation for fields that span the
        // entire place.
        let mplace = self.force_allocation(base)?;
        Ok(self.mplace_field(mplace, field)?.into())
O
Oliver Schneider 已提交
582 583
    }

R
Ralf Jung 已提交
584
    pub fn place_downcast(
585
        &self,
586
        base: PlaceTy<'tcx, M::PointerTag>,
587
        variant: VariantIdx,
588
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
589 590
        // Downcast just changes the layout
        Ok(match base.place {
M
Mark Rousskov 已提交
591 592 593
            Place::Ptr(mplace) => {
                self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
            }
R
Ralf Jung 已提交
594
            Place::Local { .. } => {
595
                let layout = base.layout.for_variant(self, variant);
R
Ralf Jung 已提交
596
                PlaceTy { layout, ..base }
O
Oliver Schneider 已提交
597
            }
R
Ralf Jung 已提交
598
        })
O
Oliver Schneider 已提交
599 600
    }

A
Alexander Regueiro 已提交
601
    /// Projects into a place.
R
Ralf Jung 已提交
602 603
    pub fn place_projection(
        &mut self,
604
        base: PlaceTy<'tcx, M::PointerTag>,
605
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
606
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
607 608
        use rustc::mir::ProjectionElem::*;
        Ok(match *proj_elem {
M
Mark Rousskov 已提交
609
            Field(field, _) => self.place_field(base, field.index() as u64)?,
R
Ralf Jung 已提交
610 611 612 613 614 615 616 617 618 619 620
            Downcast(_, variant) => self.place_downcast(base, variant)?,
            Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
            // For the other variants, we have to force an allocation.
            // This matches `operand_projection`.
            Subslice { .. } | ConstantIndex { .. } | Index(_) => {
                let mplace = self.force_allocation(base)?;
                self.mplace_projection(mplace, proj_elem)?.into()
            }
        })
    }

A
Alexander Regueiro 已提交
621
    /// Computes a place. You should only use this if you intend to write into this
622
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
623 624
    pub fn eval_place(
        &mut self,
625
        place: &mir::Place<'tcx>,
626
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
627 628
        let mut place_ty = match place.local {
            mir::RETURN_PLACE => {
629 630 631 632 633 634
                // `return_place` has the *caller* layout, but we want to use our
                // `layout to verify our assumption. The caller will validate
                // their layout on return.
                PlaceTy {
                    place: match self.frame().return_place {
                        Some(p) => *p,
R
comment  
Ralf Jung 已提交
635 636 637 638 639 640 641
                        // Even if we don't have a return place, we sometimes need to
                        // create this place, but any attempt to read from / write to it
                        // (even a ZST read/write) needs to error, so let us make this
                        // a NULL place.
                        //
                        // FIXME: Ideally we'd make sure that the place projections also
                        // bail out.
642 643
                        None => Place::null(&*self),
                    },
M
Mark Rousskov 已提交
644 645 646
                    layout: self.layout_of(self.subst_from_frame_and_normalize_erasing_regions(
                        self.frame().body.return_ty(),
                    ))?,
647
                }
M
Mark Rousskov 已提交
648
            }
649
            local => PlaceTy {
650
                // This works even for dead/uninitialized locals; we check further when writing
651 652
                place: Place::Local { frame: self.cur_frame(), local: local },
                layout: self.layout_of_local(self.frame(), local, None)?,
653 654
            },
        };
655

656 657 658
        for elem in place.projection.iter() {
            place_ty = self.place_projection(place_ty, elem)?
        }
O
Oliver Schneider 已提交
659

660 661
        self.dump_place(place_ty.place);
        Ok(place_ty)
O
Oliver Schneider 已提交
662 663
    }

R
Ralf Jung 已提交
664
    /// Write a scalar to a place
665
    #[inline(always)]
R
Ralf Jung 已提交
666
    pub fn write_scalar(
O
Oliver Schneider 已提交
667
        &mut self,
668 669
        val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
        dest: PlaceTy<'tcx, M::PointerTag>,
670
    ) -> InterpResult<'tcx> {
671
        self.write_immediate(Immediate::Scalar(val.into()), dest)
R
Ralf Jung 已提交
672
    }
O
Oliver Schneider 已提交
673

674
    /// Write an immediate to a place
675
    #[inline(always)]
676
    pub fn write_immediate(
R
Ralf Jung 已提交
677
        &mut self,
678
        src: Immediate<M::PointerTag>,
679
        dest: PlaceTy<'tcx, M::PointerTag>,
680
    ) -> InterpResult<'tcx> {
681
        self.write_immediate_no_validate(src, dest)?;
682

R
Ralf Jung 已提交
683
        if M::enforce_validity(self) {
684
            // Data got changed, better make sure it matches the type!
685
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
686 687
        }

688 689 690
        Ok(())
    }

W
Wesley Wiser 已提交
691 692 693 694 695 696
    /// Write an `Immediate` to memory.
    #[inline(always)]
    pub fn write_immediate_to_mplace(
        &mut self,
        src: Immediate<M::PointerTag>,
        dest: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
697
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
698 699 700 701
        self.write_immediate_to_mplace_no_validate(src, dest)?;

        if M::enforce_validity(self) {
            // Data got changed, better make sure it matches the type!
O
Oliver Scherer 已提交
702
            self.validate_operand(dest.into(), vec![], None)?;
W
Wesley Wiser 已提交
703 704 705 706 707
        }

        Ok(())
    }

708
    /// Write an immediate to a place.
709 710
    /// If you use this you are responsible for validating that things got copied at the
    /// right type.
711
    fn write_immediate_no_validate(
712
        &mut self,
713
        src: Immediate<M::PointerTag>,
714
        dest: PlaceTy<'tcx, M::PointerTag>,
715
    ) -> InterpResult<'tcx> {
716 717 718
        if cfg!(debug_assertions) {
            // This is a very common path, avoid some checks in release mode
            assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
719
            match src {
M
Mark Rousskov 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
                    self.pointer_size(),
                    dest.layout.size,
                    "Size mismatch when writing pointer"
                ),
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
                    assert_eq!(
                        Size::from_bytes(size.into()),
                        dest.layout.size,
                        "Size mismatch when writing bits"
                    )
                }
                Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
733
                Immediate::ScalarPair(_, _) => {
734 735 736 737
                    // FIXME: Can we check anything here?
                }
            }
        }
738
        trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
739

740
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
741
        // but not factored as a separate function.
R
Ralf Jung 已提交
742
        let mplace = match dest.place {
O
Oliver Schneider 已提交
743
            Place::Local { frame, local } => {
744 745 746 747
                match self.stack[frame].locals[local].access_mut()? {
                    Ok(local) => {
                        // Local can be updated in-place.
                        *local = LocalValue::Live(Operand::Immediate(src));
R
Ralf Jung 已提交
748
                        return Ok(());
749 750 751 752 753
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
754
                }
M
Mark Rousskov 已提交
755
            }
756
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
757
        };
758
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
759

R
Ralf Jung 已提交
760
        // This is already in memory, write there.
761
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
762 763
    }

764
    /// Write an immediate to memory.
765
    /// If you use this you are responsible for validating that things got copied at the
766
    /// right type.
767
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
768
        &mut self,
769
        value: Immediate<M::PointerTag>,
770
        dest: MPlaceTy<'tcx, M::PointerTag>,
771
    ) -> InterpResult<'tcx> {
B
Bernardo Meurer 已提交
772 773 774 775
        // Note that it is really important that the type here is the right one, and matches the
        // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
        // to handle padding properly, which is only correct if we never look at this data with the
        // wrong type.
776

777
        // Invalid places are a thing: the return place of a diverging function
M
Mark Rousskov 已提交
778
        let ptr = match self.check_mplace_access(dest, None)? {
779 780 781
            Some(ptr) => ptr,
            None => return Ok(()), // zero-sized access
        };
782

783
        let tcx = &*self.tcx;
784 785 786
        // FIXME: We should check that there are dest.layout.size many bytes available in
        // memory.  The code below is not sufficient, with enough padding it might not
        // cover all the bytes!
R
Ralf Jung 已提交
787
        match value {
788
            Immediate::Scalar(scalar) => {
789
                match dest.layout.abi {
M
Mark Rousskov 已提交
790 791 792 793
                    layout::Abi::Scalar(_) => {} // fine
                    _ => {
                        bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
                    }
794
                }
795
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
M
Mark Rousskov 已提交
796 797 798 799
                    tcx,
                    ptr,
                    scalar,
                    dest.layout.size,
R
Ralf Jung 已提交
800
                )
O
Oliver Schneider 已提交
801
            }
802
            Immediate::ScalarPair(a_val, b_val) => {
803 804 805
                // We checked `ptr_align` above, so all fields will have the alignment they need.
                // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
                // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
R
Ralf Jung 已提交
806 807
                let (a, b) = match dest.layout.abi {
                    layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
M
Mark Rousskov 已提交
808 809 810 811
                    _ => bug!(
                        "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
                        dest.layout
                    ),
R
Ralf Jung 已提交
812
                };
813
                let (a_size, b_size) = (a.size(self), b.size(self));
814
                let b_offset = a_size.align_to(b.align(self).abi);
815
                let b_ptr = ptr.offset(b_offset, self)?;
816

817 818 819 820
                // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
                // but that does not work: We could be a newtype around a pair, then the
                // fields do not match the `ScalarPair` components.

M
Mark Rousskov 已提交
821 822
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
                self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
O
Oliver Schneider 已提交
823
            }
R
Ralf Jung 已提交
824
        }
O
Oliver Schneider 已提交
825 826
    }

A
Alexander Regueiro 已提交
827
    /// Copies the data from an operand to a place. This does not support transmuting!
828 829
    /// Use `copy_op_transmute` if the layouts could disagree.
    #[inline(always)]
R
Ralf Jung 已提交
830
    pub fn copy_op(
O
Oliver Schneider 已提交
831
        &mut self,
832 833
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
834
    ) -> InterpResult<'tcx> {
835 836
        self.copy_op_no_validate(src, dest)?;

R
Ralf Jung 已提交
837
        if M::enforce_validity(self) {
838
            // Data got changed, better make sure it matches the type!
839
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
840 841 842 843 844
        }

        Ok(())
    }

A
Alexander Regueiro 已提交
845
    /// Copies the data from an operand to a place. This does not support transmuting!
846
    /// Use `copy_op_transmute` if the layouts could disagree.
847
    /// Also, if you use this you are responsible for validating that things get copied at the
848 849 850 851 852
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
853
    ) -> InterpResult<'tcx> {
854 855
        // We do NOT compare the types for equality, because well-typed code can
        // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
M
Mark Rousskov 已提交
856 857 858 859 860 861
        assert!(
            src.layout.details == dest.layout.details,
            "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}",
            src,
            dest
        );
R
Ralf Jung 已提交
862 863

        // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
864
        let src = match self.try_read_immediate(src)? {
865
            Ok(src_val) => {
866
                assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
867
                // Yay, we got a value that we can write directly.
868 869
                // FIXME: Add a check to make sure that if `src` is indirect,
                // it does not overlap with `dest`.
870
                return self.write_immediate_no_validate(*src_val, dest);
871 872
            }
            Err(mplace) => mplace,
R
Ralf Jung 已提交
873 874
        };
        // Slow path, this does not fit into an immediate. Just memcpy.
875 876
        trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);

877 878 879 880
        // This interprets `src.meta` with the `dest` local's layout, if an unsized local
        // is being initialized!
        let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
        let size = size.unwrap_or_else(|| {
M
Mark Rousskov 已提交
881 882 883 884
            assert!(
                !dest.layout.is_unsized(),
                "Cannot copy into already initialized unsized place"
            );
885 886 887
            dest.layout.size
        });
        assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
888

M
Mark Rousskov 已提交
889 890
        let src = self
            .check_mplace_access(src, Some(size))
891
            .expect("places should be checked on creation");
M
Mark Rousskov 已提交
892 893
        let dest = self
            .check_mplace_access(dest, Some(size))
894
            .expect("places should be checked on creation");
895 896 897 898 899 900
        let (src_ptr, dest_ptr) = match (src, dest) {
            (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
            (None, None) => return Ok(()), // zero-sized copy
            _ => bug!("The pointers should both be Some or both None"),
        };

M
Mark Rousskov 已提交
901
        self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
902 903
    }

A
Alexander Regueiro 已提交
904
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
905 906 907 908 909
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
910
    ) -> InterpResult<'tcx> {
911 912 913 914
        if src.layout.details == dest.layout.details {
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
915
        // We still require the sizes to match.
916
        if src.layout.size != dest.layout.size {
917 918 919 920
            // FIXME: This should be an assert instead of an error, but if we transmute within an
            // array length computation, `typeck` may not have yet been run and errored out. In fact
            // most likey we *are* running `typeck` right now. Investigate whether we can bail out
            // on `typeck_tables().has_errors` at all const eval entry points.
921
            debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
922 923
            throw_unsup!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
        }
924 925
        // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
        // to avoid that here.
M
Mark Rousskov 已提交
926 927 928 929
        assert!(
            !src.layout.is_unsized() && !dest.layout.is_unsized(),
            "Cannot transmute unsized data"
        );
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

        // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
        // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
        // We have to write them to `dest` at the offsets they were *read at*, which is
        // not necessarily the same as the offsets in `dest.layout`!
        // Hence we do the copy with the source layout on both sides.  We also make sure to write
        // into memory, because if `dest` is a local we would not even have a way to write
        // at the `src` offsets; the fact that we came from a different layout would
        // just be lost.
        let dest = self.force_allocation(dest)?;
        self.copy_op_no_validate(
            src,
            PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
        )?;

R
Ralf Jung 已提交
945
        if M::enforce_validity(self) {
946
            // Data got changed, better make sure it matches the type!
947
            self.validate_operand(dest.into(), vec![], None)?;
948
        }
949

950
        Ok(())
O
Oliver Schneider 已提交
951 952
    }

A
Alexander Regueiro 已提交
953
    /// Ensures that a place is in memory, and returns where it is.
954 955
    /// If the place currently refers to a local that doesn't yet have a matching allocation,
    /// create such an allocation.
R
Ralf Jung 已提交
956
    /// This is essentially `force_to_memplace`.
957
    ///
R
Ralf Jung 已提交
958
    /// This supports unsized types and returns the computed size to avoid some
959 960 961
    /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
    /// version.
    pub fn force_allocation_maybe_sized(
O
Oliver Schneider 已提交
962
        &mut self,
963
        place: PlaceTy<'tcx, M::PointerTag>,
964
        meta: MemPlaceMeta<M::PointerTag>,
965
    ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
966
        let (mplace, size) = match place.place {
R
Ralf Jung 已提交
967
            Place::Local { frame, local } => {
968
                match self.stack[frame].locals[local].access_mut()? {
969
                    Ok(&mut local_val) => {
970
                        // We need to make an allocation.
971

972
                        // We need the layout of the local.  We can NOT use the layout we got,
973
                        // that might e.g., be an inner field of a struct with `Scalar` layout,
R
Ralf Jung 已提交
974
                        // that has different alignment than the outer field.
975
                        let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
976
                        // We also need to support unsized types, and hence cannot use `allocate`.
M
Mark Rousskov 已提交
977 978
                        let (size, align) = self
                            .size_and_align_of(meta, local_layout)?
979 980 981
                            .expect("Cannot allocate for non-dyn-sized type");
                        let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
                        let mplace = MemPlace { ptr: ptr.into(), align, meta };
982
                        if let LocalValue::Live(Operand::Immediate(value)) = local_val {
983 984 985
                            // Preserve old value.
                            // We don't have to validate as we can assume the local
                            // was already valid for its type.
986 987
                            let mplace = MPlaceTy { mplace, layout: local_layout };
                            self.write_immediate_to_mplace_no_validate(value, mplace)?;
988 989 990 991 992
                        }
                        // Now we can call `access_mut` again, asserting it goes well,
                        // and actually overwrite things.
                        *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
                            LocalValue::Live(Operand::Indirect(mplace));
993
                        (mplace, Some(size))
994
                    }
995
                    Err(mplace) => (mplace, None), // this already was an indirect local
996
                }
R
Ralf Jung 已提交
997
            }
M
Mark Rousskov 已提交
998
            Place::Ptr(mplace) => (mplace, None),
R
Ralf Jung 已提交
999 1000
        };
        // Return with the original layout, so that the caller can go on
1001 1002 1003 1004 1005 1006 1007
        Ok((MPlaceTy { mplace, layout: place.layout }, size))
    }

    #[inline(always)]
    pub fn force_allocation(
        &mut self,
        place: PlaceTy<'tcx, M::PointerTag>,
1008
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1009
        Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
O
Oliver Schneider 已提交
1010 1011
    }

R
Ralf Jung 已提交
1012
    pub fn allocate(
O
Oliver Schneider 已提交
1013
        &mut self,
R
Ralf Jung 已提交
1014 1015
        layout: TyLayout<'tcx>,
        kind: MemoryKind<M::MemoryKinds>,
R
Ralf Jung 已提交
1016
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1017 1018
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
1019
    }
O
Oliver Schneider 已提交
1020

R
Ralf Jung 已提交
1021
    /// Returns a wide MPlace.
1022 1023 1024 1025 1026 1027 1028
    pub fn allocate_str(
        &mut self,
        str: &str,
        kind: MemoryKind<M::MemoryKinds>,
    ) -> MPlaceTy<'tcx, M::PointerTag> {
        let ptr = self.memory.allocate_static_bytes(str.as_bytes(), kind);
        let meta = Scalar::from_uint(str.len() as u128, self.pointer_size());
1029 1030 1031
        let mplace = MemPlace {
            ptr: ptr.into(),
            align: Align::from_bytes(1).unwrap(),
O
Oliver Scherer 已提交
1032
            meta: MemPlaceMeta::Meta(meta),
1033
        };
1034 1035 1036 1037 1038

        let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
        MPlaceTy { mplace, layout }
    }

1039
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
1040
        &mut self,
1041
        variant_index: VariantIdx,
1042
        dest: PlaceTy<'tcx, M::PointerTag>,
1043
    ) -> InterpResult<'tcx> {
1044 1045 1046 1047 1048
        // Layout computation excludes uninhabited variants from consideration
        // therefore there's no way to represent those variants in the given layout.
        if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
            throw_ub!(Unreachable);
        }
1049

R
Ralf Jung 已提交
1050 1051
        match dest.layout.variants {
            layout::Variants::Single { index } => {
1052
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
1053
            }
1054 1055
            layout::Variants::Multiple {
                discr_kind: layout::DiscriminantKind::Tag,
1056
                discr: ref discr_layout,
1057
                discr_index,
1058 1059
                ..
            } => {
1060 1061 1062
                // No need to validate that the discriminant here because the
                // `TyLayout::for_variant()` call earlier already checks the variant is valid.

1063 1064
                let discr_val =
                    dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
R
Ralf Jung 已提交
1065 1066 1067 1068

                // raw discriminants for enums are isize or bigger during
                // their computation, but the in-memory tag is the smallest possible
                // representation
1069
                let size = discr_layout.value.size(self);
1070
                let discr_val = truncate(discr_val, size);
R
Ralf Jung 已提交
1071

1072
                let discr_dest = self.place_field(dest, discr_index as u64)?;
1073
                self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
O
Oliver Schneider 已提交
1074
            }
1075
            layout::Variants::Multiple {
M
Mark Rousskov 已提交
1076 1077
                discr_kind:
                    layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1078
                discr: ref discr_layout,
1079
                discr_index,
R
Ralf Jung 已提交
1080
                ..
O
Oliver Schneider 已提交
1081
            } => {
1082 1083 1084
                // No need to validate that the discriminant here because the
                // `TyLayout::for_variant()` call earlier already checks the variant is valid.

R
Ralf Jung 已提交
1085
                if variant_index != dataful_variant {
1086
                    let variants_start = niche_variants.start().as_u32();
M
Mark Rousskov 已提交
1087 1088
                    let variant_index_relative = variant_index
                        .as_u32()
1089 1090
                        .checked_sub(variants_start)
                        .expect("overflow computing relative variant idx");
1091 1092
                    // We need to use machine arithmetic when taking into account `niche_start`:
                    // 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 1096
                    let variant_index_relative_val =
                        ImmTy::from_uint(variant_index_relative, discr_layout);
1097
                    let discr_val = self.binary_op(
1098
                        mir::BinOp::Add,
1099
                        variant_index_relative_val,
1100
                        niche_start_val,
1101
                    )?;
1102 1103
                    // Write result.
                    let niche_dest = self.place_field(dest, discr_index as u64)?;
1104
                    self.write_immediate(*discr_val, niche_dest)?;
R
Ralf Jung 已提交
1105
                }
O
Oliver Schneider 已提交
1106
            }
1107
        }
R
Ralf Jung 已提交
1108 1109

        Ok(())
O
Oliver Schneider 已提交
1110 1111
    }

1112 1113 1114
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
1115
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1116 1117
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1118
        let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1119
        let layout = self.layout_of(raw.ty)?;
1120
        Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1121 1122
    }

1123 1124
    /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
    /// Also return some more information so drop doesn't have to run the same code twice.
M
Mark Rousskov 已提交
1125 1126 1127 1128
    pub(super) fn unpack_dyn_trait(
        &self,
        mplace: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1129
        let vtable = mplace.vtable(); // also sanity checks the type
1130 1131 1132 1133
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1134 1135 1136
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1137
            // only ABI alignment is preserved
1138
            assert_eq!(align, layout.align.abi);
1139
        }
1140

1141
        let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1142
        Ok((instance, mplace))
1143
    }
O
Oliver Schneider 已提交
1144
}