]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_const_eval/src/interpret/place.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / compiler / rustc_const_eval / src / interpret / place.rs
CommitLineData
b7449926
XL
1//! Computations on places -- field projections, going from mir::Place, and writing
2//! into a place.
3//! All high-level functions to write to memory work on places as destinations.
4
5use std::convert::TryFrom;
0bf4aa26 6use std::hash::Hash;
b7449926 7
17df50a5 8use rustc_ast::Mutability;
60c5eb7d 9use rustc_macros::HashStable;
ba9703b0 10use rustc_middle::mir;
c295e0f8 11use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
ba9703b0 12use rustc_middle::ty::{self, Ty};
f035d41b 13use rustc_target::abi::{Abi, Align, FieldsShape, TagEncoding};
c295e0f8 14use rustc_target::abi::{HasDataLayout, Size, VariantIdx, Variants};
ff7c6d11 15
0bf4aa26 16use super::{
136023e0
XL
17 alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
18 ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy,
19 Operand, Pointer, PointerArithmetic, Provenance, Scalar, ScalarMaybeUninit,
b7449926 20};
ff7c6d11 21
136023e0 22#[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)]
dfeec247 23/// Information required for the sound usage of a `MemPlace`.
136023e0 24pub enum MemPlaceMeta<Tag: Provenance = AllocId> {
dfeec247 25 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
f9f354fc 26 Meta(Scalar<Tag>),
dfeec247
XL
27 /// `Sized` types or unsized `extern type`
28 None,
29 /// The address of this place may not be taken. This protects the `MemPlace` from coming from
ba9703b0 30 /// a ZST Operand without a backing allocation and being converted to an integer address. This
dfeec247
XL
31 /// should be impossible, because you can't take the address of an operand, but this is a second
32 /// protection layer ensuring that we don't mess up.
33 Poison,
34}
35
6a06907d
XL
36#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
37rustc_data_structures::static_assert_size!(MemPlaceMeta, 24);
38
136023e0 39impl<Tag: Provenance> MemPlaceMeta<Tag> {
f9f354fc 40 pub fn unwrap_meta(self) -> Scalar<Tag> {
dfeec247
XL
41 match self {
42 Self::Meta(s) => s,
43 Self::None | Self::Poison => {
44 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
45 }
46 }
47 }
48 fn has_meta(self) -> bool {
49 match self {
50 Self::Meta(_) => true,
51 Self::None | Self::Poison => false,
52 }
53 }
dfeec247
XL
54}
55
136023e0
XL
56#[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)]
57pub struct MemPlace<Tag: Provenance = AllocId> {
58 /// The pointer can be a pure integer, with the `None` tag.
59 pub ptr: Pointer<Option<Tag>>,
b7449926 60 pub align: Align,
9fa01778 61 /// Metadata for unsized places. Interpretation is up to the type.
b7449926 62 /// Must not be present for sized types, but can be missing for unsized types
0731742a 63 /// (e.g., `extern type`).
f9f354fc 64 pub meta: MemPlaceMeta<Tag>,
b7449926
XL
65}
66
6a06907d 67#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
136023e0 68rustc_data_structures::static_assert_size!(MemPlace, 48);
6a06907d 69
136023e0
XL
70#[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)]
71pub enum Place<Tag: Provenance = AllocId> {
2c00a5a8 72 /// A place referring to a value allocated in the `Memory` system.
f9f354fc 73 Ptr(MemPlace<Tag>),
b7449926
XL
74
75 /// To support alloc-free locals, we are able to write directly to a local.
76 /// (Without that optimization, we'd just always be a `MemPlace`.)
dfeec247 77 Local { frame: usize, local: mir::Local },
b7449926
XL
78}
79
6a06907d 80#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
136023e0 81rustc_data_structures::static_assert_size!(Place, 56);
6a06907d 82
b7449926 83#[derive(Copy, Clone, Debug)]
136023e0 84pub struct PlaceTy<'tcx, Tag: Provenance = AllocId> {
60c5eb7d 85 place: Place<Tag>, // Keep this private; it helps enforce invariants.
ba9703b0 86 pub layout: TyAndLayout<'tcx>,
ff7c6d11
XL
87}
88
6a06907d 89#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
136023e0 90rustc_data_structures::static_assert_size!(PlaceTy<'_>, 72);
6a06907d 91
136023e0 92impl<'tcx, Tag: Provenance> std::ops::Deref for PlaceTy<'tcx, Tag> {
0bf4aa26 93 type Target = Place<Tag>;
b7449926 94 #[inline(always)]
0bf4aa26 95 fn deref(&self) -> &Place<Tag> {
b7449926
XL
96 &self.place
97 }
ff7c6d11
XL
98}
99
b7449926 100/// A MemPlace with its layout. Constructing it is only possible in this module.
136023e0
XL
101#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
102pub struct MPlaceTy<'tcx, Tag: Provenance = AllocId> {
0bf4aa26 103 mplace: MemPlace<Tag>,
ba9703b0 104 pub layout: TyAndLayout<'tcx>,
b7449926
XL
105}
106
6a06907d 107#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
136023e0 108rustc_data_structures::static_assert_size!(MPlaceTy<'_>, 64);
6a06907d 109
136023e0 110impl<'tcx, Tag: Provenance> std::ops::Deref for MPlaceTy<'tcx, Tag> {
0bf4aa26 111 type Target = MemPlace<Tag>;
b7449926 112 #[inline(always)]
0bf4aa26 113 fn deref(&self) -> &MemPlace<Tag> {
b7449926
XL
114 &self.mplace
115 }
116}
117
136023e0 118impl<'tcx, Tag: Provenance> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
b7449926 119 #[inline(always)]
0bf4aa26 120 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
dfeec247 121 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
ff7c6d11 122 }
b7449926 123}
ff7c6d11 124
136023e0 125impl<Tag: Provenance> MemPlace<Tag> {
b7449926 126 #[inline(always)]
136023e0 127 pub fn from_ptr(ptr: Pointer<Option<Tag>>, align: Align) -> Self {
dfeec247 128 MemPlace { ptr, align, meta: MemPlaceMeta::None }
ff7c6d11
XL
129 }
130
136023e0
XL
131 /// Adjust the provenance of the main pointer (metadata is unaffected).
132 pub fn map_provenance(self, f: impl FnOnce(Option<Tag>) -> Option<Tag>) -> Self {
133 MemPlace { ptr: self.ptr.map_provenance(f), ..self }
ff7c6d11
XL
134 }
135
60c5eb7d 136 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
a1dfa0c6
XL
137 /// This is the inverse of `ref_to_mplace`.
138 #[inline(always)]
136023e0 139 pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Tag> {
a1dfa0c6 140 match self.meta {
136023e0
XL
141 MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)),
142 MemPlaceMeta::Meta(meta) => {
143 Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into())
144 }
dfeec247
XL
145 MemPlaceMeta::Poison => bug!(
146 "MPlaceTy::dangling may never be used to produce a \
147 place that will have the address of its pointee taken"
148 ),
a1dfa0c6
XL
149 }
150 }
151
5869c6ff 152 #[inline]
a1dfa0c6
XL
153 pub fn offset(
154 self,
155 offset: Size,
dfeec247 156 meta: MemPlaceMeta<Tag>,
a1dfa0c6 157 cx: &impl HasDataLayout,
dc9dc135 158 ) -> InterpResult<'tcx, Self> {
a1dfa0c6 159 Ok(MemPlace {
136023e0 160 ptr: self.ptr.offset(offset, cx)?,
a1dfa0c6
XL
161 align: self.align.restrict_for_offset(offset),
162 meta,
163 })
164 }
0bf4aa26 165}
b7449926 166
136023e0 167impl<'tcx, Tag: Provenance> MPlaceTy<'tcx, Tag> {
0bf4aa26
XL
168 /// Produces a MemPlace that works for ZST but nothing else
169 #[inline]
136023e0 170 pub fn dangling(layout: TyAndLayout<'tcx>) -> Self {
dfeec247 171 let align = layout.align.abi;
136023e0 172 let ptr = Pointer::new(None, Size::from_bytes(align.bytes())); // no provenance, absolute address
dfeec247
XL
173 // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
174 MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
ff7c6d11
XL
175 }
176
0731742a 177 #[inline]
a1dfa0c6 178 pub fn offset(
6a06907d 179 &self,
a1dfa0c6 180 offset: Size,
dfeec247 181 meta: MemPlaceMeta<Tag>,
ba9703b0 182 layout: TyAndLayout<'tcx>,
a1dfa0c6 183 cx: &impl HasDataLayout,
dc9dc135 184 ) -> InterpResult<'tcx, Self> {
dfeec247 185 Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
a1dfa0c6
XL
186 }
187
b7449926 188 #[inline]
136023e0 189 pub fn from_aligned_ptr(ptr: Pointer<Option<Tag>>, layout: TyAndLayout<'tcx>) -> Self {
a1dfa0c6 190 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
ff7c6d11
XL
191 }
192
b7449926 193 #[inline]
6a06907d 194 pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
b7449926 195 if self.layout.is_unsized() {
0bf4aa26 196 // We need to consult `meta` metadata
1b1a35ee 197 match self.layout.ty.kind() {
ba9703b0 198 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
b7449926 199 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
ff7c6d11 200 }
b7449926
XL
201 } else {
202 // Go through the layout. There are lots of types that support a length,
3c0e092e 203 // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!)
b7449926 204 match self.layout.fields {
ba9703b0 205 FieldsShape::Array { count, .. } => Ok(count),
b7449926
XL
206 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
207 }
208 }
209 }
ff7c6d11 210
b7449926 211 #[inline]
6a06907d 212 pub(super) fn vtable(&self) -> Scalar<Tag> {
1b1a35ee 213 match self.layout.ty.kind() {
dfeec247 214 ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
b7449926 215 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
ff7c6d11
XL
216 }
217 }
218}
219
416331ca 220// These are defined here because they produce a place.
136023e0 221impl<'tcx, Tag: Provenance> OpTy<'tcx, Tag> {
b7449926 222 #[inline(always)]
dfeec247
XL
223 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
224 /// read from the resulting mplace, not to get its address back.
136023e0 225 pub fn try_as_mplace(&self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
6a06907d 226 match **self {
b7449926 227 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
136023e0 228 Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)),
ba9703b0 229 Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
b7449926
XL
230 }
231 }
232
233 #[inline(always)]
dfeec247
XL
234 /// Note: do not call `as_ref` on the resulting place. This function should only be used to
235 /// read from the resulting mplace, not to get its address back.
136023e0
XL
236 pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Tag> {
237 self.try_as_mplace().unwrap()
b7449926
XL
238 }
239}
240
136023e0 241impl<Tag: Provenance> Place<Tag> {
b7449926 242 #[inline]
416331ca 243 pub fn assert_mem_place(self) -> MemPlace<Tag> {
b7449926
XL
244 match self {
245 Place::Ptr(mplace) => mplace,
416331ca 246 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
b7449926
XL
247 }
248 }
b7449926
XL
249}
250
136023e0 251impl<'tcx, Tag: Provenance> PlaceTy<'tcx, Tag> {
b7449926 252 #[inline]
416331ca
XL
253 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
254 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
b7449926
XL
255 }
256}
257
0bf4aa26 258// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
ba9703b0 259impl<'mir, 'tcx: 'mir, Tag, M> InterpCx<'mir, 'tcx, M>
0bf4aa26 260where
a1dfa0c6 261 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
136023e0 262 Tag: Provenance + Eq + Hash + 'static,
dc9dc135 263 M: Machine<'mir, 'tcx, PointerTag = Tag>,
0bf4aa26 264{
60c5eb7d 265 /// Take a value, which represents a (thin or wide) reference, and make it a place.
a1dfa0c6 266 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
e1599b0c
XL
267 ///
268 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
269 /// want to ever use the place for memory access!
270 /// Generally prefer `deref_operand`.
b7449926 271 pub fn ref_to_mplace(
0bf4aa26 272 &self,
6a06907d 273 val: &ImmTy<'tcx, M::PointerTag>,
dc9dc135 274 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
dfeec247
XL
275 let pointee_type =
276 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
b7449926 277 let layout = self.layout_of(pointee_type)?;
6a06907d 278 let (ptr, meta) = match **val {
136023e0
XL
279 Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None),
280 Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta.check_init()?)),
60c5eb7d 281 };
0bf4aa26 282
a1dfa0c6 283 let mplace = MemPlace {
136023e0 284 ptr: self.scalar_to_ptr(ptr.check_init()?),
9fa01778
XL
285 // We could use the run-time alignment here. For now, we do not, because
286 // the point of tracking the alignment here is to make sure that the *static*
287 // alignment information emitted with the loads is correct. The run-time
288 // alignment can only be more restrictive.
a1dfa0c6 289 align: layout.align.abi,
60c5eb7d 290 meta,
b7449926
XL
291 };
292 Ok(MPlaceTy { mplace, layout })
293 }
294
416331ca
XL
295 /// Take an operand, representing a pointer, and dereference it to a place -- that
296 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
a1dfa0c6
XL
297 pub fn deref_operand(
298 &self,
6a06907d 299 src: &OpTy<'tcx, M::PointerTag>,
dc9dc135 300 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
a1dfa0c6
XL
301 let val = self.read_immediate(src)?;
302 trace!("deref to {} on {:?}", val.layout.ty, *val);
136023e0
XL
303 let mplace = self.ref_to_mplace(&val)?;
304 self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?;
305 Ok(mplace)
0bf4aa26
XL
306 }
307
416331ca 308 #[inline]
17df50a5 309 pub(super) fn get_alloc(
416331ca 310 &self,
6a06907d 311 place: &MPlaceTy<'tcx, M::PointerTag>,
17df50a5
XL
312 ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::PointerTag, M::AllocExtra>>> {
313 assert!(!place.layout.is_unsized());
314 assert!(!place.meta.has_meta());
315 let size = place.layout.size;
316 self.memory.get(place.ptr, size, place.align)
317 }
318
319 #[inline]
320 pub(super) fn get_alloc_mut(
321 &mut self,
322 place: &MPlaceTy<'tcx, M::PointerTag>,
323 ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::PointerTag, M::AllocExtra>>> {
324 assert!(!place.layout.is_unsized());
325 assert!(!place.meta.has_meta());
326 let size = place.layout.size;
327 self.memory.get_mut(place.ptr, size, place.align)
416331ca
XL
328 }
329
136023e0
XL
330 /// Check if this mplace is dereferencable and sufficiently aligned.
331 fn check_mplace_access(
e1599b0c 332 &self,
136023e0
XL
333 mplace: MPlaceTy<'tcx, M::PointerTag>,
334 msg: CheckInAllocMsg,
335 ) -> InterpResult<'tcx> {
dfeec247 336 let (size, align) = self
136023e0
XL
337 .size_and_align_of_mplace(&mplace)?
338 .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
339 assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?");
340 let align = M::enforce_alignment(&self.memory.extra).then_some(align);
341 self.memory.check_ptr_access_align(mplace.ptr, size, align.unwrap_or(Align::ONE), msg)?;
342 Ok(())
416331ca
XL
343 }
344
ba9703b0
XL
345 /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
346 /// always possible without allocating, so it can take `&self`. Also return the field's layout.
b7449926 347 /// This supports both struct and array fields.
ba9703b0
XL
348 ///
349 /// This also works for arrays, but then the `usize` index type is restricting.
350 /// For indexing into arrays, use `mplace_index`.
b7449926
XL
351 #[inline(always)]
352 pub fn mplace_field(
8faf50e0 353 &self,
6a06907d 354 base: &MPlaceTy<'tcx, M::PointerTag>,
ba9703b0 355 field: usize,
dc9dc135 356 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
ba9703b0 357 let offset = base.layout.fields.offset(field);
94222f64 358 let field_layout = base.layout.field(self, field);
b7449926 359
9fa01778 360 // Offset may need adjustment for unsized fields.
0bf4aa26 361 let (meta, offset) = if field_layout.is_unsized() {
9fa01778
XL
362 // Re-use parent metadata to determine dynamic field layout.
363 // With custom DSTS, this *will* execute user-defined code, but the same
364 // happens at run-time so that's okay.
6a06907d 365 let align = match self.size_and_align_of(&base.meta, &field_layout)? {
a1dfa0c6 366 Some((_, align)) => align,
dfeec247 367 None if offset == Size::ZERO => {
a1dfa0c6
XL
368 // An extern type at offset 0, we fall back to its static alignment.
369 // FIXME: Once we have made decisions for how to handle size and alignment
370 // of `extern type`, this should be adapted. It is just a temporary hack
371 // to get some code to work that probably ought to work.
dfeec247
XL
372 field_layout.align.abi
373 }
f035d41b
XL
374 None => span_bug!(
375 self.cur_span(),
376 "cannot compute offset for extern type field at non-0 offset"
377 ),
a1dfa0c6
XL
378 };
379 (base.meta, offset.align_to(align))
b7449926 380 } else {
0bf4aa26 381 // base.meta could be present; we might be accessing a sized field of an unsized
b7449926 382 // struct.
dfeec247 383 (MemPlaceMeta::None, offset)
b7449926
XL
384 };
385
a1dfa0c6
XL
386 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
387 // codegen -- mostly to see if we can get away with that
388 base.offset(offset, meta, field_layout, self)
ff7c6d11
XL
389 }
390
ba9703b0
XL
391 /// Index into an array.
392 #[inline(always)]
393 pub fn mplace_index(
394 &self,
6a06907d 395 base: &MPlaceTy<'tcx, M::PointerTag>,
ba9703b0
XL
396 index: u64,
397 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
398 // Not using the layout method because we want to compute on u64
399 match base.layout.fields {
400 FieldsShape::Array { stride, .. } => {
401 let len = base.len(self)?;
402 if index >= len {
403 // This can only be reached in ConstProp and non-rustc-MIR.
404 throw_ub!(BoundsCheckFailed { len, index });
405 }
406 let offset = stride * index; // `Size` multiplication
407 // All fields have the same layout.
94222f64 408 let field_layout = base.layout.field(self, 0);
ba9703b0
XL
409
410 assert!(!field_layout.is_unsized());
411 base.offset(offset, MemPlaceMeta::None, field_layout, self)
412 }
f035d41b
XL
413 _ => span_bug!(
414 self.cur_span(),
415 "`mplace_index` called on non-array type {:?}",
416 base.layout.ty
417 ),
ba9703b0
XL
418 }
419 }
420
b7449926
XL
421 // Iterates over all fields of an array. Much more efficient than doing the
422 // same by repeatedly calling `mplace_array`.
dfeec247 423 pub(super) fn mplace_array_fields(
0531ce1d 424 &self,
6a06907d
XL
425 base: &'a MPlaceTy<'tcx, Tag>,
426 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
0bf4aa26 427 {
b7449926
XL
428 let len = base.len(self)?; // also asserts that we have a type where this makes sense
429 let stride = match base.layout.fields {
ba9703b0 430 FieldsShape::Array { stride, .. } => stride,
f035d41b 431 _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"),
94b46f34 432 };
94222f64 433 let layout = base.layout.field(self, 0);
b7449926 434 let dl = &self.tcx.data_layout;
ba9703b0
XL
435 // `Size` multiplication
436 Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
0531ce1d
XL
437 }
438
dfeec247 439 fn mplace_subslice(
8faf50e0 440 &self,
6a06907d 441 base: &MPlaceTy<'tcx, M::PointerTag>,
b7449926
XL
442 from: u64,
443 to: u64,
60c5eb7d 444 from_end: bool,
dc9dc135 445 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
b7449926 446 let len = base.len(self)?; // also asserts that we have a type where this makes sense
60c5eb7d 447 let actual_to = if from_end {
ba9703b0 448 if from.checked_add(to).map_or(true, |to| to > len) {
dfeec247 449 // This can only be reached in ConstProp and non-rustc-MIR.
ba9703b0 450 throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
dfeec247 451 }
ba9703b0 452 len.checked_sub(to).unwrap()
60c5eb7d
XL
453 } else {
454 to
455 };
b7449926
XL
456
457 // Not using layout method because that works with usize, and does not work with slices
458 // (that have count 0 in their layout).
459 let from_offset = match base.layout.fields {
ba9703b0 460 FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
f035d41b
XL
461 _ => {
462 span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout)
463 }
ff7c6d11 464 };
b7449926 465
0bf4aa26 466 // Compute meta and new layout
ba9703b0 467 let inner_len = actual_to.checked_sub(from).unwrap();
1b1a35ee 468 let (meta, ty) = match base.layout.ty.kind() {
b7449926
XL
469 // It is not nice to match on the type, but that seems to be the only way to
470 // implement this.
dfeec247 471 ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
b7449926 472 ty::Slice(..) => {
ba9703b0 473 let len = Scalar::from_machine_usize(inner_len, self);
dfeec247 474 (MemPlaceMeta::Meta(len), base.layout.ty)
b7449926 475 }
f035d41b
XL
476 _ => {
477 span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty)
478 }
b7449926
XL
479 };
480 let layout = self.layout_of(ty)?;
a1dfa0c6 481 base.offset(from_offset, meta, layout, self)
b7449926
XL
482 }
483
6a06907d 484 pub(crate) fn mplace_downcast(
b7449926 485 &self,
6a06907d 486 base: &MPlaceTy<'tcx, M::PointerTag>,
a1dfa0c6 487 variant: VariantIdx,
dc9dc135 488 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
b7449926 489 // Downcasts only change the layout
dfeec247 490 assert!(!base.meta.has_meta());
6a06907d 491 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..*base })
b7449926
XL
492 }
493
494 /// Project into an mplace
dfeec247 495 pub(super) fn mplace_projection(
b7449926 496 &self,
6a06907d 497 base: &MPlaceTy<'tcx, M::PointerTag>,
f9f354fc 498 proj_elem: mir::PlaceElem<'tcx>,
dc9dc135 499 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
ba9703b0 500 use rustc_middle::mir::ProjectionElem::*;
f9f354fc 501 Ok(match proj_elem {
ba9703b0 502 Field(field, _) => self.mplace_field(base, field.index())?,
b7449926 503 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
6a06907d 504 Deref => self.deref_operand(&base.into())?,
b7449926
XL
505
506 Index(local) => {
9fa01778
XL
507 let layout = self.layout_of(self.tcx.types.usize)?;
508 let n = self.access_local(self.frame(), local, Some(layout))?;
6a06907d 509 let n = self.read_scalar(&n)?;
136023e0 510 let n = n.to_machine_usize(self)?;
ba9703b0 511 self.mplace_index(base, n)?
b7449926
XL
512 }
513
dfeec247 514 ConstantIndex { offset, min_length, from_end } => {
b7449926 515 let n = base.len(self)?;
1b1a35ee 516 if n < min_length {
dfeec247 517 // This can only be reached in ConstProp and non-rustc-MIR.
1b1a35ee 518 throw_ub!(BoundsCheckFailed { len: min_length, index: n });
dfeec247 519 }
b7449926
XL
520
521 let index = if from_end {
ba9703b0 522 assert!(0 < offset && offset <= min_length);
1b1a35ee 523 n.checked_sub(offset).unwrap()
b7449926 524 } else {
dfeec247 525 assert!(offset < min_length);
1b1a35ee 526 offset
b7449926
XL
527 };
528
ba9703b0 529 self.mplace_index(base, index)?
b7449926
XL
530 }
531
1b1a35ee 532 Subslice { from, to, from_end } => self.mplace_subslice(base, from, to, from_end)?,
b7449926 533 })
ff7c6d11
XL
534 }
535
3c0e092e
XL
536 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
537 /// Also returns the number of elements.
538 pub fn mplace_to_simd(
539 &self,
540 base: &MPlaceTy<'tcx, M::PointerTag>,
541 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> {
542 // Basically we just transmute this place into an array following simd_size_and_type.
543 // (Transmuting is okay since this is an in-memory place. We also double-check the size
544 // stays the same.)
545 let (len, e_ty) = base.layout.ty.simd_size_and_type(*self.tcx);
546 let array = self.tcx.mk_array(e_ty, len);
547 let layout = self.layout_of(array)?;
548 assert_eq!(layout.size, base.layout.size);
549 Ok((MPlaceTy { layout, ..*base }, len))
550 }
551
9fa01778 552 /// Gets the place of a field inside the place, and also the field's type.
b7449926 553 /// Just a convenience function, but used quite a bit.
a1dfa0c6
XL
554 /// This is the only projection that might have a side-effect: We cannot project
555 /// into the field of a local `ScalarPair`, we have to first allocate it.
b7449926 556 pub fn place_field(
ff7c6d11 557 &mut self,
6a06907d 558 base: &PlaceTy<'tcx, M::PointerTag>,
ba9703b0 559 field: usize,
dc9dc135 560 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
b7449926
XL
561 // FIXME: We could try to be smarter and avoid allocation for fields that span the
562 // entire place.
563 let mplace = self.force_allocation(base)?;
6a06907d 564 Ok(self.mplace_field(&mplace, field)?.into())
ff7c6d11
XL
565 }
566
ba9703b0
XL
567 pub fn place_index(
568 &mut self,
6a06907d 569 base: &PlaceTy<'tcx, M::PointerTag>,
ba9703b0
XL
570 index: u64,
571 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
572 let mplace = self.force_allocation(base)?;
6a06907d 573 Ok(self.mplace_index(&mplace, index)?.into())
ba9703b0
XL
574 }
575
b7449926 576 pub fn place_downcast(
a1dfa0c6 577 &self,
6a06907d 578 base: &PlaceTy<'tcx, M::PointerTag>,
a1dfa0c6 579 variant: VariantIdx,
dc9dc135 580 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
b7449926
XL
581 // Downcast just changes the layout
582 Ok(match base.place {
dfeec247 583 Place::Ptr(mplace) => {
6a06907d 584 self.mplace_downcast(&MPlaceTy { mplace, layout: base.layout }, variant)?.into()
dfeec247 585 }
b7449926 586 Place::Local { .. } => {
a1dfa0c6 587 let layout = base.layout.for_variant(self, variant);
6a06907d 588 PlaceTy { layout, ..*base }
ff7c6d11 589 }
b7449926 590 })
ff7c6d11
XL
591 }
592
9fa01778 593 /// Projects into a place.
b7449926
XL
594 pub fn place_projection(
595 &mut self,
6a06907d 596 base: &PlaceTy<'tcx, M::PointerTag>,
f9f354fc 597 &proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
dc9dc135 598 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
ba9703b0 599 use rustc_middle::mir::ProjectionElem::*;
f9f354fc 600 Ok(match proj_elem {
ba9703b0 601 Field(field, _) => self.place_field(base, field.index())?,
b7449926 602 Downcast(_, variant) => self.place_downcast(base, variant)?,
6a06907d 603 Deref => self.deref_operand(&self.place_to_op(base)?)?.into(),
b7449926
XL
604 // For the other variants, we have to force an allocation.
605 // This matches `operand_projection`.
606 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
607 let mplace = self.force_allocation(base)?;
6a06907d 608 self.mplace_projection(&mplace, proj_elem)?.into()
b7449926
XL
609 }
610 })
611 }
ff7c6d11 612
3c0e092e
XL
613 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
614 /// Also returns the number of elements.
615 pub fn place_to_simd(
616 &mut self,
617 base: &PlaceTy<'tcx, M::PointerTag>,
618 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> {
619 let mplace = self.force_allocation(base)?;
620 self.mplace_to_simd(&mplace)
621 }
622
9fa01778 623 /// Computes a place. You should only use this if you intend to write into this
b7449926 624 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
0bf4aa26
XL
625 pub fn eval_place(
626 &mut self,
ba9703b0 627 place: mir::Place<'tcx>,
dc9dc135 628 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
f9f354fc
XL
629 let mut place_ty = PlaceTy {
630 // This works even for dead/uninitialized locals; we check further when writing
631 place: Place::Local { frame: self.frame_idx(), local: place.local },
632 layout: self.layout_of_local(self.frame(), place.local, None)?,
e1599b0c 633 };
b7449926 634
e1599b0c 635 for elem in place.projection.iter() {
6a06907d 636 place_ty = self.place_projection(&place_ty, &elem)?
e1599b0c 637 }
ff7c6d11 638
3dfed10e 639 trace!("{:?}", self.dump_place(place_ty.place));
f9f354fc
XL
640 // Sanity-check the type we ended up with.
641 debug_assert!(mir_assign_valid_types(
642 *self.tcx,
f035d41b 643 self.param_env,
f9f354fc
XL
644 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
645 place.ty(&self.frame().body.local_decls, *self.tcx).ty
646 ))?,
647 place_ty.layout,
648 ));
e1599b0c 649 Ok(place_ty)
ff7c6d11
XL
650 }
651
a1dfa0c6 652 /// Write an immediate to a place
0bf4aa26 653 #[inline(always)]
a1dfa0c6 654 pub fn write_immediate(
b7449926 655 &mut self,
a1dfa0c6 656 src: Immediate<M::PointerTag>,
6a06907d 657 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 658 ) -> InterpResult<'tcx> {
a1dfa0c6 659 self.write_immediate_no_validate(src, dest)?;
0bf4aa26
XL
660
661 if M::enforce_validity(self) {
662 // Data got changed, better make sure it matches the type!
6a06907d 663 self.validate_operand(&self.place_to_op(dest)?)?;
dc9dc135
XL
664 }
665
666 Ok(())
667 }
668
136023e0 669 /// Write a scalar to a place
dc9dc135 670 #[inline(always)]
136023e0 671 pub fn write_scalar(
dc9dc135 672 &mut self,
136023e0
XL
673 val: impl Into<ScalarMaybeUninit<M::PointerTag>>,
674 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 675 ) -> InterpResult<'tcx> {
136023e0
XL
676 self.write_immediate(Immediate::Scalar(val.into()), dest)
677 }
0bf4aa26 678
136023e0
XL
679 /// Write a pointer to a place
680 #[inline(always)]
681 pub fn write_pointer(
682 &mut self,
683 ptr: impl Into<Pointer<Option<M::PointerTag>>>,
684 dest: &PlaceTy<'tcx, M::PointerTag>,
685 ) -> InterpResult<'tcx> {
686 self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
0bf4aa26
XL
687 }
688
a1dfa0c6 689 /// Write an immediate to a place.
0bf4aa26
XL
690 /// If you use this you are responsible for validating that things got copied at the
691 /// right type.
a1dfa0c6 692 fn write_immediate_no_validate(
0bf4aa26 693 &mut self,
a1dfa0c6 694 src: Immediate<M::PointerTag>,
6a06907d 695 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 696 ) -> InterpResult<'tcx> {
0bf4aa26
XL
697 if cfg!(debug_assertions) {
698 // This is a very common path, avoid some checks in release mode
699 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
a1dfa0c6 700 match src {
136023e0 701 Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Ptr(..))) => assert_eq!(
dfeec247
XL
702 self.pointer_size(),
703 dest.layout.size,
704 "Size mismatch when writing pointer"
705 ),
29967ef6
XL
706 Immediate::Scalar(ScalarMaybeUninit::Scalar(Scalar::Int(int))) => {
707 assert_eq!(int.size(), dest.layout.size, "Size mismatch when writing bits")
dfeec247 708 }
3dfed10e 709 Immediate::Scalar(ScalarMaybeUninit::Uninit) => {} // uninit can have any size
a1dfa0c6 710 Immediate::ScalarPair(_, _) => {
0bf4aa26
XL
711 // FIXME: Can we check anything here?
712 }
713 }
714 }
a1dfa0c6 715 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
0bf4aa26 716
a1dfa0c6 717 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
b7449926
XL
718 // but not factored as a separate function.
719 let mplace = match dest.place {
ff7c6d11 720 Place::Local { frame, local } => {
f035d41b 721 match M::access_local_mut(self, frame, local)? {
48663c56
XL
722 Ok(local) => {
723 // Local can be updated in-place.
724 *local = LocalValue::Live(Operand::Immediate(src));
b7449926 725 return Ok(());
48663c56
XL
726 }
727 Err(mplace) => {
728 // The local is in memory, go on below.
729 mplace
730 }
ff7c6d11 731 }
dfeec247 732 }
48663c56 733 Place::Ptr(mplace) => mplace, // already referring to memory
ff7c6d11 734 };
0bf4aa26 735 let dest = MPlaceTy { mplace, layout: dest.layout };
ff7c6d11 736
b7449926 737 // This is already in memory, write there.
6a06907d 738 self.write_immediate_to_mplace_no_validate(src, &dest)
ff7c6d11
XL
739 }
740
a1dfa0c6 741 /// Write an immediate to memory.
dc9dc135 742 /// If you use this you are responsible for validating that things got copied at the
0bf4aa26 743 /// right type.
a1dfa0c6 744 fn write_immediate_to_mplace_no_validate(
b7449926 745 &mut self,
a1dfa0c6 746 value: Immediate<M::PointerTag>,
6a06907d 747 dest: &MPlaceTy<'tcx, M::PointerTag>,
dc9dc135 748 ) -> InterpResult<'tcx> {
b7449926
XL
749 // Note that it is really important that the type here is the right one, and matches the
750 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
751 // to handle padding properly, which is only correct if we never look at this data with the
752 // wrong type.
753
60c5eb7d 754 // Invalid places are a thing: the return place of a diverging function
17df50a5
XL
755 let tcx = *self.tcx;
756 let mut alloc = match self.get_alloc_mut(dest)? {
757 Some(a) => a,
dc9dc135
XL
758 None => return Ok(()), // zero-sized access
759 };
b7449926 760
0bf4aa26
XL
761 // FIXME: We should check that there are dest.layout.size many bytes available in
762 // memory. The code below is not sufficient, with enough padding it might not
763 // cover all the bytes!
b7449926 764 match value {
a1dfa0c6 765 Immediate::Scalar(scalar) => {
0bf4aa26 766 match dest.layout.abi {
ba9703b0 767 Abi::Scalar(_) => {} // fine
f035d41b
XL
768 _ => span_bug!(
769 self.cur_span(),
770 "write_immediate_to_mplace: invalid Scalar layout: {:#?}",
771 dest.layout
772 ),
0bf4aa26 773 }
17df50a5 774 alloc.write_scalar(alloc_range(Size::ZERO, dest.layout.size), scalar)
ff7c6d11 775 }
a1dfa0c6 776 Immediate::ScalarPair(a_val, b_val) => {
dc9dc135
XL
777 // We checked `ptr_align` above, so all fields will have the alignment they need.
778 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
779 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
b7449926 780 let (a, b) = match dest.layout.abi {
c295e0f8 781 Abi::ScalarPair(a, b) => (a.value, b.value),
f035d41b
XL
782 _ => span_bug!(
783 self.cur_span(),
dfeec247
XL
784 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
785 dest.layout
786 ),
b7449926 787 };
17df50a5
XL
788 let (a_size, b_size) = (a.size(&tcx), b.size(&tcx));
789 let b_offset = a_size.align_to(b.align(&tcx).abi);
a1dfa0c6 790
0bf4aa26
XL
791 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
792 // but that does not work: We could be a newtype around a pair, then the
793 // fields do not match the `ScalarPair` components.
794
17df50a5
XL
795 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
796 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
ff7c6d11 797 }
b7449926 798 }
ff7c6d11
XL
799 }
800
9fa01778 801 /// Copies the data from an operand to a place. This does not support transmuting!
0bf4aa26
XL
802 /// Use `copy_op_transmute` if the layouts could disagree.
803 #[inline(always)]
b7449926 804 pub fn copy_op(
ff7c6d11 805 &mut self,
6a06907d
XL
806 src: &OpTy<'tcx, M::PointerTag>,
807 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 808 ) -> InterpResult<'tcx> {
0bf4aa26
XL
809 self.copy_op_no_validate(src, dest)?;
810
811 if M::enforce_validity(self) {
812 // Data got changed, better make sure it matches the type!
6a06907d 813 self.validate_operand(&self.place_to_op(dest)?)?;
0bf4aa26
XL
814 }
815
816 Ok(())
817 }
818
9fa01778 819 /// Copies the data from an operand to a place. This does not support transmuting!
0bf4aa26 820 /// Use `copy_op_transmute` if the layouts could disagree.
dc9dc135 821 /// Also, if you use this you are responsible for validating that things get copied at the
0bf4aa26
XL
822 /// right type.
823 fn copy_op_no_validate(
824 &mut self,
6a06907d
XL
825 src: &OpTy<'tcx, M::PointerTag>,
826 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 827 ) -> InterpResult<'tcx> {
0bf4aa26
XL
828 // We do NOT compare the types for equality, because well-typed code can
829 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
f035d41b 830 if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) {
ba9703b0 831 span_bug!(
f035d41b 832 self.cur_span(),
ba9703b0
XL
833 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
834 src.layout.ty,
835 dest.layout.ty,
836 );
837 }
b7449926
XL
838
839 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
a1dfa0c6 840 let src = match self.try_read_immediate(src)? {
0bf4aa26 841 Ok(src_val) => {
48663c56 842 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
0bf4aa26 843 // Yay, we got a value that we can write directly.
9fa01778
XL
844 // FIXME: Add a check to make sure that if `src` is indirect,
845 // it does not overlap with `dest`.
dc9dc135 846 return self.write_immediate_no_validate(*src_val, dest);
0bf4aa26
XL
847 }
848 Err(mplace) => mplace,
b7449926
XL
849 };
850 // Slow path, this does not fit into an immediate. Just memcpy.
0bf4aa26
XL
851 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
852
48663c56
XL
853 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
854 // is being initialized!
855 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
856 let size = size.unwrap_or_else(|| {
dfeec247
XL
857 assert!(
858 !dest.layout.is_unsized(),
859 "Cannot copy into already initialized unsized place"
860 );
48663c56
XL
861 dest.layout.size
862 });
863 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
416331ca 864
17df50a5
XL
865 self.memory
866 .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true)
0bf4aa26
XL
867 }
868
9fa01778 869 /// Copies the data from an operand to a place. The layouts may disagree, but they must
0bf4aa26
XL
870 /// have the same size.
871 pub fn copy_op_transmute(
872 &mut self,
6a06907d
XL
873 src: &OpTy<'tcx, M::PointerTag>,
874 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 875 ) -> InterpResult<'tcx> {
f035d41b 876 if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) {
0bf4aa26
XL
877 // Fast path: Just use normal `copy_op`
878 return self.copy_op(src, dest);
879 }
48663c56 880 // We still require the sizes to match.
dfeec247
XL
881 if src.layout.size != dest.layout.size {
882 // FIXME: This should be an assert instead of an error, but if we transmute within an
883 // array length computation, `typeck` may not have yet been run and errored out. In fact
884 // most likey we *are* running `typeck` right now. Investigate whether we can bail out
3dfed10e 885 // on `typeck_results().has_errors` at all const eval entry points.
dfeec247 886 debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
ba9703b0 887 self.tcx.sess.delay_span_bug(
f035d41b 888 self.cur_span(),
ba9703b0
XL
889 "size-changing transmute, should have been caught by transmute checking",
890 );
891 throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
dfeec247 892 }
48663c56
XL
893 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
894 // to avoid that here.
dfeec247
XL
895 assert!(
896 !src.layout.is_unsized() && !dest.layout.is_unsized(),
897 "Cannot transmute unsized data"
898 );
0bf4aa26
XL
899
900 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
901 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
902 // We have to write them to `dest` at the offsets they were *read at*, which is
903 // not necessarily the same as the offsets in `dest.layout`!
904 // Hence we do the copy with the source layout on both sides. We also make sure to write
905 // into memory, because if `dest` is a local we would not even have a way to write
906 // at the `src` offsets; the fact that we came from a different layout would
907 // just be lost.
908 let dest = self.force_allocation(dest)?;
909 self.copy_op_no_validate(
910 src,
6a06907d 911 &PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
0bf4aa26
XL
912 )?;
913
914 if M::enforce_validity(self) {
915 // Data got changed, better make sure it matches the type!
6a06907d 916 self.validate_operand(&dest.into())?;
0bf4aa26
XL
917 }
918
919 Ok(())
ff7c6d11
XL
920 }
921
9fa01778 922 /// Ensures that a place is in memory, and returns where it is.
a1dfa0c6
XL
923 /// If the place currently refers to a local that doesn't yet have a matching allocation,
924 /// create such an allocation.
b7449926 925 /// This is essentially `force_to_memplace`.
48663c56
XL
926 ///
927 /// This supports unsized types and returns the computed size to avoid some
928 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
929 /// version.
930 pub fn force_allocation_maybe_sized(
ff7c6d11 931 &mut self,
6a06907d 932 place: &PlaceTy<'tcx, M::PointerTag>,
dfeec247 933 meta: MemPlaceMeta<M::PointerTag>,
dc9dc135 934 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
48663c56 935 let (mplace, size) = match place.place {
b7449926 936 Place::Local { frame, local } => {
f035d41b 937 match M::access_local_mut(self, frame, local)? {
dfeec247 938 Ok(&mut local_val) => {
b7449926 939 // We need to make an allocation.
48663c56 940
b7449926 941 // We need the layout of the local. We can NOT use the layout we got,
0731742a 942 // that might e.g., be an inner field of a struct with `Scalar` layout,
b7449926 943 // that has different alignment than the outer field.
ba9703b0
XL
944 let local_layout =
945 self.layout_of_local(&self.stack()[frame], local, None)?;
dfeec247
XL
946 // We also need to support unsized types, and hence cannot use `allocate`.
947 let (size, align) = self
6a06907d 948 .size_and_align_of(&meta, &local_layout)?
48663c56 949 .expect("Cannot allocate for non-dyn-sized type");
136023e0 950 let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?;
48663c56 951 let mplace = MemPlace { ptr: ptr.into(), align, meta };
dfeec247 952 if let LocalValue::Live(Operand::Immediate(value)) = local_val {
48663c56
XL
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 };
6a06907d 957 self.write_immediate_to_mplace_no_validate(value, &mplace)?;
48663c56
XL
958 }
959 // Now we can call `access_mut` again, asserting it goes well,
960 // and actually overwrite things.
f035d41b 961 *M::access_local_mut(self, frame, local).unwrap().unwrap() =
48663c56
XL
962 LocalValue::Live(Operand::Indirect(mplace));
963 (mplace, Some(size))
b7449926 964 }
48663c56 965 Err(mplace) => (mplace, None), // this already was an indirect local
b7449926
XL
966 }
967 }
dfeec247 968 Place::Ptr(mplace) => (mplace, None),
b7449926
XL
969 };
970 // Return with the original layout, so that the caller can go on
48663c56
XL
971 Ok((MPlaceTy { mplace, layout: place.layout }, size))
972 }
973
974 #[inline(always)]
975 pub fn force_allocation(
976 &mut self,
6a06907d 977 place: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 978 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
dfeec247 979 Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
ff7c6d11
XL
980 }
981
b7449926 982 pub fn allocate(
ff7c6d11 983 &mut self,
ba9703b0
XL
984 layout: TyAndLayout<'tcx>,
985 kind: MemoryKind<M::MemoryKind>,
136023e0
XL
986 ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> {
987 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?;
988 Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
b7449926 989 }
ff7c6d11 990
17df50a5 991 /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
60c5eb7d
XL
992 pub fn allocate_str(
993 &mut self,
994 str: &str,
ba9703b0 995 kind: MemoryKind<M::MemoryKind>,
17df50a5 996 mutbl: Mutability,
60c5eb7d 997 ) -> MPlaceTy<'tcx, M::PointerTag> {
17df50a5 998 let ptr = self.memory.allocate_bytes(str.as_bytes(), Align::ONE, kind, mutbl);
ba9703b0 999 let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
17df50a5
XL
1000 let mplace =
1001 MemPlace { ptr: ptr.into(), align: Align::ONE, meta: MemPlaceMeta::Meta(meta) };
60c5eb7d 1002
17df50a5
XL
1003 let ty = self.tcx.mk_ref(
1004 self.tcx.lifetimes.re_static,
1005 ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
1006 );
1007 let layout = self.layout_of(ty).unwrap();
60c5eb7d
XL
1008 MPlaceTy { mplace, layout }
1009 }
1010
f035d41b
XL
1011 /// Writes the discriminant of the given variant.
1012 pub fn write_discriminant(
b7449926 1013 &mut self,
a1dfa0c6 1014 variant_index: VariantIdx,
6a06907d 1015 dest: &PlaceTy<'tcx, M::PointerTag>,
dc9dc135 1016 ) -> InterpResult<'tcx> {
c295e0f8
XL
1017 // This must be an enum or generator.
1018 match dest.layout.ty.kind() {
1019 ty::Adt(adt, _) => assert!(adt.is_enum()),
1020 ty::Generator(..) => {}
1021 _ => span_bug!(
1022 self.cur_span(),
1023 "write_discriminant called on non-variant-type (neither enum nor generator)"
1024 ),
1025 }
60c5eb7d
XL
1026 // Layout computation excludes uninhabited variants from consideration
1027 // therefore there's no way to represent those variants in the given layout.
c295e0f8
XL
1028 // Essentially, uninhabited variants do not have a tag that corresponds to their
1029 // discriminant, so we cannot do anything here.
1030 // When evaluating we will always error before even getting here, but ConstProp 'executes'
1031 // dead code, so we cannot ICE here.
60c5eb7d 1032 if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
c295e0f8 1033 throw_ub!(UninhabitedEnumVariantWritten)
60c5eb7d 1034 }
e74abb32 1035
b7449926 1036 match dest.layout.variants {
ba9703b0 1037 Variants::Single { index } => {
60c5eb7d 1038 assert_eq!(index, variant_index);
ff7c6d11 1039 }
ba9703b0 1040 Variants::Multiple {
f035d41b 1041 tag_encoding: TagEncoding::Direct,
c295e0f8 1042 tag: tag_layout,
f035d41b 1043 tag_field,
532ac7d7
XL
1044 ..
1045 } => {
60c5eb7d 1046 // No need to validate that the discriminant here because the
ba9703b0 1047 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
60c5eb7d 1048
48663c56
XL
1049 let discr_val =
1050 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
b7449926
XL
1051
1052 // raw discriminants for enums are isize or bigger during
1053 // their computation, but the in-memory tag is the smallest possible
1054 // representation
f035d41b 1055 let size = tag_layout.value.size(self);
29967ef6 1056 let tag_val = size.truncate(discr_val);
b7449926 1057
f035d41b 1058 let tag_dest = self.place_field(dest, tag_field)?;
6a06907d 1059 self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?;
ff7c6d11 1060 }
ba9703b0 1061 Variants::Multiple {
f035d41b
XL
1062 tag_encoding:
1063 TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start },
c295e0f8 1064 tag: tag_layout,
f035d41b 1065 tag_field,
b7449926 1066 ..
ff7c6d11 1067 } => {
60c5eb7d 1068 // No need to validate that the discriminant here because the
ba9703b0 1069 // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
60c5eb7d 1070
b7449926 1071 if variant_index != dataful_variant {
e1599b0c 1072 let variants_start = niche_variants.start().as_u32();
dfeec247
XL
1073 let variant_index_relative = variant_index
1074 .as_u32()
e1599b0c
XL
1075 .checked_sub(variants_start)
1076 .expect("overflow computing relative variant idx");
1077 // We need to use machine arithmetic when taking into account `niche_start`:
f035d41b
XL
1078 // tag_val = variant_index_relative + niche_start_val
1079 let tag_layout = self.layout_of(tag_layout.value.to_int_ty(*self.tcx))?;
1080 let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
e1599b0c 1081 let variant_index_relative_val =
f035d41b
XL
1082 ImmTy::from_uint(variant_index_relative, tag_layout);
1083 let tag_val = self.binary_op(
e1599b0c 1084 mir::BinOp::Add,
6a06907d
XL
1085 &variant_index_relative_val,
1086 &niche_start_val,
b7449926 1087 )?;
e1599b0c 1088 // Write result.
f035d41b 1089 let niche_dest = self.place_field(dest, tag_field)?;
6a06907d 1090 self.write_immediate(*tag_val, &niche_dest)?;
b7449926
XL
1091 }
1092 }
1093 }
ff7c6d11 1094
b7449926
XL
1095 Ok(())
1096 }
ff7c6d11 1097
a1dfa0c6
XL
1098 pub fn raw_const_to_mplace(
1099 &self,
1b1a35ee 1100 raw: ConstAlloc<'tcx>,
dc9dc135 1101 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
a1dfa0c6 1102 // This must be an allocation in `tcx`
f9f354fc 1103 let _ = self.tcx.global_alloc(raw.alloc_id);
3dfed10e 1104 let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
a1dfa0c6 1105 let layout = self.layout_of(raw.ty)?;
136023e0 1106 Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
a1dfa0c6
XL
1107 }
1108
b7449926
XL
1109 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1110 /// Also return some more information so drop doesn't have to run the same code twice.
dfeec247
XL
1111 pub(super) fn unpack_dyn_trait(
1112 &self,
6a06907d 1113 mplace: &MPlaceTy<'tcx, M::PointerTag>,
dfeec247 1114 ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
136023e0 1115 let vtable = self.scalar_to_ptr(mplace.vtable()); // also sanity checks the type
b7449926
XL
1116 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1117 let layout = self.layout_of(ty)?;
1118
1119 // More sanity checks
1120 if cfg!(debug_assertions) {
1121 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1122 assert_eq!(size, layout.size);
a1dfa0c6
XL
1123 // only ABI alignment is preserved
1124 assert_eq!(align, layout.align.abi);
ff7c6d11 1125 }
ff7c6d11 1126
6a06907d 1127 let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..**mplace }, layout };
b7449926 1128 Ok((instance, mplace))
ff7c6d11
XL
1129 }
1130}