Skip to main content

rustc_middle/ty/
layout.rs

1use std::{cmp, fmt};
2
3use rustc_abi as abi;
4use rustc_abi::{
5    AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
6    PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
7    TyAbiInterface, VariantIdx, Variants,
8};
9use rustc_errors::{
10    Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
11};
12use rustc_hir as hir;
13use rustc_hir::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
16use rustc_session::config::OptLevel;
17use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
18use rustc_target::callconv::FnAbi;
19use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
20use tracing::debug;
21
22use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
23use crate::query::TyCtxtAt;
24use crate::traits::ObligationCause;
25use crate::ty::normalize_erasing_regions::NormalizationError;
26use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
27
28impl IntegerExt for abi::Integer {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match (*self, signed) {
            (I8, false) => tcx.types.u8,
            (I16, false) => tcx.types.u16,
            (I32, false) => tcx.types.u32,
            (I64, false) => tcx.types.u64,
            (I128, false) => tcx.types.u128,
            (I8, true) => tcx.types.i8,
            (I16, true) => tcx.types.i16,
            (I32, true) => tcx.types.i32,
            (I64, true) => tcx.types.i64,
            (I128, true) => tcx.types.i128,
        }
    }
    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match ity {
            ty::IntTy::I8 => I8,
            ty::IntTy::I16 => I16,
            ty::IntTy::I32 => I32,
            ty::IntTy::I64 => I64,
            ty::IntTy::I128 => I128,
            ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
        }
    }
    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
        -> abi::Integer {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match ity {
            ty::UintTy::U8 => I8,
            ty::UintTy::U16 => I16,
            ty::UintTy::U32 => I32,
            ty::UintTy::U64 => I64,
            ty::UintTy::U128 => I128,
            ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
        }
    }
    #[doc =
    " Finds the appropriate Integer type and signedness for the given"]
    #[doc = " signed discriminant range and `#[repr]` attribute."]
    #[doc =
    " N.B.: `u128` values above `i128::MAX` will be treated as signed, but"]
    #[doc = " that shouldn\'t affect anything, other than maybe debuginfo."]
    #[doc = ""]
    #[doc =
    " This is the basis for computing the type of the *tag* of an enum (which can be smaller than"]
    #[doc =
    " the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`])."]
    fn discr_range_of_repr<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>,
        repr: &ReprOptions, min: i128, max: i128) -> (abi::Integer, bool) {
        let unsigned_fit =
            abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
        let signed_fit =
            cmp::max(abi::Integer::fit_signed(min),
                abi::Integer::fit_signed(max));
        if let Some(ity) = repr.int {
            let discr = abi::Integer::from_attr(&tcx, ity);
            let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
            if discr < fit {
                crate::util::bug::bug_fmt(format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
                        ty))
            }
            return (discr, ity.is_signed());
        }
        let at_least =
            if repr.c() {
                tcx.data_layout().c_enum_min_size
            } else { abi::Integer::I8 };
        if unsigned_fit <= signed_fit {
            (cmp::max(unsigned_fit, at_least), false)
        } else { (cmp::max(signed_fit, at_least), true) }
    }
}#[extension(pub trait IntegerExt)]
29impl abi::Integer {
30    #[inline]
31    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
32        use abi::Integer::{I8, I16, I32, I64, I128};
33        match (*self, signed) {
34            (I8, false) => tcx.types.u8,
35            (I16, false) => tcx.types.u16,
36            (I32, false) => tcx.types.u32,
37            (I64, false) => tcx.types.u64,
38            (I128, false) => tcx.types.u128,
39            (I8, true) => tcx.types.i8,
40            (I16, true) => tcx.types.i16,
41            (I32, true) => tcx.types.i32,
42            (I64, true) => tcx.types.i64,
43            (I128, true) => tcx.types.i128,
44        }
45    }
46
47    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
48        use abi::Integer::{I8, I16, I32, I64, I128};
49        match ity {
50            ty::IntTy::I8 => I8,
51            ty::IntTy::I16 => I16,
52            ty::IntTy::I32 => I32,
53            ty::IntTy::I64 => I64,
54            ty::IntTy::I128 => I128,
55            ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
56        }
57    }
58    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
59        use abi::Integer::{I8, I16, I32, I64, I128};
60        match ity {
61            ty::UintTy::U8 => I8,
62            ty::UintTy::U16 => I16,
63            ty::UintTy::U32 => I32,
64            ty::UintTy::U64 => I64,
65            ty::UintTy::U128 => I128,
66            ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
67        }
68    }
69
70    /// Finds the appropriate Integer type and signedness for the given
71    /// signed discriminant range and `#[repr]` attribute.
72    /// N.B.: `u128` values above `i128::MAX` will be treated as signed, but
73    /// that shouldn't affect anything, other than maybe debuginfo.
74    ///
75    /// This is the basis for computing the type of the *tag* of an enum (which can be smaller than
76    /// the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`]).
77    fn discr_range_of_repr<'tcx>(
78        tcx: TyCtxt<'tcx>,
79        ty: Ty<'tcx>,
80        repr: &ReprOptions,
81        min: i128,
82        max: i128,
83    ) -> (abi::Integer, bool) {
84        // Theoretically, negative values could be larger in unsigned representation
85        // than the unsigned representation of the signed minimum. However, if there
86        // are any negative values, the only valid unsigned representation is u128
87        // which can fit all i128 values, so the result remains unaffected.
88        let unsigned_fit = abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
89        let signed_fit = cmp::max(abi::Integer::fit_signed(min), abi::Integer::fit_signed(max));
90
91        if let Some(ity) = repr.int {
92            let discr = abi::Integer::from_attr(&tcx, ity);
93            let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
94            if discr < fit {
95                bug!(
96                    "Integer::repr_discr: `#[repr]` hint too small for \
97                      discriminant range of enum `{}`",
98                    ty
99                )
100            }
101            return (discr, ity.is_signed());
102        }
103
104        let at_least = if repr.c() {
105            // This is usually I32, however it can be different on some platforms,
106            // notably hexagon and arm-none/thumb-none
107            tcx.data_layout().c_enum_min_size
108        } else {
109            // repr(Rust) enums try to be as small as possible
110            abi::Integer::I8
111        };
112
113        // Pick the smallest fit. Prefer unsigned; that matches clang in cases where this makes a
114        // difference (https://godbolt.org/z/h4xEasW1d) so it is crucial for repr(C).
115        if unsigned_fit <= signed_fit {
116            (cmp::max(unsigned_fit, at_least), false)
117        } else {
118            (cmp::max(signed_fit, at_least), true)
119        }
120    }
121}
122
123impl FloatExt for abi::Float {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        use abi::Float::*;
        match *self {
            F16 => tcx.types.f16,
            F32 => tcx.types.f32,
            F64 => tcx.types.f64,
            F128 => tcx.types.f128,
        }
    }
    fn from_float_ty(fty: ty::FloatTy) -> Self {
        use abi::Float::*;
        match fty {
            ty::FloatTy::F16 => F16,
            ty::FloatTy::F32 => F32,
            ty::FloatTy::F64 => F64,
            ty::FloatTy::F128 => F128,
        }
    }
}#[extension(pub trait FloatExt)]
124impl abi::Float {
125    #[inline]
126    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
127        use abi::Float::*;
128        match *self {
129            F16 => tcx.types.f16,
130            F32 => tcx.types.f32,
131            F64 => tcx.types.f64,
132            F128 => tcx.types.f128,
133        }
134    }
135
136    fn from_float_ty(fty: ty::FloatTy) -> Self {
137        use abi::Float::*;
138        match fty {
139            ty::FloatTy::F16 => F16,
140            ty::FloatTy::F32 => F32,
141            ty::FloatTy::F64 => F64,
142            ty::FloatTy::F128 => F128,
143        }
144    }
145}
146
147impl PrimitiveExt for Primitive {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match *self {
            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
            Primitive::Float(f) => f.to_ty(tcx),
            Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
        }
    }
    #[doc = " Return an *integer* type matching this primitive."]
    #[doc = " Useful in particular when dealing with enum discriminants."]
    #[inline]
    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match *self {
            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
            Primitive::Pointer(_) => {
                let signed = false;
                tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
            }
            Primitive::Float(_) =>
                crate::util::bug::bug_fmt(format_args!("floats do not have an int type")),
        }
    }
}#[extension(pub trait PrimitiveExt)]
148impl Primitive {
149    #[inline]
150    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
151        match *self {
152            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
153            Primitive::Float(f) => f.to_ty(tcx),
154            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
155            Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
156        }
157    }
158
159    /// Return an *integer* type matching this primitive.
160    /// Useful in particular when dealing with enum discriminants.
161    #[inline]
162    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
163        match *self {
164            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
165            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
166            Primitive::Pointer(_) => {
167                let signed = false;
168                tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
169            }
170            Primitive::Float(_) => bug!("floats do not have an int type"),
171        }
172    }
173}
174
175/// The first half of a wide pointer.
176///
177/// - For a trait object, this is the address of the box.
178/// - For a slice, this is the base address.
179pub const WIDE_PTR_ADDR: usize = 0;
180
181/// The second half of a wide pointer.
182///
183/// - For a trait object, this is the address of the vtable.
184/// - For a slice, this is the length.
185pub const WIDE_PTR_EXTRA: usize = 1;
186
187pub const MAX_SIMD_LANES: u64 = rustc_abi::MAX_SIMD_LANES;
188
189/// Used in `check_validity_requirement` to indicate the kind of initialization
190/// that is checked to be valid
191#[derive(#[automatically_derived]
impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ValidityRequirement {
    #[inline]
    fn clone(&self) -> ValidityRequirement { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ValidityRequirement {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ValidityRequirement::Inhabited => "Inhabited",
                ValidityRequirement::Zero => "Zero",
                ValidityRequirement::UninitMitigated0x01Fill =>
                    "UninitMitigated0x01Fill",
                ValidityRequirement::Uninit => "Uninit",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ValidityRequirement {
    #[inline]
    fn eq(&self, other: &ValidityRequirement) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ValidityRequirement {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ValidityRequirement {
    #[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)
    }
}Hash, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            ValidityRequirement {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    ValidityRequirement::Inhabited => {}
                    ValidityRequirement::Zero => {}
                    ValidityRequirement::UninitMitigated0x01Fill => {}
                    ValidityRequirement::Uninit => {}
                }
            }
        }
    };StableHash)]
192pub enum ValidityRequirement {
193    Inhabited,
194    Zero,
195    /// The return value of mem::uninitialized, 0x01
196    /// (unless -Zstrict-init-checks is on, in which case it's the same as Uninit).
197    UninitMitigated0x01Fill,
198    /// True uninitialized memory.
199    Uninit,
200}
201
202impl ValidityRequirement {
203    pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
204        match intrinsic {
205            sym::assert_inhabited => Some(Self::Inhabited),
206            sym::assert_zero_valid => Some(Self::Zero),
207            sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
208            _ => None,
209        }
210    }
211}
212
213impl fmt::Display for ValidityRequirement {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        match self {
216            Self::Inhabited => f.write_str("is inhabited"),
217            Self::Zero => f.write_str("allows being left zeroed"),
218            Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
219            Self::Uninit => f.write_str("allows being left uninitialized"),
220        }
221    }
222}
223
224#[derive(#[automatically_derived]
impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SimdLayoutError {
    #[inline]
    fn clone(&self) -> SimdLayoutError {
        let _: ::core::clone::AssertParamIsClone<u64>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SimdLayoutError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SimdLayoutError::ZeroLength =>
                ::core::fmt::Formatter::write_str(f, "ZeroLength"),
            SimdLayoutError::TooManyLanes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TooManyLanes", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            SimdLayoutError {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    SimdLayoutError::ZeroLength => {}
                    SimdLayoutError::TooManyLanes(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for SimdLayoutError {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        SimdLayoutError::ZeroLength => { 0usize }
                        SimdLayoutError::TooManyLanes(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    SimdLayoutError::ZeroLength => {}
                    SimdLayoutError::TooManyLanes(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for SimdLayoutError {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { SimdLayoutError::ZeroLength }
                    1usize => {
                        SimdLayoutError::TooManyLanes(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SimdLayoutError`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable)]
225pub enum SimdLayoutError {
226    /// The vector has 0 lanes.
227    ZeroLength,
228    /// The vector has more lanes than supported or permitted by
229    /// #\[rustc_simd_monomorphize_lane_limit\].
230    TooManyLanes(u64),
231}
232
233#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutError<'tcx> {
    #[inline]
    fn clone(&self) -> LayoutError<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<SimdLayoutError>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<NormalizationError<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LayoutError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LayoutError::Unknown(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Unknown", &__self_0),
            LayoutError::SizeOverflow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SizeOverflow", &__self_0),
            LayoutError::InvalidSimd { ty: __self_0, kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "InvalidSimd", "ty", __self_0, "kind", &__self_1),
            LayoutError::TooGeneric(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TooGeneric", &__self_0),
            LayoutError::NormalizationFailure(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "NormalizationFailure", __self_0, &__self_1),
            LayoutError::ReferencesError(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ReferencesError", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            LayoutError<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    LayoutError::Unknown(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::SizeOverflow(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::InvalidSimd {
                        ty: ref __binding_0, kind: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::TooGeneric(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::NormalizationFailure(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::ReferencesError(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for LayoutError<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        LayoutError::Unknown(ref __binding_0) => { 0usize }
                        LayoutError::SizeOverflow(ref __binding_0) => { 1usize }
                        LayoutError::InvalidSimd {
                            ty: ref __binding_0, kind: ref __binding_1 } => {
                            2usize
                        }
                        LayoutError::TooGeneric(ref __binding_0) => { 3usize }
                        LayoutError::NormalizationFailure(ref __binding_0,
                            ref __binding_1) => {
                            4usize
                        }
                        LayoutError::ReferencesError(ref __binding_0) => { 5usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    LayoutError::Unknown(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::SizeOverflow(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::InvalidSimd {
                        ty: ref __binding_0, kind: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    LayoutError::TooGeneric(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::NormalizationFailure(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    LayoutError::ReferencesError(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for LayoutError<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        LayoutError::Unknown(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        LayoutError::SizeOverflow(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        LayoutError::InvalidSimd {
                            ty: ::rustc_serialize::Decodable::decode(__decoder),
                            kind: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    3usize => {
                        LayoutError::TooGeneric(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    4usize => {
                        LayoutError::NormalizationFailure(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    5usize => {
                        LayoutError::ReferencesError(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `LayoutError`, expected 0..6, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable)]
234pub enum LayoutError<'tcx> {
235    /// A type doesn't have a sensible layout.
236    ///
237    /// This variant is used for layout errors that don't necessarily cause
238    /// compile errors.
239    ///
240    /// For example, this can happen if a struct contains an unsized type in a
241    /// non-tail field, but has an unsatisfiable bound like `str: Sized`.
242    Unknown(Ty<'tcx>),
243    /// The size of a type exceeds [`TargetDataLayout::obj_size_bound`].
244    SizeOverflow(Ty<'tcx>),
245    /// A SIMD vector has invalid layout, such as zero-length or too many lanes.
246    InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
247    /// The layout can vary due to a generic parameter.
248    ///
249    /// Unlike `Unknown`, this variant is a "soft" error and indicates that the layout
250    /// may become computable after further instantiating the generic parameter(s).
251    TooGeneric(Ty<'tcx>),
252    /// An alias failed to normalize.
253    ///
254    /// This variant is necessary, because, due to trait solver incompleteness, it is
255    /// possible than an alias that was rigid during analysis fails to normalize after
256    /// revealing opaque types.
257    ///
258    /// See `tests/ui/layout/normalization-failure.rs` for an example.
259    NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
260    /// A non-layout error is reported elsewhere.
261    ReferencesError(ErrorGuaranteed),
262}
263
264impl<'tcx> fmt::Display for LayoutError<'tcx> {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        match *self {
267            LayoutError::Unknown(ty) => f.write_fmt(format_args!("the type `{0}` has an unknown layout", ty))write!(f, "the type `{ty}` has an unknown layout"),
268            LayoutError::TooGeneric(ty) => {
269                f.write_fmt(format_args!("the type `{0}` does not have a fixed layout", ty))write!(f, "the type `{ty}` does not have a fixed layout")
270            }
271            LayoutError::SizeOverflow(ty) => {
272                f.write_fmt(format_args!("values of the type `{0}` are too big for the target architecture",
        ty))write!(f, "values of the type `{ty}` are too big for the target architecture")
273            }
274            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
275                f.write_fmt(format_args!("the SIMD type `{0}` has more elements than the limit {1}",
        ty, max_lanes))write!(f, "the SIMD type `{ty}` has more elements than the limit {max_lanes}")
276            }
277            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
278                f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
279            }
280            LayoutError::NormalizationFailure(t, e) => f.write_fmt(format_args!("unable to determine layout for `{0}` because `{1}` cannot be normalized",
        t, e.get_type_for_failure()))write!(
281                f,
282                "unable to determine layout for `{}` because `{}` cannot be normalized",
283                t,
284                e.get_type_for_failure()
285            ),
286            LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
287        }
288    }
289}
290
291impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
292    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
293        self.to_string().into_diag_arg(&mut None)
294    }
295}
296
297#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
    #[inline]
    fn clone(&self) -> LayoutCx<'tcx> {
        let _:
                ::core::clone::AssertParamIsClone<abi::LayoutCalculator<TyCtxt<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<ty::TypingEnv<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutCx<'tcx> { }Copy)]
298pub struct LayoutCx<'tcx> {
299    pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
300    pub typing_env: ty::TypingEnv<'tcx>,
301}
302
303impl<'tcx> LayoutCx<'tcx> {
304    pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
305        Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
306    }
307}
308
309/// Type size "skeleton", i.e., the only information determining a type's size.
310/// While this is conservative, (aside from constant sizes, only pointers,
311/// newtypes thereof and null pointer optimized enums are allowed), it is
312/// enough to statically check common use cases of transmute.
313#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for SizeSkeleton<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx> {
    #[inline]
    fn clone(&self) -> SizeSkeleton<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Size>;
        let _: ::core::clone::AssertParamIsClone<Option<Align>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SizeSkeleton<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SizeSkeleton::Known(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Known",
                    __self_0, &__self_1),
            SizeSkeleton::Pointer { non_zero: __self_0, tail: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Pointer", "non_zero", __self_0, "tail", &__self_1),
        }
    }
}Debug)]
314pub enum SizeSkeleton<'tcx> {
315    /// Any statically computable Layout.
316    /// Alignment can be `None` if unknown.
317    Known(Size, Option<Align>),
318
319    /// A potentially-wide pointer.
320    Pointer {
321        /// If true, this pointer is never null.
322        non_zero: bool,
323        /// The type which determines the unsized metadata, if any,
324        /// of this pointer. Either a type parameter or a projection
325        /// depending on one, with regions erased.
326        tail: Ty<'tcx>,
327    },
328}
329
330impl<'tcx> SizeSkeleton<'tcx> {
331    pub fn compute(
332        ty: Ty<'tcx>,
333        tcx: TyCtxt<'tcx>,
334        typing_env: ty::TypingEnv<'tcx>,
335        span: Span,
336    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
337        Self::compute_inner(ty, tcx, typing_env, span, 0)
338    }
339
340    fn compute_inner(
341        ty: Ty<'tcx>,
342        tcx: TyCtxt<'tcx>,
343        typing_env: ty::TypingEnv<'tcx>,
344        span: Span,
345        depth: usize,
346    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
347        if true {
    if !!ty.has_non_region_infer() {
        ::core::panicking::panic("assertion failed: !ty.has_non_region_infer()")
    };
};debug_assert!(!ty.has_non_region_infer());
348
349        // Bail out if we've recursed too deeply (issue #156137); a cyclic type
350        // alias can otherwise blow the stack here. Using `>=` rather than `>`
351        // means we fire exactly at the limit, which lets us report the
352        // cycle-root type (`Thing<T>`) instead of an innocent field type.
353        let recursion_limit = tcx.recursion_limit();
354        if depth >= recursion_limit.0 {
355            let suggested_limit = match recursion_limit {
356                hir::limit::Limit(0) => hir::limit::Limit(2),
357                limit => limit * 2,
358            };
359            let reported = tcx.dcx().emit_err(crate::error::RecursionLimitReachedSizeSkeleton {
360                span,
361                ty,
362                suggested_limit,
363            });
364            return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
365        }
366
367        // First try computing a static layout.
368        let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
369            Ok(layout) => {
370                if layout.is_sized() {
371                    return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
372                } else {
373                    // Just to be safe, don't claim a known layout for unsized types.
374                    return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
375                }
376            }
377            Err(err @ LayoutError::TooGeneric(_)) => err,
378            // We can't extract SizeSkeleton info from other layout errors
379            Err(
380                e @ LayoutError::Unknown(_)
381                | e @ LayoutError::SizeOverflow(_)
382                | e @ LayoutError::InvalidSimd { .. }
383                | e @ LayoutError::NormalizationFailure(..)
384                | e @ LayoutError::ReferencesError(_),
385            ) => return Err(e),
386        };
387
388        match *ty.kind() {
389            ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
390                let non_zero = !ty.is_raw_ptr();
391
392                tcx.assert_fully_normalized(typing_env, pointee);
393                let tail = tcx.struct_tail_raw(
394                    pointee,
395                    &ObligationCause::dummy(),
396                    |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
397                        Ok(ty) => ty,
398                        Err(e) => Ty::new_error_with_message(
399                            tcx,
400                            DUMMY_SP,
401                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
                e.get_type_for_failure()))
    })format!(
402                                "normalization failed for {} but no errors reported",
403                                e.get_type_for_failure()
404                            ),
405                        ),
406                    },
407                    || {},
408                );
409
410                match tail.kind() {
411                    ty::Param(_)
412                    | ty::Alias(ty::AliasTy {
413                        kind: ty::Projection { .. } | ty::Inherent { .. },
414                        ..
415                    }) => {
416                        if true {
    if !tail.has_non_region_param() {
        ::core::panicking::panic("assertion failed: tail.has_non_region_param()")
    };
};debug_assert!(tail.has_non_region_param());
417                        Ok(SizeSkeleton::Pointer {
418                            non_zero,
419                            tail: tcx.erase_and_anonymize_regions(tail),
420                        })
421                    }
422                    ty::Error(guar) => {
423                        // Fixes ICE #124031
424                        return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
425                    }
426                    _ => crate::util::bug::bug_fmt(format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
        ty, err, tail))bug!(
427                        "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
428                              tail `{tail}` is not a type parameter or a projection",
429                    ),
430                }
431            }
432            ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
433                let len_eval = len.try_to_target_usize(tcx);
434                if len_eval == Some(0) {
435                    return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
436                }
437
438                match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
439                    // This may succeed because the multiplication of two types may overflow
440                    // but a single size of a nested array will not.
441                    SizeSkeleton::Known(s, a) => {
442                        if let Some(c) = len_eval {
443                            let size = s
444                                .bytes()
445                                .checked_mul(c)
446                                .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
447                            // Alignment is unchanged by arrays.
448                            return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
449                        }
450                        Err(err)
451                    }
452                    SizeSkeleton::Pointer { .. } => Err(err),
453                }
454            }
455
456            ty::Adt(def, args) => {
457                // Only newtypes and enums w/ nullable pointer optimization (NPO).
458                if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
459                    return Err(err);
460                }
461                // Only default repr types.
462                {
463                    // We can ignore the seed and some particular flags that can never affect the
464                    // layout of newtypes / NPO types, but we have to check everything else.
465                    // If you are adding a new field to `ReprOptions`, make sure to extend the check
466                    // below so that we bail out if it is not at its default value!
467                    let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
468                        def.repr();
469                    let mut ignored_flags = ReprFlags::IS_TRANSPARENT
470                        | ReprFlags::IS_LINEAR
471                        | ReprFlags::RANDOMIZE_LAYOUT;
472                    if def.is_struct() {
473                        // `repr(C)` is only okay for structs, not for enums.
474                        // Below, the *only* thing we do for structs is propagating
475                        // `SizeSkeleton::Pointer`. We do *not* assume that `repr(C)` preserved
476                        // ZST-ness (which might stop being true eventually).
477                        ignored_flags |= ReprFlags::IS_C;
478                    }
479                    if int.is_some()
480                        || align.is_some()
481                        || pack.is_some()
482                        || flags.difference(ignored_flags) != ReprFlags::default()
483                        || scalable.is_some()
484                    {
485                        return Err(err);
486                    }
487                }
488
489                // Get a zero-sized variant or a pointer newtype.
490                // Returns `Ok(None)` for 1-ZST types, `Ok(Some)` if (ignoring all 1-ZST fields)
491                // there's just a single pointer, and `Err` otherwise.
492                let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
493                    let i = VariantIdx::from_usize(i);
494                    let fields = def.variant(i).fields.iter().map(|field| {
495                        SizeSkeleton::compute_inner(
496                            field.ty(tcx, args).skip_norm_wip(),
497                            tcx,
498                            typing_env,
499                            span,
500                            depth + 1,
501                        )
502                    });
503                    let mut ptr = None;
504                    for field in fields {
505                        let field = field?;
506                        match field {
507                            SizeSkeleton::Known(size, align) => {
508                                let is_1zst = size.bytes() == 0
509                                    && align.is_some_and(|align| align.bytes() == 1);
510                                if !is_1zst {
511                                    return Err(err);
512                                }
513                            }
514                            SizeSkeleton::Pointer { .. } => {
515                                if ptr.is_some() {
516                                    return Err(err);
517                                }
518                                ptr = Some(field);
519                            }
520                        }
521                    }
522                    Ok(ptr)
523                };
524
525                let v0 = zero_or_ptr_variant(0)?;
526                // Single-variant case: Check if this is a newtype around a pointer.
527                // Such types are themselves pointer-sized.
528                if def.variants().len() == 1 {
529                    if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
530                        return Ok(SizeSkeleton::Pointer { non_zero, tail });
531                    } else {
532                        return Err(err);
533                    }
534                }
535
536                let v1 = zero_or_ptr_variant(1)?;
537                // 2-variant case: Check if one variant is a *non-zero* pointer and the other a
538                // 1-ZST. Such types are eligible to for the nullable pointer enum optimization, so
539                // they are themselves pointer-sized.
540                match (v0, v1) {
541                    (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
542                    | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
543                        Ok(SizeSkeleton::Pointer { non_zero: false, tail })
544                    }
545                    _ => Err(err),
546                }
547            }
548
549            ty::Alias(..) => {
550                let normalized =
551                    tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
552                if ty == normalized {
553                    Err(err)
554                } else {
555                    SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
556                }
557            }
558
559            ty::Pat(base, pat) => {
560                // Pattern types are always the same size as their base.
561                let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
562                match *pat {
563                    ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
564                    // But in the case of `!null` patterns we need to note that in the
565                    // raw pointer.
566                    ty::PatternKind::NotNull => match base? {
567                        SizeSkeleton::Known(..) => base,
568                        SizeSkeleton::Pointer { non_zero: _, tail } => {
569                            Ok(SizeSkeleton::Pointer { non_zero: true, tail })
570                        }
571                    },
572                }
573            }
574
575            _ => Err(err),
576        }
577    }
578
579    pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
580        match (self, other) {
581            (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
582            (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
583                a == b
584            }
585            _ => false,
586        }
587    }
588}
589
590pub trait HasTyCtxt<'tcx>: HasDataLayout {
591    fn tcx(&self) -> TyCtxt<'tcx>;
592}
593
594pub trait HasTypingEnv<'tcx> {
595    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
596}
597
598impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
599    #[inline]
600    fn data_layout(&self) -> &TargetDataLayout {
601        &self.data_layout
602    }
603}
604
605impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
606    fn target_spec(&self) -> &Target {
607        &self.sess.target
608    }
609}
610
611impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
612    fn x86_abi_opt(&self) -> X86Abi {
613        X86Abi {
614            regparm: self.sess.opts.unstable_opts.regparm,
615            reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
616        }
617    }
618}
619
620impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
621    #[inline]
622    fn tcx(&self) -> TyCtxt<'tcx> {
623        *self
624    }
625}
626
627impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
628    #[inline]
629    fn data_layout(&self) -> &TargetDataLayout {
630        &self.data_layout
631    }
632}
633
634impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
635    fn target_spec(&self) -> &Target {
636        &self.sess.target
637    }
638}
639
640impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
641    #[inline]
642    fn tcx(&self) -> TyCtxt<'tcx> {
643        **self
644    }
645}
646
647impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
648    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
649        self.typing_env
650    }
651}
652
653impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
654    fn data_layout(&self) -> &TargetDataLayout {
655        self.calc.cx.data_layout()
656    }
657}
658
659impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
660    fn target_spec(&self) -> &Target {
661        self.calc.cx.target_spec()
662    }
663}
664
665impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
666    fn x86_abi_opt(&self) -> X86Abi {
667        self.calc.cx.x86_abi_opt()
668    }
669}
670
671impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
672    fn tcx(&self) -> TyCtxt<'tcx> {
673        self.calc.cx
674    }
675}
676
677pub trait MaybeResult<T> {
678    type Error;
679
680    fn from(x: Result<T, Self::Error>) -> Self;
681    fn to_result(self) -> Result<T, Self::Error>;
682}
683
684impl<T> MaybeResult<T> for T {
685    type Error = !;
686
687    fn from(Ok(x): Result<T, Self::Error>) -> Self {
688        x
689    }
690    fn to_result(self) -> Result<T, Self::Error> {
691        Ok(self)
692    }
693}
694
695impl<T, E> MaybeResult<T> for Result<T, E> {
696    type Error = E;
697
698    fn from(x: Result<T, Self::Error>) -> Self {
699        x
700    }
701    fn to_result(self) -> Result<T, Self::Error> {
702        self
703    }
704}
705
706pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
707
708/// Trait for contexts that want to be able to compute layouts of types.
709/// This automatically gives access to `LayoutOf`, through a blanket `impl`.
710pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
711    /// The `TyAndLayout`-wrapping type (or `TyAndLayout` itself), which will be
712    /// returned from `layout_of` (see also `handle_layout_err`).
713    type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
714
715    /// `Span` to use for `tcx.at(span)`, from `layout_of`.
716    // FIXME(eddyb) perhaps make this mandatory to get contexts to track it better?
717    #[inline]
718    fn layout_tcx_at_span(&self) -> Span {
719        DUMMY_SP
720    }
721
722    /// Helper used for `layout_of`, to adapt `tcx.layout_of(...)` into a
723    /// `Self::LayoutOfResult` (which does not need to be a `Result<...>`).
724    ///
725    /// Most `impl`s, which propagate `LayoutError`s, should simply return `err`,
726    /// but this hook allows e.g. codegen to return only `TyAndLayout` from its
727    /// `cx.layout_of(...)`, without any `Result<...>` around it to deal with
728    /// (and any `LayoutError`s are turned into fatal errors or ICEs).
729    fn handle_layout_err(
730        &self,
731        err: LayoutError<'tcx>,
732        span: Span,
733        ty: Ty<'tcx>,
734    ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
735}
736
737/// Blanket extension trait for contexts that can compute layouts of types.
738pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
739    /// Computes the layout of a type. Note that this implicitly
740    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
741    #[inline]
742    fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
743        self.spanned_layout_of(ty, DUMMY_SP)
744    }
745
746    /// Computes the layout of a type, at `span`. Note that this implicitly
747    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
748    // FIXME(eddyb) avoid passing information like this, and instead add more
749    // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`.
750    #[inline]
751    fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
752        let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
753        let tcx = self.tcx().at(span);
754
755        MaybeResult::from(
756            tcx.layout_of(self.typing_env().as_query_input(ty))
757                .map_err(|err| self.handle_layout_err(*err, span, ty)),
758        )
759    }
760}
761
762impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
763
764impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
765    type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
766
767    #[inline]
768    fn handle_layout_err(
769        &self,
770        err: LayoutError<'tcx>,
771        _: Span,
772        _: Ty<'tcx>,
773    ) -> &'tcx LayoutError<'tcx> {
774        self.tcx().arena.alloc(err)
775    }
776}
777
778impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
779where
780    C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
781{
782    fn ty_and_layout_for_variant(
783        this: TyAndLayout<'tcx>,
784        cx: &C,
785        variant_index: VariantIdx,
786    ) -> TyAndLayout<'tcx> {
787        let layout = match this.variants {
788            // If all variants but one are uninhabited, the variant layout is the enum layout.
789            Variants::Single { index } if index == variant_index => {
790                return this;
791            }
792
793            Variants::Single { .. } | Variants::Empty => {
794                // Single-variant and no-variant enums *can* have other variants, but those are
795                // uninhabited. Produce a layout that has the right fields for that variant, so that
796                // the rest of the compiler can project fields etc as usual.
797
798                let tcx = cx.tcx();
799                let typing_env = cx.typing_env();
800
801                // Deny calling for_variant more than once for non-Single enums.
802                if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
803                    match (&original_layout.variants, &this.variants) {
    (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!(original_layout.variants, this.variants);
804                }
805
806                let fields = match this.ty.kind() {
807                    ty::Adt(def, _) if def.variants().is_empty() => {
808                        crate::util::bug::bug_fmt(format_args!("for_variant called on zero-variant enum {0}",
        this.ty))bug!("for_variant called on zero-variant enum {}", this.ty)
809                    }
810                    ty::Adt(def, _) => def.variant(variant_index).fields.len(),
811                    _ => crate::util::bug::bug_fmt(format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
        this.ty))bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
812                };
813                tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
814            }
815
816            Variants::Multiple { .. } => {
817                cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
818            }
819        };
820
821        match (&*layout.variants(), &Variants::Single { index: variant_index }) {
    (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!(*layout.variants(), Variants::Single { index: variant_index });
822
823        TyAndLayout { ty: this.ty, layout }
824    }
825
826    fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
827        enum TyMaybeWithLayout<'tcx> {
828            Ty(Ty<'tcx>),
829            TyAndLayout(TyAndLayout<'tcx>),
830        }
831
832        fn field_ty_or_layout<'tcx>(
833            this: TyAndLayout<'tcx>,
834            cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
835            i: usize,
836        ) -> TyMaybeWithLayout<'tcx> {
837            let tcx = cx.tcx();
838            let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
839                TyAndLayout {
840                    layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
841                    ty: tag.primitive().to_ty(tcx),
842                }
843            };
844
845            match *this.ty.kind() {
846                ty::Bool
847                | ty::Char
848                | ty::Int(_)
849                | ty::Uint(_)
850                | ty::Float(_)
851                | ty::FnPtr(..)
852                | ty::Never
853                | ty::FnDef(..)
854                | ty::CoroutineWitness(..)
855                | ty::Foreign(..)
856                | ty::Dynamic(_, _) => {
857                    crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
        this))bug!("TyAndLayout::field({:?}): not applicable", this)
858                }
859
860                ty::Pat(base, _) => {
861                    match (&i, &0) {
    (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!(i, 0);
862                    TyMaybeWithLayout::Ty(base)
863                }
864
865                ty::UnsafeBinder(bound_ty) => {
866                    let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
867                    field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
868                }
869
870                // Potentially-wide pointers.
871                ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
872                    if !(i < this.fields.count()) {
    ::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
873
874                    // Reuse the wide `*T` type as its own thin pointer data field.
875                    // This provides information about, e.g., DST struct pointees
876                    // (which may have no non-DST form), and will work as long
877                    // as the `Abi` or `FieldsShape` is checked by users.
878                    if i == 0 {
879                        let nil = tcx.types.unit;
880                        let unit_ptr_ty = if this.ty.is_raw_ptr() {
881                            Ty::new_mut_ptr(tcx, nil)
882                        } else {
883                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
884                        };
885
886                        // NOTE: using an fully monomorphized typing env and `unwrap`-ing
887                        // the `Result` should always work because the type is always either
888                        // `*mut ()` or `&'static mut ()`.
889                        let typing_env = ty::TypingEnv::fully_monomorphized();
890                        return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
891                            ty: this.ty,
892                            ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
893                        });
894                    }
895
896                    let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
897                        let min_count = ty::vtable_min_entries(
898                            tcx,
899                            principal.map(|principal| {
900                                tcx.instantiate_bound_regions_with_erased(principal)
901                            }),
902                        );
903                        Ty::new_imm_ref(
904                            tcx,
905                            tcx.lifetimes.re_static,
906                            // FIXME: properly type (e.g. usize and fn pointers) the fields.
907                            Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
908                        )
909                    };
910
911                    let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
912                        // Projection eagerly bails out when the pointee references errors,
913                        // fall back to structurally deducing metadata.
914                        && !pointee.references_error()
915                    {
916                        let metadata = tcx.normalize_erasing_regions(
917                            cx.typing_env(),
918                            Unnormalized::new(Ty::new_projection(tcx, metadata_def_id, [pointee])),
919                        );
920
921                        // Map `Metadata = DynMetadata<dyn Trait>` back to a vtable, since it
922                        // offers better information than `std::ptr::metadata::VTable`,
923                        // and we rely on this layout information to trigger a panic in
924                        // `std::mem::uninitialized::<&dyn Trait>()`, for example.
925                        if let ty::Adt(def, args) = metadata.kind()
926                            && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
927                            && let ty::Dynamic(data, _) = args.type_at(0).kind()
928                        {
929                            mk_dyn_vtable(data.principal())
930                        } else {
931                            metadata
932                        }
933                    } else {
934                        match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
935                            ty::Slice(_) | ty::Str => tcx.types.usize,
936                            ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
937                            _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
        this))bug!("TyAndLayout::field({:?}): not applicable", this),
938                        }
939                    };
940
941                    TyMaybeWithLayout::Ty(metadata)
942                }
943
944                // Arrays and slices.
945                ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
946                ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
947
948                // Tuples, coroutines and closures.
949                ty::Closure(_, args) => field_ty_or_layout(
950                    TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
951                    cx,
952                    i,
953                ),
954
955                ty::CoroutineClosure(_, args) => field_ty_or_layout(
956                    TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
957                    cx,
958                    i,
959                ),
960
961                ty::Coroutine(def_id, args) => match this.variants {
962                    Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
963                    Variants::Single { index } => TyMaybeWithLayout::Ty(
964                        args.as_coroutine()
965                            .state_tys(def_id, tcx)
966                            .nth(index.as_usize())
967                            .unwrap()
968                            .nth(i)
969                            .unwrap(),
970                    ),
971                    Variants::Multiple { tag, tag_field, .. } => {
972                        if FieldIdx::from_usize(i) == tag_field {
973                            return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
974                        }
975                        TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i])
976                    }
977                },
978
979                ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
980
981                // ADTs.
982                ty::Adt(def, args) => {
983                    match this.variants {
984                        Variants::Single { index } => {
985                            let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
986                            TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
987                        }
988                        Variants::Empty => {
    ::core::panicking::panic_fmt(format_args!("there is no field in Variants::Empty types"));
}panic!("there is no field in Variants::Empty types"),
989
990                        // Discriminant field for enums (where applicable).
991                        Variants::Multiple { tag, .. } => {
992                            match (&i, &0) {
    (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!(i, 0);
993                            return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
994                        }
995                    }
996                }
997
998                ty::Alias(..)
999                | ty::Bound(..)
1000                | ty::Placeholder(..)
1001                | ty::Param(_)
1002                | ty::Infer(_)
1003                | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
        this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1004            }
1005        }
1006
1007        match field_ty_or_layout(this, cx, i) {
1008            TyMaybeWithLayout::Ty(field_ty) => {
1009                cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1010                    crate::util::bug::bug_fmt(format_args!("failed to get layout for `{0}`: {1:?},\ndespite it being a field (#{2}) of an existing layout: {3:#?}",
        field_ty, e, i, this))bug!(
1011                        "failed to get layout for `{field_ty}`: {e:?},\n\
1012                         despite it being a field (#{i}) of an existing layout: {this:#?}",
1013                    )
1014                })
1015            }
1016            TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1017        }
1018    }
1019
1020    /// Compute the information for the pointer stored at the given offset inside this type.
1021    /// This will recurse into fields of ADTs to find the inner pointer.
1022    fn ty_and_layout_pointee_info_at(
1023        this: TyAndLayout<'tcx>,
1024        cx: &C,
1025        offset: Size,
1026    ) -> Option<PointeeInfo> {
1027        let tcx = cx.tcx();
1028        let typing_env = cx.typing_env();
1029
1030        // Use conservative pointer kind if not optimizing. This saves us the
1031        // Freeze/Unpin queries, and can save time in the codegen backend (noalias
1032        // attributes in LLVM have compile-time cost even in unoptimized builds).
1033        let optimize = tcx.sess.opts.optimize != OptLevel::No;
1034
1035        let pointee_info = match *this.ty.kind() {
1036            ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1037                Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1038            }
1039            ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1040                tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1041                    let kind = match mt {
1042                        hir::Mutability::Not => {
1043                            let frozen = optimize && ty.is_freeze(tcx, typing_env);
1044                            PointerKind::SharedRef { frozen }
1045                        }
1046                        hir::Mutability::Mut => {
1047                            let unpin = optimize
1048                                && ty.is_unpin(tcx, typing_env)
1049                                && ty.is_unsafe_unpin(tcx, typing_env);
1050                            PointerKind::MutableRef { unpin }
1051                        }
1052                    };
1053                    PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1054                })
1055            }
1056
1057            ty::Adt(..)
1058                if offset.bytes() == 0
1059                    && let Some(pointee) = this.ty.boxed_ty() =>
1060            {
1061                tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1062                    safe: Some(PointerKind::Box {
1063                        // Same logic as for mutable references above.
1064                        unpin: optimize
1065                            && pointee.is_unpin(tcx, typing_env)
1066                            && pointee.is_unsafe_unpin(tcx, typing_env),
1067                        global: this.ty.is_box_global(tcx),
1068                    }),
1069                    size: layout.size,
1070                    align: layout.align.abi,
1071                })
1072            }
1073
1074            ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1075                Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1076                    PointeeInfo {
1077                        // Mark the pointer as raw
1078                        // (thus removing noalias/readonly/etc in case of the llvm backend)
1079                        safe: None,
1080                        // Make sure we don't assert dereferenceability of the pointer.
1081                        size: Size::ZERO,
1082                        // Preserve the alignment assertion! That is required even inside `MaybeDangling`.
1083                        align: info.align,
1084                    }
1085                })
1086            }
1087
1088            _ => {
1089                let mut data_variant = match &this.variants {
1090                    // Within the discriminant field, only the niche itself is
1091                    // always initialized, so we only check for a pointer at its
1092                    // offset.
1093                    //
1094                    // Our goal here is to check whether this represents a
1095                    // "dereferenceable or null" pointer, so we need to ensure
1096                    // that there is only one other variant, and it must be null.
1097                    // Below, we will then check whether the pointer is indeed
1098                    // dereferenceable.
1099                    Variants::Multiple {
1100                        tag_encoding:
1101                            TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1102                        tag_field,
1103                        variants,
1104                        ..
1105                    } if variants.len() == 2
1106                        && this.fields.offset(tag_field.as_usize()) == offset =>
1107                    {
1108                        let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1109                            VariantIdx::from_u32(1)
1110                        } else {
1111                            VariantIdx::from_u32(0)
1112                        };
1113                        match (&tagged_variant, &niche_variants.start) {
    (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!(tagged_variant, niche_variants.start);
1114                        if *niche_start == 0 {
1115                            // The other variant is encoded as "null", so we can recurse searching for
1116                            // a pointer here. This relies on the fact that the codegen backend
1117                            // only adds "dereferenceable" if there's also a "nonnull" proof,
1118                            // and that null is aligned for all alignments so it's okay to forward
1119                            // the pointer's alignment.
1120                            Some(this.for_variant(cx, *untagged_variant))
1121                        } else {
1122                            None
1123                        }
1124                    }
1125                    Variants::Multiple { .. } => None,
1126                    Variants::Empty | Variants::Single { .. } => Some(this),
1127                };
1128
1129                if let Some(variant) = data_variant
1130                    // We're not interested in any unions.
1131                    && let FieldsShape::Union(_) = variant.fields
1132                {
1133                    data_variant = None;
1134                }
1135
1136                let mut result = None;
1137
1138                if let Some(variant) = data_variant {
1139                    // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1140                    // (requires passing in the expected address space from the caller)
1141                    let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1142                    for i in 0..variant.fields.count() {
1143                        let field_start = variant.fields.offset(i);
1144                        if field_start <= offset {
1145                            let field = variant.field(cx, i);
1146                            result = field.to_result().ok().and_then(|field| {
1147                                if ptr_end <= field_start + field.size {
1148                                    // We found the right field, look inside it.
1149                                    let field_info =
1150                                        field.pointee_info_at(cx, offset - field_start);
1151                                    field_info
1152                                } else {
1153                                    None
1154                                }
1155                            });
1156                            if result.is_some() {
1157                                break;
1158                            }
1159                        }
1160                    }
1161                }
1162
1163                result
1164            }
1165        };
1166
1167        {
    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/ty/layout.rs:1167",
                        "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1167u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                        ::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!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
                                                    offset, this.ty.kind(), pointee_info) as &dyn Value))])
            });
    } else { ; }
};debug!(
1168            "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1169            offset,
1170            this.ty.kind(),
1171            pointee_info
1172        );
1173
1174        pointee_info
1175    }
1176
1177    fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1178        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1179    }
1180
1181    fn is_never(this: TyAndLayout<'tcx>) -> bool {
1182        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(this.ty.kind(), ty::Never)
1183    }
1184
1185    fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1186        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1187    }
1188
1189    fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1190        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Tuple(list) if list.len() == 0 => true,
    _ => false,
}matches!(this.ty.kind(), ty::Tuple(list) if list.len() == 0)
1191    }
1192
1193    fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1194        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(def, _) if def.repr().transparent() => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().transparent())
1195    }
1196
1197    fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1198        this.ty.is_scalable_vector()
1199    }
1200
1201    /// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
1202    fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1203        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(def, _) if
        def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS)
        => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS))
1204    }
1205}
1206
1207/// Calculates whether a function's ABI can unwind or not.
1208///
1209/// This takes two primary parameters:
1210///
1211/// * `fn_def_id` - the `DefId` of the function. If this is provided then we can
1212///   determine more precisely if the function can unwind. If this is not provided
1213///   then we will only infer whether the function can unwind or not based on the
1214///   ABI of the function. For example, a function marked with `#[rustc_nounwind]`
1215///   is known to not unwind even if it's using Rust ABI.
1216///
1217/// * `abi` - this is the ABI that the function is defined with. This is the
1218///   primary factor for determining whether a function can unwind or not.
1219///
1220/// Note that in this case unwinding is not necessarily panicking in Rust. Rust
1221/// panics are implemented with unwinds on most platform (when
1222/// `-Cpanic=unwind`), but this also accounts for `-Cpanic=abort` build modes.
1223/// Notably unwinding is disallowed for more non-Rust ABIs unless it's
1224/// specifically in the name (e.g. `"C-unwind"`). Unwinding within each ABI is
1225/// defined for each ABI individually, but it always corresponds to some form of
1226/// stack-based unwinding (the exact mechanism of which varies
1227/// platform-by-platform).
1228///
1229/// Rust functions are classified whether or not they can unwind based on the
1230/// active "panic strategy". In other words Rust functions are considered to
1231/// unwind in `-Cpanic=unwind` mode and cannot unwind in `-Cpanic=abort` mode.
1232/// Note that Rust supports intermingling panic=abort and panic=unwind code, but
1233/// only if the final panic mode is panic=abort. In this scenario any code
1234/// previously compiled assuming that a function can unwind is still correct, it
1235/// just never happens to actually unwind at runtime.
1236///
1237/// This function's answer to whether or not a function can unwind is quite
1238/// impactful throughout the compiler. This affects things like:
1239///
1240/// * Calling a function which can't unwind means codegen simply ignores any
1241///   associated unwinding cleanup.
1242/// * Calling a function which can unwind from a function which can't unwind
1243///   causes the `abort_unwinding_calls` MIR pass to insert a landing pad that
1244///   aborts the process.
1245/// * This affects whether functions have the LLVM `nounwind` attribute, which
1246///   affects various optimizations and codegen.
1247#[inline]
1248#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_can_unwind",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1248u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&["fn_def_id", "abi"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(did) = fn_def_id {
                if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
                    {
                    return false;
                }
                if !tcx.sess.panic_strategy().unwinds() &&
                        !tcx.is_foreign_item(did) {
                    return false;
                }
                if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
                        tcx.is_lang_item(did, LangItem::DropGlue) {
                    return false;
                }
            }
            use ExternAbi::*;
            match abi {
                C { unwind } | System { unwind } | Cdecl { unwind } |
                    Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
                    unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
                    unwind } | SysV64 { unwind } => unwind,
                PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
                    EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
                    CmseNonSecureCall | CmseNonSecureEntry | Custom |
                    RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
                    Unadjusted => false,
                Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
                    tcx.sess.panic_strategy().unwinds()
                }
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(tcx))]
1249pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1250    if let Some(did) = fn_def_id {
1251        // Special attribute for functions which can't unwind.
1252        if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1253            return false;
1254        }
1255
1256        // With `-C panic=abort`, all non-FFI functions are required to not unwind.
1257        //
1258        // Note that this is true regardless ABI specified on the function -- a `extern "C-unwind"`
1259        // function defined in Rust is also required to abort.
1260        if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1261            return false;
1262        }
1263
1264        // With -Z panic-in-drop=abort, `drop_glue` never unwinds.
1265        //
1266        // This is not part of `codegen_fn_attrs` as it can differ between crates
1267        // and therefore cannot be computed in core.
1268        if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1269            && tcx.is_lang_item(did, LangItem::DropGlue)
1270        {
1271            return false;
1272        }
1273    }
1274
1275    // Otherwise if this isn't special then unwinding is generally determined by
1276    // the ABI of the itself. ABIs like `C` have variants which also
1277    // specifically allow unwinding (`C-unwind`), but not all platform-specific
1278    // ABIs have such an option. Otherwise the only other thing here is Rust
1279    // itself, and those ABIs are determined by the panic strategy configured
1280    // for this compilation.
1281    use ExternAbi::*;
1282    match abi {
1283        C { unwind }
1284        | System { unwind }
1285        | Cdecl { unwind }
1286        | Stdcall { unwind }
1287        | Fastcall { unwind }
1288        | Vectorcall { unwind }
1289        | Thiscall { unwind }
1290        | Aapcs { unwind }
1291        | Win64 { unwind }
1292        | SysV64 { unwind } => unwind,
1293        PtxKernel
1294        | Msp430Interrupt
1295        | X86Interrupt
1296        | GpuKernel
1297        | EfiApi
1298        | AvrInterrupt
1299        | AvrNonBlockingInterrupt
1300        | CmseNonSecureCall
1301        | CmseNonSecureEntry
1302        | Custom
1303        | RiscvInterruptM
1304        | RiscvInterruptS
1305        | RustInvalid
1306        | Swift
1307        | Unadjusted => false,
1308        Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1309            tcx.sess.panic_strategy().unwinds()
1310        }
1311    }
1312}
1313
1314/// Error produced by attempting to compute or adjust a `FnAbi`.
1315#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
    #[inline]
    fn clone(&self) -> FnAbiError<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnAbiError::Layout(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
                    &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            FnAbiError<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    FnAbiError::Layout(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1316pub enum FnAbiError<'tcx> {
1317    /// Error produced by a `layout_of` call, while computing `FnAbi` initially.
1318    Layout(LayoutError<'tcx>),
1319}
1320
1321impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1322    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1323        match self {
1324            Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1325        }
1326    }
1327}
1328
1329// FIXME(eddyb) maybe use something like this for an unified `fn_abi_of`, not
1330// just for error handling.
1331#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiRequest<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnAbiRequest::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfFnPtr", "sig", __self_0, "extra_args", &__self_1),
            FnAbiRequest::OfInstance {
                instance: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfInstance", "instance", __self_0, "extra_args",
                    &__self_1),
        }
    }
}Debug)]
1332pub enum FnAbiRequest<'tcx> {
1333    OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1334    OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1335}
1336
1337/// Trait for contexts that want to be able to compute `FnAbi`s.
1338/// This automatically gives access to `FnAbiOf`, through a blanket `impl`.
1339pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1340    /// The `&FnAbi`-wrapping type (or `&FnAbi` itself), which will be
1341    /// returned from `fn_abi_of_*` (see also `handle_fn_abi_err`).
1342    type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1343
1344    /// Helper used for `fn_abi_of_*`, to adapt `tcx.fn_abi_of_*(...)` into a
1345    /// `Self::FnAbiOfResult` (which does not need to be a `Result<...>`).
1346    ///
1347    /// Most `impl`s, which propagate `FnAbiError`s, should simply return `err`,
1348    /// but this hook allows e.g. codegen to return only `&FnAbi` from its
1349    /// `cx.fn_abi_of_*(...)`, without any `Result<...>` around it to deal with
1350    /// (and any `FnAbiError`s are turned into fatal errors or ICEs).
1351    fn handle_fn_abi_err(
1352        &self,
1353        err: FnAbiError<'tcx>,
1354        span: Span,
1355        fn_abi_request: FnAbiRequest<'tcx>,
1356    ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1357}
1358
1359/// Blanket extension trait for contexts that can compute `FnAbi`s.
1360pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1361    /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers.
1362    ///
1363    /// NB: this doesn't handle virtual calls - those should use `fn_abi_of_instance`
1364    /// instead, where the instance is an `InstanceKind::Virtual`.
1365    #[inline]
1366    fn fn_abi_of_fn_ptr(
1367        &self,
1368        sig: ty::PolyFnSig<'tcx>,
1369        extra_args: &'tcx ty::List<Ty<'tcx>>,
1370    ) -> Self::FnAbiOfResult {
1371        // FIXME(eddyb) get a better `span` here.
1372        let span = self.layout_tcx_at_span();
1373        let tcx = self.tcx().at(span);
1374
1375        MaybeResult::from(
1376            tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1377                |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1378            ),
1379        )
1380    }
1381
1382    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1383    /// to an `fn`. Indirectly-passed parameters in the returned ABI might not include all possible
1384    /// codegen optimization attributes (such as `ReadOnly` or `CapturesNone`), as deducing these
1385    /// requires inspection of function bodies that can lead to cycles when performed during typeck.
1386    /// Post typeck, you should prefer the optimized ABI returned by `fn_abi_of_instance`.
1387    ///
1388    /// NB: the ABI returned by this query must not differ from that returned by
1389    ///     `fn_abi_of_instance` in any other way.
1390    ///
1391    /// * that includes virtual calls, which are represented by "direct calls" to an
1392    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1393    #[inline]
1394    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_abi_of_instance_no_deduced_attrs",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1394u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&["instance",
                                                    "extra_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.layout_tcx_at_span();
            let tcx = self.tcx().at(span);
            MaybeResult::from(tcx.fn_abi_of_instance_no_deduced_attrs(self.typing_env().as_query_input((instance,
                                extra_args))).map_err(|err|
                        {
                            let span =
                                if !span.is_dummy() {
                                    span
                                } else { tcx.def_span(instance.def_id()) };
                            self.handle_fn_abi_err(*err, span,
                                FnAbiRequest::OfInstance { instance, extra_args })
                        }))
        }
    }
}#[tracing::instrument(level = "debug", skip(self))]
1395    fn fn_abi_of_instance_no_deduced_attrs(
1396        &self,
1397        instance: ty::Instance<'tcx>,
1398        extra_args: &'tcx ty::List<Ty<'tcx>>,
1399    ) -> Self::FnAbiOfResult {
1400        // FIXME(eddyb) get a better `span` here.
1401        let span = self.layout_tcx_at_span();
1402        let tcx = self.tcx().at(span);
1403
1404        MaybeResult::from(
1405            tcx.fn_abi_of_instance_no_deduced_attrs(
1406                self.typing_env().as_query_input((instance, extra_args)),
1407            )
1408            .map_err(|err| {
1409                // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1410                // we can get some kind of span even if one wasn't provided.
1411                // However, we don't do this early in order to avoid calling
1412                // `def_span` unconditionally (which may have a perf penalty).
1413                let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1414                self.handle_fn_abi_err(
1415                    *err,
1416                    span,
1417                    FnAbiRequest::OfInstance { instance, extra_args },
1418                )
1419            }),
1420        )
1421    }
1422
1423    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1424    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
1425    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
1426    /// which requires inspection of function bodies that can lead to cycles when performed during
1427    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
1428    /// `fn_abi_of_instance_no_deduced_attrs`.
1429    ///
1430    /// * that includes virtual calls, which are represented by "direct calls" to an
1431    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1432    #[inline]
1433    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_abi_of_instance",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1433u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&["instance",
                                                    "extra_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.layout_tcx_at_span();
            let tcx = self.tcx().at(span);
            MaybeResult::from(tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance,
                                extra_args))).map_err(|err|
                        {
                            let span =
                                if !span.is_dummy() {
                                    span
                                } else { tcx.def_span(instance.def_id()) };
                            self.handle_fn_abi_err(*err, span,
                                FnAbiRequest::OfInstance { instance, extra_args })
                        }))
        }
    }
}#[tracing::instrument(level = "debug", skip(self))]
1434    fn fn_abi_of_instance(
1435        &self,
1436        instance: ty::Instance<'tcx>,
1437        extra_args: &'tcx ty::List<Ty<'tcx>>,
1438    ) -> Self::FnAbiOfResult {
1439        // FIXME(eddyb) get a better `span` here.
1440        let span = self.layout_tcx_at_span();
1441        let tcx = self.tcx().at(span);
1442
1443        MaybeResult::from(
1444            tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1445                .map_err(|err| {
1446                    // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1447                    // we can get some kind of span even if one wasn't provided.
1448                    // However, we don't do this early in order to avoid calling
1449                    // `def_span` unconditionally (which may have a perf penalty).
1450                    let span =
1451                        if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1452                    self.handle_fn_abi_err(
1453                        *err,
1454                        span,
1455                        FnAbiRequest::OfInstance { instance, extra_args },
1456                    )
1457                }),
1458        )
1459    }
1460}
1461
1462impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}