Skip to main content

rustc_middle/ty/
layout.rs

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