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.
45use std::assert_matches;
67use either::{Either, Left, Right};
8use rustc_abi::{BackendRepr, HasDataLayout, Size};
9use rustc_middle::ty::layout::TyAndLayout;
10use rustc_middle::ty::{self, Ty};
11use rustc_middle::{bug, mir, span_bug};
12use tracing::field::Empty;
13use tracing::{instrument, trace};
1415use super::{
16AllocInit, AllocRef, AllocRefMut, CheckAlignMsg, CheckInAllocMsg, CtfeProvenance, ImmTy,
17Immediate, InterpCx, InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy,
18Operand, Pointer, Projectable, Provenance, Scalar, alloc_range, err_ub, err_ub_format,
19interp_ok, mir_assign_valid_types, throw_ub_format,
20};
21use crate::enter_trace_span;
2223#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
MemPlaceMeta<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MemPlaceMeta<Prov> {
#[inline]
fn clone(&self) -> MemPlaceMeta<Prov> {
match self {
MemPlaceMeta::Meta(__self_0) =>
MemPlaceMeta::Meta(::core::clone::Clone::clone(__self_0)),
MemPlaceMeta::None => MemPlaceMeta::None,
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MemPlaceMeta<Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
MemPlaceMeta::Meta(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[automatically_derived]
impl<Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq for
MemPlaceMeta<Prov> {
#[inline]
fn eq(&self, other: &MemPlaceMeta<Prov>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MemPlaceMeta::Meta(__self_0), MemPlaceMeta::Meta(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for
MemPlaceMeta<Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Scalar<Prov>>;
}
}Eq, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
MemPlaceMeta<Prov> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MemPlaceMeta::Meta(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Meta",
&__self_0),
MemPlaceMeta::None =>
::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug)]
24/// Information required for the sound usage of a `MemPlace`.
25pub enum MemPlaceMeta<Prov: Provenance = CtfeProvenance> {
26/// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
27Meta(Scalar<Prov>),
28/// `Sized` types or unsized `extern type`
29None,
30}
3132impl<Prov: Provenance> MemPlaceMeta<Prov> {
33#[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
34pub fn unwrap_meta(self) -> Scalar<Prov> {
35match self {
36Self::Meta(s) => s,
37Self::None => {
38::rustc_middle::util::bug::bug_fmt(format_args!("expected wide pointer extra data (e.g. slice length or trait object vtable)"))bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")39 }
40 }
41 }
4243#[inline(always)]
44pub fn has_meta(self) -> bool {
45match self {
46Self::Meta(_) => true,
47Self::None => false,
48 }
49 }
50}
5152#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
MemPlace<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MemPlace<Prov> {
#[inline]
fn clone(&self) -> MemPlace<Prov> {
MemPlace {
ptr: ::core::clone::Clone::clone(&self.ptr),
meta: ::core::clone::Clone::clone(&self.meta),
misaligned: ::core::clone::Clone::clone(&self.misaligned),
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MemPlace<Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.ptr, state);
::core::hash::Hash::hash(&self.meta, state);
::core::hash::Hash::hash(&self.misaligned, state)
}
}Hash, #[automatically_derived]
impl<Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq for
MemPlace<Prov> {
#[inline]
fn eq(&self, other: &MemPlace<Prov>) -> bool {
self.ptr == other.ptr && self.meta == other.meta &&
self.misaligned == other.misaligned
}
}PartialEq, #[automatically_derived]
impl<Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for MemPlace<Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Pointer<Option<Prov>>>;
let _: ::core::cmp::AssertParamIsEq<MemPlaceMeta<Prov>>;
let _: ::core::cmp::AssertParamIsEq<Option<Misalignment>>;
}
}Eq, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
MemPlace<Prov> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "MemPlace",
"ptr", &self.ptr, "meta", &self.meta, "misaligned",
&&self.misaligned)
}
}Debug)]
53pub(super) struct MemPlace<Prov: Provenance = CtfeProvenance> {
54/// The pointer can be a pure integer, with the `None` provenance.
55pub 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`).
59pub meta: MemPlaceMeta<Prov>,
60/// Stores whether this place was created based on a sufficiently aligned pointer.
61misaligned: Option<Misalignment>,
62}
6364impl<Prov: Provenance> MemPlace<Prov> {
65/// Adjust the provenance of the main pointer (metadata is unaffected).
66fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
67MemPlace { ptr: self.ptr.map_provenance(|p| p.map(f)), ..self }
68 }
6970/// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
71#[inline]
72fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
73Immediate::new_pointer_with_meta(self.ptr, self.meta, cx)
74 }
7576#[inline]
77// Not called `offset_with_meta` to avoid confusion with the trait method.
78fn offset_with_meta_<'tcx, M: Machine<'tcx, Provenance = Prov>>(
79self,
80 offset: Size,
81 mode: OffsetMode,
82 meta: MemPlaceMeta<Prov>,
83 ecx: &InterpCx<'tcx, M>,
84 ) -> InterpResult<'tcx, Self> {
85if true {
if !(!meta.has_meta() || self.meta.has_meta()) {
{
::core::panicking::panic_fmt(format_args!("cannot use `offset_with_meta` to add metadata to a place"));
}
};
};debug_assert!(
86 !meta.has_meta() || self.meta.has_meta(),
87"cannot use `offset_with_meta` to add metadata to a place"
88);
89let ptr = match mode {
90 OffsetMode::Inbounds => {
91 ecx.ptr_offset_inbounds(self.ptr, offset.bytes().try_into().unwrap())?
92}
93 OffsetMode::Wrapping => self.ptr.wrapping_offset(offset, ecx),
94 };
95interp_ok(MemPlace { ptr, meta, misaligned: self.misaligned })
96 }
97}
9899/// A MemPlace with its layout. Constructing it is only possible in this module.
100#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MPlaceTy<'tcx, Prov> {
#[inline]
fn clone(&self) -> MPlaceTy<'tcx, Prov> {
MPlaceTy {
mplace: ::core::clone::Clone::clone(&self.mplace),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone, #[automatically_derived]
impl<'tcx, Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MPlaceTy<'tcx, Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.mplace, state);
::core::hash::Hash::hash(&self.layout, state)
}
}Hash, #[automatically_derived]
impl<'tcx, Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for
MPlaceTy<'tcx, Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<MemPlace<Prov>>;
let _: ::core::cmp::AssertParamIsEq<TyAndLayout<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx, Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq
for MPlaceTy<'tcx, Prov> {
#[inline]
fn eq(&self, other: &MPlaceTy<'tcx, Prov>) -> bool {
self.mplace == other.mplace && self.layout == other.layout
}
}PartialEq)]
101pub struct MPlaceTy<'tcx, Prov: Provenance = CtfeProvenance> {
102 mplace: MemPlace<Prov>,
103pub layout: TyAndLayout<'tcx>,
104}
105106impl<Prov: Provenance> std::fmt::Debugfor MPlaceTy<'_, Prov> {
107fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108// Printing `layout` results in too much noise; just print a nice version of the type.
109f.debug_struct("MPlaceTy")
110 .field("mplace", &self.mplace)
111 .field("ty", &format_args!("{0}", self.layout.ty)format_args!("{}", self.layout.ty))
112 .finish()
113 }
114}
115116impl<'tcx, Prov: Provenance> MPlaceTy<'tcx, Prov> {
117/// Produces a MemPlace that works for ZST but nothing else.
118 /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
119 /// don't need to worry about memory leaks.
120#[inline]
121pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
122if !layout.is_zst() {
::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
123let align = layout.align.abi;
124let ptr = Pointer::without_provenance(align.bytes()); // no provenance, absolute address
125MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None, misaligned: None }, layout }
126 }
127128/// Adjust the provenance of the main pointer (metadata is unaffected).
129pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
130MPlaceTy { mplace: self.mplace.map_provenance(f), ..self }
131 }
132133#[inline(always)]
134pub(super) fn mplace(&self) -> &MemPlace<Prov> {
135&self.mplace
136 }
137138#[inline(always)]
139pub fn ptr(&self) -> Pointer<Option<Prov>> {
140self.mplace.ptr
141 }
142143#[inline(always)]
144pub fn to_ref(&self, cx: &impl HasDataLayout) -> Immediate<Prov> {
145self.mplace.to_ref(cx)
146 }
147}
148149impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
150#[inline(always)]
151fn layout(&self) -> TyAndLayout<'tcx> {
152self.layout
153 }
154155#[inline(always)]
156fn meta(&self) -> MemPlaceMeta<Prov> {
157self.mplace.meta
158 }
159160fn offset_with_meta<M: Machine<'tcx, Provenance = Prov>>(
161&self,
162 offset: Size,
163 mode: OffsetMode,
164 meta: MemPlaceMeta<Prov>,
165 layout: TyAndLayout<'tcx>,
166 ecx: &InterpCx<'tcx, M>,
167 ) -> InterpResult<'tcx, Self> {
168interp_ok(MPlaceTy {
169 mplace: self.mplace.offset_with_meta_(offset, mode, meta, ecx)?,
170layout,
171 })
172 }
173174#[inline(always)]
175fn to_op<M: Machine<'tcx, Provenance = Prov>>(
176&self,
177 _ecx: &InterpCx<'tcx, M>,
178 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
179interp_ok(self.clone().into())
180 }
181}
182183#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
Place<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
Place<Prov> {
#[inline]
fn clone(&self) -> Place<Prov> {
match self {
Place::Ptr(__self_0) =>
Place::Ptr(::core::clone::Clone::clone(__self_0)),
Place::Local {
local: __self_0, offset: __self_1, locals_addr: __self_2 } =>
Place::Local {
local: ::core::clone::Clone::clone(__self_0),
offset: ::core::clone::Clone::clone(__self_1),
locals_addr: ::core::clone::Clone::clone(__self_2),
},
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for Place<Prov>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Place::Ptr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ptr",
&__self_0),
Place::Local {
local: __self_0, offset: __self_1, locals_addr: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f, "Local",
"local", __self_0, "offset", __self_1, "locals_addr",
&__self_2),
}
}
}Debug)]
184pub(super) enum Place<Prov: Provenance = CtfeProvenance> {
185/// A place referring to a value allocated in the `Memory` system.
186Ptr(MemPlace<Prov>),
187188/// To support alloc-free locals, we are able to write directly to a local. The offset indicates
189 /// where in the local this place is located; if it is `None`, no projection has been applied
190 /// and the type of the place is exactly the type of the local.
191 /// Such projections are meaningful even if the offset is 0, since they can change layouts.
192 /// (Without that optimization, we'd just always be a `MemPlace`.)
193 /// `Local` places always refer to the current stack frame, so they are unstable under
194 /// function calls/returns and switching betweens stacks of different threads!
195 /// We carry around the address of the `locals` buffer of the correct stack frame as a sanity
196 /// check to be able to catch some cases of using a dangling `Place`.
197 ///
198 /// This variant shall not be used for unsized types -- those must always live in memory.
199Local { local: mir::Local, offset: Option<Size>, locals_addr: usize },
200}
201202/// An evaluated place, together with its type.
203///
204/// This may reference a stack frame by its index, so `PlaceTy` should generally not be kept around
205/// for longer than a single operation. Popping and then pushing a stack frame can make `PlaceTy`
206/// point to the wrong destination. If the interpreter has multiple stacks, stack switching will
207/// also invalidate a `PlaceTy`.
208#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
PlaceTy<'tcx, Prov> {
#[inline]
fn clone(&self) -> PlaceTy<'tcx, Prov> {
PlaceTy {
place: ::core::clone::Clone::clone(&self.place),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone)]
209pub struct PlaceTy<'tcx, Prov: Provenance = CtfeProvenance> {
210 place: Place<Prov>, // Keep this private; it helps enforce invariants.
211pub layout: TyAndLayout<'tcx>,
212}
213214impl<Prov: Provenance> std::fmt::Debugfor PlaceTy<'_, Prov> {
215fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216// Printing `layout` results in too much noise; just print a nice version of the type.
217f.debug_struct("PlaceTy")
218 .field("place", &self.place)
219 .field("ty", &format_args!("{0}", self.layout.ty)format_args!("{}", self.layout.ty))
220 .finish()
221 }
222}
223224impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
225#[inline(always)]
226fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
227PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
228 }
229}
230231impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
232#[inline(always)]
233pub(super) fn place(&self) -> &Place<Prov> {
234&self.place
235 }
236237/// A place is either an mplace or some local.
238 ///
239 /// Note that the return value can be different even for logically identical places!
240 /// Specifically, if a local is stored in-memory, this may return `Local` or `MPlaceTy`
241 /// depending on how the place was constructed. In other words, seeing `Local` here does *not*
242 /// imply that this place does not point to memory. Every caller must therefore always handle
243 /// both cases.
244#[inline(always)]
245pub fn as_mplace_or_local(
246&self,
247 ) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)> {
248match self.place {
249 Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout }),
250 Place::Local { local, offset, locals_addr } => {
251Right((local, offset, locals_addr, self.layout))
252 }
253 }
254 }
255256#[inline(always)]
257 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
258pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
259self.as_mplace_or_local().left().unwrap_or_else(|| {
260::rustc_middle::util::bug::bug_fmt(format_args!("PlaceTy of type {0} was a local when it was expected to be an MPlace",
self.layout.ty))bug!(
261"PlaceTy of type {} was a local when it was expected to be an MPlace",
262self.layout.ty
263 )264 })
265 }
266}
267268impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
269#[inline(always)]
270fn layout(&self) -> TyAndLayout<'tcx> {
271self.layout
272 }
273274#[inline]
275fn meta(&self) -> MemPlaceMeta<Prov> {
276match self.as_mplace_or_local() {
277Left(mplace) => mplace.meta(),
278Right(_) => {
279if true {
if !self.layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals should live in memory"));
}
};
};debug_assert!(self.layout.is_sized(), "unsized locals should live in memory");
280 MemPlaceMeta::None281 }
282 }
283 }
284285fn offset_with_meta<M: Machine<'tcx, Provenance = Prov>>(
286&self,
287 offset: Size,
288 mode: OffsetMode,
289 meta: MemPlaceMeta<Prov>,
290 layout: TyAndLayout<'tcx>,
291 ecx: &InterpCx<'tcx, M>,
292 ) -> InterpResult<'tcx, Self> {
293interp_ok(match self.as_mplace_or_local() {
294Left(mplace) => mplace.offset_with_meta(offset, mode, meta, layout, ecx)?.into(),
295Right((local, old_offset, locals_addr, _)) => {
296if true {
if !layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals should live in memory"));
}
};
};debug_assert!(layout.is_sized(), "unsized locals should live in memory");
297{
match meta {
MemPlaceMeta::None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"MemPlaceMeta::None", ::core::option::Option::None);
}
}
};assert_matches!(meta, MemPlaceMeta::None); // we couldn't store it anyway...
298 // `Place::Local` are always in-bounds of their surrounding local, so we can just
299 // check directly if this remains in-bounds. This cannot actually be violated since
300 // projections are type-checked and bounds-checked.
301if !(offset + layout.size <= self.layout.size) {
::core::panicking::panic("assertion failed: offset + layout.size <= self.layout.size")
};assert!(offset + layout.size <= self.layout.size);
302303// Size `+`, ensures no overflow.
304let new_offset = old_offset.unwrap_or(Size::ZERO) + offset;
305306PlaceTy {
307 place: Place::Local { local, offset: Some(new_offset), locals_addr },
308layout,
309 }
310 }
311 })
312 }
313314#[inline(always)]
315fn to_op<M: Machine<'tcx, Provenance = Prov>>(
316&self,
317 ecx: &InterpCx<'tcx, M>,
318 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
319ecx.place_to_op(self)
320 }
321}
322323// These are defined here because they produce a place.
324impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
325#[inline(always)]
326pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
327match self.op() {
328 Operand::Indirect(mplace) => Left(MPlaceTy { mplace: *mplace, layout: self.layout }),
329 Operand::Immediate(imm) => Right(ImmTy::from_immediate(*imm, self.layout)),
330 }
331 }
332333#[inline(always)]
334 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
335pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
336self.as_mplace_or_imm().left().unwrap_or_else(|| {
337::rustc_middle::util::bug::bug_fmt(format_args!("OpTy of type {0} was immediate when it was expected to be an MPlace",
self.layout.ty))bug!(
338"OpTy of type {} was immediate when it was expected to be an MPlace",
339self.layout.ty
340 )341 })
342 }
343}
344345/// The `Weiteable` trait describes interpreter values that can be written to.
346pub trait Writeable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
347fn to_place(&self) -> PlaceTy<'tcx, Prov>;
348349fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
350&self,
351 ecx: &mut InterpCx<'tcx, M>,
352 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>>;
353}
354355impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
356#[inline(always)]
357fn to_place(&self) -> PlaceTy<'tcx, Prov> {
358self.clone()
359 }
360361#[inline(always)]
362fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
363&self,
364 ecx: &mut InterpCx<'tcx, M>,
365 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
366ecx.force_allocation(self)
367 }
368}
369370impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
371#[inline(always)]
372fn to_place(&self) -> PlaceTy<'tcx, Prov> {
373self.clone().into()
374 }
375376#[inline(always)]
377fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
378&self,
379 _ecx: &mut InterpCx<'tcx, M>,
380 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
381interp_ok(self.clone())
382 }
383}
384385// FIXME: Working around https://github.com/rust-lang/rust/issues/54385
386impl<'tcx, Prov, M> InterpCx<'tcx, M>
387where
388Prov: Provenance,
389 M: Machine<'tcx, Provenance = Prov>,
390{
391fn ptr_with_meta_to_mplace(
392&self,
393 ptr: Pointer<Option<M::Provenance>>,
394 meta: MemPlaceMeta<M::Provenance>,
395 layout: TyAndLayout<'tcx>,
396 unaligned: bool,
397 ) -> MPlaceTy<'tcx, M::Provenance> {
398let misaligned =
399if unaligned { None } else { self.is_ptr_misaligned(ptr, layout.align.abi) };
400MPlaceTy { mplace: MemPlace { ptr, meta, misaligned }, layout }
401 }
402403pub fn ptr_to_mplace(
404&self,
405 ptr: Pointer<Option<M::Provenance>>,
406 layout: TyAndLayout<'tcx>,
407 ) -> MPlaceTy<'tcx, M::Provenance> {
408if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
409self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ false)
410 }
411412pub fn ptr_to_mplace_unaligned(
413&self,
414 ptr: Pointer<Option<M::Provenance>>,
415 layout: TyAndLayout<'tcx>,
416 ) -> MPlaceTy<'tcx, M::Provenance> {
417if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
418self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ true)
419 }
420421/// Take a value, which represents a (thin or wide) pointer, and make it a place.
422 /// Alignment is just based on the type. This is the inverse of `mplace_to_imm_ptr()`.
423 ///
424 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
425 /// want to ever use the place for memory access!
426 /// Generally prefer `deref_pointer`.
427pub fn imm_ptr_to_mplace(
428&self,
429 val: &ImmTy<'tcx, M::Provenance>,
430 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
431let pointee_type =
432val.layout.ty.builtin_deref(true).expect("`imm_ptr_to_mplace` called on non-ptr type");
433let layout = self.layout_of(pointee_type)?;
434let (ptr, meta) = val.to_scalar_and_meta();
435436// `imm_ptr_to_mplace` is called on raw pointers even if they don't actually get dereferenced;
437 // we hence can't call `size_and_align_of` since that asserts more validity than we want.
438let ptr = ptr.to_pointer(self)?;
439interp_ok(self.ptr_with_meta_to_mplace(ptr, meta, layout, /*unaligned*/ false))
440 }
441442/// Turn a mplace into a (thin or wide) mutable raw pointer, pointing to the same space.
443 ///
444 /// `align` information is lost!
445 /// This is the inverse of `imm_ptr_to_mplace`.
446 ///
447 /// If `ptr_ty` is provided, the resulting pointer will be of that type. Otherwise, it defaults to `*mut _`.
448 /// `ptr_ty` must be a type with builtin deref which derefs to the type of `mplace` (`mplace.layout.ty`).
449pub fn mplace_to_imm_ptr(
450&self,
451 mplace: &MPlaceTy<'tcx, M::Provenance>,
452 ptr_ty: Option<Ty<'tcx>>,
453 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
454let imm = mplace.mplace.to_ref(self);
455456let ptr_ty = ptr_ty457 .inspect(|t| {
match (&t.builtin_deref(true), &Some(mplace.layout.ty)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
}assert_eq!(t.builtin_deref(true), Some(mplace.layout.ty)))
458 .unwrap_or_else(|| Ty::new_mut_ptr(self.tcx.tcx, mplace.layout.ty));
459460let layout = self.layout_of(ptr_ty)?;
461interp_ok(ImmTy::from_immediate(imm, layout))
462 }
463464/// Take an operand, representing a pointer, and dereference it to a place.
465 /// Corresponds to the `*` operator in Rust.
466 /// Unlike `imm_ptr_to_mplace`, this checks that the pointer is valid for its type.
467#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("deref_pointer",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(467u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("src")
}> =
::tracing::__macro_support::FieldName::new("src");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
let ptr_ty = src.layout().ty;
if !(ptr_ty.is_ref() || ptr_ty.is_raw_ptr() ||
ptr_ty.is_box_global(*self.tcx)) {
::rustc_middle::util::bug::bug_fmt(format_args!("dereferencing {0}",
src.layout().ty));
}
let val = self.read_immediate(src)?;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:479",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(479u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deref to {0} on {1:?}",
val.layout.ty, *val) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let mplace = self.imm_ptr_to_mplace(&val)?;
if ptr_ty.is_ref() || ptr_ty.is_box() {
let kind = if ptr_ty.is_ref() { "reference" } else { "box" };
let scalar_ptr =
Scalar::from_maybe_pointer(mplace.ptr(), self);
if self.scalar_may_be_null(scalar_ptr)? {
let maybe =
!M::Provenance::OFFSET_IS_ADDR &&
#[allow(non_exhaustive_omitted_patterns)] match scalar_ptr {
Scalar::Ptr(..) => true,
_ => false,
};
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("dereferencing a {0}null {1}",
if maybe { "maybe-" } else { "" }, kind))
})));
}
let (size, align) =
self.size_and_align_of_val(&mplace)?.unwrap_or_else(||
(mplace.layout.size, mplace.layout.align.abi));
self.check_ptr_access(mplace.ptr(), size,
CheckInAllocMsg::Dereferenceable(kind))?;
self.check_ptr_align(mplace.ptr(),
align).map_err_kind(|err|
{
let ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AlignmentCheckFailed(Misalignment {
required, has }, _msg)) =
err else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("encountered an unaligned {2} (required {0} byte alignment but found {1})",
required.bytes(), has.bytes(), kind))
})))
})?;
} else {
if !ptr_ty.is_raw_ptr() {
::core::panicking::panic("assertion failed: ptr_ty.is_raw_ptr()")
};
if mplace.layout.is_unsized() {
let tail =
self.tcx.struct_tail_for_codegen(mplace.layout.ty,
self.typing_env);
match tail.kind() {
ty::Dynamic(data, _) => {
let vtable = mplace.meta().unwrap_meta().to_pointer(self)?;
self.get_ptr_vtable_ty(vtable, Some(data))?;
}
ty::Slice(..) | ty::Str | ty::Foreign(..) => {}
_ =>
::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected unsized type tail: {0:?}",
tail)),
}
}
}
interp_ok(mplace)
}
}
}#[instrument(skip(self), level = "trace")]468pub fn deref_pointer(
469&self,
470 src: &impl Projectable<'tcx, M::Provenance>,
471 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
472let ptr_ty = src.layout().ty;
473if !(ptr_ty.is_ref() || ptr_ty.is_raw_ptr() || ptr_ty.is_box_global(*self.tcx)) {
474bug!("dereferencing {}", src.layout().ty);
475 }
476477let val = self.read_immediate(src)?;
478// Construct a place for that pointer.
479trace!("deref to {} on {:?}", val.layout.ty, *val);
480let mplace = self.imm_ptr_to_mplace(&val)?;
481482// This is conceptually a typed load from `src` to get the pointer. Most of the time when
483 // we do typed loads for primitive operations, all relevant invariants are checked
484 // implicitly, e.g. when we call `to_bool()` on a Boolean.
485 // But here, we do need to specifically check for metadata validity, null, alignment, and
486 // dereferenceability, or they will not be checked anywhere at all.
487 // This duplicates some of the logic in the validity check, but so far we found no
488 // good way to share that logic.
489if ptr_ty.is_ref() || ptr_ty.is_box() {
490let kind = if ptr_ty.is_ref() { "reference" } else { "box" };
491492// Null check.
493let scalar_ptr = Scalar::from_maybe_pointer(mplace.ptr(), self);
494if self.scalar_may_be_null(scalar_ptr)? {
495let maybe = !M::Provenance::OFFSET_IS_ADDR && matches!(scalar_ptr, Scalar::Ptr(..));
496throw_ub_format!(
497"dereferencing a {maybe}null {kind}",
498 maybe = if maybe { "maybe-" } else { "" }
499 );
500 }
501502// Dereferencability and alignment check. This also implicitly checks metadata validity.
503let (size, align) = self
504.size_and_align_of_val(&mplace)?
505.unwrap_or_else(|| (mplace.layout.size, mplace.layout.align.abi));
506self.check_ptr_access(mplace.ptr(), size, CheckInAllocMsg::Dereferenceable(kind))?;
507self.check_ptr_align(mplace.ptr(), align).map_err_kind(|err| {
508let err_ub!(AlignmentCheckFailed(Misalignment { required, has }, _msg)) = err else { bug!() };
509err_ub_format!(
510"encountered an unaligned {kind} (required {required_bytes} byte alignment but found {found_bytes})",
511 required_bytes = required.bytes(),
512 found_bytes = has.bytes()
513 )
514 })?;
515 } else {
516assert!(ptr_ty.is_raw_ptr());
517// For raw pointers, the validity invariant is pretty weak, but we do require the vtable
518 // to make sense, so we do have to check that if there is one.
519if mplace.layout.is_unsized() {
520let tail = self.tcx.struct_tail_for_codegen(mplace.layout.ty, self.typing_env);
521match tail.kind() {
522 ty::Dynamic(data, _) => {
523let vtable = mplace.meta().unwrap_meta().to_pointer(self)?;
524self.get_ptr_vtable_ty(vtable, Some(data))?;
525 }
526 ty::Slice(..) | ty::Str | ty::Foreign(..) => {
527// Nothing to check (`read_immediate` already ensured initialization).
528}
529_ => bug!("Unexpected unsized type tail: {:?}", tail),
530 }
531 }
532 }
533534 interp_ok(mplace)
535 }
536537#[inline]
538pub(super) fn get_place_alloc(
539&self,
540 mplace: &MPlaceTy<'tcx, M::Provenance>,
541 ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
542 {
543let (size, _align) = self
544.size_and_align_of_val(mplace)?
545.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
546// We check alignment separately, and *after* checking everything else.
547 // If an access is both OOB and misaligned, we want to see the bounds error.
548let a = self.get_ptr_alloc(mplace.ptr(), size)?;
549self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn)?;
550interp_ok(a)
551 }
552553#[inline]
554pub(super) fn get_place_alloc_mut(
555&mut self,
556 mplace: &MPlaceTy<'tcx, M::Provenance>,
557 ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
558 {
559let (size, _align) = self
560.size_and_align_of_val(mplace)?
561.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
562// We check alignment separately, and raise that error *after* checking everything else.
563 // If an access is both OOB and misaligned, we want to see the bounds error.
564 // However we have to call `check_misalign` first to make the borrow checker happy.
565let misalign_res = self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn);
566// An error from get_ptr_alloc_mut takes precedence.
567let (a, ()) = self.get_ptr_alloc_mut(mplace.ptr(), size).and(misalign_res)?;
568interp_ok(a)
569 }
570571/// Turn a local in the current frame into a place.
572pub fn local_to_place(
573&self,
574 local: mir::Local,
575 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
576let frame = self.frame();
577let layout = self.layout_of_local(frame, local, None)?;
578let place = if layout.is_sized() {
579// We can just always use the `Local` for sized values.
580Place::Local { local, offset: None, locals_addr: frame.locals_addr() }
581 } else {
582// Other parts of the system rely on `Place::Local` never being unsized.
583match frame.locals[local].access()? {
584 Operand::Immediate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
585 Operand::Indirect(mplace) => Place::Ptr(*mplace),
586 }
587 };
588interp_ok(PlaceTy { place, layout })
589 }
590591/// Computes a place. You should only use this if you intend to write into this
592 /// place; for reading, a more efficient alternative is `eval_place_to_op`.
593#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("eval_place",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(593u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("mir_place")
}> =
::tracing::__macro_support::FieldName::new("mir_place");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mir_place)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
let _trace =
<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("step",
"rustc_const_eval::interpret::place",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(599u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("step")
}> =
::tracing::__macro_support::FieldName::new("step");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("mir_place")
}> =
::tracing::__macro_support::FieldName::new("mir_place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracing_separate_thread")
}> =
::tracing::__macro_support::FieldName::new("tracing_separate_thread");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"eval_place")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mir_place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&Empty as
&dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
});
let mut place = self.local_to_place(mir_place.local)?;
for elem in mir_place.projection.iter() {
place = self.project(&place, elem)?
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:607",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(607u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
self.dump_place(&place)) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if true {
let normalized_place_ty =
self.instantiate_from_current_frame_and_normalize_erasing_regions(mir_place.ty(&self.frame().body.local_decls,
*self.tcx).ty)?;
if !mir_assign_valid_types(*self.tcx, self.typing_env,
self.layout_of(normalized_place_ty)?, place.layout) {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("eval_place of a MIR place with type {0} produced an interpreter place with type {1}",
normalized_place_ty, place.layout.ty))
}
}
interp_ok(place)
}
}
}#[instrument(skip(self), level = "trace")]594pub fn eval_place(
595&self,
596 mir_place: mir::Place<'tcx>,
597 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
598let _trace =
599enter_trace_span!(M, step::eval_place, ?mir_place, tracing_separate_thread = Empty);
600601let mut place = self.local_to_place(mir_place.local)?;
602// Using `try_fold` turned out to be bad for performance, hence the loop.
603for elem in mir_place.projection.iter() {
604 place = self.project(&place, elem)?
605}
606607trace!("{:?}", self.dump_place(&place));
608// Sanity-check the type we ended up with.
609if cfg!(debug_assertions) {
610let normalized_place_ty = self
611.instantiate_from_current_frame_and_normalize_erasing_regions(
612 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
613 )?;
614if !mir_assign_valid_types(
615*self.tcx,
616self.typing_env,
617self.layout_of(normalized_place_ty)?,
618 place.layout,
619 ) {
620span_bug!(
621self.cur_span(),
622"eval_place of a MIR place with type {} produced an interpreter place with type {}",
623 normalized_place_ty,
624 place.layout.ty,
625 )
626 }
627 }
628 interp_ok(place)
629 }
630631/// Given a place, returns either the underlying mplace or a reference to where the value of
632 /// this place is stored.
633#[inline(always)]
634fn as_mplace_or_mutable_local(
635&mut self,
636 place: &PlaceTy<'tcx, M::Provenance>,
637 ) -> InterpResult<
638'tcx,
639Either<
640MPlaceTy<'tcx, M::Provenance>,
641 (&mut Immediate<M::Provenance>, TyAndLayout<'tcx>, mir::Local),
642 >,
643 > {
644interp_ok(match place.to_place().as_mplace_or_local() {
645Left(mplace) => Left(mplace),
646Right((local, offset, locals_addr, layout)) => {
647if offset.is_some() {
648// This has been projected to a part of this local, or had the type changed.
649 // FIXME: there are cases where we could still avoid allocating an mplace.
650Left(place.force_mplace(self)?)
651 } else {
652if true {
{
match (&locals_addr, &self.frame().locals_addr()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(locals_addr, self.frame().locals_addr());
653if true {
{
match (&self.layout_of_local(self.frame(), local, None)?, &layout) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.layout_of_local(self.frame(), local, None)?, layout);
654match self.frame_mut().locals[local].access_mut()? {
655 Operand::Indirect(mplace) => {
656// The local is in memory.
657Left(MPlaceTy { mplace: *mplace, layout })
658 }
659 Operand::Immediate(local_val) => {
660// The local still has the optimized representation.
661Right((local_val, layout, local))
662 }
663 }
664 }
665 }
666 })
667 }
668669/// Write an immediate to a place
670#[inline(always)]
671#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("write_immediate",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(671u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("src")
}> =
::tracing::__macro_support::FieldName::new("src");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dest")
}> =
::tracing::__macro_support::FieldName::new("dest");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.write_immediate_no_validate(src, dest)?;
if M::enforce_validity(self, dest.layout()) {
self.validate_place(&dest.to_place(),
M::enforce_validity_recursively(self, dest.layout()),
true)?;
}
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]672pub fn write_immediate(
673&mut self,
674 src: Immediate<M::Provenance>,
675 dest: &impl Writeable<'tcx, M::Provenance>,
676 ) -> InterpResult<'tcx> {
677self.write_immediate_no_validate(src, dest)?;
678679if M::enforce_validity(self, dest.layout()) {
680// Data got changed, better make sure it matches the type!
681 // Also needed to reset padding.
682self.validate_place(
683&dest.to_place(),
684 M::enforce_validity_recursively(self, dest.layout()),
685/*reset_provenance_and_padding*/ true,
686 )?;
687 }
688689 interp_ok(())
690 }
691692/// Write a scalar to a place
693#[inline(always)]
694pub fn write_scalar(
695&mut self,
696 val: impl Into<Scalar<M::Provenance>>,
697 dest: &impl Writeable<'tcx, M::Provenance>,
698 ) -> InterpResult<'tcx> {
699self.write_immediate(Immediate::Scalar(val.into()), dest)
700 }
701702/// Write a pointer to a place
703#[inline(always)]
704pub fn write_pointer(
705&mut self,
706 ptr: impl Into<Pointer<Option<M::Provenance>>>,
707 dest: &impl Writeable<'tcx, M::Provenance>,
708 ) -> InterpResult<'tcx> {
709self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
710 }
711712/// Write an immediate to a place.
713 /// If you use this you are responsible for validating that things got copied at the
714 /// right type.
715pub(super) fn write_immediate_no_validate(
716&mut self,
717 src: Immediate<M::Provenance>,
718 dest: &impl Writeable<'tcx, M::Provenance>,
719 ) -> InterpResult<'tcx> {
720if !dest.layout().is_sized() {
{
::core::panicking::panic_fmt(format_args!("Cannot write unsized immediate data"));
}
};assert!(dest.layout().is_sized(), "Cannot write unsized immediate data");
721722match self.as_mplace_or_mutable_local(&dest.to_place())? {
723Right((local_val, local_layout, local)) => {
724// Local can be updated in-place.
725*local_val = src;
726// Call the machine hook (the data race detector needs to know about this write).
727if !self.validation_in_progress() {
728 M::after_local_write(self, local, /*storage_live*/ false)?;
729 }
730// Double-check that the value we are storing and the local fit to each other.
731 // Things can ge wrong in quite weird ways when this is violated.
732 // Unfortunately this is too expensive to do in release builds.
733if truecfg!(debug_assertions) {
734src.assert_matches_abi(
735local_layout.backend_repr,
736"invalid immediate for given destination place",
737self,
738 );
739 }
740 }
741Left(mplace) => {
742self.write_immediate_to_mplace_no_validate(src, mplace.layout, mplace.mplace)?;
743 }
744 }
745interp_ok(())
746 }
747748/// Write an immediate to memory.
749 /// If you use this you are responsible for validating that things got copied at the
750 /// right layout.
751fn write_immediate_to_mplace_no_validate(
752&mut self,
753 value: Immediate<M::Provenance>,
754 layout: TyAndLayout<'tcx>,
755 dest: MemPlace<M::Provenance>,
756 ) -> InterpResult<'tcx> {
757// We use the sizes from `value` below.
758 // Ensure that matches the type of the place it is written to.
759value.assert_matches_abi(
760layout.backend_repr,
761"invalid immediate for given destination place",
762self,
763 );
764// Note that it is really important that the type here is the right one, and matches the
765 // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
766 // to handle padding properly, which is only correct if we never look at this data with the
767 // wrong type.
768769let will_later_validate = M::enforce_validity(self, layout);
770let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout })? else {
771// zero-sized access
772return interp_ok(());
773 };
774775match value {
776 Immediate::Scalar(scalar) => {
777 alloc.write_scalar(alloc_range(Size::ZERO, scalar.size()), scalar)?;
778 }
779 Immediate::ScalarPair(a_val, b_val) => {
780let BackendRepr::ScalarPair { a: _, b: _, b_offset } = layout.backend_repr else {
781::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("write_immediate_to_mplace: invalid ScalarPair layout: {0:#?}",
layout))span_bug!(
782self.cur_span(),
783"write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
784 layout
785 )786 };
787let a_size = a_val.size();
788let b_size = b_val.size();
789if !(b_offset.bytes() > 0) {
::core::panicking::panic("assertion failed: b_offset.bytes() > 0")
};assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
790791 // 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.
794795 // In preparation, if we do *not* later reset the padding, we clear the entire
796 // destination now to ensure that no stray pointer fragments are being
797 // preserved (see <https://github.com/rust-lang/rust/issues/148470>).
798 // We can skip this if there is no padding (e.g. for wide pointers).
799if !will_later_validate && a_size + b_size != layout.size {
800alloc.write_uninit_full();
801 }
802803 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
804 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)?;
805 }
806 Immediate::Uninit => alloc.write_uninit_full(),
807 }
808interp_ok(())
809 }
810811pub fn write_uninit(
812&mut self,
813 dest: &impl Writeable<'tcx, M::Provenance>,
814 ) -> InterpResult<'tcx> {
815match self.as_mplace_or_mutable_local(&dest.to_place())? {
816Right((local_val, _local_layout, local)) => {
817*local_val = Immediate::Uninit;
818// Call the machine hook (the data race detector needs to know about this write).
819if !self.validation_in_progress() {
820 M::after_local_write(self, local, /*storage_live*/ false)?;
821 }
822 }
823Left(mplace) => {
824let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
825// Zero-sized access
826return interp_ok(());
827 };
828alloc.write_uninit_full();
829 }
830 }
831interp_ok(())
832 }
833834/// Remove all provenance in the given place.
835pub fn clear_provenance(
836&mut self,
837 dest: &impl Writeable<'tcx, M::Provenance>,
838 ) -> InterpResult<'tcx> {
839// If this is an efficiently represented local variable without provenance, skip the
840 // `as_mplace_or_mutable_local` that would otherwise force this local into memory.
841if let Right(imm) = dest.to_op(self)?.as_mplace_or_imm() {
842if !imm.has_provenance() {
843return interp_ok(());
844 }
845 }
846match self.as_mplace_or_mutable_local(&dest.to_place())? {
847Right((local_val, _local_layout, local)) => {
848 local_val.clear_provenance()?;
849// Call the machine hook (the data race detector needs to know about this write).
850if !self.validation_in_progress() {
851 M::after_local_write(self, local, /*storage_live*/ false)?;
852 }
853 }
854Left(mplace) => {
855let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
856// Zero-sized access
857return interp_ok(());
858 };
859alloc.clear_provenance();
860 }
861 }
862interp_ok(())
863 }
864865/// Copies the data from an operand to a place.
866 /// The layouts of the `src` and `dest` may disagree.
867#[inline(always)]
868pub fn copy_op_allow_transmute(
869&mut self,
870 src: &impl Projectable<'tcx, M::Provenance>,
871 dest: &impl Writeable<'tcx, M::Provenance>,
872 ) -> InterpResult<'tcx> {
873self.copy_op_inner(src, dest, /* allow_transmute */ true)
874 }
875876/// Copies the data from an operand to a place.
877 /// `src` and `dest` must have the same layout and the copied value will be validated.
878#[inline(always)]
879pub fn copy_op(
880&mut self,
881 src: &impl Projectable<'tcx, M::Provenance>,
882 dest: &impl Writeable<'tcx, M::Provenance>,
883 ) -> InterpResult<'tcx> {
884self.copy_op_inner(src, dest, /* allow_transmute */ false)
885 }
886887/// Perform a typed copy of the data from an operand to a place.
888 ///
889 /// `allow_transmute` indicates whether the layouts may disagree. In that case there are
890 /// technically *two* typed copies: `src` is a not-yet-loaded value, so we're doing a typed copy
891 /// at `src` type from there to some intermediate storage. And then we're doing a second typed
892 /// copy at `dest` type from that intermediate storage to `dest`. As an optimization, we only
893 /// make a single direct copy here, but we still have to ensure the data is valid at both types.
894#[inline(always)]
895#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("copy_op_inner",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(895u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("src")
}> =
::tracing::__macro_support::FieldName::new("src");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dest")
}> =
::tracing::__macro_support::FieldName::new("dest");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("allow_transmute")
}> =
::tracing::__macro_support::FieldName::new("allow_transmute");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&allow_transmute
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.copy_op_no_validate(src, dest, allow_transmute)?;
if M::enforce_validity(self, dest.layout()) {
let dest = dest.to_place();
if src.layout().ty != dest.layout().ty {
self.validate_place(&dest.transmute(src.layout(), self)?,
M::enforce_validity_recursively(self, src.layout()), true)?;
}
self.validate_place(&dest,
M::enforce_validity_recursively(self, dest.layout()),
true)?;
}
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]896fn copy_op_inner(
897&mut self,
898 src: &impl Projectable<'tcx, M::Provenance>,
899 dest: &impl Writeable<'tcx, M::Provenance>,
900 allow_transmute: bool,
901 ) -> InterpResult<'tcx> {
902// Do the actual copy.
903self.copy_op_no_validate(src, dest, allow_transmute)?;
904905if M::enforce_validity(self, dest.layout()) {
906let dest = dest.to_place();
907// Given that there were two typed copies, we have to ensure this is valid at both
908 // types, and we have to ensure this loses provenance and padding according to both
909 // types. We also transmute both ways: when transmuting `*ptr` from `&T` to `*const T`,
910 // it seems nice to ensure that the resulting pointer value indeed is derived from a
911 // shared reference.
912 // But if the types are identical, that is strictly redundant so we only do one pass.
913if src.layout().ty != dest.layout().ty {
914self.validate_place(
915&dest.transmute(src.layout(), self)?,
916 M::enforce_validity_recursively(self, src.layout()),
917/*reset_provenance_and_padding*/ true,
918 )?;
919 }
920self.validate_place(
921&dest,
922 M::enforce_validity_recursively(self, dest.layout()),
923/*reset_provenance_and_padding*/ true,
924 )?;
925 }
926927 interp_ok(())
928 }
929930/// Perform an untyped copy of the data from an operand to a place.
931 /// You are responsible for validating that things get copied at the right type.
932 ///
933 /// `allow_transmute` indicates whether the layouts may disagree.
934#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("copy_op_no_validate",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(934u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("src")
}> =
::tracing::__macro_support::FieldName::new("src");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dest")
}> =
::tracing::__macro_support::FieldName::new("dest");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("allow_transmute")
}> =
::tracing::__macro_support::FieldName::new("allow_transmute");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&allow_transmute
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let layout_compat =
mir_assign_valid_types(*self.tcx, self.typing_env,
src.layout(), dest.layout());
if !allow_transmute && !layout_compat {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("type mismatch when copying!\nsrc: {0},\ndest: {1}",
src.layout().ty, dest.layout().ty));
}
let src_has_padding =
match src.layout().backend_repr {
BackendRepr::Scalar(_) => false,
BackendRepr::ScalarPair { a: left, b: right, b_offset: _ }
if
#[allow(non_exhaustive_omitted_patterns)] match src.layout().ty.kind()
{
ty::Ref(..) | ty::RawPtr(..) => true,
_ => false,
} => {
if true {
{
match (&(left.size(self) + right.size(self)),
&src.layout().size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
false
}
BackendRepr::ScalarPair { a: left, b: right, b_offset: _ }
=> {
let left_size = left.size(self);
let right_size = right.size(self);
left_size + right_size != src.layout().size
}
BackendRepr::SimdVector { .. } |
BackendRepr::SimdScalableVector { .. } |
BackendRepr::Memory { .. } => true,
};
let src_val =
if src_has_padding {
src.to_op(self)?.as_mplace_or_imm()
} else { self.read_immediate_raw(src)? };
let src =
match src_val {
Right(src_val) => {
if !!src.layout().is_unsized() {
::core::panicking::panic("assertion failed: !src.layout().is_unsized()")
};
if !!dest.layout().is_unsized() {
::core::panicking::panic("assertion failed: !dest.layout().is_unsized()")
};
{
match (&src.layout().size, &dest.layout().size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
return if layout_compat {
self.write_immediate_no_validate(*src_val, dest)
} else {
let dest_mem = dest.force_mplace(self)?;
self.write_immediate_to_mplace_no_validate(*src_val,
src.layout(), dest_mem.mplace)
};
}
Left(mplace) => mplace,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:1010",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(1010u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copy_op: {0:?} <- {1:?}: {2}",
*dest, src, dest.layout().ty) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
let dest = dest.force_mplace(self)?;
let Some((dest_size, _)) =
self.size_and_align_of_val(&dest)? else {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("copy_op needs (dynamically) sized values"))
};
if true {
let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
{
match (&src_size, &dest_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Cannot copy differently-sized data")));
}
}
}
};
} else {
{
match (&src.layout.size, &dest.layout.size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
}
self.mem_copy(src.ptr(), dest.ptr(), dest_size, true)?;
self.check_misalign(src.mplace.misaligned,
CheckAlignMsg::BasedOn)?;
self.check_misalign(dest.mplace.misaligned,
CheckAlignMsg::BasedOn)?;
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]935pub(super) fn copy_op_no_validate(
936&mut self,
937 src: &impl Projectable<'tcx, M::Provenance>,
938 dest: &impl Writeable<'tcx, M::Provenance>,
939 allow_transmute: bool,
940 ) -> InterpResult<'tcx> {
941// We do NOT compare the types for equality, because well-typed code can
942 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
943let layout_compat =
944 mir_assign_valid_types(*self.tcx, self.typing_env, src.layout(), dest.layout());
945if !allow_transmute && !layout_compat {
946span_bug!(
947self.cur_span(),
948"type mismatch when copying!\nsrc: {},\ndest: {}",
949 src.layout().ty,
950 dest.layout().ty,
951 );
952 }
953// If the source has padding, we want to always do a mem-to-mem copy to ensure consistent
954 // padding in the target independent of layout choices.
955let src_has_padding = match src.layout().backend_repr {
956 BackendRepr::Scalar(_) => false,
957 BackendRepr::ScalarPair { a: left, b: right, b_offset: _ }
958if matches!(src.layout().ty.kind(), ty::Ref(..) | ty::RawPtr(..)) =>
959 {
960// Wide pointers never have padding, so we can avoid calling `size()`.
961debug_assert_eq!(left.size(self) + right.size(self), src.layout().size);
962false
963}
964 BackendRepr::ScalarPair { a: left, b: right, b_offset: _ } => {
965let left_size = left.size(self);
966let right_size = right.size(self);
967// We have padding if the sizes don't add up to the total.
968 // (Why don't we need to check the offset? The scalars don't overlap so no padding
969 // implies `b_offset == left_size`, which would be superfluous to check explicitly.)
970left_size + right_size != src.layout().size
971 }
972// Everything else can only exist in memory anyway, so it doesn't matter.
973BackendRepr::SimdVector { .. }
974 | BackendRepr::SimdScalableVector { .. }
975 | BackendRepr::Memory { .. } => true,
976 };
977978let src_val = if src_has_padding {
979// Do our best to get an mplace. If there's no mplace, then this is stored as an
980 // "optimized" local, so its padding is definitely uninitialized and we are fine.
981src.to_op(self)?.as_mplace_or_imm()
982 } else {
983// Do our best to get an immediate, to avoid having to force_allocate the destination.
984self.read_immediate_raw(src)?
985};
986let src = match src_val {
987 Right(src_val) => {
988assert!(!src.layout().is_unsized());
989assert!(!dest.layout().is_unsized());
990assert_eq!(src.layout().size, dest.layout().size);
991// Yay, we got a value that we can write directly.
992return if layout_compat {
993self.write_immediate_no_validate(*src_val, dest)
994 } else {
995// This is tricky. The problematic case is `ScalarPair`: the `src_val` was
996 // loaded using the offsets defined by `src.layout`. When we put this back into
997 // the destination, we have to use the same offsets! So (a) we make sure we
998 // write back to memory, and (b) we use `dest` *with the source layout*.
999let dest_mem = dest.force_mplace(self)?;
1000self.write_immediate_to_mplace_no_validate(
1001*src_val,
1002 src.layout(),
1003 dest_mem.mplace,
1004 )
1005 };
1006 }
1007 Left(mplace) => mplace,
1008 };
1009// Slow path, this does not fit into an immediate. Just memcpy.
1010trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout().ty);
10111012let dest = dest.force_mplace(self)?;
1013let Some((dest_size, _)) = self.size_and_align_of_val(&dest)? else {
1014span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
1015 };
1016if cfg!(debug_assertions) {
1017let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
1018assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
1019 } else {
1020// As a cheap approximation, we compare the fixed parts of the size.
1021assert_eq!(src.layout.size, dest.layout.size);
1022 }
10231024// Setting `nonoverlapping` here only has an effect when we don't hit the fast-path above,
1025 // but that should at least match what LLVM does where `memcpy` is also only used when the
1026 // type does not have Scalar/ScalarPair layout.
1027 // (Or as the `Assign` docs put it, assignments "not producing primitives" must be
1028 // non-overlapping.)
1029 // We check alignment separately, and *after* checking everything else.
1030 // If an access is both OOB and misaligned, we want to see the bounds error.
1031self.mem_copy(src.ptr(), dest.ptr(), dest_size, /*nonoverlapping*/ true)?;
1032self.check_misalign(src.mplace.misaligned, CheckAlignMsg::BasedOn)?;
1033self.check_misalign(dest.mplace.misaligned, CheckAlignMsg::BasedOn)?;
1034 interp_ok(())
1035 }
10361037/// Ensures that a place is in memory, and returns where it is.
1038 /// If the place currently refers to a local that doesn't yet have a matching allocation,
1039 /// create such an allocation.
1040 /// This is essentially `force_to_memplace`.
1041#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("force_allocation",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(1041u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
let mplace =
match place.place {
Place::Local { local, offset, locals_addr } => {
if true {
{
match (&locals_addr, &self.frame().locals_addr()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let whole_local =
match self.frame_mut().locals[local].access_mut()? {
&mut Operand::Immediate(local_val) => {
let local_layout =
self.layout_of_local(&self.frame(), local, None)?;
if !local_layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals cannot be immediate"));
}
};
let mplace =
self.allocate(local_layout, MemoryKind::Stack)?;
if !#[allow(non_exhaustive_omitted_patterns)] match local_val
{
Immediate::Uninit => true,
_ => false,
} {
self.write_immediate_to_mplace_no_validate(local_val,
local_layout, mplace.mplace)?;
}
M::after_local_moved_to_memory(self, local, &mplace)?;
*self.frame_mut().locals[local].access_mut().unwrap() =
Operand::Indirect(mplace.mplace);
mplace.mplace
}
&mut Operand::Indirect(mplace) => mplace,
};
if let Some(offset) = offset {
whole_local.offset_with_meta_(offset, OffsetMode::Wrapping,
MemPlaceMeta::None, self)?
} else { whole_local }
}
Place::Ptr(mplace) => mplace,
};
interp_ok(MPlaceTy { mplace, layout: place.layout })
}
}
}#[instrument(skip(self), level = "trace")]1042pub fn force_allocation(
1043&mut self,
1044 place: &PlaceTy<'tcx, M::Provenance>,
1045 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1046let mplace = match place.place {
1047 Place::Local { local, offset, locals_addr } => {
1048debug_assert_eq!(locals_addr, self.frame().locals_addr());
1049let whole_local = match self.frame_mut().locals[local].access_mut()? {
1050&mut Operand::Immediate(local_val) => {
1051// We need to make an allocation.
10521053 // We need the layout of the local. We can NOT use the layout we got,
1054 // that might e.g., be an inner field of a struct with `Scalar` layout,
1055 // that has different alignment than the outer field.
1056let local_layout = self.layout_of_local(&self.frame(), local, None)?;
1057assert!(local_layout.is_sized(), "unsized locals cannot be immediate");
1058let mplace = self.allocate(local_layout, MemoryKind::Stack)?;
1059// Preserve old value. (As an optimization, we can skip this if it was uninit.)
1060if !matches!(local_val, Immediate::Uninit) {
1061// We don't have to validate as we can assume the local was already
1062 // valid for its type. We must not use any part of `place` here, that
1063 // could be a projection to a part of the local!
1064self.write_immediate_to_mplace_no_validate(
1065 local_val,
1066 local_layout,
1067 mplace.mplace,
1068 )?;
1069 }
1070 M::after_local_moved_to_memory(self, local, &mplace)?;
1071// Now we can call `access_mut` again, asserting it goes well, and actually
1072 // overwrite things. This points to the entire allocation, not just the part
1073 // the place refers to, i.e. we do this before we apply `offset`.
1074*self.frame_mut().locals[local].access_mut().unwrap() =
1075 Operand::Indirect(mplace.mplace);
1076 mplace.mplace
1077 }
1078&mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
1079};
1080if let Some(offset) = offset {
1081// This offset is always inbounds, no need to check it again.
1082whole_local.offset_with_meta_(
1083 offset,
1084 OffsetMode::Wrapping,
1085 MemPlaceMeta::None,
1086self,
1087 )?
1088} else {
1089// Preserve wide place metadata, do not call `offset`.
1090whole_local
1091 }
1092 }
1093 Place::Ptr(mplace) => mplace,
1094 };
1095// Return with the original layout and align, so that the caller can go on
1096interp_ok(MPlaceTy { mplace, layout: place.layout })
1097 }
10981099pub fn allocate_dyn(
1100&mut self,
1101 layout: TyAndLayout<'tcx>,
1102 kind: MemoryKind<M::MemoryKind>,
1103 meta: MemPlaceMeta<M::Provenance>,
1104 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1105let Some((size, align)) = self.size_and_align_from_meta(&meta, &layout)? else {
1106::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("cannot allocate space for `extern` type, size is not known"))span_bug!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")1107 };
1108let ptr = self.allocate_ptr(size, align, kind, AllocInit::Uninit)?;
1109interp_ok(self.ptr_with_meta_to_mplace(ptr.into(), meta, layout, /*unaligned*/ false))
1110 }
11111112pub fn allocate(
1113&mut self,
1114 layout: TyAndLayout<'tcx>,
1115 kind: MemoryKind<M::MemoryKind>,
1116 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1117if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1118self.allocate_dyn(layout, kind, MemPlaceMeta::None)
1119 }
11201121/// Allocates a sequence of bytes in the interpreter's memory with alignment 1.
1122 /// This is allocated in immutable global memory and deduplicated.
1123pub fn allocate_bytes_dedup(
1124&mut self,
1125 bytes: &[u8],
1126 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
1127let salt = M::get_global_alloc_salt(self, None);
1128let id = self.tcx.allocate_bytes_dedup(bytes, salt);
11291130// Turn untagged "global" pointers (obtained via `tcx`) into the machine pointer to the allocation.
1131M::adjust_alloc_root_pointer(
1132&self,
1133Pointer::from(id),
1134 M::GLOBAL_KIND.map(MemoryKind::Machine),
1135 )
1136 }
11371138/// Allocates a string in the interpreter's memory, returning it as a (wide) place.
1139 /// This is allocated in immutable global memory and deduplicated.
1140pub fn allocate_str_dedup(
1141&mut self,
1142 s: &str,
1143 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1144let bytes = s.as_bytes();
1145let ptr = self.allocate_bytes_dedup(bytes)?;
11461147// Create length metadata for the string.
1148let meta = Scalar::from_target_usize(u64::try_from(bytes.len()).unwrap(), self);
11491150// Get layout for Rust's str type.
1151let layout = self.layout_of(self.tcx.types.str_).unwrap();
11521153// Combine pointer and metadata into a wide pointer.
1154interp_ok(self.ptr_with_meta_to_mplace(
1155ptr.into(),
1156 MemPlaceMeta::Meta(meta),
1157layout,
1158/*unaligned*/ false,
1159 ))
1160 }
11611162pub fn raw_const_to_mplace(
1163&self,
1164 raw: mir::ConstAlloc<'tcx>,
1165 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1166// This must be an allocation in `tcx`
1167let _ = self.tcx.global_alloc(raw.alloc_id);
1168let ptr = self.global_root_pointer(Pointer::from(raw.alloc_id))?;
1169let layout = self.layout_of(raw.ty)?;
1170interp_ok(self.ptr_to_mplace(ptr.into(), layout))
1171 }
1172}
11731174// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1175#[cfg(target_pointer_width = "64")]
1176mod size_asserts {
1177use rustc_data_structures::static_assert_size;
11781179use super::*;
1180// tidy-alphabetical-start
1181const _: [(); 64] = [(); ::std::mem::size_of::<MPlaceTy<'_>>()];static_assert_size!(MPlaceTy<'_>, 64);
1182const _: [(); 48] = [(); ::std::mem::size_of::<MemPlace>()];static_assert_size!(MemPlace, 48);
1183const _: [(); 24] = [(); ::std::mem::size_of::<MemPlaceMeta>()];static_assert_size!(MemPlaceMeta, 24);
1184const _: [(); 48] = [(); ::std::mem::size_of::<Place>()];static_assert_size!(Place, 48);
1185const _: [(); 64] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];static_assert_size!(PlaceTy<'_>, 64);
1186// tidy-alphabetical-end
1187}