]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_const_eval/src/interpret/place.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_const_eval / src / interpret / place.rs
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
5 use std::assert_matches::assert_matches;
6
7 use either::{Either, Left, Right};
8
9 use rustc_ast::Mutability;
10 use rustc_index::IndexSlice;
11 use rustc_middle::mir;
12 use rustc_middle::ty;
13 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
14 use rustc_middle::ty::Ty;
15 use rustc_target::abi::{Abi, Align, FieldIdx, HasDataLayout, Size, FIRST_VARIANT};
16
17 use super::{
18 alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg, ImmTy,
19 Immediate, InterpCx, InterpResult, Machine, MemoryKind, OpTy, Operand, Pointer,
20 PointerArithmetic, Projectable, Provenance, Readable, Scalar,
21 };
22
23 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
24 /// Information required for the sound usage of a `MemPlace`.
25 pub enum MemPlaceMeta<Prov: Provenance = AllocId> {
26 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
27 Meta(Scalar<Prov>),
28 /// `Sized` types or unsized `extern type`
29 None,
30 }
31
32 impl<Prov: Provenance> MemPlaceMeta<Prov> {
33 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
34 pub fn unwrap_meta(self) -> Scalar<Prov> {
35 match self {
36 Self::Meta(s) => s,
37 Self::None => {
38 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
39 }
40 }
41 }
42
43 #[inline(always)]
44 pub fn has_meta(self) -> bool {
45 match self {
46 Self::Meta(_) => true,
47 Self::None => false,
48 }
49 }
50 }
51
52 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
53 pub(super) struct MemPlace<Prov: Provenance = AllocId> {
54 /// The pointer can be a pure integer, with the `None` provenance.
55 pub ptr: Pointer<Option<Prov>>,
56 /// Metadata for unsized places. Interpretation is up to the type.
57 /// Must not be present for sized types, but can be missing for unsized types
58 /// (e.g., `extern type`).
59 pub meta: MemPlaceMeta<Prov>,
60 }
61
62 impl<Prov: Provenance> MemPlace<Prov> {
63 #[inline(always)]
64 pub fn from_ptr(ptr: Pointer<Option<Prov>>) -> Self {
65 MemPlace { ptr, meta: MemPlaceMeta::None }
66 }
67
68 #[inline(always)]
69 pub fn from_ptr_with_meta(ptr: Pointer<Option<Prov>>, meta: MemPlaceMeta<Prov>) -> Self {
70 MemPlace { ptr, meta }
71 }
72
73 /// Adjust the provenance of the main pointer (metadata is unaffected).
74 pub fn map_provenance(self, f: impl FnOnce(Option<Prov>) -> Option<Prov>) -> Self {
75 MemPlace { ptr: self.ptr.map_provenance(f), ..self }
76 }
77
78 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
79 #[inline]
80 pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
81 match self.meta {
82 MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)),
83 MemPlaceMeta::Meta(meta) => {
84 Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx), meta)
85 }
86 }
87 }
88
89 #[inline]
90 // Not called `offset_with_meta` to avoid confusion with the trait method.
91 fn offset_with_meta_<'tcx>(
92 self,
93 offset: Size,
94 meta: MemPlaceMeta<Prov>,
95 cx: &impl HasDataLayout,
96 ) -> InterpResult<'tcx, Self> {
97 debug_assert!(
98 !meta.has_meta() || self.meta.has_meta(),
99 "cannot use `offset_with_meta` to add metadata to a place"
100 );
101 Ok(MemPlace { ptr: self.ptr.offset(offset, cx)?, meta })
102 }
103 }
104
105 /// A MemPlace with its layout. Constructing it is only possible in this module.
106 #[derive(Clone, Hash, Eq, PartialEq)]
107 pub struct MPlaceTy<'tcx, Prov: Provenance = AllocId> {
108 mplace: MemPlace<Prov>,
109 pub layout: TyAndLayout<'tcx>,
110 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
111 /// it needs to have a different alignment than the field type would usually have.
112 /// So we represent this here with a separate field that "overwrites" `layout.align`.
113 /// This means `layout.align` should never be used for a `MPlaceTy`!
114 pub align: Align,
115 }
116
117 impl<Prov: Provenance> std::fmt::Debug for MPlaceTy<'_, Prov> {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 // Printing `layout` results in too much noise; just print a nice version of the type.
120 f.debug_struct("MPlaceTy")
121 .field("mplace", &self.mplace)
122 .field("ty", &format_args!("{}", self.layout.ty))
123 .finish()
124 }
125 }
126
127 impl<'tcx, Prov: Provenance> MPlaceTy<'tcx, Prov> {
128 /// Produces a MemPlace that works for ZST but nothing else.
129 /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
130 /// don't need to worry about memory leaks.
131 #[inline]
132 pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
133 assert!(layout.is_zst());
134 let align = layout.align.abi;
135 let ptr = Pointer::from_addr_invalid(align.bytes()); // no provenance, absolute address
136 MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None }, layout, align }
137 }
138
139 #[inline]
140 pub fn from_aligned_ptr(ptr: Pointer<Option<Prov>>, layout: TyAndLayout<'tcx>) -> Self {
141 MPlaceTy { mplace: MemPlace::from_ptr(ptr), layout, align: layout.align.abi }
142 }
143
144 #[inline]
145 pub fn from_aligned_ptr_with_meta(
146 ptr: Pointer<Option<Prov>>,
147 layout: TyAndLayout<'tcx>,
148 meta: MemPlaceMeta<Prov>,
149 ) -> Self {
150 MPlaceTy {
151 mplace: MemPlace::from_ptr_with_meta(ptr, meta),
152 layout,
153 align: layout.align.abi,
154 }
155 }
156
157 /// Adjust the provenance of the main pointer (metadata is unaffected).
158 pub fn map_provenance(self, f: impl FnOnce(Option<Prov>) -> Option<Prov>) -> Self {
159 MPlaceTy { mplace: self.mplace.map_provenance(f), ..self }
160 }
161
162 #[inline(always)]
163 pub(super) fn mplace(&self) -> &MemPlace<Prov> {
164 &self.mplace
165 }
166
167 #[inline(always)]
168 pub fn ptr(&self) -> Pointer<Option<Prov>> {
169 self.mplace.ptr
170 }
171
172 #[inline(always)]
173 pub fn to_ref(&self, cx: &impl HasDataLayout) -> Immediate<Prov> {
174 self.mplace.to_ref(cx)
175 }
176 }
177
178 impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
179 #[inline(always)]
180 fn layout(&self) -> TyAndLayout<'tcx> {
181 self.layout
182 }
183
184 #[inline(always)]
185 fn meta(&self) -> MemPlaceMeta<Prov> {
186 self.mplace.meta
187 }
188
189 fn offset_with_meta<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
190 &self,
191 offset: Size,
192 meta: MemPlaceMeta<Prov>,
193 layout: TyAndLayout<'tcx>,
194 ecx: &InterpCx<'mir, 'tcx, M>,
195 ) -> InterpResult<'tcx, Self> {
196 Ok(MPlaceTy {
197 mplace: self.mplace.offset_with_meta_(offset, meta, ecx)?,
198 align: self.align.restrict_for_offset(offset),
199 layout,
200 })
201 }
202
203 fn to_op<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
204 &self,
205 _ecx: &InterpCx<'mir, 'tcx, M>,
206 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
207 Ok(self.clone().into())
208 }
209 }
210
211 #[derive(Copy, Clone, Debug)]
212 pub(super) enum Place<Prov: Provenance = AllocId> {
213 /// A place referring to a value allocated in the `Memory` system.
214 Ptr(MemPlace<Prov>),
215
216 /// To support alloc-free locals, we are able to write directly to a local. The offset indicates
217 /// where in the local this place is located; if it is `None`, no projection has been applied.
218 /// Such projections are meaningful even if the offset is 0, since they can change layouts.
219 /// (Without that optimization, we'd just always be a `MemPlace`.)
220 /// Note that this only stores the frame index, not the thread this frame belongs to -- that is
221 /// implicit. This means a `Place` must never be moved across interpreter thread boundaries!
222 ///
223 /// This variant shall not be used for unsized types -- those must always live in memory.
224 Local { frame: usize, local: mir::Local, offset: Option<Size> },
225 }
226
227 #[derive(Clone)]
228 pub struct PlaceTy<'tcx, Prov: Provenance = AllocId> {
229 place: Place<Prov>, // Keep this private; it helps enforce invariants.
230 pub layout: TyAndLayout<'tcx>,
231 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
232 /// it needs to have a different alignment than the field type would usually have.
233 /// So we represent this here with a separate field that "overwrites" `layout.align`.
234 /// This means `layout.align` should never be used for a `PlaceTy`!
235 pub align: Align,
236 }
237
238 impl<Prov: Provenance> std::fmt::Debug for PlaceTy<'_, Prov> {
239 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240 // Printing `layout` results in too much noise; just print a nice version of the type.
241 f.debug_struct("PlaceTy")
242 .field("place", &self.place)
243 .field("ty", &format_args!("{}", self.layout.ty))
244 .finish()
245 }
246 }
247
248 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
249 #[inline(always)]
250 fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
251 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout, align: mplace.align }
252 }
253 }
254
255 impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
256 #[inline(always)]
257 pub(super) fn place(&self) -> &Place<Prov> {
258 &self.place
259 }
260
261 /// A place is either an mplace or some local.
262 #[inline(always)]
263 pub fn as_mplace_or_local(
264 &self,
265 ) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>)> {
266 match self.place {
267 Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout, align: self.align }),
268 Place::Local { frame, local, offset } => Right((frame, local, offset)),
269 }
270 }
271
272 #[inline(always)]
273 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
274 pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
275 self.as_mplace_or_local().left().unwrap_or_else(|| {
276 bug!(
277 "PlaceTy of type {} was a local when it was expected to be an MPlace",
278 self.layout.ty
279 )
280 })
281 }
282 }
283
284 impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
285 #[inline(always)]
286 fn layout(&self) -> TyAndLayout<'tcx> {
287 self.layout
288 }
289
290 #[inline]
291 fn meta(&self) -> MemPlaceMeta<Prov> {
292 match self.as_mplace_or_local() {
293 Left(mplace) => mplace.meta(),
294 Right(_) => {
295 debug_assert!(self.layout.is_sized(), "unsized locals should live in memory");
296 MemPlaceMeta::None
297 }
298 }
299 }
300
301 fn offset_with_meta<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
302 &self,
303 offset: Size,
304 meta: MemPlaceMeta<Prov>,
305 layout: TyAndLayout<'tcx>,
306 ecx: &InterpCx<'mir, 'tcx, M>,
307 ) -> InterpResult<'tcx, Self> {
308 Ok(match self.as_mplace_or_local() {
309 Left(mplace) => mplace.offset_with_meta(offset, meta, layout, ecx)?.into(),
310 Right((frame, local, old_offset)) => {
311 debug_assert!(layout.is_sized(), "unsized locals should live in memory");
312 assert_matches!(meta, MemPlaceMeta::None); // we couldn't store it anyway...
313 let new_offset = ecx
314 .data_layout()
315 .offset(old_offset.unwrap_or(Size::ZERO).bytes(), offset.bytes())?;
316 PlaceTy {
317 place: Place::Local {
318 frame,
319 local,
320 offset: Some(Size::from_bytes(new_offset)),
321 },
322 align: self.align.restrict_for_offset(offset),
323 layout,
324 }
325 }
326 })
327 }
328
329 fn to_op<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
330 &self,
331 ecx: &InterpCx<'mir, 'tcx, M>,
332 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
333 ecx.place_to_op(self)
334 }
335 }
336
337 // These are defined here because they produce a place.
338 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
339 #[inline(always)]
340 pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
341 match self.op() {
342 Operand::Indirect(mplace) => {
343 Left(MPlaceTy { mplace: *mplace, layout: self.layout, align: self.align.unwrap() })
344 }
345 Operand::Immediate(imm) => Right(ImmTy::from_immediate(*imm, self.layout)),
346 }
347 }
348
349 #[inline(always)]
350 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
351 pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
352 self.as_mplace_or_imm().left().unwrap_or_else(|| {
353 bug!(
354 "OpTy of type {} was immediate when it was expected to be an MPlace",
355 self.layout.ty
356 )
357 })
358 }
359 }
360
361 /// The `Weiteable` trait describes interpreter values that can be written to.
362 pub trait Writeable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
363 fn as_mplace_or_local(
364 &self,
365 ) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, Align, TyAndLayout<'tcx>)>;
366
367 fn force_mplace<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
368 &self,
369 ecx: &mut InterpCx<'mir, 'tcx, M>,
370 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>>;
371 }
372
373 impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
374 #[inline(always)]
375 fn as_mplace_or_local(
376 &self,
377 ) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, Align, TyAndLayout<'tcx>)>
378 {
379 self.as_mplace_or_local()
380 .map_right(|(frame, local, offset)| (frame, local, offset, self.align, self.layout))
381 }
382
383 #[inline(always)]
384 fn force_mplace<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
385 &self,
386 ecx: &mut InterpCx<'mir, 'tcx, M>,
387 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
388 ecx.force_allocation(self)
389 }
390 }
391
392 impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
393 #[inline(always)]
394 fn as_mplace_or_local(
395 &self,
396 ) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, Align, TyAndLayout<'tcx>)>
397 {
398 Left(self.clone())
399 }
400
401 #[inline(always)]
402 fn force_mplace<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
403 &self,
404 _ecx: &mut InterpCx<'mir, 'tcx, M>,
405 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
406 Ok(self.clone())
407 }
408 }
409
410 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
411 impl<'mir, 'tcx: 'mir, Prov, M> InterpCx<'mir, 'tcx, M>
412 where
413 Prov: Provenance,
414 M: Machine<'mir, 'tcx, Provenance = Prov>,
415 {
416 /// Take a value, which represents a (thin or wide) reference, and make it a place.
417 /// Alignment is just based on the type. This is the inverse of `mplace_to_ref()`.
418 ///
419 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
420 /// want to ever use the place for memory access!
421 /// Generally prefer `deref_pointer`.
422 pub fn ref_to_mplace(
423 &self,
424 val: &ImmTy<'tcx, M::Provenance>,
425 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
426 let pointee_type =
427 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
428 let layout = self.layout_of(pointee_type)?;
429 let (ptr, meta) = match **val {
430 Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None),
431 Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta)),
432 Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
433 };
434
435 // `ref_to_mplace` is called on raw pointers even if they don't actually get dereferenced;
436 // we hence can't call `size_and_align_of` since that asserts more validity than we want.
437 Ok(MPlaceTy::from_aligned_ptr_with_meta(ptr.to_pointer(self)?, layout, meta))
438 }
439
440 /// Turn a mplace into a (thin or wide) mutable raw pointer, pointing to the same space.
441 /// `align` information is lost!
442 /// This is the inverse of `ref_to_mplace`.
443 pub fn mplace_to_ref(
444 &self,
445 mplace: &MPlaceTy<'tcx, M::Provenance>,
446 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
447 let imm = mplace.mplace.to_ref(self);
448 let layout = self.layout_of(Ty::new_mut_ptr(self.tcx.tcx, mplace.layout.ty))?;
449 Ok(ImmTy::from_immediate(imm, layout))
450 }
451
452 /// Take an operand, representing a pointer, and dereference it to a place.
453 /// Corresponds to the `*` operator in Rust.
454 #[instrument(skip(self), level = "debug")]
455 pub fn deref_pointer(
456 &self,
457 src: &impl Readable<'tcx, M::Provenance>,
458 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
459 let val = self.read_immediate(src)?;
460 trace!("deref to {} on {:?}", val.layout.ty, *val);
461
462 if val.layout.ty.is_box() {
463 bug!("dereferencing {}", val.layout.ty);
464 }
465
466 let mplace = self.ref_to_mplace(&val)?;
467 self.check_mplace(&mplace)?;
468 Ok(mplace)
469 }
470
471 #[inline]
472 pub(super) fn get_place_alloc(
473 &self,
474 mplace: &MPlaceTy<'tcx, M::Provenance>,
475 ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
476 {
477 let (size, _align) = self
478 .size_and_align_of_mplace(&mplace)?
479 .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
480 // Due to packed places, only `mplace.align` matters.
481 self.get_ptr_alloc(mplace.ptr(), size, mplace.align)
482 }
483
484 #[inline]
485 pub(super) fn get_place_alloc_mut(
486 &mut self,
487 mplace: &MPlaceTy<'tcx, M::Provenance>,
488 ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
489 {
490 let (size, _align) = self
491 .size_and_align_of_mplace(&mplace)?
492 .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
493 // Due to packed places, only `mplace.align` matters.
494 self.get_ptr_alloc_mut(mplace.ptr(), size, mplace.align)
495 }
496
497 /// Check if this mplace is dereferenceable and sufficiently aligned.
498 pub fn check_mplace(&self, mplace: &MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
499 let (size, _align) = self
500 .size_and_align_of_mplace(&mplace)?
501 .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
502 // Due to packed places, only `mplace.align` matters.
503 let align =
504 if M::enforce_alignment(self).should_check() { mplace.align } else { Align::ONE };
505 self.check_ptr_access_align(mplace.ptr(), size, align, CheckInAllocMsg::DerefTest)?;
506 Ok(())
507 }
508
509 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
510 /// Also returns the number of elements.
511 pub fn mplace_to_simd(
512 &self,
513 mplace: &MPlaceTy<'tcx, M::Provenance>,
514 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
515 // Basically we just transmute this place into an array following simd_size_and_type.
516 // (Transmuting is okay since this is an in-memory place. We also double-check the size
517 // stays the same.)
518 let (len, e_ty) = mplace.layout.ty.simd_size_and_type(*self.tcx);
519 let array = Ty::new_array(self.tcx.tcx, e_ty, len);
520 let layout = self.layout_of(array)?;
521 assert_eq!(layout.size, mplace.layout.size);
522 Ok((MPlaceTy { layout, ..*mplace }, len))
523 }
524
525 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
526 /// Also returns the number of elements.
527 pub fn place_to_simd(
528 &mut self,
529 place: &PlaceTy<'tcx, M::Provenance>,
530 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
531 let mplace = self.force_allocation(place)?;
532 self.mplace_to_simd(&mplace)
533 }
534
535 pub fn local_to_place(
536 &self,
537 frame: usize,
538 local: mir::Local,
539 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
540 // Other parts of the system rely on `Place::Local` never being unsized.
541 // So we eagerly check here if this local has an MPlace, and if yes we use it.
542 let frame_ref = &self.stack()[frame];
543 let layout = self.layout_of_local(frame_ref, local, None)?;
544 let place = if layout.is_sized() {
545 // We can just always use the `Local` for sized values.
546 Place::Local { frame, local, offset: None }
547 } else {
548 // Unsized `Local` isn't okay (we cannot store the metadata).
549 match frame_ref.locals[local].access()? {
550 Operand::Immediate(_) => {
551 // ConstProp marks *all* locals as `Immediate::Uninit` since it cannot
552 // efficiently check whether they are sized. We have to catch that case here.
553 throw_inval!(ConstPropNonsense);
554 }
555 Operand::Indirect(mplace) => Place::Ptr(*mplace),
556 }
557 };
558 Ok(PlaceTy { place, layout, align: layout.align.abi })
559 }
560
561 /// Computes a place. You should only use this if you intend to write into this
562 /// place; for reading, a more efficient alternative is `eval_place_to_op`.
563 #[instrument(skip(self), level = "debug")]
564 pub fn eval_place(
565 &self,
566 mir_place: mir::Place<'tcx>,
567 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
568 let mut place = self.local_to_place(self.frame_idx(), mir_place.local)?;
569 // Using `try_fold` turned out to be bad for performance, hence the loop.
570 for elem in mir_place.projection.iter() {
571 place = self.project(&place, elem)?
572 }
573
574 trace!("{:?}", self.dump_place(&place));
575 // Sanity-check the type we ended up with.
576 debug_assert!(
577 mir_assign_valid_types(
578 *self.tcx,
579 self.param_env,
580 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
581 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
582 )?)?,
583 place.layout,
584 ),
585 "eval_place of a MIR place with type {:?} produced an interpreter place with type {}",
586 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
587 place.layout.ty,
588 );
589 Ok(place)
590 }
591
592 /// Write an immediate to a place
593 #[inline(always)]
594 #[instrument(skip(self), level = "debug")]
595 pub fn write_immediate(
596 &mut self,
597 src: Immediate<M::Provenance>,
598 dest: &impl Writeable<'tcx, M::Provenance>,
599 ) -> InterpResult<'tcx> {
600 self.write_immediate_no_validate(src, dest)?;
601
602 if M::enforce_validity(self, dest.layout()) {
603 // Data got changed, better make sure it matches the type!
604 self.validate_operand(&dest.to_op(self)?)?;
605 }
606
607 Ok(())
608 }
609
610 /// Write a scalar to a place
611 #[inline(always)]
612 pub fn write_scalar(
613 &mut self,
614 val: impl Into<Scalar<M::Provenance>>,
615 dest: &impl Writeable<'tcx, M::Provenance>,
616 ) -> InterpResult<'tcx> {
617 self.write_immediate(Immediate::Scalar(val.into()), dest)
618 }
619
620 /// Write a pointer to a place
621 #[inline(always)]
622 pub fn write_pointer(
623 &mut self,
624 ptr: impl Into<Pointer<Option<M::Provenance>>>,
625 dest: &impl Writeable<'tcx, M::Provenance>,
626 ) -> InterpResult<'tcx> {
627 self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
628 }
629
630 /// Write an immediate to a place.
631 /// If you use this you are responsible for validating that things got copied at the
632 /// right type.
633 fn write_immediate_no_validate(
634 &mut self,
635 src: Immediate<M::Provenance>,
636 dest: &impl Writeable<'tcx, M::Provenance>,
637 ) -> InterpResult<'tcx> {
638 assert!(dest.layout().is_sized(), "Cannot write unsized immediate data");
639
640 // See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
641 // but not factored as a separate function.
642 let mplace = match dest.as_mplace_or_local() {
643 Right((frame, local, offset, align, layout)) => {
644 if offset.is_some() {
645 // This has been projected to a part of this local. We could have complicated
646 // logic to still keep this local as an `Operand`... but it's much easier to
647 // just fall back to the indirect path.
648 dest.force_mplace(self)?
649 } else {
650 M::before_access_local_mut(self, frame, local)?;
651 match self.stack_mut()[frame].locals[local].access_mut()? {
652 Operand::Immediate(local_val) => {
653 // Local can be updated in-place.
654 *local_val = src;
655 // Double-check that the value we are storing and the local fit to each other.
656 // (*After* doing the update for borrow checker reasons.)
657 if cfg!(debug_assertions) {
658 let local_layout =
659 self.layout_of_local(&self.stack()[frame], local, None)?;
660 match (src, local_layout.abi) {
661 (Immediate::Scalar(scalar), Abi::Scalar(s)) => {
662 assert_eq!(scalar.size(), s.size(self))
663 }
664 (
665 Immediate::ScalarPair(a_val, b_val),
666 Abi::ScalarPair(a, b),
667 ) => {
668 assert_eq!(a_val.size(), a.size(self));
669 assert_eq!(b_val.size(), b.size(self));
670 }
671 (Immediate::Uninit, _) => {}
672 (src, abi) => {
673 bug!(
674 "value {src:?} cannot be written into local with type {} (ABI {abi:?})",
675 local_layout.ty
676 )
677 }
678 };
679 }
680 return Ok(());
681 }
682 Operand::Indirect(mplace) => {
683 // The local is in memory, go on below.
684 MPlaceTy { mplace: *mplace, align, layout }
685 }
686 }
687 }
688 }
689 Left(mplace) => mplace, // already referring to memory
690 };
691
692 // This is already in memory, write there.
693 self.write_immediate_to_mplace_no_validate(src, mplace.layout, mplace.align, mplace.mplace)
694 }
695
696 /// Write an immediate to memory.
697 /// If you use this you are responsible for validating that things got copied at the
698 /// right layout.
699 fn write_immediate_to_mplace_no_validate(
700 &mut self,
701 value: Immediate<M::Provenance>,
702 layout: TyAndLayout<'tcx>,
703 align: Align,
704 dest: MemPlace<M::Provenance>,
705 ) -> InterpResult<'tcx> {
706 // Note that it is really important that the type here is the right one, and matches the
707 // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
708 // to handle padding properly, which is only correct if we never look at this data with the
709 // wrong type.
710
711 let tcx = *self.tcx;
712 let Some(mut alloc) =
713 self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })?
714 else {
715 // zero-sized access
716 return Ok(());
717 };
718
719 match value {
720 Immediate::Scalar(scalar) => {
721 let Abi::Scalar(s) = layout.abi else {
722 span_bug!(
723 self.cur_span(),
724 "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
725 )
726 };
727 let size = s.size(&tcx);
728 assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
729 alloc.write_scalar(alloc_range(Size::ZERO, size), scalar)
730 }
731 Immediate::ScalarPair(a_val, b_val) => {
732 // We checked `ptr_align` above, so all fields will have the alignment they need.
733 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
734 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
735 let Abi::ScalarPair(a, b) = layout.abi else {
736 span_bug!(
737 self.cur_span(),
738 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
739 layout
740 )
741 };
742 let (a_size, b_size) = (a.size(&tcx), b.size(&tcx));
743 let b_offset = a_size.align_to(b.align(&tcx).abi);
744 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
745
746 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
747 // but that does not work: We could be a newtype around a pair, then the
748 // fields do not match the `ScalarPair` components.
749
750 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
751 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
752 }
753 Immediate::Uninit => alloc.write_uninit(),
754 }
755 }
756
757 pub fn write_uninit(
758 &mut self,
759 dest: &impl Writeable<'tcx, M::Provenance>,
760 ) -> InterpResult<'tcx> {
761 let mplace = match dest.as_mplace_or_local() {
762 Left(mplace) => mplace,
763 Right((frame, local, offset, align, layout)) => {
764 if offset.is_some() {
765 // This has been projected to a part of this local. We could have complicated
766 // logic to still keep this local as an `Operand`... but it's much easier to
767 // just fall back to the indirect path.
768 // FIXME: share the logic with `write_immediate_no_validate`.
769 dest.force_mplace(self)?
770 } else {
771 M::before_access_local_mut(self, frame, local)?;
772 match self.stack_mut()[frame].locals[local].access_mut()? {
773 Operand::Immediate(local) => {
774 *local = Immediate::Uninit;
775 return Ok(());
776 }
777 Operand::Indirect(mplace) => {
778 // The local is in memory, go on below.
779 MPlaceTy { mplace: *mplace, layout, align }
780 }
781 }
782 }
783 }
784 };
785 let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
786 // Zero-sized access
787 return Ok(());
788 };
789 alloc.write_uninit()?;
790 Ok(())
791 }
792
793 /// Copies the data from an operand to a place.
794 /// `allow_transmute` indicates whether the layouts may disagree.
795 #[inline(always)]
796 #[instrument(skip(self), level = "debug")]
797 pub fn copy_op(
798 &mut self,
799 src: &impl Readable<'tcx, M::Provenance>,
800 dest: &impl Writeable<'tcx, M::Provenance>,
801 allow_transmute: bool,
802 ) -> InterpResult<'tcx> {
803 // Generally for transmutation, data must be valid both at the old and new type.
804 // But if the types are the same, the 2nd validation below suffices.
805 if src.layout().ty != dest.layout().ty && M::enforce_validity(self, src.layout()) {
806 self.validate_operand(&src.to_op(self)?)?;
807 }
808
809 // Do the actual copy.
810 self.copy_op_no_validate(src, dest, allow_transmute)?;
811
812 if M::enforce_validity(self, dest.layout()) {
813 // Data got changed, better make sure it matches the type!
814 self.validate_operand(&dest.to_op(self)?)?;
815 }
816
817 Ok(())
818 }
819
820 /// Copies the data from an operand to a place.
821 /// `allow_transmute` indicates whether the layouts may disagree.
822 /// Also, if you use this you are responsible for validating that things get copied at the
823 /// right type.
824 #[instrument(skip(self), level = "debug")]
825 fn copy_op_no_validate(
826 &mut self,
827 src: &impl Readable<'tcx, M::Provenance>,
828 dest: &impl Writeable<'tcx, M::Provenance>,
829 allow_transmute: bool,
830 ) -> InterpResult<'tcx> {
831 // We do NOT compare the types for equality, because well-typed code can
832 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
833 let layout_compat =
834 mir_assign_valid_types(*self.tcx, self.param_env, src.layout(), dest.layout());
835 if !allow_transmute && !layout_compat {
836 span_bug!(
837 self.cur_span(),
838 "type mismatch when copying!\nsrc: {},\ndest: {}",
839 src.layout().ty,
840 dest.layout().ty,
841 );
842 }
843
844 // Let us see if the layout is simple so we take a shortcut,
845 // avoid force_allocation.
846 let src = match self.read_immediate_raw(src)? {
847 Right(src_val) => {
848 // FIXME(const_prop): Const-prop can possibly evaluate an
849 // unsized copy operation when it thinks that the type is
850 // actually sized, due to a trivially false where-clause
851 // predicate like `where Self: Sized` with `Self = dyn Trait`.
852 // See #102553 for an example of such a predicate.
853 if src.layout().is_unsized() {
854 throw_inval!(ConstPropNonsense);
855 }
856 if dest.layout().is_unsized() {
857 throw_inval!(ConstPropNonsense);
858 }
859 assert_eq!(src.layout().size, dest.layout().size);
860 // Yay, we got a value that we can write directly.
861 return if layout_compat {
862 self.write_immediate_no_validate(*src_val, dest)
863 } else {
864 // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
865 // loaded using the offsets defined by `src.layout`. When we put this back into
866 // the destination, we have to use the same offsets! So (a) we make sure we
867 // write back to memory, and (b) we use `dest` *with the source layout*.
868 let dest_mem = dest.force_mplace(self)?;
869 self.write_immediate_to_mplace_no_validate(
870 *src_val,
871 src.layout(),
872 dest_mem.align,
873 dest_mem.mplace,
874 )
875 };
876 }
877 Left(mplace) => mplace,
878 };
879 // Slow path, this does not fit into an immediate. Just memcpy.
880 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout().ty);
881
882 let dest = dest.force_mplace(self)?;
883 let Some((dest_size, _)) = self.size_and_align_of_mplace(&dest)? else {
884 span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
885 };
886 if cfg!(debug_assertions) {
887 let src_size = self.size_and_align_of_mplace(&src)?.unwrap().0;
888 assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
889 } else {
890 // As a cheap approximation, we compare the fixed parts of the size.
891 assert_eq!(src.layout.size, dest.layout.size);
892 }
893
894 // Setting `nonoverlapping` here only has an effect when we don't hit the fast-path above,
895 // but that should at least match what LLVM does where `memcpy` is also only used when the
896 // type does not have Scalar/ScalarPair layout.
897 // (Or as the `Assign` docs put it, assignments "not producing primitives" must be
898 // non-overlapping.)
899 self.mem_copy(
900 src.ptr(),
901 src.align,
902 dest.ptr(),
903 dest.align,
904 dest_size,
905 /*nonoverlapping*/ true,
906 )
907 }
908
909 /// Ensures that a place is in memory, and returns where it is.
910 /// If the place currently refers to a local that doesn't yet have a matching allocation,
911 /// create such an allocation.
912 /// This is essentially `force_to_memplace`.
913 #[instrument(skip(self), level = "debug")]
914 pub fn force_allocation(
915 &mut self,
916 place: &PlaceTy<'tcx, M::Provenance>,
917 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
918 let mplace = match place.place {
919 Place::Local { frame, local, offset } => {
920 M::before_access_local_mut(self, frame, local)?;
921 let whole_local = match self.stack_mut()[frame].locals[local].access_mut()? {
922 &mut Operand::Immediate(local_val) => {
923 // We need to make an allocation.
924
925 // We need the layout of the local. We can NOT use the layout we got,
926 // that might e.g., be an inner field of a struct with `Scalar` layout,
927 // that has different alignment than the outer field.
928 let local_layout =
929 self.layout_of_local(&self.stack()[frame], local, None)?;
930 assert!(local_layout.is_sized(), "unsized locals cannot be immediate");
931 let mplace = self.allocate(local_layout, MemoryKind::Stack)?;
932 // Preserve old value. (As an optimization, we can skip this if it was uninit.)
933 if !matches!(local_val, Immediate::Uninit) {
934 // We don't have to validate as we can assume the local was already
935 // valid for its type. We must not use any part of `place` here, that
936 // could be a projection to a part of the local!
937 self.write_immediate_to_mplace_no_validate(
938 local_val,
939 local_layout,
940 local_layout.align.abi,
941 mplace.mplace,
942 )?;
943 }
944 M::after_local_allocated(self, frame, local, &mplace)?;
945 // Now we can call `access_mut` again, asserting it goes well, and actually
946 // overwrite things. This points to the entire allocation, not just the part
947 // the place refers to, i.e. we do this before we apply `offset`.
948 *self.stack_mut()[frame].locals[local].access_mut().unwrap() =
949 Operand::Indirect(mplace.mplace);
950 mplace.mplace
951 }
952 &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
953 };
954 if let Some(offset) = offset {
955 whole_local.offset_with_meta_(offset, MemPlaceMeta::None, self)?
956 } else {
957 // Preserve wide place metadata, do not call `offset`.
958 whole_local
959 }
960 }
961 Place::Ptr(mplace) => mplace,
962 };
963 // Return with the original layout and align, so that the caller can go on
964 Ok(MPlaceTy { mplace, layout: place.layout, align: place.align })
965 }
966
967 pub fn allocate_dyn(
968 &mut self,
969 layout: TyAndLayout<'tcx>,
970 kind: MemoryKind<M::MemoryKind>,
971 meta: MemPlaceMeta<M::Provenance>,
972 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
973 let Some((size, align)) = self.size_and_align_of(&meta, &layout)? else {
974 span_bug!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")
975 };
976 let ptr = self.allocate_ptr(size, align, kind)?;
977 Ok(MPlaceTy::from_aligned_ptr_with_meta(ptr.into(), layout, meta))
978 }
979
980 pub fn allocate(
981 &mut self,
982 layout: TyAndLayout<'tcx>,
983 kind: MemoryKind<M::MemoryKind>,
984 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
985 assert!(layout.is_sized());
986 self.allocate_dyn(layout, kind, MemPlaceMeta::None)
987 }
988
989 /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
990 pub fn allocate_str(
991 &mut self,
992 str: &str,
993 kind: MemoryKind<M::MemoryKind>,
994 mutbl: Mutability,
995 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
996 let ptr = self.allocate_bytes_ptr(str.as_bytes(), Align::ONE, kind, mutbl)?;
997 let meta = Scalar::from_target_usize(u64::try_from(str.len()).unwrap(), self);
998 let mplace = MemPlace { ptr: ptr.into(), meta: MemPlaceMeta::Meta(meta) };
999
1000 let ty = Ty::new_ref(
1001 self.tcx.tcx,
1002 self.tcx.lifetimes.re_static,
1003 ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
1004 );
1005 let layout = self.layout_of(ty).unwrap();
1006 Ok(MPlaceTy { mplace, layout, align: layout.align.abi })
1007 }
1008
1009 /// Writes the aggregate to the destination.
1010 #[instrument(skip(self), level = "trace")]
1011 pub fn write_aggregate(
1012 &mut self,
1013 kind: &mir::AggregateKind<'tcx>,
1014 operands: &IndexSlice<FieldIdx, mir::Operand<'tcx>>,
1015 dest: &PlaceTy<'tcx, M::Provenance>,
1016 ) -> InterpResult<'tcx> {
1017 self.write_uninit(dest)?;
1018 let (variant_index, variant_dest, active_field_index) = match *kind {
1019 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
1020 let variant_dest = self.project_downcast(dest, variant_index)?;
1021 (variant_index, variant_dest, active_field_index)
1022 }
1023 _ => (FIRST_VARIANT, dest.clone(), None),
1024 };
1025 if active_field_index.is_some() {
1026 assert_eq!(operands.len(), 1);
1027 }
1028 for (field_index, operand) in operands.iter_enumerated() {
1029 let field_index = active_field_index.unwrap_or(field_index);
1030 let field_dest = self.project_field(&variant_dest, field_index.as_usize())?;
1031 let op = self.eval_operand(operand, Some(field_dest.layout))?;
1032 self.copy_op(&op, &field_dest, /*allow_transmute*/ false)?;
1033 }
1034 self.write_discriminant(variant_index, dest)
1035 }
1036
1037 pub fn raw_const_to_mplace(
1038 &self,
1039 raw: mir::ConstAlloc<'tcx>,
1040 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1041 // This must be an allocation in `tcx`
1042 let _ = self.tcx.global_alloc(raw.alloc_id);
1043 let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
1044 let layout = self.layout_of(raw.ty)?;
1045 Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
1046 }
1047
1048 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1049 /// Aso returns the vtable.
1050 pub(super) fn unpack_dyn_trait(
1051 &self,
1052 mplace: &MPlaceTy<'tcx, M::Provenance>,
1053 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, Pointer<Option<M::Provenance>>)> {
1054 assert!(
1055 matches!(mplace.layout.ty.kind(), ty::Dynamic(_, _, ty::Dyn)),
1056 "`unpack_dyn_trait` only makes sense on `dyn*` types"
1057 );
1058 let vtable = mplace.meta().unwrap_meta().to_pointer(self)?;
1059 let (ty, _) = self.get_ptr_vtable(vtable)?;
1060 let layout = self.layout_of(ty)?;
1061
1062 let mplace = MPlaceTy {
1063 mplace: MemPlace { meta: MemPlaceMeta::None, ..mplace.mplace },
1064 layout,
1065 align: layout.align.abi,
1066 };
1067 Ok((mplace, vtable))
1068 }
1069
1070 /// Turn a `dyn* Trait` type into an value with the actual dynamic type.
1071 /// Also returns the vtable.
1072 pub(super) fn unpack_dyn_star<P: Projectable<'tcx, M::Provenance>>(
1073 &self,
1074 val: &P,
1075 ) -> InterpResult<'tcx, (P, Pointer<Option<M::Provenance>>)> {
1076 assert!(
1077 matches!(val.layout().ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
1078 "`unpack_dyn_star` only makes sense on `dyn*` types"
1079 );
1080 let data = self.project_field(val, 0)?;
1081 let vtable = self.project_field(val, 1)?;
1082 let vtable = self.read_pointer(&vtable.to_op(self)?)?;
1083 let (ty, _) = self.get_ptr_vtable(vtable)?;
1084 let layout = self.layout_of(ty)?;
1085 // `data` is already the right thing but has the wrong type. So we transmute it, by
1086 // projecting with offset 0.
1087 let data = data.transmute(layout, self)?;
1088 Ok((data, vtable))
1089 }
1090 }
1091
1092 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1093 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1094 mod size_asserts {
1095 use super::*;
1096 use rustc_data_structures::static_assert_size;
1097 // tidy-alphabetical-start
1098 static_assert_size!(MemPlace, 40);
1099 static_assert_size!(MemPlaceMeta, 24);
1100 static_assert_size!(MPlaceTy<'_>, 64);
1101 static_assert_size!(Place, 40);
1102 static_assert_size!(PlaceTy<'_>, 64);
1103 // tidy-alphabetical-end
1104 }