Skip to main content

rustc_middle/ty/
layout.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(did) = fn_def_id {
                if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
                    {
                    return false;
                }
                if !tcx.sess.panic_strategy().unwinds() &&
                        !tcx.is_foreign_item(did) {
                    return false;
                }
                if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
                        tcx.is_lang_item(did, LangItem::DropGlue) {
                    return false;
                }
            }
            use ExternAbi::*;
            match abi {
                C { unwind } | System { unwind } | Cdecl { unwind } |
                    Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
                    unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
                    unwind } | SysV64 { unwind } => unwind,
                PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
                    EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
                    CmseNonSecureCall | CmseNonSecureEntry | Custom |
                    RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
                    LlvmIntrinsic => false,
                Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
                    tcx.sess.panic_strategy().unwinds()
                }
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(tcx))]
1277pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1278    if let Some(did) = fn_def_id {
1279        // Special attribute for functions which can't unwind.
1280        if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1281            return false;
1282        }
1283
1284        // With `-C panic=abort`, all non-FFI functions are required to not unwind.
1285        //
1286        // Note that this is true regardless ABI specified on the function -- a `extern "C-unwind"`
1287        // function defined in Rust is also required to abort.
1288        if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1289            return false;
1290        }
1291
1292        // With -Z panic-in-drop=abort, `drop_glue` never unwinds.
1293        //
1294        // This is not part of `codegen_fn_attrs` as it can differ between crates
1295        // and therefore cannot be computed in core.
1296        if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1297            && tcx.is_lang_item(did, LangItem::DropGlue)
1298        {
1299            return false;
1300        }
1301    }
1302
1303    // Otherwise if this isn't special then unwinding is generally determined by
1304    // the ABI of the itself. ABIs like `C` have variants which also
1305    // specifically allow unwinding (`C-unwind`), but not all platform-specific
1306    // ABIs have such an option. Otherwise the only other thing here is Rust
1307    // itself, and those ABIs are determined by the panic strategy configured
1308    // for this compilation.
1309    use ExternAbi::*;
1310    match abi {
1311        C { unwind }
1312        | System { unwind }
1313        | Cdecl { unwind }
1314        | Stdcall { unwind }
1315        | Fastcall { unwind }
1316        | Vectorcall { unwind }
1317        | Thiscall { unwind }
1318        | Aapcs { unwind }
1319        | Win64 { unwind }
1320        | SysV64 { unwind } => unwind,
1321        PtxKernel
1322        | Msp430Interrupt
1323        | X86Interrupt
1324        | GpuKernel
1325        | EfiApi
1326        | AvrInterrupt
1327        | AvrNonBlockingInterrupt
1328        | CmseNonSecureCall
1329        | CmseNonSecureEntry
1330        | Custom
1331        | RiscvInterruptM
1332        | RiscvInterruptS
1333        | RustInvalid
1334        | Swift
1335        | LlvmIntrinsic => false,
1336        Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1337            tcx.sess.panic_strategy().unwinds()
1338        }
1339    }
1340}
1341
1342/// Error produced by attempting to compute or adjust a `FnAbi`.
1343#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for FnAbiError<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
    #[inline]
    fn clone(&self) -> FnAbiError<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnAbiError::Layout(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
                    &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            FnAbiError<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    FnAbiError::Layout(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1344pub enum FnAbiError<'tcx> {
1345    /// Error produced by a `layout_of` call, while computing `FnAbi` initially.
1346    Layout(LayoutError<'tcx>),
1347}
1348
1349impl<'a, 'b, G> Diagnostic<'a, G> for FnAbiError<'b> {
1350    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1351        match self {
1352            Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1353        }
1354    }
1355}
1356
1357// FIXME(eddyb) maybe use something like this for an unified `fn_abi_of`, not
1358// just for error handling.
1359#[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)]
1360pub enum FnAbiRequest<'tcx> {
1361    OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1362    OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1363}
1364
1365/// Trait for contexts that want to be able to compute `FnAbi`s.
1366/// This automatically gives access to `FnAbiOf`, through a blanket `impl`.
1367pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1368    /// The `&FnAbi`-wrapping type (or `&FnAbi` itself), which will be
1369    /// returned from `fn_abi_of_*` (see also `handle_fn_abi_err`).
1370    type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1371
1372    /// Helper used for `fn_abi_of_*`, to adapt `tcx.fn_abi_of_*(...)` into a
1373    /// `Self::FnAbiOfResult` (which does not need to be a `Result<...>`).
1374    ///
1375    /// Most `impl`s, which propagate `FnAbiError`s, should simply return `err`,
1376    /// but this hook allows e.g. codegen to return only `&FnAbi` from its
1377    /// `cx.fn_abi_of_*(...)`, without any `Result<...>` around it to deal with
1378    /// (and any `FnAbiError`s are turned into fatal errors or ICEs).
1379    ///
1380    /// Codegen backends should use [`codegen_handle_fn_abi_err`] as implementation.
1381    fn handle_fn_abi_err(
1382        &self,
1383        err: FnAbiError<'tcx>,
1384        span: Span,
1385        fn_abi_request: FnAbiRequest<'tcx>,
1386    ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1387}
1388
1389/// Implementation of [`FnAbiOfHelpers::handle_fn_abi_err`] for codegen backends.
1390pub fn codegen_handle_fn_abi_err<'tcx>(
1391    tcx: TyCtxt<'tcx>,
1392    err: FnAbiError<'tcx>,
1393    span: Span,
1394    fn_abi_request: FnAbiRequest<'tcx>,
1395) -> ErrorGuaranteed {
1396    match err {
1397        FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::InvalidSimd { .. }) => {
1398            tcx.dcx().emit_err(Spanned { span, node: err })
1399        }
1400        _ => match fn_abi_request {
1401            FnAbiRequest::OfFnPtr { sig, extra_args } => {
1402                bug_impl(Some(span),
    format_args!("`fn_abi_of_fn_ptr({0}, {1:?})` failed: {2:?}", sig,
        extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1403            }
1404            FnAbiRequest::OfInstance { instance, extra_args } => {
1405                bug_impl(Some(span),
    format_args!("`fn_abi_of_instance({0}, {1:?})` failed: {2:?}", instance,
        extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",);
1406            }
1407        },
1408    }
1409}
1410
1411/// Blanket extension trait for contexts that can compute `FnAbi`s.
1412pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1413    /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers.
1414    ///
1415    /// NB: this doesn't handle virtual calls - those should use `fn_abi_of_instance`
1416    /// instead, where the instance is an `InstanceKind::Virtual`.
1417    #[inline]
1418    fn fn_abi_of_fn_ptr(
1419        &self,
1420        sig: ty::PolyFnSig<'tcx>,
1421        extra_args: &'tcx ty::List<Ty<'tcx>>,
1422    ) -> Self::FnAbiOfResult {
1423        // FIXME(eddyb) get a better `span` here.
1424        let span = self.layout_tcx_at_span();
1425        let tcx = self.tcx().at(span);
1426
1427        MaybeResult::from(
1428            tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1429                |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1430            ),
1431        )
1432    }
1433
1434    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1435    /// to an `fn`. Indirectly-passed parameters in the returned ABI might not include all possible
1436    /// codegen optimization attributes (such as `ReadOnly` or `CapturesNone`), as deducing these
1437    /// requires inspection of function bodies that can lead to cycles when performed during typeck.
1438    /// Post typeck, you should prefer the optimized ABI returned by `fn_abi_of_instance`.
1439    ///
1440    /// NB: the ABI returned by this query must not differ from that returned by
1441    ///     `fn_abi_of_instance` in any other way.
1442    ///
1443    /// * that includes virtual calls, which are represented by "direct calls" to an
1444    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1445    #[inline]
1446    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1446u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("extra_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("extra_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
1447    fn fn_abi_of_instance_no_deduced_attrs(
1448        &self,
1449        instance: ty::Instance<'tcx>,
1450        extra_args: &'tcx ty::List<Ty<'tcx>>,
1451    ) -> Self::FnAbiOfResult {
1452        // FIXME(eddyb) get a better `span` here.
1453        let span = self.layout_tcx_at_span();
1454        let tcx = self.tcx().at(span);
1455
1456        MaybeResult::from(
1457            tcx.fn_abi_of_instance_no_deduced_attrs(
1458                self.typing_env().as_query_input((instance, extra_args)),
1459            )
1460            .map_err(|err| {
1461                // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1462                // we can get some kind of span even if one wasn't provided.
1463                // However, we don't do this early in order to avoid calling
1464                // `def_span` unconditionally (which may have a perf penalty).
1465                let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1466                self.handle_fn_abi_err(
1467                    *err,
1468                    span,
1469                    FnAbiRequest::OfInstance { instance, extra_args },
1470                )
1471            }),
1472        )
1473    }
1474
1475    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1476    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
1477    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
1478    /// which requires inspection of function bodies that can lead to cycles when performed during
1479    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
1480    /// `fn_abi_of_instance_no_deduced_attrs`.
1481    ///
1482    /// * that includes virtual calls, which are represented by "direct calls" to an
1483    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1484    #[inline]
1485    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1485u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("extra_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("extra_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
1486    fn fn_abi_of_instance(
1487        &self,
1488        instance: ty::Instance<'tcx>,
1489        extra_args: &'tcx ty::List<Ty<'tcx>>,
1490    ) -> Self::FnAbiOfResult {
1491        // FIXME(eddyb) get a better `span` here.
1492        let span = self.layout_tcx_at_span();
1493        let tcx = self.tcx().at(span);
1494
1495        MaybeResult::from(
1496            tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1497                .map_err(|err| {
1498                    // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1499                    // we can get some kind of span even if one wasn't provided.
1500                    // However, we don't do this early in order to avoid calling
1501                    // `def_span` unconditionally (which may have a perf penalty).
1502                    let span =
1503                        if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1504                    self.handle_fn_abi_err(
1505                        *err,
1506                        span,
1507                        FnAbiRequest::OfInstance { instance, extra_args },
1508                    )
1509                }),
1510        )
1511    }
1512}
1513
1514impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}