Skip to main content

rustc_const_eval/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
5use std::assert_matches;
6
7use 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};
14
15use super::{
16    AllocInit, AllocRef, AllocRefMut, CheckAlignMsg, CheckInAllocMsg, CtfeProvenance, ImmTy,
17    Immediate, InterpCx, InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy,
18    Operand, Pointer, Projectable, Provenance, Scalar, alloc_range, err_ub, err_ub_format,
19    interp_ok, mir_assign_valid_types, throw_ub_format,
20};
21use crate::enter_trace_span;
22
23#[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).
27    Meta(Scalar<Prov>),
28    /// `Sized` types or unsized `extern type`
29    None,
30}
31
32impl<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                ::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    }
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(#[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.
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    /// Stores whether this place was created based on a sufficiently aligned pointer.
61    misaligned: Option<Misalignment>,
62}
63
64impl<Prov: Provenance> MemPlace<Prov> {
65    /// Adjust the provenance of the main pointer (metadata is unaffected).
66    fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
67        MemPlace { ptr: self.ptr.map_provenance(|p| p.map(f)), ..self }
68    }
69
70    /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
71    #[inline]
72    fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
73        Immediate::new_pointer_with_meta(self.ptr, self.meta, cx)
74    }
75
76    #[inline]
77    // Not called `offset_with_meta` to avoid confusion with the trait method.
78    fn offset_with_meta_<'tcx, M: Machine<'tcx, Provenance = Prov>>(
79        self,
80        offset: Size,
81        mode: OffsetMode,
82        meta: MemPlaceMeta<Prov>,
83        ecx: &InterpCx<'tcx, M>,
84    ) -> InterpResult<'tcx, Self> {
85        if 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        );
89        let 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        };
95        interp_ok(MemPlace { ptr, meta, misaligned: self.misaligned })
96    }
97}
98
99/// 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>,
103    pub layout: TyAndLayout<'tcx>,
104}
105
106impl<Prov: Provenance> std::fmt::Debug for MPlaceTy<'_, Prov> {
107    fn 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.
109        f.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}
115
116impl<'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]
121    pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
122        if !layout.is_zst() {
    ::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
123        let align = layout.align.abi;
124        let ptr = Pointer::without_provenance(align.bytes()); // no provenance, absolute address
125        MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None, misaligned: None }, layout }
126    }
127
128    /// Adjust the provenance of the main pointer (metadata is unaffected).
129    pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
130        MPlaceTy { mplace: self.mplace.map_provenance(f), ..self }
131    }
132
133    #[inline(always)]
134    pub(super) fn mplace(&self) -> &MemPlace<Prov> {
135        &self.mplace
136    }
137
138    #[inline(always)]
139    pub fn ptr(&self) -> Pointer<Option<Prov>> {
140        self.mplace.ptr
141    }
142
143    #[inline(always)]
144    pub fn to_ref(&self, cx: &impl HasDataLayout) -> Immediate<Prov> {
145        self.mplace.to_ref(cx)
146    }
147}
148
149impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
150    #[inline(always)]
151    fn layout(&self) -> TyAndLayout<'tcx> {
152        self.layout
153    }
154
155    #[inline(always)]
156    fn meta(&self) -> MemPlaceMeta<Prov> {
157        self.mplace.meta
158    }
159
160    fn 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> {
168        interp_ok(MPlaceTy {
169            mplace: self.mplace.offset_with_meta_(offset, mode, meta, ecx)?,
170            layout,
171        })
172    }
173
174    #[inline(always)]
175    fn to_op<M: Machine<'tcx, Provenance = Prov>>(
176        &self,
177        _ecx: &InterpCx<'tcx, M>,
178    ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
179        interp_ok(self.clone().into())
180    }
181}
182
183#[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.
186    Ptr(MemPlace<Prov>),
187
188    /// 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.
199    Local { local: mir::Local, offset: Option<Size>, locals_addr: usize },
200}
201
202/// 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.
211    pub layout: TyAndLayout<'tcx>,
212}
213
214impl<Prov: Provenance> std::fmt::Debug for PlaceTy<'_, Prov> {
215    fn 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.
217        f.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}
223
224impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
225    #[inline(always)]
226    fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
227        PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
228    }
229}
230
231impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
232    #[inline(always)]
233    pub(super) fn place(&self) -> &Place<Prov> {
234        &self.place
235    }
236
237    /// 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)]
245    pub fn as_mplace_or_local(
246        &self,
247    ) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)> {
248        match self.place {
249            Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout }),
250            Place::Local { local, offset, locals_addr } => {
251                Right((local, offset, locals_addr, self.layout))
252            }
253        }
254    }
255
256    #[inline(always)]
257    #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
258    pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
259        self.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",
262                self.layout.ty
263            )
264        })
265    }
266}
267
268impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
269    #[inline(always)]
270    fn layout(&self) -> TyAndLayout<'tcx> {
271        self.layout
272    }
273
274    #[inline]
275    fn meta(&self) -> MemPlaceMeta<Prov> {
276        match self.as_mplace_or_local() {
277            Left(mplace) => mplace.meta(),
278            Right(_) => {
279                if 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::None
281            }
282        }
283    }
284
285    fn 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> {
293        interp_ok(match self.as_mplace_or_local() {
294            Left(mplace) => mplace.offset_with_meta(offset, mode, meta, layout, ecx)?.into(),
295            Right((local, old_offset, locals_addr, _)) => {
296                if 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.
301                if !(offset + layout.size <= self.layout.size) {
    ::core::panicking::panic("assertion failed: offset + layout.size <= self.layout.size")
};assert!(offset + layout.size <= self.layout.size);
302
303                // Size `+`, ensures no overflow.
304                let new_offset = old_offset.unwrap_or(Size::ZERO) + offset;
305
306                PlaceTy {
307                    place: Place::Local { local, offset: Some(new_offset), locals_addr },
308                    layout,
309                }
310            }
311        })
312    }
313
314    #[inline(always)]
315    fn to_op<M: Machine<'tcx, Provenance = Prov>>(
316        &self,
317        ecx: &InterpCx<'tcx, M>,
318    ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
319        ecx.place_to_op(self)
320    }
321}
322
323// These are defined here because they produce a place.
324impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
325    #[inline(always)]
326    pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
327        match 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    }
332
333    #[inline(always)]
334    #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
335    pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
336        self.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",
339                self.layout.ty
340            )
341        })
342    }
343}
344
345/// The `Weiteable` trait describes interpreter values that can be written to.
346pub trait Writeable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
347    fn to_place(&self) -> PlaceTy<'tcx, Prov>;
348
349    fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
350        &self,
351        ecx: &mut InterpCx<'tcx, M>,
352    ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>>;
353}
354
355impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
356    #[inline(always)]
357    fn to_place(&self) -> PlaceTy<'tcx, Prov> {
358        self.clone()
359    }
360
361    #[inline(always)]
362    fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
363        &self,
364        ecx: &mut InterpCx<'tcx, M>,
365    ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
366        ecx.force_allocation(self)
367    }
368}
369
370impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
371    #[inline(always)]
372    fn to_place(&self) -> PlaceTy<'tcx, Prov> {
373        self.clone().into()
374    }
375
376    #[inline(always)]
377    fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
378        &self,
379        _ecx: &mut InterpCx<'tcx, M>,
380    ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
381        interp_ok(self.clone())
382    }
383}
384
385// FIXME: Working around https://github.com/rust-lang/rust/issues/54385
386impl<'tcx, Prov, M> InterpCx<'tcx, M>
387where
388    Prov: Provenance,
389    M: Machine<'tcx, Provenance = Prov>,
390{
391    fn 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> {
398        let misaligned =
399            if unaligned { None } else { self.is_ptr_misaligned(ptr, layout.align.abi) };
400        MPlaceTy { mplace: MemPlace { ptr, meta, misaligned }, layout }
401    }
402
403    pub fn ptr_to_mplace(
404        &self,
405        ptr: Pointer<Option<M::Provenance>>,
406        layout: TyAndLayout<'tcx>,
407    ) -> MPlaceTy<'tcx, M::Provenance> {
408        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
409        self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ false)
410    }
411
412    pub fn ptr_to_mplace_unaligned(
413        &self,
414        ptr: Pointer<Option<M::Provenance>>,
415        layout: TyAndLayout<'tcx>,
416    ) -> MPlaceTy<'tcx, M::Provenance> {
417        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
418        self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ true)
419    }
420
421    /// 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`.
427    pub fn imm_ptr_to_mplace(
428        &self,
429        val: &ImmTy<'tcx, M::Provenance>,
430    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
431        let pointee_type =
432            val.layout.ty.builtin_deref(true).expect("`imm_ptr_to_mplace` called on non-ptr type");
433        let layout = self.layout_of(pointee_type)?;
434        let (ptr, meta) = val.to_scalar_and_meta();
435
436        // `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.
438        let ptr = ptr.to_pointer(self)?;
439        interp_ok(self.ptr_with_meta_to_mplace(ptr, meta, layout, /*unaligned*/ false))
440    }
441
442    /// 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`).
449    pub 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>> {
454        let imm = mplace.mplace.to_ref(self);
455
456        let ptr_ty = ptr_ty
457            .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));
459
460        let layout = self.layout_of(ptr_ty)?;
461        interp_ok(ImmTy::from_immediate(imm, layout))
462    }
463
464    /// 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 M::enforce_validity(self, val.layout) {
                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")]
468    pub fn deref_pointer(
469        &self,
470        src: &impl Projectable<'tcx, M::Provenance>,
471    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
472        let ptr_ty = src.layout().ty;
473        if !(ptr_ty.is_ref() || ptr_ty.is_raw_ptr() || ptr_ty.is_box_global(*self.tcx)) {
474            bug!("dereferencing {}", src.layout().ty);
475        }
476
477        let val = self.read_immediate(src)?;
478        // Construct a place for that pointer.
479        trace!("deref to {} on {:?}", val.layout.ty, *val);
480        let mplace = self.imm_ptr_to_mplace(&val)?;
481
482        if M::enforce_validity(self, val.layout) {
483            // This is conceptually a typed load from `src` to get the pointer. Most of the time when
484            // we do typed loads for primitive operations, all relevant invariants are checked
485            // implicitly, e.g. when we call `to_bool()` on a Boolean.
486            // But here, we do need to specifically check for metadata validity, null, alignment, and
487            // dereferenceability, or they will not be checked anywhere at all.
488            // This duplicates some of the logic in the validity check, but so far we found no
489            // good way to share that logic.
490            if ptr_ty.is_ref() || ptr_ty.is_box() {
491                let kind = if ptr_ty.is_ref() { "reference" } else { "box" };
492
493                // Null check.
494                let scalar_ptr = Scalar::from_maybe_pointer(mplace.ptr(), self);
495                if self.scalar_may_be_null(scalar_ptr)? {
496                    let maybe =
497                        !M::Provenance::OFFSET_IS_ADDR && matches!(scalar_ptr, Scalar::Ptr(..));
498                    throw_ub_format!(
499                        "dereferencing a {maybe}null {kind}",
500                        maybe = if maybe { "maybe-" } else { "" }
501                    );
502                }
503
504                // Dereferencability and alignment check. This also implicitly checks metadata validity.
505                let (size, align) = self
506                    .size_and_align_of_val(&mplace)?
507                    .unwrap_or_else(|| (mplace.layout.size, mplace.layout.align.abi));
508                self.check_ptr_access(mplace.ptr(), size, CheckInAllocMsg::Dereferenceable(kind))?;
509                self.check_ptr_align(mplace.ptr(), align).map_err_kind(|err| {
510                let err_ub!(AlignmentCheckFailed(Misalignment { required, has }, _msg)) = err else { bug!() };
511                err_ub_format!(
512                    "encountered an unaligned {kind} (required {required_bytes} byte alignment but found {found_bytes})",
513                    required_bytes = required.bytes(),
514                    found_bytes = has.bytes()
515                )
516            })?;
517            } else {
518                assert!(ptr_ty.is_raw_ptr());
519                // For raw pointers, the validity invariant is pretty weak, but we do require the vtable
520                // to make sense, so we do have to check that if there is one.
521                if mplace.layout.is_unsized() {
522                    let tail = self.tcx.struct_tail_for_codegen(mplace.layout.ty, self.typing_env);
523                    match tail.kind() {
524                        ty::Dynamic(data, _) => {
525                            let vtable = mplace.meta().unwrap_meta().to_pointer(self)?;
526                            self.get_ptr_vtable_ty(vtable, Some(data))?;
527                        }
528                        ty::Slice(..) | ty::Str | ty::Foreign(..) => {
529                            // Nothing to check (`read_immediate` already ensured initialization).
530                        }
531                        _ => bug!("Unexpected unsized type tail: {:?}", tail),
532                    }
533                }
534            }
535        }
536
537        interp_ok(mplace)
538    }
539
540    #[inline]
541    pub(super) fn get_place_alloc(
542        &self,
543        mplace: &MPlaceTy<'tcx, M::Provenance>,
544    ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
545    {
546        let (size, _align) = self
547            .size_and_align_of_val(mplace)?
548            .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
549        // We check alignment separately, and *after* checking everything else.
550        // If an access is both OOB and misaligned, we want to see the bounds error.
551        let a = self.get_ptr_alloc(mplace.ptr(), size)?;
552        self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn)?;
553        interp_ok(a)
554    }
555
556    #[inline]
557    pub(super) fn get_place_alloc_mut(
558        &mut self,
559        mplace: &MPlaceTy<'tcx, M::Provenance>,
560    ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
561    {
562        let (size, _align) = self
563            .size_and_align_of_val(mplace)?
564            .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
565        // We check alignment separately, and raise that error *after* checking everything else.
566        // If an access is both OOB and misaligned, we want to see the bounds error.
567        // However we have to call `check_misalign` first to make the borrow checker happy.
568        let misalign_res = self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn);
569        // An error from get_ptr_alloc_mut takes precedence.
570        let (a, ()) = self.get_ptr_alloc_mut(mplace.ptr(), size).and(misalign_res)?;
571        interp_ok(a)
572    }
573
574    /// Turn a local in the current frame into a place.
575    pub fn local_to_place(
576        &self,
577        local: mir::Local,
578    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
579        let frame = self.frame();
580        let layout = self.layout_of_local(frame, local, None)?;
581        let place = if layout.is_sized() {
582            // We can just always use the `Local` for sized values.
583            Place::Local { local, offset: None, locals_addr: frame.locals_addr() }
584        } else {
585            // Other parts of the system rely on `Place::Local` never being unsized.
586            match frame.locals[local].access()? {
587                Operand::Immediate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
588                Operand::Indirect(mplace) => Place::Ptr(*mplace),
589            }
590        };
591        interp_ok(PlaceTy { place, layout })
592    }
593
594    /// Computes a place. You should only use this if you intend to write into this
595    /// place; for reading, a more efficient alternative is `eval_place_to_op`.
596    ///
597    /// If `skip_validity_for_simple_deref` is true, then we do not check validity of the inner
598    /// pointer for places of the form `*ptr`. The caller must justify why that is okay.
599    #[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(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("mir_place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mir_place");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("skip_validity_for_simple_deref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("skip_validity_for_simple_deref");
                                                        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)),
                                                (::tracing::__macro_support::Option::Some(&skip_validity_for_simple_deref
                                                            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(606u32),
                                                ::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)?;
            if skip_validity_for_simple_deref &&
                    mir_place.projection.as_slice() ==
                        &[mir::ProjectionElem::Deref] {
                let val = self.read_immediate(&place)?;
                let place = self.imm_ptr_to_mplace(&val)?;
                return interp_ok(place.into());
            }
            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:622",
                                    "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(622u32),
                                    ::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")]
600    pub fn eval_place(
601        &self,
602        mir_place: mir::Place<'tcx>,
603        skip_validity_for_simple_deref: bool,
604    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
605        let _trace =
606            enter_trace_span!(M, step::eval_place, ?mir_place, tracing_separate_thread = Empty);
607
608        let mut place = self.local_to_place(mir_place.local)?;
609        if skip_validity_for_simple_deref
610            && mir_place.projection.as_slice() == &[mir::ProjectionElem::Deref]
611        {
612            // We want to skip the checks in `deref_pointer`.
613            let val = self.read_immediate(&place)?;
614            let place = self.imm_ptr_to_mplace(&val)?;
615            return interp_ok(place.into());
616        }
617        // Using `try_fold` turned out to be bad for performance, hence the loop.
618        for elem in mir_place.projection.iter() {
619            place = self.project(&place, elem)?
620        }
621
622        trace!("{:?}", self.dump_place(&place));
623        // Sanity-check the type we ended up with.
624        if cfg!(debug_assertions) {
625            let normalized_place_ty = self
626                .instantiate_from_current_frame_and_normalize_erasing_regions(
627                    mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
628                )?;
629            if !mir_assign_valid_types(
630                *self.tcx,
631                self.typing_env,
632                self.layout_of(normalized_place_ty)?,
633                place.layout,
634            ) {
635                span_bug!(
636                    self.cur_span(),
637                    "eval_place of a MIR place with type {} produced an interpreter place with type {}",
638                    normalized_place_ty,
639                    place.layout.ty,
640                )
641            }
642        }
643        interp_ok(place)
644    }
645
646    /// Given a place, returns either the underlying mplace or a reference to where the value of
647    /// this place is stored.
648    #[inline(always)]
649    fn as_mplace_or_mutable_local(
650        &mut self,
651        place: &PlaceTy<'tcx, M::Provenance>,
652    ) -> InterpResult<
653        'tcx,
654        Either<
655            MPlaceTy<'tcx, M::Provenance>,
656            (&mut Immediate<M::Provenance>, TyAndLayout<'tcx>, mir::Local),
657        >,
658    > {
659        interp_ok(match place.to_place().as_mplace_or_local() {
660            Left(mplace) => Left(mplace),
661            Right((local, offset, locals_addr, layout)) => {
662                if offset.is_some() {
663                    // This has been projected to a part of this local, or had the type changed.
664                    // FIXME: there are cases where we could still avoid allocating an mplace.
665                    Left(place.force_mplace(self)?)
666                } else {
667                    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);
                }
            }
        }
    };
};debug_assert_eq!(locals_addr, self.frame().locals_addr());
668                    if 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);
669                    match self.frame_mut().locals[local].access_mut()? {
670                        Operand::Indirect(mplace) => {
671                            // The local is in memory.
672                            Left(MPlaceTy { mplace: *mplace, layout })
673                        }
674                        Operand::Immediate(local_val) => {
675                            // The local still has the optimized representation.
676                            Right((local_val, layout, local))
677                        }
678                    }
679                }
680            }
681        })
682    }
683
684    /// Write an immediate to a place
685    #[inline(always)]
686    #[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(686u32),
                                    ::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")]
687    pub fn write_immediate(
688        &mut self,
689        src: Immediate<M::Provenance>,
690        dest: &impl Writeable<'tcx, M::Provenance>,
691    ) -> InterpResult<'tcx> {
692        self.write_immediate_no_validate(src, dest)?;
693
694        if M::enforce_validity(self, dest.layout()) {
695            // Data got changed, better make sure it matches the type!
696            // Also needed to reset padding.
697            self.validate_place(
698                &dest.to_place(),
699                M::enforce_validity_recursively(self, dest.layout()),
700                /*reset_provenance_and_padding*/ true,
701            )?;
702        }
703
704        interp_ok(())
705    }
706
707    /// Write a scalar to a place
708    #[inline(always)]
709    pub fn write_scalar(
710        &mut self,
711        val: impl Into<Scalar<M::Provenance>>,
712        dest: &impl Writeable<'tcx, M::Provenance>,
713    ) -> InterpResult<'tcx> {
714        self.write_immediate(Immediate::Scalar(val.into()), dest)
715    }
716
717    /// Write a pointer to a place
718    #[inline(always)]
719    pub fn write_pointer(
720        &mut self,
721        ptr: impl Into<Pointer<Option<M::Provenance>>>,
722        dest: &impl Writeable<'tcx, M::Provenance>,
723    ) -> InterpResult<'tcx> {
724        self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
725    }
726
727    /// Write an immediate to a place.
728    /// If you use this you are responsible for validating that things got copied at the
729    /// right type.
730    pub(super) fn write_immediate_no_validate(
731        &mut self,
732        src: Immediate<M::Provenance>,
733        dest: &impl Writeable<'tcx, M::Provenance>,
734    ) -> InterpResult<'tcx> {
735        if !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");
736
737        match self.as_mplace_or_mutable_local(&dest.to_place())? {
738            Right((local_val, local_layout, local)) => {
739                // Local can be updated in-place.
740                *local_val = src;
741                // Call the machine hook (the data race detector needs to know about this write).
742                if !self.validation_in_progress() {
743                    M::after_local_write(self, local, /*storage_live*/ false)?;
744                }
745                // Double-check that the value we are storing and the local fit to each other.
746                // Things can ge wrong in quite weird ways when this is violated.
747                // Unfortunately this is too expensive to do in release builds.
748                if truecfg!(debug_assertions) {
749                    src.assert_matches_abi(
750                        local_layout.backend_repr,
751                        "invalid immediate for given destination place",
752                        self,
753                    );
754                }
755            }
756            Left(mplace) => {
757                self.write_immediate_to_mplace_no_validate(src, mplace.layout, mplace.mplace)?;
758            }
759        }
760        interp_ok(())
761    }
762
763    /// Write an immediate to memory.
764    /// If you use this you are responsible for validating that things got copied at the
765    /// right layout.
766    fn write_immediate_to_mplace_no_validate(
767        &mut self,
768        value: Immediate<M::Provenance>,
769        layout: TyAndLayout<'tcx>,
770        dest: MemPlace<M::Provenance>,
771    ) -> InterpResult<'tcx> {
772        // We use the sizes from `value` below.
773        // Ensure that matches the type of the place it is written to.
774        value.assert_matches_abi(
775            layout.backend_repr,
776            "invalid immediate for given destination place",
777            self,
778        );
779        // Note that it is really important that the type here is the right one, and matches the
780        // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
781        // to handle padding properly, which is only correct if we never look at this data with the
782        // wrong type.
783
784        let will_later_validate = M::enforce_validity(self, layout);
785        let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout })? else {
786            // zero-sized access
787            return interp_ok(());
788        };
789
790        match value {
791            Immediate::Scalar(scalar) => {
792                alloc.write_scalar(alloc_range(Size::ZERO, scalar.size()), scalar)?;
793            }
794            Immediate::ScalarPair(a_val, b_val) => {
795                let BackendRepr::ScalarPair { a: _, b: _, b_offset } = layout.backend_repr else {
796                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("write_immediate_to_mplace: invalid ScalarPair layout: {0:#?}",
        layout))span_bug!(
797                        self.cur_span(),
798                        "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
799                        layout
800                    )
801                };
802                let a_size = a_val.size();
803                let b_size = b_val.size();
804                if !(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
805
806                // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
807                // but that does not work: We could be a newtype around a pair, then the
808                // fields do not match the `ScalarPair` components.
809
810                // In preparation, if we do *not* later reset the padding, we clear the entire
811                // destination now to ensure that no stray pointer fragments are being
812                // preserved (see <https://github.com/rust-lang/rust/issues/148470>).
813                // We can skip this if there is no padding (e.g. for wide pointers).
814                if !will_later_validate && a_size + b_size != layout.size {
815                    alloc.write_uninit_full();
816                }
817
818                alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
819                alloc.write_scalar(alloc_range(b_offset, b_size), b_val)?;
820            }
821            Immediate::Uninit => alloc.write_uninit_full(),
822        }
823        interp_ok(())
824    }
825
826    pub fn write_uninit(
827        &mut self,
828        dest: &impl Writeable<'tcx, M::Provenance>,
829    ) -> InterpResult<'tcx> {
830        match self.as_mplace_or_mutable_local(&dest.to_place())? {
831            Right((local_val, _local_layout, local)) => {
832                *local_val = Immediate::Uninit;
833                // Call the machine hook (the data race detector needs to know about this write).
834                if !self.validation_in_progress() {
835                    M::after_local_write(self, local, /*storage_live*/ false)?;
836                }
837            }
838            Left(mplace) => {
839                let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
840                    // Zero-sized access
841                    return interp_ok(());
842                };
843                alloc.write_uninit_full();
844            }
845        }
846        interp_ok(())
847    }
848
849    /// Remove all provenance in the given place.
850    pub fn clear_provenance(
851        &mut self,
852        dest: &impl Writeable<'tcx, M::Provenance>,
853    ) -> InterpResult<'tcx> {
854        // If this is an efficiently represented local variable without provenance, skip the
855        // `as_mplace_or_mutable_local` that would otherwise force this local into memory.
856        if let Right(imm) = dest.to_op(self)?.as_mplace_or_imm() {
857            if !imm.has_provenance() {
858                return interp_ok(());
859            }
860        }
861        match self.as_mplace_or_mutable_local(&dest.to_place())? {
862            Right((local_val, _local_layout, local)) => {
863                local_val.clear_provenance()?;
864                // Call the machine hook (the data race detector needs to know about this write).
865                if !self.validation_in_progress() {
866                    M::after_local_write(self, local, /*storage_live*/ false)?;
867                }
868            }
869            Left(mplace) => {
870                let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
871                    // Zero-sized access
872                    return interp_ok(());
873                };
874                alloc.clear_provenance();
875            }
876        }
877        interp_ok(())
878    }
879
880    /// Copies the data from an operand to a place.
881    /// The layouts of the `src` and `dest` may disagree.
882    #[inline(always)]
883    pub fn copy_op_allow_transmute(
884        &mut self,
885        src: &impl Projectable<'tcx, M::Provenance>,
886        dest: &impl Writeable<'tcx, M::Provenance>,
887    ) -> InterpResult<'tcx> {
888        self.copy_op_inner(src, dest, /* allow_transmute */ true)
889    }
890
891    /// Copies the data from an operand to a place.
892    /// `src` and `dest` must have the same layout and the copied value will be validated.
893    #[inline(always)]
894    pub fn copy_op(
895        &mut self,
896        src: &impl Projectable<'tcx, M::Provenance>,
897        dest: &impl Writeable<'tcx, M::Provenance>,
898    ) -> InterpResult<'tcx> {
899        self.copy_op_inner(src, dest, /* allow_transmute */ false)
900    }
901
902    /// Perform a typed copy of the data from an operand to a place.
903    ///
904    /// `allow_transmute` indicates whether the layouts may disagree. In that case there are
905    /// technically *two* typed copies: `src` is a not-yet-loaded value, so we're doing a typed copy
906    /// at `src` type from there to some intermediate storage. And then we're doing a second typed
907    /// copy at `dest` type from that intermediate storage to `dest`. As an optimization, we only
908    /// make a single direct copy here, but we still have to ensure the data is valid at both types.
909    #[inline(always)]
910    #[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(910u32),
                                    ::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")]
911    fn copy_op_inner(
912        &mut self,
913        src: &impl Projectable<'tcx, M::Provenance>,
914        dest: &impl Writeable<'tcx, M::Provenance>,
915        allow_transmute: bool,
916    ) -> InterpResult<'tcx> {
917        // Do the actual copy.
918        self.copy_op_no_validate(src, dest, allow_transmute)?;
919
920        if M::enforce_validity(self, dest.layout()) {
921            let dest = dest.to_place();
922            // Given that there were two typed copies, we have to ensure this is valid at both
923            // types, and we have to ensure this loses provenance and padding according to both
924            // types. We also transmute both ways: when transmuting `*ptr` from `&T` to `*const T`,
925            // it seems nice to ensure that the resulting pointer value indeed is derived from a
926            // shared reference.
927            // But if the types are identical, that is strictly redundant so we only do one pass.
928            if src.layout().ty != dest.layout().ty {
929                self.validate_place(
930                    &dest.transmute(src.layout(), self)?,
931                    M::enforce_validity_recursively(self, src.layout()),
932                    /*reset_provenance_and_padding*/ true,
933                )?;
934            }
935            self.validate_place(
936                &dest,
937                M::enforce_validity_recursively(self, dest.layout()),
938                /*reset_provenance_and_padding*/ true,
939            )?;
940        }
941
942        interp_ok(())
943    }
944
945    /// Perform an untyped copy of the data from an operand to a place.
946    /// You are responsible for validating that things get copied at the right type.
947    ///
948    /// `allow_transmute` indicates whether the layouts may disagree.
949    #[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(949u32),
                                    ::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:1025",
                                    "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(1025u32),
                                    ::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")]
950    pub(super) fn copy_op_no_validate(
951        &mut self,
952        src: &impl Projectable<'tcx, M::Provenance>,
953        dest: &impl Writeable<'tcx, M::Provenance>,
954        allow_transmute: bool,
955    ) -> InterpResult<'tcx> {
956        // We do NOT compare the types for equality, because well-typed code can
957        // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
958        let layout_compat =
959            mir_assign_valid_types(*self.tcx, self.typing_env, src.layout(), dest.layout());
960        if !allow_transmute && !layout_compat {
961            span_bug!(
962                self.cur_span(),
963                "type mismatch when copying!\nsrc: {},\ndest: {}",
964                src.layout().ty,
965                dest.layout().ty,
966            );
967        }
968        // If the source has padding, we want to always do a mem-to-mem copy to ensure consistent
969        // padding in the target independent of layout choices.
970        let src_has_padding = match src.layout().backend_repr {
971            BackendRepr::Scalar(_) => false,
972            BackendRepr::ScalarPair { a: left, b: right, b_offset: _ }
973                if matches!(src.layout().ty.kind(), ty::Ref(..) | ty::RawPtr(..)) =>
974            {
975                // Wide pointers never have padding, so we can avoid calling `size()`.
976                debug_assert_eq!(left.size(self) + right.size(self), src.layout().size);
977                false
978            }
979            BackendRepr::ScalarPair { a: left, b: right, b_offset: _ } => {
980                let left_size = left.size(self);
981                let right_size = right.size(self);
982                // We have padding if the sizes don't add up to the total.
983                // (Why don't we need to check the offset?  The scalars don't overlap so no padding
984                // implies `b_offset == left_size`, which would be superfluous to check explicitly.)
985                left_size + right_size != src.layout().size
986            }
987            // Everything else can only exist in memory anyway, so it doesn't matter.
988            BackendRepr::SimdVector { .. }
989            | BackendRepr::SimdScalableVector { .. }
990            | BackendRepr::Memory { .. } => true,
991        };
992
993        let src_val = if src_has_padding {
994            // Do our best to get an mplace. If there's no mplace, then this is stored as an
995            // "optimized" local, so its padding is definitely uninitialized and we are fine.
996            src.to_op(self)?.as_mplace_or_imm()
997        } else {
998            // Do our best to get an immediate, to avoid having to force_allocate the destination.
999            self.read_immediate_raw(src)?
1000        };
1001        let src = match src_val {
1002            Right(src_val) => {
1003                assert!(!src.layout().is_unsized());
1004                assert!(!dest.layout().is_unsized());
1005                assert_eq!(src.layout().size, dest.layout().size);
1006                // Yay, we got a value that we can write directly.
1007                return if layout_compat {
1008                    self.write_immediate_no_validate(*src_val, dest)
1009                } else {
1010                    // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
1011                    // loaded using the offsets defined by `src.layout`. When we put this back into
1012                    // the destination, we have to use the same offsets! So (a) we make sure we
1013                    // write back to memory, and (b) we use `dest` *with the source layout*.
1014                    let dest_mem = dest.force_mplace(self)?;
1015                    self.write_immediate_to_mplace_no_validate(
1016                        *src_val,
1017                        src.layout(),
1018                        dest_mem.mplace,
1019                    )
1020                };
1021            }
1022            Left(mplace) => mplace,
1023        };
1024        // Slow path, this does not fit into an immediate. Just memcpy.
1025        trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout().ty);
1026
1027        let dest = dest.force_mplace(self)?;
1028        let Some((dest_size, _)) = self.size_and_align_of_val(&dest)? else {
1029            span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
1030        };
1031        if cfg!(debug_assertions) {
1032            let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
1033            assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
1034        } else {
1035            // As a cheap approximation, we compare the fixed parts of the size.
1036            assert_eq!(src.layout.size, dest.layout.size);
1037        }
1038
1039        // Setting `nonoverlapping` here only has an effect when we don't hit the fast-path above,
1040        // but that should at least match what LLVM does where `memcpy` is also only used when the
1041        // type does not have Scalar/ScalarPair layout.
1042        // (Or as the `Assign` docs put it, assignments "not producing primitives" must be
1043        // non-overlapping.)
1044        // We check alignment separately, and *after* checking everything else.
1045        // If an access is both OOB and misaligned, we want to see the bounds error.
1046        self.mem_copy(src.ptr(), dest.ptr(), dest_size, /*nonoverlapping*/ true)?;
1047        self.check_misalign(src.mplace.misaligned, CheckAlignMsg::BasedOn)?;
1048        self.check_misalign(dest.mplace.misaligned, CheckAlignMsg::BasedOn)?;
1049        interp_ok(())
1050    }
1051
1052    /// Ensures that a place is in memory, and returns where it is.
1053    /// If the place currently refers to a local that doesn't yet have a matching allocation,
1054    /// create such an allocation.
1055    /// This is essentially `force_to_memplace`.
1056    #[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(1056u32),
                                    ::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")]
1057    pub fn force_allocation(
1058        &mut self,
1059        place: &PlaceTy<'tcx, M::Provenance>,
1060    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1061        let mplace = match place.place {
1062            Place::Local { local, offset, locals_addr } => {
1063                debug_assert_eq!(locals_addr, self.frame().locals_addr());
1064                let whole_local = match self.frame_mut().locals[local].access_mut()? {
1065                    &mut Operand::Immediate(local_val) => {
1066                        // We need to make an allocation.
1067
1068                        // We need the layout of the local. We can NOT use the layout we got,
1069                        // that might e.g., be an inner field of a struct with `Scalar` layout,
1070                        // that has different alignment than the outer field.
1071                        let local_layout = self.layout_of_local(&self.frame(), local, None)?;
1072                        assert!(local_layout.is_sized(), "unsized locals cannot be immediate");
1073                        let mplace = self.allocate(local_layout, MemoryKind::Stack)?;
1074                        // Preserve old value. (As an optimization, we can skip this if it was uninit.)
1075                        if !matches!(local_val, Immediate::Uninit) {
1076                            // We don't have to validate as we can assume the local was already
1077                            // valid for its type. We must not use any part of `place` here, that
1078                            // could be a projection to a part of the local!
1079                            self.write_immediate_to_mplace_no_validate(
1080                                local_val,
1081                                local_layout,
1082                                mplace.mplace,
1083                            )?;
1084                        }
1085                        M::after_local_moved_to_memory(self, local, &mplace)?;
1086                        // Now we can call `access_mut` again, asserting it goes well, and actually
1087                        // overwrite things. This points to the entire allocation, not just the part
1088                        // the place refers to, i.e. we do this before we apply `offset`.
1089                        *self.frame_mut().locals[local].access_mut().unwrap() =
1090                            Operand::Indirect(mplace.mplace);
1091                        mplace.mplace
1092                    }
1093                    &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
1094                };
1095                if let Some(offset) = offset {
1096                    // This offset is always inbounds, no need to check it again.
1097                    whole_local.offset_with_meta_(
1098                        offset,
1099                        OffsetMode::Wrapping,
1100                        MemPlaceMeta::None,
1101                        self,
1102                    )?
1103                } else {
1104                    // Preserve wide place metadata, do not call `offset`.
1105                    whole_local
1106                }
1107            }
1108            Place::Ptr(mplace) => mplace,
1109        };
1110        // Return with the original layout and align, so that the caller can go on
1111        interp_ok(MPlaceTy { mplace, layout: place.layout })
1112    }
1113
1114    pub fn allocate_dyn(
1115        &mut self,
1116        layout: TyAndLayout<'tcx>,
1117        kind: MemoryKind<M::MemoryKind>,
1118        meta: MemPlaceMeta<M::Provenance>,
1119    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1120        let Some((size, align)) = self.size_and_align_from_meta(&meta, &layout)? else {
1121            ::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")
1122        };
1123        let ptr = self.allocate_ptr(size, align, kind, AllocInit::Uninit)?;
1124        interp_ok(self.ptr_with_meta_to_mplace(ptr.into(), meta, layout, /*unaligned*/ false))
1125    }
1126
1127    pub fn allocate(
1128        &mut self,
1129        layout: TyAndLayout<'tcx>,
1130        kind: MemoryKind<M::MemoryKind>,
1131    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1132        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1133        self.allocate_dyn(layout, kind, MemPlaceMeta::None)
1134    }
1135
1136    /// Allocates a sequence of bytes in the interpreter's memory with alignment 1.
1137    /// This is allocated in immutable global memory and deduplicated.
1138    pub fn allocate_bytes_dedup(
1139        &mut self,
1140        bytes: &[u8],
1141    ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
1142        let salt = M::get_global_alloc_salt(self, None);
1143        let id = self.tcx.allocate_bytes_dedup(bytes, salt);
1144
1145        // Turn untagged "global" pointers (obtained via `tcx`) into the machine pointer to the allocation.
1146        M::adjust_alloc_root_pointer(
1147            &self,
1148            Pointer::from(id),
1149            M::GLOBAL_KIND.map(MemoryKind::Machine),
1150        )
1151    }
1152
1153    /// Allocates a string in the interpreter's memory, returning it as a (wide) place.
1154    /// This is allocated in immutable global memory and deduplicated.
1155    pub fn allocate_str_dedup(
1156        &mut self,
1157        s: &str,
1158    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1159        let bytes = s.as_bytes();
1160        let ptr = self.allocate_bytes_dedup(bytes)?;
1161
1162        // Create length metadata for the string.
1163        let meta = Scalar::from_target_usize(u64::try_from(bytes.len()).unwrap(), self);
1164
1165        // Get layout for Rust's str type.
1166        let layout = self.layout_of(self.tcx.types.str_).unwrap();
1167
1168        // Combine pointer and metadata into a wide pointer.
1169        interp_ok(self.ptr_with_meta_to_mplace(
1170            ptr.into(),
1171            MemPlaceMeta::Meta(meta),
1172            layout,
1173            /*unaligned*/ false,
1174        ))
1175    }
1176
1177    pub fn raw_const_to_mplace(
1178        &self,
1179        raw: mir::ConstAlloc<'tcx>,
1180    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1181        // This must be an allocation in `tcx`
1182        let _ = self.tcx.global_alloc(raw.alloc_id);
1183        let ptr = self.global_root_pointer(Pointer::from(raw.alloc_id))?;
1184        let layout = self.layout_of(raw.ty)?;
1185        interp_ok(self.ptr_to_mplace(ptr.into(), layout))
1186    }
1187}
1188
1189// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1190#[cfg(target_pointer_width = "64")]
1191mod size_asserts {
1192    use rustc_data_structures::static_assert_size;
1193
1194    use super::*;
1195    // tidy-alphabetical-start
1196    const _: [(); 64] = [(); ::std::mem::size_of::<MPlaceTy<'_>>()];static_assert_size!(MPlaceTy<'_>, 64);
1197    const _: [(); 48] = [(); ::std::mem::size_of::<MemPlace>()];static_assert_size!(MemPlace, 48);
1198    const _: [(); 24] = [(); ::std::mem::size_of::<MemPlaceMeta>()];static_assert_size!(MemPlaceMeta, 24);
1199    const _: [(); 48] = [(); ::std::mem::size_of::<Place>()];static_assert_size!(Place, 48);
1200    const _: [(); 64] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];static_assert_size!(PlaceTy<'_>, 64);
1201    // tidy-alphabetical-end
1202}