Skip to main content

rustc_middle/mir/interpret/
mod.rs

1//! An interpreter for MIR used in CTFE and by miri.
2
3#[macro_use]
4mod error;
5
6mod allocation;
7mod pointer;
8mod queries;
9mod value;
10
11use std::io::{Read, Write};
12use std::num::NonZero;
13use std::{fmt, io};
14
15use rustc_abi::{AddressSpace, Align, Endian, HasDataLayout, Size};
16use rustc_ast::Mutability;
17use rustc_data_structures::fx::FxHashMap;
18use rustc_data_structures::sharded::ShardedHashMap;
19use rustc_data_structures::sync::{AtomicU64, Lock};
20use rustc_hir::def::DefKind;
21use rustc_hir::def_id::{DefId, LocalDefId};
22use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
23use rustc_serialize::{Decodable, Encodable};
24use tracing::{debug, trace};
25// Also make the error macros available from this module.
26pub use {
27    err_exhaust, err_inval, err_machine_stop, err_ub, err_ub_custom, err_ub_format, err_unsup,
28    err_unsup_format, throw_exhaust, throw_inval, throw_machine_stop, throw_ub, throw_ub_custom,
29    throw_ub_format, throw_unsup, throw_unsup_format,
30};
31
32pub use self::allocation::{
33    AllocBytes, AllocError, AllocInit, AllocRange, AllocResult, Allocation, ConstAllocation,
34    InitChunk, InitChunkIter, alloc_range,
35};
36pub use self::error::{
37    BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalStaticInitializerRawResult,
38    EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind,
39    InterpErrorInfo, InterpErrorKind, InterpResult, InvalidMetaKind, InvalidProgramInfo,
40    MachineStopType, Misalignment, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo,
41    ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, ValTreeCreationError,
42    ValidationErrorInfo, ValidationErrorKind, interp_ok,
43};
44pub use self::pointer::{CtfeProvenance, Pointer, PointerArithmetic, Provenance};
45pub use self::value::Scalar;
46use crate::mir;
47use crate::ty::codec::{TyDecoder, TyEncoder};
48use crate::ty::print::with_no_trimmed_paths;
49use crate::ty::{self, Instance, Ty, TyCtxt};
50
51/// Uniquely identifies one of the following:
52/// - A constant
53/// - A static
54#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for GlobalId<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for GlobalId<'tcx> {
    #[inline]
    fn clone(&self) -> GlobalId<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::Instance<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<mir::Promoted>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for GlobalId<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "GlobalId",
            "instance", &self.instance, "promoted", &&self.promoted)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for GlobalId<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::Instance<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Option<mir::Promoted>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for GlobalId<'tcx> {
    #[inline]
    fn eq(&self, other: &GlobalId<'tcx>) -> bool {
        self.instance == other.instance && self.promoted == other.promoted
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for GlobalId<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.instance, state);
        ::core::hash::Hash::hash(&self.promoted, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for GlobalId<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    GlobalId {
                        instance: ref __binding_0, promoted: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for GlobalId<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                GlobalId {
                    instance: ::rustc_serialize::Decodable::decode(__decoder),
                    promoted: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
55#[derive(const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for GlobalId<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    GlobalId {
                        instance: ref __binding_0, promoted: ref __binding_1 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for GlobalId<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        GlobalId { instance: __binding_0, promoted: __binding_1 } =>
                            {
                            GlobalId {
                                instance: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                promoted: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    GlobalId { instance: __binding_0, promoted: __binding_1 } =>
                        {
                        GlobalId {
                            instance: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            promoted: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for GlobalId<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    GlobalId {
                        instance: ref __binding_0, promoted: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
56pub struct GlobalId<'tcx> {
57    /// For a constant or static, the `Instance` of the item itself.
58    /// For a promoted global, the `Instance` of the function they belong to.
59    pub instance: ty::Instance<'tcx>,
60
61    /// The index for promoted globals within their function's `mir::Body`.
62    pub promoted: Option<mir::Promoted>,
63}
64
65impl<'tcx> GlobalId<'tcx> {
66    pub fn display(self, tcx: TyCtxt<'tcx>) -> String {
67        let instance_name = {
    let _guard = NoTrimmedGuard::new();
    tcx.def_path_str(self.instance.def.def_id())
}with_no_trimmed_paths!(tcx.def_path_str(self.instance.def.def_id()));
68        if let Some(promoted) = self.promoted {
69            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1:?}", instance_name,
                promoted))
    })format!("{instance_name}::{promoted:?}")
70        } else {
71            instance_name
72        }
73    }
74}
75
76#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllocId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllocId {
    #[inline]
    fn clone(&self) -> AllocId {
        let _: ::core::clone::AssertParamIsClone<NonZero<u64>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for AllocId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NonZero<u64>>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for AllocId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::cmp::Ord for AllocId {
    #[inline]
    fn cmp(&self, other: &AllocId) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl ::core::cmp::PartialEq for AllocId {
    #[inline]
    fn eq(&self, other: &AllocId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for AllocId {
    #[inline]
    fn partial_cmp(&self, other: &AllocId)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}PartialOrd)]
77pub struct AllocId(pub NonZero<u64>);
78
79// We want the `Debug` output to be readable as it is used by `derive(Debug)` for
80// all the Miri types.
81impl fmt::Debug for AllocId {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        if f.alternate() { f.write_fmt(format_args!("a{0}", self.0))write!(f, "a{}", self.0) } else { f.write_fmt(format_args!("alloc{0}", self.0))write!(f, "alloc{}", self.0) }
84    }
85}
86
87// No "Display" since AllocIds are not usually user-visible.
88
89#[derive(const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for AllocDiscriminant {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { AllocDiscriminant::Alloc }
                    1usize => { AllocDiscriminant::Fn }
                    2usize => { AllocDiscriminant::VTable }
                    3usize => { AllocDiscriminant::Static }
                    4usize => { AllocDiscriminant::Type }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `AllocDiscriminant`, expected 0..5, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AllocDiscriminant {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        AllocDiscriminant::Alloc => { 0usize }
                        AllocDiscriminant::Fn => { 1usize }
                        AllocDiscriminant::VTable => { 2usize }
                        AllocDiscriminant::Static => { 3usize }
                        AllocDiscriminant::Type => { 4usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    AllocDiscriminant::Alloc => {}
                    AllocDiscriminant::Fn => {}
                    AllocDiscriminant::VTable => {}
                    AllocDiscriminant::Static => {}
                    AllocDiscriminant::Type => {}
                }
            }
        }
    };TyEncodable)]
90enum AllocDiscriminant {
91    Alloc,
92    Fn,
93    VTable,
94    Static,
95    Type,
96}
97
98pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<'tcx>>(
99    encoder: &mut E,
100    tcx: TyCtxt<'tcx>,
101    alloc_id: AllocId,
102) {
103    match tcx.global_alloc(alloc_id) {
104        GlobalAlloc::Memory(alloc) => {
105            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:105",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(105u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encoding {0:?} with {1:#?}",
                                                    alloc_id, alloc) as &dyn Value))])
            });
    } else { ; }
};trace!("encoding {:?} with {:#?}", alloc_id, alloc);
106            AllocDiscriminant::Alloc.encode(encoder);
107            alloc.encode(encoder);
108        }
109        GlobalAlloc::Function { instance } => {
110            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:110",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(110u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encoding {0:?} with {1:#?}",
                                                    alloc_id, instance) as &dyn Value))])
            });
    } else { ; }
};trace!("encoding {:?} with {:#?}", alloc_id, instance);
111            AllocDiscriminant::Fn.encode(encoder);
112            instance.encode(encoder);
113        }
114        GlobalAlloc::VTable(ty, poly_trait_ref) => {
115            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:115",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(115u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encoding {0:?} with {1:#?}, {2:#?}",
                                                    alloc_id, ty, poly_trait_ref) as &dyn Value))])
            });
    } else { ; }
};trace!("encoding {:?} with {ty:#?}, {poly_trait_ref:#?}", alloc_id);
116            AllocDiscriminant::VTable.encode(encoder);
117            ty.encode(encoder);
118            poly_trait_ref.encode(encoder);
119        }
120        GlobalAlloc::TypeId { ty } => {
121            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:121",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(121u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encoding {0:?} with {1:#?}",
                                                    alloc_id, ty) as &dyn Value))])
            });
    } else { ; }
};trace!("encoding {alloc_id:?} with {ty:#?}");
122            AllocDiscriminant::Type.encode(encoder);
123            ty.encode(encoder);
124        }
125        GlobalAlloc::Static(did) => {
126            if !!tcx.is_thread_local_static(did) {
    ::core::panicking::panic("assertion failed: !tcx.is_thread_local_static(did)")
};assert!(!tcx.is_thread_local_static(did));
127            // References to statics doesn't need to know about their allocations,
128            // just about its `DefId`.
129            AllocDiscriminant::Static.encode(encoder);
130            // Cannot use `did.encode(encoder)` because of a bug around
131            // specializations and method calls.
132            Encodable::<E>::encode(&did, encoder);
133        }
134    }
135}
136
137#[derive(#[automatically_derived]
impl ::core::clone::Clone for State {
    #[inline]
    fn clone(&self) -> State {
        match self {
            State::Empty => State::Empty,
            State::Done(__self_0) =>
                State::Done(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
138enum State {
139    Empty,
140    Done(AllocId),
141}
142
143pub struct AllocDecodingState {
144    // For each `AllocId`, we keep track of which decoding state it's currently in.
145    decoding_state: Vec<Lock<State>>,
146    // The offsets of each allocation in the data stream.
147    data_offsets: Vec<u64>,
148}
149
150impl AllocDecodingState {
151    #[inline]
152    pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
153        AllocDecodingSession { state: self }
154    }
155
156    pub fn new(data_offsets: Vec<u64>) -> Self {
157        let decoding_state =
158            std::iter::repeat_with(|| Lock::new(State::Empty)).take(data_offsets.len()).collect();
159
160        Self { decoding_state, data_offsets }
161    }
162}
163
164#[derive(#[automatically_derived]
impl<'s> ::core::marker::Copy for AllocDecodingSession<'s> { }Copy, #[automatically_derived]
impl<'s> ::core::clone::Clone for AllocDecodingSession<'s> {
    #[inline]
    fn clone(&self) -> AllocDecodingSession<'s> {
        let _: ::core::clone::AssertParamIsClone<&'s AllocDecodingState>;
        *self
    }
}Clone)]
165pub struct AllocDecodingSession<'s> {
166    state: &'s AllocDecodingState,
167}
168
169impl<'s> AllocDecodingSession<'s> {
170    /// Decodes an `AllocId` in a thread-safe way.
171    pub fn decode_alloc_id<'tcx, D>(&self, decoder: &mut D) -> AllocId
172    where
173        D: TyDecoder<'tcx>,
174    {
175        // Read the index of the allocation.
176        let idx = usize::try_from(decoder.read_u32()).unwrap();
177        let pos = usize::try_from(self.state.data_offsets[idx]).unwrap();
178
179        // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
180        // `AllocId`.
181        let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
182            let alloc_kind = AllocDiscriminant::decode(decoder);
183            (alloc_kind, decoder.position())
184        });
185
186        // We are going to hold this lock during the entire decoding of this allocation, which may
187        // require that we decode other allocations. This cannot deadlock for two reasons:
188        //
189        // At the time of writing, it is only possible to create an allocation that contains a pointer
190        // to itself using the const_allocate intrinsic (which is for testing only), and even attempting
191        // to evaluate such consts blows the stack. If we ever grow a mechanism for producing
192        // cyclic allocations, we will need a new strategy for decoding that doesn't bring back
193        // https://github.com/rust-lang/rust/issues/126741.
194        //
195        // It is also impossible to create two allocations (call them A and B) where A is a pointer to B, and B
196        // is a pointer to A, because attempting to evaluate either of those consts will produce a
197        // query cycle, failing compilation.
198        let mut entry = self.state.decoding_state[idx].lock();
199        // Check the decoding state to see if it's already decoded or if we should
200        // decode it here.
201        if let State::Done(alloc_id) = *entry {
202            return alloc_id;
203        }
204
205        // Now decode the actual data.
206        let alloc_id = decoder.with_position(pos, |decoder| match alloc_kind {
207            AllocDiscriminant::Alloc => {
208                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:208",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(208u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating memory alloc ID")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating memory alloc ID");
209                let alloc = <ConstAllocation<'tcx> as Decodable<_>>::decode(decoder);
210                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:210",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(210u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("decoded alloc {0:?}",
                                                    alloc) as &dyn Value))])
            });
    } else { ; }
};trace!("decoded alloc {:?}", alloc);
211                decoder.interner().reserve_and_set_memory_alloc(alloc)
212            }
213            AllocDiscriminant::Fn => {
214                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:214",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(214u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating fn alloc ID")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating fn alloc ID");
215                let instance = ty::Instance::decode(decoder);
216                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:216",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(216u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("decoded fn alloc instance: {0:?}",
                                                    instance) as &dyn Value))])
            });
    } else { ; }
};trace!("decoded fn alloc instance: {:?}", instance);
217                decoder.interner().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT)
218            }
219            AllocDiscriminant::VTable => {
220                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:220",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(220u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating vtable alloc ID")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating vtable alloc ID");
221                let ty = Decodable::decode(decoder);
222                let poly_trait_ref = Decodable::decode(decoder);
223                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:223",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(223u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("decoded vtable alloc instance: {0:?}, {1:?}",
                                                    ty, poly_trait_ref) as &dyn Value))])
            });
    } else { ; }
};trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}");
224                decoder.interner().reserve_and_set_vtable_alloc(ty, poly_trait_ref, CTFE_ALLOC_SALT)
225            }
226            AllocDiscriminant::Type => {
227                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:227",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(227u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating typeid alloc ID")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating typeid alloc ID");
228                let ty = Decodable::decode(decoder);
229                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:229",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(229u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("decoded typid: {0:?}",
                                                    ty) as &dyn Value))])
            });
    } else { ; }
};trace!("decoded typid: {ty:?}");
230                decoder.interner().reserve_and_set_type_id_alloc(ty)
231            }
232            AllocDiscriminant::Static => {
233                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:233",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(233u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating extern static alloc ID")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating extern static alloc ID");
234                let did = <DefId as Decodable<D>>::decode(decoder);
235                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:235",
                        "rustc_middle::mir::interpret", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(235u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("decoded static def-ID: {0:?}",
                                                    did) as &dyn Value))])
            });
    } else { ; }
};trace!("decoded static def-ID: {:?}", did);
236                decoder.interner().reserve_and_set_static_alloc(did)
237            }
238        });
239
240        *entry = State::Done(alloc_id);
241
242        alloc_id
243    }
244}
245
246/// An allocation in the global (tcx-managed) memory can be either a function pointer,
247/// a static, or a "real" allocation with some data in it.
248#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for GlobalAlloc<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            GlobalAlloc::Function { instance: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Function", "instance", &__self_0),
            GlobalAlloc::VTable(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "VTable",
                    __self_0, &__self_1),
            GlobalAlloc::Static(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Static",
                    &__self_0),
            GlobalAlloc::Memory(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Memory",
                    &__self_0),
            GlobalAlloc::TypeId { ty: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TypeId", "ty", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for GlobalAlloc<'tcx> {
    #[inline]
    fn clone(&self) -> GlobalAlloc<'tcx> {
        match self {
            GlobalAlloc::Function { instance: __self_0 } =>
                GlobalAlloc::Function {
                    instance: ::core::clone::Clone::clone(__self_0),
                },
            GlobalAlloc::VTable(__self_0, __self_1) =>
                GlobalAlloc::VTable(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            GlobalAlloc::Static(__self_0) =>
                GlobalAlloc::Static(::core::clone::Clone::clone(__self_0)),
            GlobalAlloc::Memory(__self_0) =>
                GlobalAlloc::Memory(::core::clone::Clone::clone(__self_0)),
            GlobalAlloc::TypeId { ty: __self_0 } =>
                GlobalAlloc::TypeId {
                    ty: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for GlobalAlloc<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Instance<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _:
                ::core::cmp::AssertParamIsEq<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<ConstAllocation<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for GlobalAlloc<'tcx> {
    #[inline]
    fn eq(&self, other: &GlobalAlloc<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (GlobalAlloc::Function { instance: __self_0 },
                    GlobalAlloc::Function { instance: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (GlobalAlloc::VTable(__self_0, __self_1),
                    GlobalAlloc::VTable(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (GlobalAlloc::Static(__self_0), GlobalAlloc::Static(__arg1_0))
                    => __self_0 == __arg1_0,
                (GlobalAlloc::Memory(__self_0), GlobalAlloc::Memory(__arg1_0))
                    => __self_0 == __arg1_0,
                (GlobalAlloc::TypeId { ty: __self_0 }, GlobalAlloc::TypeId {
                    ty: __arg1_0 }) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for GlobalAlloc<'tcx> {
    #[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 {
            GlobalAlloc::Function { instance: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            GlobalAlloc::VTable(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            GlobalAlloc::Static(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            GlobalAlloc::Memory(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            GlobalAlloc::TypeId { ty: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for GlobalAlloc<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        GlobalAlloc::Function {
                            instance: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    1usize => {
                        GlobalAlloc::VTable(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_middle::ty::codec::RefDecodable::decode(__decoder))
                    }
                    2usize => {
                        GlobalAlloc::Static(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    3usize => {
                        GlobalAlloc::Memory(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    4usize => {
                        GlobalAlloc::TypeId {
                            ty: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `GlobalAlloc`, expected 0..5, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for GlobalAlloc<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        GlobalAlloc::Function { instance: ref __binding_0 } => {
                            0usize
                        }
                        GlobalAlloc::VTable(ref __binding_0, __binding_1) => {
                            1usize
                        }
                        GlobalAlloc::Static(ref __binding_0) => { 2usize }
                        GlobalAlloc::Memory(ref __binding_0) => { 3usize }
                        GlobalAlloc::TypeId { ty: ref __binding_0 } => { 4usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    GlobalAlloc::Function { instance: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    GlobalAlloc::VTable(ref __binding_0, __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    GlobalAlloc::Static(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    GlobalAlloc::Memory(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    GlobalAlloc::TypeId { ty: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for GlobalAlloc<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    GlobalAlloc::Function { instance: ref __binding_0 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    GlobalAlloc::VTable(ref __binding_0, ref __binding_1) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                    GlobalAlloc::Static(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    GlobalAlloc::Memory(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    GlobalAlloc::TypeId { ty: ref __binding_0 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
249pub enum GlobalAlloc<'tcx> {
250    /// The alloc ID is used as a function pointer.
251    Function { instance: Instance<'tcx> },
252    /// This alloc ID points to a symbolic (not-reified) vtable.
253    /// We remember the full dyn type, not just the principal trait, so that
254    /// const-eval and Miri can detect UB due to invalid transmutes of
255    /// `dyn Trait` types.
256    VTable(Ty<'tcx>, &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>),
257    /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
258    /// This is also used to break the cycle in recursive statics.
259    Static(DefId),
260    /// The alloc ID points to memory.
261    Memory(ConstAllocation<'tcx>),
262    /// The first pointer-sized segment of a type id. On 64 bit systems, the 128 bit type id
263    /// is split into two segments, on 32 bit systems there are 4 segments, and so on.
264    TypeId { ty: Ty<'tcx> },
265}
266
267impl<'tcx> GlobalAlloc<'tcx> {
268    /// Panics if the `GlobalAlloc` does not refer to an `GlobalAlloc::Memory`
269    #[track_caller]
270    #[inline]
271    pub fn unwrap_memory(&self) -> ConstAllocation<'tcx> {
272        match *self {
273            GlobalAlloc::Memory(mem) => mem,
274            _ => crate::util::bug::bug_fmt(format_args!("expected memory, got {0:?}", self))bug!("expected memory, got {:?}", self),
275        }
276    }
277
278    /// Panics if the `GlobalAlloc` is not `GlobalAlloc::Function`
279    #[track_caller]
280    #[inline]
281    pub fn unwrap_fn(&self) -> Instance<'tcx> {
282        match *self {
283            GlobalAlloc::Function { instance, .. } => instance,
284            _ => crate::util::bug::bug_fmt(format_args!("expected function, got {0:?}", self))bug!("expected function, got {:?}", self),
285        }
286    }
287
288    /// Panics if the `GlobalAlloc` is not `GlobalAlloc::VTable`
289    #[track_caller]
290    #[inline]
291    pub fn unwrap_vtable(&self) -> (Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>) {
292        match *self {
293            GlobalAlloc::VTable(ty, dyn_ty) => (ty, dyn_ty.principal()),
294            _ => crate::util::bug::bug_fmt(format_args!("expected vtable, got {0:?}", self))bug!("expected vtable, got {:?}", self),
295        }
296    }
297
298    /// The address space that this `GlobalAlloc` should be placed in.
299    #[inline]
300    pub fn address_space(&self, cx: &impl HasDataLayout) -> AddressSpace {
301        match self {
302            GlobalAlloc::Function { .. } => cx.data_layout().instruction_address_space,
303            GlobalAlloc::TypeId { .. }
304            | GlobalAlloc::Static(..)
305            | GlobalAlloc::Memory(..)
306            | GlobalAlloc::VTable(..) => AddressSpace::ZERO,
307        }
308    }
309
310    pub fn mutability(&self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Mutability {
311        // Let's see what kind of memory we are.
312        match self {
313            GlobalAlloc::Static(did) => {
314                let DefKind::Static { safety: _, mutability, nested } = tcx.def_kind(did) else {
315                    crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
316                };
317                if nested {
318                    // Nested statics in a `static` are never interior mutable,
319                    // so just use the declared mutability.
320                    if truecfg!(debug_assertions) {
321                        let alloc = tcx.eval_static_initializer(did).unwrap();
322                        match (&alloc.0.mutability, &mutability) {
    (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!(alloc.0.mutability, mutability);
323                    }
324                    mutability
325                } else {
326                    let mutability = match mutability {
327                        Mutability::Not
328                            if !tcx
329                                .type_of(did)
330                                .no_bound_vars()
331                                .expect("statics should not have generic parameters")
332                                .is_freeze(tcx, typing_env) =>
333                        {
334                            Mutability::Mut
335                        }
336                        _ => mutability,
337                    };
338                    mutability
339                }
340            }
341            GlobalAlloc::Memory(alloc) => alloc.inner().mutability,
342            GlobalAlloc::TypeId { .. } | GlobalAlloc::Function { .. } | GlobalAlloc::VTable(..) => {
343                // These are immutable.
344                Mutability::Not
345            }
346        }
347    }
348
349    pub fn size_and_align(
350        &self,
351        tcx: TyCtxt<'tcx>,
352        typing_env: ty::TypingEnv<'tcx>,
353    ) -> (Size, Align) {
354        match self {
355            GlobalAlloc::Static(def_id) => {
356                let DefKind::Static { nested, .. } = tcx.def_kind(def_id) else {
357                    crate::util::bug::bug_fmt(format_args!("GlobalAlloc::Static is not a static"))bug!("GlobalAlloc::Static is not a static")
358                };
359
360                if nested {
361                    // Nested anonymous statics are untyped, so let's get their
362                    // size and alignment from the allocation itself. This always
363                    // succeeds, as the query is fed at DefId creation time, so no
364                    // evaluation actually occurs.
365                    let alloc = tcx.eval_static_initializer(def_id).unwrap();
366                    (alloc.0.size(), alloc.0.align)
367                } else {
368                    // Use size and align of the type for everything else. We need
369                    // to do that to
370                    // * avoid cycle errors in case of self-referential statics,
371                    // * be able to get information on extern statics.
372                    let ty = tcx
373                        .type_of(def_id)
374                        .no_bound_vars()
375                        .expect("statics should not have generic parameters");
376                    let layout = tcx.layout_of(typing_env.as_query_input(ty)).unwrap();
377                    if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
378
379                    // Take over-alignment from attributes into account.
380                    let align = match tcx.codegen_fn_attrs(def_id).alignment {
381                        Some(align_from_attribute) => {
382                            Ord::max(align_from_attribute, layout.align.abi)
383                        }
384                        None => layout.align.abi,
385                    };
386
387                    (layout.size, align)
388                }
389            }
390            GlobalAlloc::Memory(alloc) => {
391                let alloc = alloc.inner();
392                (alloc.size(), alloc.align)
393            }
394            GlobalAlloc::Function { .. } => (Size::ZERO, Align::ONE),
395            GlobalAlloc::VTable(..) => {
396                // No data to be accessed here. But vtables are pointer-aligned.
397                (Size::ZERO, tcx.data_layout.pointer_align().abi)
398            }
399            // Fake allocation, there's nothing to access here
400            GlobalAlloc::TypeId { .. } => (Size::ZERO, Align::ONE),
401        }
402    }
403}
404
405pub const CTFE_ALLOC_SALT: usize = 0;
406
407pub(crate) struct AllocMap<'tcx> {
408    /// Maps `AllocId`s to their corresponding allocations.
409    // Note that this map on rustc workloads seems to be rather dense, but in miri workloads should
410    // be pretty sparse. In #136105 we considered replacing it with a (dense) Vec-based map, but
411    // since there are workloads where it can be sparse we decided to go with sharding for now. At
412    // least up to 32 cores the one workload tested didn't exhibit much difference between the two.
413    //
414    // Should be locked *after* locking dedup if locking both to avoid deadlocks.
415    to_alloc: ShardedHashMap<AllocId, GlobalAlloc<'tcx>>,
416
417    /// Used to deduplicate global allocations: functions, vtables, string literals, ...
418    ///
419    /// The `usize` is a "salt" used by Miri to make deduplication imperfect, thus better emulating
420    /// the actual guarantees.
421    dedup: Lock<FxHashMap<(GlobalAlloc<'tcx>, usize), AllocId>>,
422
423    /// The `AllocId` to assign to the next requested ID.
424    /// Always incremented; never gets smaller.
425    next_id: AtomicU64,
426}
427
428impl<'tcx> AllocMap<'tcx> {
429    pub(crate) fn new() -> Self {
430        AllocMap {
431            to_alloc: Default::default(),
432            dedup: Default::default(),
433            next_id: AtomicU64::new(1),
434        }
435    }
436    fn reserve(&self) -> AllocId {
437        // Technically there is a window here where we overflow and then another thread
438        // increments `next_id` *again* and uses it before we panic and tear down the entire session.
439        // We consider this fine since such overflows cannot realistically occur.
440        let next_id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
441        AllocId(NonZero::new(next_id).unwrap())
442    }
443}
444
445impl<'tcx> TyCtxt<'tcx> {
446    /// Obtains a new allocation ID that can be referenced but does not
447    /// yet have an allocation backing it.
448    ///
449    /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
450    /// an `AllocId` from a query.
451    pub fn reserve_alloc_id(self) -> AllocId {
452        self.alloc_map.reserve()
453    }
454
455    /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
456    /// Should not be used for mutable memory.
457    fn reserve_and_set_dedup(self, alloc: GlobalAlloc<'tcx>, salt: usize) -> AllocId {
458        if let GlobalAlloc::Memory(mem) = alloc {
459            if mem.inner().mutability.is_mut() {
460                crate::util::bug::bug_fmt(format_args!("trying to dedup-reserve mutable memory"));bug!("trying to dedup-reserve mutable memory");
461            }
462        }
463        let alloc_salt = (alloc, salt);
464        // Locking this *before* `to_alloc` also to ensure correct lock order.
465        let mut dedup = self.alloc_map.dedup.lock();
466        if let Some(&alloc_id) = dedup.get(&alloc_salt) {
467            return alloc_id;
468        }
469        let id = self.alloc_map.reserve();
470        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/interpret/mod.rs:470",
                        "rustc_middle::mir::interpret", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/interpret/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(470u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating alloc {0:?} with id {1:?}",
                                                    alloc_salt.0, id) as &dyn Value))])
            });
    } else { ; }
};debug!("creating alloc {:?} with id {id:?}", alloc_salt.0);
471        let had_previous = self.alloc_map.to_alloc.insert(id, alloc_salt.0.clone()).is_some();
472        // We just reserved, so should always be unique.
473        if !!had_previous {
    ::core::panicking::panic("assertion failed: !had_previous")
};assert!(!had_previous);
474        dedup.insert(alloc_salt, id);
475        id
476    }
477
478    /// Generates an `AllocId` for a memory allocation. If the exact same memory has been
479    /// allocated before, this will return the same `AllocId`.
480    pub fn reserve_and_set_memory_dedup(self, mem: ConstAllocation<'tcx>, salt: usize) -> AllocId {
481        self.reserve_and_set_dedup(GlobalAlloc::Memory(mem), salt)
482    }
483
484    /// Generates an `AllocId` for a static or return a cached one in case this function has been
485    /// called on the same static before.
486    pub fn reserve_and_set_static_alloc(self, static_id: DefId) -> AllocId {
487        let salt = 0; // Statics have a guaranteed unique address, no salt added.
488        self.reserve_and_set_dedup(GlobalAlloc::Static(static_id), salt)
489    }
490
491    /// Generates an `AllocId` for a function. Will get deduplicated.
492    pub fn reserve_and_set_fn_alloc(self, instance: Instance<'tcx>, salt: usize) -> AllocId {
493        self.reserve_and_set_dedup(GlobalAlloc::Function { instance }, salt)
494    }
495
496    /// Generates an `AllocId` for a (symbolic, not-reified) vtable. Will get deduplicated.
497    pub fn reserve_and_set_vtable_alloc(
498        self,
499        ty: Ty<'tcx>,
500        dyn_ty: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
501        salt: usize,
502    ) -> AllocId {
503        self.reserve_and_set_dedup(GlobalAlloc::VTable(ty, dyn_ty), salt)
504    }
505
506    /// Generates an [AllocId] for a [core::any::TypeId]. Will get deduplicated.
507    pub fn reserve_and_set_type_id_alloc(self, ty: Ty<'tcx>) -> AllocId {
508        self.reserve_and_set_dedup(GlobalAlloc::TypeId { ty }, 0)
509    }
510
511    /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
512    /// `Allocation` with a different `AllocId`.
513    /// Statics with identical content will still point to the same `Allocation`, i.e.,
514    /// their data will be deduplicated through `Allocation` interning -- but they
515    /// are different places in memory and as such need different IDs.
516    pub fn reserve_and_set_memory_alloc(self, mem: ConstAllocation<'tcx>) -> AllocId {
517        let id = self.reserve_alloc_id();
518        self.set_alloc_id_memory(id, mem);
519        id
520    }
521
522    /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
523    /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
524    /// illegal and will likely ICE.
525    /// This function exists to allow const eval to detect the difference between evaluation-
526    /// local dangling pointers and allocations in constants/statics.
527    #[inline]
528    pub fn try_get_global_alloc(self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
529        self.alloc_map.to_alloc.get(&id)
530    }
531
532    #[inline]
533    #[track_caller]
534    /// Panics in case the `AllocId` is dangling. Since that is impossible for `AllocId`s in
535    /// constants (as all constants must pass interning and validation that check for dangling
536    /// ids), this function is frequently used throughout rustc, but should not be used within
537    /// the interpreter.
538    pub fn global_alloc(self, id: AllocId) -> GlobalAlloc<'tcx> {
539        match self.try_get_global_alloc(id) {
540            Some(alloc) => alloc,
541            None => crate::util::bug::bug_fmt(format_args!("could not find allocation for {0:?}",
        id))bug!("could not find allocation for {id:?}"),
542        }
543    }
544
545    /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
546    /// call this function twice, even with the same `Allocation` will ICE the compiler.
547    pub fn set_alloc_id_memory(self, id: AllocId, mem: ConstAllocation<'tcx>) {
548        if let Some(old) = self.alloc_map.to_alloc.insert(id, GlobalAlloc::Memory(mem)) {
549            crate::util::bug::bug_fmt(format_args!("tried to set allocation ID {0:?}, but it was already existing as {1:#?}",
        id, old));bug!("tried to set allocation ID {id:?}, but it was already existing as {old:#?}");
550        }
551    }
552
553    /// Freezes an `AllocId` created with `reserve` by pointing it at a static item. Trying to
554    /// call this function twice, even with the same `DefId` will ICE the compiler.
555    pub fn set_nested_alloc_id_static(self, id: AllocId, def_id: LocalDefId) {
556        if let Some(old) =
557            self.alloc_map.to_alloc.insert(id, GlobalAlloc::Static(def_id.to_def_id()))
558        {
559            crate::util::bug::bug_fmt(format_args!("tried to set allocation ID {0:?}, but it was already existing as {1:#?}",
        id, old));bug!("tried to set allocation ID {id:?}, but it was already existing as {old:#?}");
560        }
561    }
562}
563
564////////////////////////////////////////////////////////////////////////////////
565// Methods to access integers in the target endianness
566////////////////////////////////////////////////////////////////////////////////
567
568#[inline]
569pub fn write_target_uint(
570    endianness: Endian,
571    mut target: &mut [u8],
572    data: u128,
573) -> Result<(), io::Error> {
574    // This u128 holds an "any-size uint" (since smaller uints can fits in it)
575    // So we do not write all bytes of the u128, just the "payload".
576    match endianness {
577        Endian::Little => target.write(&data.to_le_bytes())?,
578        Endian::Big => target.write(&data.to_be_bytes()[16 - target.len()..])?,
579    };
580    if true {
    if !(target.len() == 0) {
        ::core::panicking::panic("assertion failed: target.len() == 0")
    };
};debug_assert!(target.len() == 0); // We should have filled the target buffer.
581    Ok(())
582}
583
584#[inline]
585pub fn read_target_uint(endianness: Endian, mut source: &[u8]) -> Result<u128, io::Error> {
586    // This u128 holds an "any-size uint" (since smaller uints can fits in it)
587    let mut buf = [0u8; size_of::<u128>()];
588    // So we do not read exactly 16 bytes into the u128, just the "payload".
589    let uint = match endianness {
590        Endian::Little => {
591            source.read_exact(&mut buf[..source.len()])?;
592            Ok(u128::from_le_bytes(buf))
593        }
594        Endian::Big => {
595            source.read_exact(&mut buf[16 - source.len()..])?;
596            Ok(u128::from_be_bytes(buf))
597        }
598    };
599    if true {
    if !(source.len() == 0) {
        ::core::panicking::panic("assertion failed: source.len() == 0")
    };
};debug_assert!(source.len() == 0); // We should have consumed the source buffer.
600    uint
601}