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