Skip to main content

rustc_abi/
layout.rs

1use std::fmt::{self, Write};
2use std::num::NonZero;
3use std::ops::Deref;
4use std::range::{RangeFrom, RangeInclusive, RangeToInclusive};
5use std::{cmp, iter};
6
7use rustc_hashes::Hash64;
8use rustc_index::Idx;
9use rustc_index::bit_set::BitMatrix;
10use tracing::{debug, trace};
11
12use crate::{
13    AbiAlign, Align, BackendLaneCount, BackendRepr, FieldsShape, HasDataLayout, IndexSlice,
14    IndexVec, Integer, LayoutData, Niche, NicheOptimizations, NumScalableVectors, Primitive,
15    ReprOptions, Scalar, Size, StructKind, TagEncoding, TargetDataLayout, VariantLayout, Variants,
16    WrappingRange,
17};
18
19mod coroutine;
20mod simple;
21
22#[cfg(feature = "nightly")]
23mod ty;
24
25#[cfg(feature = "nightly")]
26pub use ty::{Layout, TyAbiInterface, TyAndLayout};
27
28#[automatically_derived]
impl ::core::marker::Copy for FieldIdx { }
impl FieldIdx {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for FieldIdx {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for FieldIdx {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for FieldIdx {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for FieldIdx {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for FieldIdx {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for FieldIdx {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl ::rustc_data_structures::stable_hash::StableHash for FieldIdx {
    fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
        hcx: &mut __Hcx,
        hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
        self.as_u32().stable_hash(hcx, hasher)
    }
}
impl From<FieldIdx> for u32 {
    #[inline]
    fn from(v: FieldIdx) -> u32 { v.as_u32() }
}
impl From<FieldIdx> for usize {
    #[inline]
    fn from(v: FieldIdx) -> usize { v.as_usize() }
}
impl From<usize> for FieldIdx {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for FieldIdx {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for FieldIdx {}
impl ::std::cmp::PartialEq for FieldIdx {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for FieldIdx { }
impl ::std::hash::Hash for FieldIdx {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
    FieldIdx {
    fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
    FieldIdx {
    fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for FieldIdx {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
29    /// The *source-order* index of a field in a variant.
30    ///
31    /// This is how most code after type checking refers to fields, rather than
32    /// using names (as names have hygiene complications and more complex lookup).
33    ///
34    /// Particularly for `repr(Rust)` types, this may not be the same as *layout* order.
35    /// (It is for `repr(C)` `struct`s, however.)
36    ///
37    /// For example, in the following types,
38    /// ```rust
39    /// # enum Never {}
40    /// # #[repr(u16)]
41    /// enum Demo1 {
42    ///    Variant0 { a: Never, b: i32 } = 100,
43    ///    Variant1 { c: u8, d: u64 } = 10,
44    /// }
45    /// struct Demo2 { e: u8, f: u16, g: u8 }
46    /// ```
47    /// `b` is `FieldIdx(1)` in `VariantIdx(0)`,
48    /// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and
49    /// `f` is `FieldIdx(1)` in `VariantIdx(0)`.
50    #[stable_hash]
51    #[encodable]
52    #[orderable]
53    #[gate_rustc_only]
54    pub struct FieldIdx {}
55}
56
57impl FieldIdx {
58    /// The second field, at index 1.
59    ///
60    /// For use alongside [`FieldIdx::ZERO`], particularly with scalar pairs.
61    pub const ONE: FieldIdx = FieldIdx::from_u32(1);
62}
63
64#[automatically_derived]
impl ::core::marker::Copy for VariantIdx { }
#[doc = " Equivalent to `VariantIdx(0)`."]
pub const FIRST_VARIANT: VariantIdx = VariantIdx::from_u32(0);
impl VariantIdx {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for VariantIdx {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for VariantIdx {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for VariantIdx {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for VariantIdx {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for VariantIdx {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for VariantIdx {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl ::rustc_data_structures::stable_hash::StableHash for VariantIdx {
    fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
        hcx: &mut __Hcx,
        hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
        self.as_u32().stable_hash(hcx, hasher)
    }
}
impl From<VariantIdx> for u32 {
    #[inline]
    fn from(v: VariantIdx) -> u32 { v.as_u32() }
}
impl From<VariantIdx> for usize {
    #[inline]
    fn from(v: VariantIdx) -> usize { v.as_usize() }
}
impl From<usize> for VariantIdx {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for VariantIdx {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for VariantIdx {}
impl ::std::cmp::PartialEq for VariantIdx {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for VariantIdx { }
impl ::std::hash::Hash for VariantIdx {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
    VariantIdx {
    fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
    VariantIdx {
    fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for VariantIdx {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
65    /// The *source-order* index of a variant in a type.
66    ///
67    /// For enums, these are always `0..variant_count`, regardless of any
68    /// custom discriminants that may have been defined, and including any
69    /// variants that may end up uninhabited due to field types.  (Some of the
70    /// variants may not be present in a monomorphized ABI [`Variants`], but
71    /// those skipped variants are always counted when determining the *index*.)
72    ///
73    /// `struct`s, `tuples`, and `unions`s are considered to have a single variant
74    /// with variant index zero, aka [`FIRST_VARIANT`].
75    #[stable_hash]
76    #[encodable]
77    #[orderable]
78    #[gate_rustc_only]
79    pub struct VariantIdx {
80        /// Equivalent to `VariantIdx(0)`.
81        const FIRST_VARIANT = 0;
82    }
83}
84
85// A variant is absent if it's uninhabited and only has ZST fields.
86// Present uninhabited variants only require space for their fields,
87// but *not* an encoding of the discriminant (e.g., a tag value).
88// See issue #49298 for more details on the need to leave space
89// for non-ZST uninhabited data (mostly partial initialization).
90fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
91where
92    FieldIdx: Idx,
93    VariantIdx: Idx,
94    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
95{
96    let uninhabited = fields.iter().any(|f| f.is_uninhabited());
97    // We cannot ignore alignment; that might lead us to entirely discard a variant and
98    // produce an enum that is less aligned than it should be!
99    let is_1zst = fields.iter().all(|f| f.is_1zst());
100    uninhabited && is_1zst
101}
102
103/// Determines towards which end of a struct layout optimizations will try to place the best niches.
104enum NicheBias {
105    Start,
106    End,
107}
108
109#[derive(#[automatically_derived]
impl<F: ::core::marker::Copy> ::core::marker::Copy for
    LayoutCalculatorError<F> {
}Copy, #[automatically_derived]
impl<F: ::core::clone::Clone> ::core::clone::Clone for
    LayoutCalculatorError<F> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::UnexpectedUnsized(__self_0) =>
                Self::UnexpectedUnsized(::core::clone::Clone::clone(__self_0)),
            Self::SizeOverflow => Self::SizeOverflow,
            Self::EmptyUnion => Self::EmptyUnion,
            Self::ReprConflict => Self::ReprConflict,
            Self::ZeroLengthSimdType => Self::ZeroLengthSimdType,
            Self::OversizedSimdType { max_lanes: __self_0 } =>
                Self::OversizedSimdType {
                    max_lanes: ::core::clone::Clone::clone(__self_0),
                },
            Self::NonPrimitiveSimdType(__self_0) =>
                Self::NonPrimitiveSimdType(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<F: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculatorError<F> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::UnexpectedUnsized(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "UnexpectedUnsized", &__self_0),
            Self::SizeOverflow =>
                ::core::fmt::Formatter::write_str(f, "SizeOverflow"),
            Self::EmptyUnion =>
                ::core::fmt::Formatter::write_str(f, "EmptyUnion"),
            Self::ReprConflict =>
                ::core::fmt::Formatter::write_str(f, "ReprConflict"),
            Self::ZeroLengthSimdType =>
                ::core::fmt::Formatter::write_str(f, "ZeroLengthSimdType"),
            Self::OversizedSimdType { max_lanes: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OversizedSimdType", "max_lanes", &__self_0),
            Self::NonPrimitiveSimdType(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NonPrimitiveSimdType", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    LayoutCalculatorError<F> {
}
#[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    LayoutCalculatorError<F> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::UnexpectedUnsized(__self_0),
                    Self::UnexpectedUnsized(__arg1_0)) => __self_0 == __arg1_0,
                (Self::OversizedSimdType { max_lanes: __self_0 },
                    Self::OversizedSimdType { max_lanes: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (Self::NonPrimitiveSimdType(__self_0),
                    Self::NonPrimitiveSimdType(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<F: ::core::cmp::Eq> ::core::cmp::Eq for LayoutCalculatorError<F> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<F>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq)]
110pub enum LayoutCalculatorError<F> {
111    /// An unsized type was found in a location where a sized type was expected.
112    ///
113    /// This is not always a compile error, for example if there is a `[T]: Sized`
114    /// bound in a where clause.
115    ///
116    /// Contains the field that was unexpectedly unsized.
117    UnexpectedUnsized(F),
118
119    /// A type was too large for the target platform.
120    SizeOverflow,
121
122    /// A union had no fields.
123    EmptyUnion,
124
125    /// The fields or variants have irreconcilable reprs
126    ReprConflict,
127
128    /// The length of an SIMD type is zero
129    ZeroLengthSimdType,
130
131    /// The length of an SIMD type exceeds the maximum number of lanes
132    OversizedSimdType { max_lanes: usize },
133
134    /// An element type of an SIMD type isn't a primitive
135    NonPrimitiveSimdType(F),
136}
137
138impl<F> LayoutCalculatorError<F> {
139    pub fn without_payload(&self) -> LayoutCalculatorError<()> {
140        use LayoutCalculatorError::*;
141        match *self {
142            UnexpectedUnsized(_) => UnexpectedUnsized(()),
143            SizeOverflow => SizeOverflow,
144            EmptyUnion => EmptyUnion,
145            ReprConflict => ReprConflict,
146            ZeroLengthSimdType => ZeroLengthSimdType,
147            OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
148            NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
149        }
150    }
151
152    /// Format an untranslated diagnostic for this type
153    ///
154    /// Intended for use by rust-analyzer, as neither it nor `rustc_abi` depend on fluent infra.
155    pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        use LayoutCalculatorError::*;
157        f.write_str(match self {
158            UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
159            SizeOverflow => "size overflow",
160            EmptyUnion => "type is a union with no fields",
161            ReprConflict => "type has an invalid repr",
162            ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
163                "invalid simd type definition"
164            }
165        })
166    }
167}
168
169type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
170    Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
171
172#[derive(#[automatically_derived]
impl<Cx: ::core::clone::Clone> ::core::clone::Clone for LayoutCalculator<Cx> {
    #[inline]
    fn clone(&self) -> Self {
        Self { cx: ::core::clone::Clone::clone(&self.cx) }
    }
}Clone, #[automatically_derived]
impl<Cx: ::core::marker::Copy> ::core::marker::Copy for LayoutCalculator<Cx> {
}Copy, #[automatically_derived]
impl<Cx: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculator<Cx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "LayoutCalculator", "cx", &&self.cx)
    }
}Debug)]
173pub struct LayoutCalculator<Cx> {
174    pub cx: Cx,
175}
176
177impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
178    pub fn new(cx: Cx) -> Self {
179        Self { cx }
180    }
181
182    pub fn layout_of_array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
183        &self,
184        element: &LayoutData<FieldIdx, VariantIdx>,
185        count_if_sized: Option<u64>, // None for slices
186    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
187        let count = count_if_sized.unwrap_or(0);
188        let size =
189            element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
190
191        Ok(LayoutData {
192            variants: Variants::Single { index: VariantIdx::new(0) },
193            fields: FieldsShape::Array { stride: element.size, count },
194            backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
195            largest_niche: element.largest_niche.filter(|_| count != 0),
196            uninhabited: element.uninhabited && count != 0,
197            align: element.align,
198            size,
199            max_repr_align: None,
200            unadjusted_abi_align: element.align.abi,
201            randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
202        })
203    }
204
205    pub fn layout_of_scalable_vector_type<FieldIdx, VariantIdx, F>(
206        &self,
207        element: F,
208        count: u64,
209        number_of_vectors: NumScalableVectors,
210    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
211    where
212        FieldIdx: Idx,
213        VariantIdx: Idx,
214        F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
215    {
216        vector_type_layout(
217            SimdVectorKind::Scalable(number_of_vectors),
218            self.cx.data_layout(),
219            element,
220            count,
221        )
222    }
223
224    pub fn layout_of_simd_type<FieldIdx, VariantIdx, F>(
225        &self,
226        element: F,
227        count: u64,
228        repr_packed: bool,
229    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
230    where
231        FieldIdx: Idx,
232        VariantIdx: Idx,
233        F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
234    {
235        let kind = if repr_packed { SimdVectorKind::PackedFixed } else { SimdVectorKind::Fixed };
236        vector_type_layout(kind, self.cx.data_layout(), element, count)
237    }
238
239    /// Compute the layout for a coroutine.
240    ///
241    /// This uses dedicated code instead of [`Self::layout_of_struct_or_enum`], as coroutine
242    /// fields may be shared between multiple variants (see the [`coroutine`] module for details).
243    pub fn layout_of_coroutine<'a, F, VariantIdx, FieldIdx, LocalIdx>(
244        &self,
245        local_layouts: &IndexSlice<LocalIdx, F>,
246        prefix_layouts: IndexVec<FieldIdx, F>,
247        variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
248        storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
249        tag_to_layout: impl Fn(Scalar) -> F,
250    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
251    where
252        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
253        VariantIdx: Idx,
254        FieldIdx: Idx,
255        LocalIdx: Idx,
256    {
257        coroutine::layout(
258            self,
259            local_layouts,
260            prefix_layouts,
261            variant_fields,
262            storage_conflicts,
263            tag_to_layout,
264        )
265    }
266
267    /// Compute the layout for a univariant (see [`Variants::Single`]).
268    ///
269    /// As a consumer of `rustc_abi`, you should only use this method for non-ADTs.
270    /// For structs and univariant enums, use [`Self::layout_of_struct`] instead
271    /// (it uses this function internally).
272    pub fn layout_of_univariant<'a, FieldIdx, VariantIdx, F>(
273        &self,
274        fields: &IndexSlice<FieldIdx, F>,
275        repr: &ReprOptions,
276        kind: StructKind,
277    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
278    where
279        FieldIdx: Idx,
280        VariantIdx: Idx,
281        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
282    {
283        let dl = self.cx.data_layout();
284        let layout = self.layout_of_univariant_biased(fields, repr, kind, NicheBias::Start);
285        // Enums prefer niches close to the beginning or the end of the variants so that other
286        // (smaller) data-carrying variants can be packed into the space after/before the niche.
287        // If the default field ordering does not give us a niche at the front then we do a second
288        // run and bias niches to the right and then check which one is closer to one of the
289        // struct's edges.
290        if let Ok(layout) = &layout
291            // Don't try to calculate an end-biased layout for unsizable structs,
292            // otherwise we could end up with different layouts for
293            // Foo<Type> and Foo<dyn Trait> which would break unsizing.
294            && !#[allow(non_exhaustive_omitted_patterns)] match kind {
    StructKind::MaybeUnsized => true,
    _ => false,
}matches!(kind, StructKind::MaybeUnsized)
295            && let Some(niche) = layout.largest_niche
296            && let head_space = niche.offset.bytes()
297            && let niche_len = niche.value.size(dl).bytes()
298            && let tail_space = layout.size.bytes() - head_space - niche_len
299            // This may end up doing redundant work if the niche is already in the last
300            // field (e.g. a trailing bool) and there is tail padding. But it's non-trivial
301            // to get the unpadded size so we try anyway.
302            && (fields.len() > 1 && head_space != 0 && tail_space > 0)
303        {
304            let alt_layout = self
305                .layout_of_univariant_biased(fields, repr, kind, NicheBias::End)
306                .expect("alt layout should always work");
307            let alt_niche = alt_layout
308                .largest_niche
309                .expect("alt layout should have a niche like the regular one");
310            let alt_head_space = alt_niche.offset.bytes();
311            let alt_niche_len = alt_niche.value.size(dl).bytes();
312            let alt_tail_space = alt_layout.size.bytes() - alt_head_space - alt_niche_len;
313
314            if true {
    {
        match (&layout.size.bytes(), &alt_layout.size.bytes()) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(layout.size.bytes(), alt_layout.size.bytes());
315
316            let prefer_alt_layout = alt_head_space > head_space && alt_head_space > tail_space;
317
318            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:318",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(318u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::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!("sz: {0}, default_niche_at: {1}+{2}, default_tail_space: {3}, alt_niche_at/head_space: {4}+{5}, alt_tail: {6}, num_fields: {7}, better: {8}\nlayout: {9}\nalt_layout: {10}\n",
                                                    layout.size.bytes(), head_space, niche_len, tail_space,
                                                    alt_head_space, alt_niche_len, alt_tail_space,
                                                    layout.fields.count(), prefer_alt_layout,
                                                    self.format_field_niches(layout, fields),
                                                    self.format_field_niches(&alt_layout, fields)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
319                "sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
320                layout: {}\n\
321                alt_layout: {}\n",
322                layout.size.bytes(),
323                head_space,
324                niche_len,
325                tail_space,
326                alt_head_space,
327                alt_niche_len,
328                alt_tail_space,
329                layout.fields.count(),
330                prefer_alt_layout,
331                self.format_field_niches(layout, fields),
332                self.format_field_niches(&alt_layout, fields),
333            );
334
335            if prefer_alt_layout {
336                return Ok(alt_layout);
337            }
338        }
339        layout
340    }
341
342    pub fn layout_of_struct_or_enum<'a, FieldIdx, VariantIdx, F>(
343        &self,
344        repr: &ReprOptions,
345        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
346        is_enum: bool,
347        niche_optimizations: NicheOptimizations,
348        discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
349        discriminants: impl Iterator<Item = (VariantIdx, u128)>,
350        always_sized: bool,
351    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
352    where
353        FieldIdx: Idx,
354        VariantIdx: Idx,
355        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
356    {
357        let (present_first, present_second) = {
358            let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
359                if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
360            });
361            (present_variants.next(), present_variants.next())
362        };
363        let present_first = match present_first {
364            Some(present_first) => present_first,
365            // Uninhabited because it has no variants, or only absent ones.
366            None if is_enum => {
367                return Ok(LayoutData::never_type(&self.cx));
368            }
369            // If it's a struct, still compute a layout so that we can still compute the
370            // field offsets.
371            None => VariantIdx::new(0),
372        };
373
374        // take the struct path if it is an actual struct
375        if !is_enum ||
376            // or for optimizing univariant enums
377            (present_second.is_none() && !repr.inhibit_enum_layout_opt())
378        {
379            self.layout_of_struct(
380                repr,
381                variants,
382                present_first,
383                is_enum,
384                niche_optimizations,
385                always_sized,
386            )
387        } else {
388            // At this point, we have handled all unions and
389            // structs. (We have also handled univariant enums
390            // that allow representation optimization.)
391            if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
392            self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
393        }
394    }
395
396    pub fn layout_of_union<'a, FieldIdx, VariantIdx, F>(
397        &self,
398        repr: &ReprOptions,
399        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
400    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
401    where
402        FieldIdx: Idx,
403        VariantIdx: Idx,
404        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
405    {
406        let dl = self.cx.data_layout();
407        let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
408        let mut max_repr_align = repr.align;
409
410        // If all the non-ZST fields have the same repr and union repr optimizations aren't
411        // disabled, we can use that common repr for the union as a whole.
412        struct AbiMismatch;
413        let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
414            // Can't optimize
415            Err(AbiMismatch)
416        } else {
417            Ok(None)
418        };
419
420        let mut size = Size::ZERO;
421        let only_variant_idx = VariantIdx::new(0);
422        let only_variant = &variants[only_variant_idx];
423        for field in only_variant {
424            if field.is_unsized() {
425                return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
426            }
427
428            align = align.max(field.align.abi);
429            max_repr_align = max_repr_align.max(field.max_repr_align);
430            size = cmp::max(size, field.size);
431
432            if field.is_zst() {
433                // Nothing more to do for ZST fields
434                continue;
435            }
436
437            if let Ok(common) = common_non_zst_repr_and_align {
438                // Discard valid range information and allow undef
439                let field_abi = field.backend_repr.to_union();
440
441                if let Some((common_abi, common_align)) = common {
442                    if common_abi != field_abi {
443                        // Different fields have different ABI: disable opt
444                        common_non_zst_repr_and_align = Err(AbiMismatch);
445                    } else {
446                        // Fields with the same non-Aggregate ABI should also
447                        // have the same alignment
448                        if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
    BackendRepr::Memory { .. } => true,
    _ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
449                            {
    match (&common_align, &field.align.abi) {
        (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::Some(format_args!("non-Aggregate field with matching ABI but differing alignment")));
            }
        }
    }
};assert_eq!(
450                                common_align, field.align.abi,
451                                "non-Aggregate field with matching ABI but differing alignment"
452                            );
453                        }
454                    }
455                } else {
456                    // First non-ZST field: record its ABI and alignment
457                    common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
458                }
459            }
460        }
461
462        if let Some(pack) = repr.pack {
463            align = align.min(pack);
464        }
465        // The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
466        // See documentation on `LayoutData::unadjusted_abi_align`.
467        let unadjusted_abi_align = align;
468        if let Some(repr_align) = repr.align {
469            align = align.max(repr_align);
470        }
471        // `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate.
472        let align = align;
473
474        // If all non-ZST fields have the same ABI, we may forward that ABI
475        // for the union as a whole, unless otherwise inhibited.
476        let backend_repr = match common_non_zst_repr_and_align {
477            Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
478            Ok(Some((repr, _))) => match repr {
479                // Mismatched alignment (e.g. union is #[repr(packed)]): disable opt
480                BackendRepr::Scalar(_) | BackendRepr::ScalarPair { .. }
481                    if repr.scalar_platform_align(dl).unwrap() != align =>
482                {
483                    BackendRepr::Memory { sized: true }
484                }
485                // Vectors require at least element alignment, else disable the opt
486                BackendRepr::SimdVector { element, count: _ }
487                    if element.default_align(dl).abi > align =>
488                {
489                    BackendRepr::Memory { sized: true }
490                }
491                // the alignment tests passed and we can use this
492                BackendRepr::Scalar(..)
493                | BackendRepr::ScalarPair { .. }
494                | BackendRepr::SimdVector { .. }
495                | BackendRepr::SimdScalableVector { .. }
496                | BackendRepr::Memory { .. } => repr,
497            },
498        };
499
500        let Some(union_field_count) = NonZero::new(only_variant.len()) else {
501            return Err(LayoutCalculatorError::EmptyUnion);
502        };
503
504        let combined_seed = only_variant
505            .iter()
506            .map(|v| v.randomization_seed)
507            .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
508
509        Ok(LayoutData {
510            variants: Variants::Single { index: only_variant_idx },
511            fields: FieldsShape::Union(union_field_count),
512            backend_repr,
513            largest_niche: None,
514            uninhabited: false,
515            align: AbiAlign::new(align),
516            size: size.align_to(align),
517            max_repr_align,
518            unadjusted_abi_align,
519            randomization_seed: combined_seed,
520        })
521    }
522
523    /// Calculate the layout for a struct, or a single-variant enum.
524    ///
525    /// They are the same thing, if you think about it
526    /// (Typechecking will reject discriminant-sizing attrs.)
527    fn layout_of_struct<'a, FieldIdx, VariantIdx, F>(
528        &self,
529        repr: &ReprOptions,
530        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
531        variant_idx: VariantIdx,
532        is_enum: bool,
533        niche_optimizations: NicheOptimizations,
534        always_sized: bool,
535    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
536    where
537        FieldIdx: Idx,
538        VariantIdx: Idx,
539        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
540    {
541        let dl = self.cx.data_layout();
542        let v = variant_idx;
543        let kind = if is_enum || variants[v].is_empty() || always_sized {
544            StructKind::AlwaysSized
545        } else {
546            StructKind::MaybeUnsized
547        };
548
549        let mut st = self.layout_of_univariant(&variants[v], repr, kind)?;
550        st.variants = Variants::Single { index: v };
551
552        if niche_optimizations == NicheOptimizations::Disabled {
553            let hide_niches = |scalar: &mut _| match scalar {
554                Scalar::Initialized { value, valid_range } => {
555                    *valid_range = WrappingRange::full(value.size(dl))
556                }
557                // Already doesn't have any niches
558                Scalar::Union { .. } => {}
559            };
560            match &mut st.backend_repr {
561                BackendRepr::Scalar(scalar) => hide_niches(scalar),
562                BackendRepr::ScalarPair { a, b, b_offset: _ } => {
563                    hide_niches(a);
564                    hide_niches(b);
565                }
566                BackendRepr::SimdVector { element, .. }
567                | BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
568                BackendRepr::Memory { sized: _ } => {}
569            }
570            st.largest_niche = None;
571            return Ok(st);
572        }
573
574        Ok(st)
575    }
576
577    fn layout_of_enum<'a, FieldIdx, VariantIdx, F>(
578        &self,
579        repr: &ReprOptions,
580        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
581        discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
582        discriminants: impl Iterator<Item = (VariantIdx, u128)>,
583    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
584    where
585        FieldIdx: Idx,
586        VariantIdx: Idx,
587        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
588    {
589        let dl = self.cx.data_layout();
590        // bail if the enum has an incoherent repr that cannot be computed
591        if repr.packed() {
592            return Err(LayoutCalculatorError::ReprConflict);
593        }
594
595        let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
596            struct VariantLayoutInfo {
597                align_abi: Align,
598            }
599
600            if repr.inhibit_enum_layout_opt() {
601                return None;
602            }
603
604            if variants.len() < 2 {
605                return None;
606            }
607
608            let mut align = dl.aggregate_align;
609            let mut max_repr_align = repr.align;
610            let mut unadjusted_abi_align = align;
611            let mut combined_seed = repr.field_shuffle_seed;
612
613            let mut variants_info = IndexVec::<VariantIdx, _>::with_capacity(variants.len());
614            let mut variant_layouts = variants
615                .iter()
616                .map(|v| {
617                    let st = self.layout_of_univariant(v, repr, StructKind::AlwaysSized).ok()?;
618
619                    variants_info.push(VariantLayoutInfo { align_abi: st.align.abi });
620
621                    align = align.max(st.align.abi);
622                    max_repr_align = max_repr_align.max(st.max_repr_align);
623                    unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
624                    combined_seed = combined_seed.wrapping_add(st.randomization_seed);
625
626                    Some(VariantLayout::from_layout(st))
627                })
628                .collect::<Option<IndexVec<VariantIdx, _>>>()?;
629
630            let largest_variant_index = variant_layouts
631                .iter_enumerated()
632                .max_by_key(|(_i, layout)| layout.size.bytes())
633                .map(|(i, _layout)| i)?;
634
635            let all_indices = variants.indices();
636            let needs_disc =
637                |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
638            let niche_variants = RangeInclusive {
639                start: all_indices.clone().find(|v| needs_disc(*v)).unwrap(),
640                last: all_indices.rev().find(|v| needs_disc(*v)).unwrap(),
641            };
642
643            let count =
644                (niche_variants.last.index() as u128 - niche_variants.start.index() as u128) + 1;
645
646            // Use the largest niche in the largest variant.
647            let niche = variant_layouts[largest_variant_index].largest_niche?;
648            let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
649            let niche_offset = niche.offset;
650            let niche_size = niche.value.size(dl);
651            let size = variant_layouts[largest_variant_index].size.align_to(align);
652
653            let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
654                if i == largest_variant_index {
655                    return true;
656                }
657
658                layout.largest_niche = None;
659
660                if layout.size <= niche_offset {
661                    // This variant will fit before the niche.
662                    return true;
663                }
664
665                // Determine if it'll fit after the niche.
666                let this_align = variants_info[i].align_abi;
667                let this_offset = (niche_offset + niche_size).align_to(this_align);
668
669                if this_offset + layout.size > size {
670                    return false;
671                }
672
673                // It'll fit, but we need to make some adjustments.
674                for offset in layout.field_offsets.iter_mut() {
675                    *offset += this_offset;
676                }
677
678                // It can't be a Scalar or ScalarPair because the offset isn't 0.
679                if !layout.is_uninhabited() {
680                    layout.backend_repr = BackendRepr::Memory { sized: true };
681                }
682                layout.size += this_offset;
683
684                true
685            });
686
687            if !all_variants_fit {
688                return None;
689            }
690
691            let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
692
693            let others_zst = variant_layouts
694                .iter_enumerated()
695                .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
696            let same_size = size == variant_layouts[largest_variant_index].size;
697            let same_align = align == variants_info[largest_variant_index].align_abi;
698
699            let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
700            let abi = if same_size && same_align && others_zst {
701                match variant_layouts[largest_variant_index].backend_repr {
702                    // When the total alignment and size match, we can use the
703                    // same ABI as the scalar variant with the reserved niche.
704                    BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
705                    BackendRepr::ScalarPair { a: first, b: second, b_offset } => {
706                        // Only the niche is guaranteed to be initialised,
707                        // so use union layouts for the other primitive.
708                        if niche_offset == Size::ZERO {
709                            BackendRepr::ScalarPair {
710                                a: niche_scalar,
711                                b: second.to_union(),
712                                b_offset,
713                            }
714                        } else {
715                            BackendRepr::ScalarPair {
716                                a: first.to_union(),
717                                b: niche_scalar,
718                                b_offset,
719                            }
720                        }
721                    }
722                    _ => BackendRepr::Memory { sized: true },
723                }
724            } else {
725                BackendRepr::Memory { sized: true }
726            };
727
728            let layout = LayoutData {
729                variants: Variants::Multiple {
730                    tag: niche_scalar,
731                    tag_encoding: TagEncoding::Niche {
732                        untagged_variant: largest_variant_index,
733                        niche_variants,
734                        niche_start,
735                    },
736                    tag_field: FieldIdx::new(0),
737                    variants: variant_layouts,
738                },
739                fields: FieldsShape::Arbitrary {
740                    offsets: [niche_offset].into(),
741                    in_memory_order: [FieldIdx::new(0)].into(),
742                },
743                backend_repr: abi,
744                largest_niche,
745                uninhabited,
746                size,
747                align: AbiAlign::new(align),
748                max_repr_align,
749                unadjusted_abi_align,
750                randomization_seed: combined_seed,
751            };
752
753            Some(layout)
754        };
755
756        let niche_filling_layout = calculate_niche_filling_layout();
757
758        let discr_type = repr.discr_type();
759        let discr_size = Integer::from_attr(dl, discr_type).size();
760
761        let necessary_discriminants: Vec<u128> = discriminants
762            .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
763            .map(|(_, val)| val)
764            .collect();
765
766        // When picking the integer to use, we respect how the discriminants were written
767        // in the original rust code, rather than looking only at the bit pattern.
768        let (min_negative, max_positive): (i128, u128) = if discr_type.is_signed() {
769            necessary_discriminants.iter().copied().map(|val| discr_size.sign_extend(val)).fold(
770                (0_i128, 0_u128),
771                |(min, max), val| {
772                    if let Ok(val) = u128::try_from(val) {
773                        (min, max.max(val))
774                    } else {
775                        (min.min(val), max)
776                    }
777                },
778            )
779        } else {
780            // We might have no inhabited variants, so pretend there's at least one.
781            (0, necessary_discriminants.iter().copied().max().unwrap_or(0))
782        };
783        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:783",
                        "rustc_abi::layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(783u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("min_negative")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("min_negative");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("max_positive")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("max_positive");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_negative)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&max_positive)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?min_negative, ?max_positive);
784
785        let (min_ity, signed) = discr_range_of_repr(
786            RangeFrom { start: min_negative },
787            RangeToInclusive { last: max_positive },
788        ); //Integer::discr_range_of_repr(tcx, ty, &repr, min, max);
789
790        let mut align = dl.aggregate_align;
791        let mut max_repr_align = repr.align;
792        let mut unadjusted_abi_align = align;
793        let mut combined_seed = repr.field_shuffle_seed;
794
795        let mut size = Size::ZERO;
796
797        // We're interested in the smallest alignment, so start large.
798        let mut start_align = Align::from_bytes(256).unwrap();
799        {
    match (&Integer::for_align(dl, start_align), &None) {
        (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!(Integer::for_align(dl, start_align), None);
800
801        // repr(C) on an enum tells us to make a (tag, union) layout,
802        // so we need to grow the prefix alignment to be at least
803        // the alignment of the union. (This value is used both for
804        // determining the alignment of the overall enum, and the
805        // determining the alignment of the payload after the tag.)
806        let mut prefix_align = min_ity.align(dl).abi;
807        if repr.c() {
808            for fields in variants {
809                for field in fields {
810                    prefix_align = prefix_align.max(field.align.abi);
811                }
812            }
813        }
814
815        // Create the set of structs that represent each variant.
816        let mut layout_variants = variants
817            .iter()
818            .map(|field_layouts| {
819                let st = self.layout_of_univariant(
820                    field_layouts,
821                    repr,
822                    StructKind::Prefixed(min_ity.size(), prefix_align),
823                )?;
824                // Find the first field we can't move later
825                // to make room for a larger discriminant.
826                for field_idx in st.fields.index_by_increasing_offset() {
827                    let field = &field_layouts[FieldIdx::new(field_idx)];
828                    if !field.is_1zst() {
829                        start_align = start_align.min(field.align.abi);
830                        break;
831                    }
832                }
833                size = cmp::max(size, st.size);
834                align = align.max(st.align.abi);
835                max_repr_align = max_repr_align.max(st.max_repr_align);
836                unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
837                combined_seed = combined_seed.wrapping_add(st.randomization_seed);
838                Ok(VariantLayout::from_layout(st))
839            })
840            .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
841
842        // Align the maximum variant size to the largest alignment.
843        size = size.align_to(align);
844
845        // FIXME(oli-obk): deduplicate and harden these checks
846        if size.bytes() >= dl.obj_size_bound() {
847            return Err(LayoutCalculatorError::SizeOverflow);
848        }
849
850        let typeck_ity = Integer::from_attr(dl, repr.discr_type());
851        if typeck_ity < min_ity {
852            // It is a bug if Layout decided on a greater discriminant size than typeck for
853            // some reason at this point (based on values discriminant can take on). Mostly
854            // because this discriminant will be loaded, and then stored into variable of
855            // type calculated by typeck. Consider such case (a bug): typeck decided on
856            // byte-sized discriminant, but layout thinks we need a 16-bit to store all
857            // discriminant values. That would be a bug, because then, in codegen, in order
858            // to store this 16-bit discriminant into 8-bit sized temporary some of the
859            // space necessary to represent would have to be discarded (or layout is wrong
860            // on thinking it needs 16 bits)
861            {
    ::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
            min_ity, typeck_ity));
};panic!(
862                "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
863            );
864            // However, it is fine to make discr type however large (as an optimisation)
865            // after this point – we’ll just truncate the value we load in codegen.
866        }
867
868        // Check to see if we should use a different type for the
869        // discriminant. We can safely use a type with the same size
870        // as the alignment of the first field of each variant.
871        // We increase the size of the discriminant to avoid LLVM copying
872        // padding when it doesn't need to. This normally causes unaligned
873        // load/stores and excessive memcpy/memset operations. By using a
874        // bigger integer size, LLVM can be sure about its contents and
875        // won't be so conservative.
876
877        // Use the initial field alignment
878        let mut ity = if repr.c() || repr.int.is_some() {
879            min_ity
880        } else {
881            Integer::for_align(dl, start_align).unwrap_or(min_ity)
882        };
883
884        // If the alignment is not larger than the chosen discriminant size,
885        // don't use the alignment as the final size.
886        if ity <= min_ity {
887            ity = min_ity;
888        } else {
889            // Patch up the variants' first few fields.
890            let old_ity_size = min_ity.size();
891            let new_ity_size = ity.size();
892            for variant in &mut layout_variants {
893                for i in &mut variant.field_offsets {
894                    if *i <= old_ity_size {
895                        {
    match (&*i, &old_ity_size) {
        (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, old_ity_size);
896                        *i = new_ity_size;
897                    }
898                }
899                // We might be making the struct larger.
900                if variant.size <= old_ity_size {
901                    variant.size = new_ity_size;
902                }
903            }
904        }
905
906        let tag_valid_range = {
907            let tag_size = ity.size();
908            let tags = necessary_discriminants.into_iter().map(|d| tag_size.truncate(d));
909            WrappingRange::smallest_range_containing(tags, tag_size)
910                // We might have no inhabited variants, so pretend there's at least one.
911                .unwrap_or(WrappingRange { start: 0, end: 0 })
912        };
913        let tag = Scalar::Initialized {
914            value: Primitive::Int(ity, signed),
915            valid_range: tag_valid_range,
916        };
917        let mut abi = BackendRepr::Memory { sized: true };
918
919        let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
920        if tag.size(dl) == size {
921            // Make sure we only use scalar layout when the enum is entirely its
922            // own tag (i.e. it has no padding nor any non-ZST variant fields).
923            abi = BackendRepr::Scalar(tag);
924        } else {
925            // Try to use a ScalarPair for all tagged enums.
926            // That's possible only if we can find a common primitive type for all variants.
927            let mut common_prim = None;
928            let mut common_prim_initialized_in_all_variants = true;
929            for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
930                // We skip *all* ZST here and later check if we are good in terms of alignment.
931                // This lets us handle some cases involving aligned ZST.
932                let mut fields = iter::zip(field_layouts, &layout_variant.field_offsets)
933                    .filter(|p| !p.0.is_zst());
934                let (field, offset) = match (fields.next(), fields.next()) {
935                    (None, None) => {
936                        common_prim_initialized_in_all_variants = false;
937                        continue;
938                    }
939                    (Some(pair), None) => pair,
940                    _ => {
941                        common_prim = None;
942                        break;
943                    }
944                };
945                let prim = match field.backend_repr {
946                    BackendRepr::Scalar(scalar) => {
947                        common_prim_initialized_in_all_variants &=
948                            #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Initialized { .. } => true,
    _ => false,
}matches!(scalar, Scalar::Initialized { .. });
949                        scalar.primitive()
950                    }
951                    _ => {
952                        common_prim = None;
953                        break;
954                    }
955                };
956                if let Some((old_prim, common_offset)) = common_prim {
957                    // All variants must be at the same offset
958                    if offset != common_offset {
959                        common_prim = None;
960                        break;
961                    }
962                    // This is pretty conservative. We could go fancier
963                    // by realising that (u8, u8) could just cohabit with
964                    // u16 or even u32.
965                    let new_prim = match (old_prim, prim) {
966                        // Allow all identical primitives.
967                        (x, y) if x == y => x,
968                        // Allow integers of the same size with differing signedness.
969                        // We arbitrarily choose the signedness of the first variant.
970                        (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
971                        // Allow integers mixed with pointers of the same layout.
972                        // We must represent this using a pointer, to avoid
973                        // roundtripping pointers through ptrtoint/inttoptr.
974                        (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
975                        | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
976                            if p.size(dl) == i.size(dl)
977                                && p.default_align(dl) == i.default_align(dl) =>
978                        {
979                            p
980                        }
981                        _ => {
982                            common_prim = None;
983                            break;
984                        }
985                    };
986                    // We may be updating the primitive here, for example from int->ptr.
987                    common_prim = Some((new_prim, common_offset));
988                } else {
989                    common_prim = Some((prim, offset));
990                }
991            }
992            if let Some((prim, offset)) = common_prim {
993                let prim_scalar = if common_prim_initialized_in_all_variants {
994                    let size = prim.size(dl);
995                    if !(size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
996                    Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
997                } else {
998                    // Common prim might be uninit.
999                    Scalar::Union { value: prim }
1000                };
1001                let pair =
1002                    LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1003                let pair_offsets = match pair.fields {
1004                    FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1005                        {
    match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
        (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!(in_memory_order.raw, [FieldIdx::new(0), FieldIdx::new(1)]);
1006                        offsets
1007                    }
1008                    _ => {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1009                };
1010                if pair_offsets[FieldIdx::new(0)] == Size::ZERO
1011                    && pair_offsets[FieldIdx::new(1)] == *offset
1012                    && align == pair.align.abi
1013                    && size == pair.size
1014                {
1015                    // We can use `ScalarPair` only when it matches our
1016                    // already computed layout (including `#[repr(C)]`).
1017                    abi = pair.backend_repr;
1018                }
1019            }
1020        }
1021
1022        // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1023        // variants to ensure they are consistent. This is because a downcast is
1024        // semantically a NOP, and thus should not affect layout.
1025        if #[allow(non_exhaustive_omitted_patterns)] match abi {
    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } => true,
    _ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) {
1026            for variant in &mut layout_variants {
1027                // We only do this for variants with fields; the others are not accessed anyway.
1028                // Also do not overwrite any already existing "clever" ABIs.
1029                if #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
    BackendRepr::Memory { .. } if variant.has_fields() => true,
    _ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. } if variant.has_fields())
1030                {
1031                    variant.backend_repr = abi;
1032                    // Also need to bump up the size, so that the entire value fits in here.
1033                    variant.size = cmp::max(variant.size, size);
1034                }
1035            }
1036        }
1037
1038        let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1039
1040        let tagged_layout = LayoutData {
1041            variants: Variants::Multiple {
1042                tag,
1043                tag_encoding: TagEncoding::Direct,
1044                tag_field: FieldIdx::new(0),
1045                variants: layout_variants,
1046            },
1047            fields: FieldsShape::Arbitrary {
1048                offsets: [Size::ZERO].into(),
1049                in_memory_order: [FieldIdx::new(0)].into(),
1050            },
1051            largest_niche,
1052            uninhabited,
1053            backend_repr: abi,
1054            align: AbiAlign::new(align),
1055            size,
1056            max_repr_align,
1057            unadjusted_abi_align,
1058            randomization_seed: combined_seed,
1059        };
1060
1061        let best_layout = match (tagged_layout, niche_filling_layout) {
1062            (tl, Some(nl)) => {
1063                // Pick the smaller layout; otherwise,
1064                // pick the layout with the larger niche; otherwise,
1065                // pick tagged as it has simpler codegen.
1066                use cmp::Ordering::*;
1067                let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1068                    l.largest_niche.map_or(0, |n| n.available(dl))
1069                };
1070                match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1071                    (Greater, _) => nl,
1072                    (Equal, Less) => nl,
1073                    _ => tl,
1074                }
1075            }
1076            (tl, None) => tl,
1077        };
1078
1079        Ok(best_layout)
1080    }
1081
1082    fn layout_of_univariant_biased<'a, FieldIdx, VariantIdx, F>(
1083        &self,
1084        fields: &IndexSlice<FieldIdx, F>,
1085        repr: &ReprOptions,
1086        kind: StructKind,
1087        niche_bias: NicheBias,
1088    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1089    where
1090        FieldIdx: Idx,
1091        VariantIdx: Idx,
1092        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1093    {
1094        let dl = self.cx.data_layout();
1095        let pack = repr.pack;
1096        let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1097        let mut max_repr_align = repr.align;
1098        let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1099        let optimize_field_order = !repr.inhibit_struct_field_reordering();
1100        let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1101        let optimizing = &mut in_memory_order.raw[..end];
1102        let fields_excluding_tail = &fields.raw[..end];
1103        // unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
1104        let field_seed = fields_excluding_tail
1105            .iter()
1106            .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
1107
1108        if optimize_field_order && fields.len() > 1 {
1109            // If `-Z randomize-layout` was enabled for the type definition we can shuffle
1110            // the field ordering to try and catch some code making assumptions about layouts
1111            // we don't guarantee.
1112            // In the future, we might do more than shuffle field order (e.g. introduce extra padding),
1113            // but never for `repr(Rust)` structs with only zero-sized fields, single-variant
1114            // `repr(Rust)` enums with only zero-sized fields, or zero-variant `repr(Rust)` enums,
1115            // which must remain zero-sized as per T-lang decisions in
1116            // https://github.com/rust-lang/reference/pull/2262 and https://github.com/rust-lang/reference/pull/2293
1117            if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1118                #[cfg(feature = "randomize")]
1119                {
1120                    use rand::SeedableRng;
1121                    use rand::seq::SliceRandom;
1122                    // `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
1123                    // ordering.
1124                    let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1125                        field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1126                    );
1127
1128                    // Shuffle the ordering of the fields.
1129                    optimizing.shuffle(&mut rng);
1130                }
1131                // Otherwise we just leave things alone and actually optimize the type's fields
1132            } else {
1133                // To allow unsizing `&Foo<Type>` -> `&Foo<dyn Trait>`, the layout of the struct must
1134                // not depend on the layout of the tail.
1135                let max_field_align =
1136                    fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1137                let largest_niche_size = fields_excluding_tail
1138                    .iter()
1139                    .filter_map(|f| f.largest_niche)
1140                    .map(|n| n.available(dl))
1141                    .max()
1142                    .unwrap_or(0);
1143
1144                // Calculates a sort key to group fields by their alignment or possibly some
1145                // size-derived pseudo-alignment.
1146                let alignment_group_key = |layout: &F| {
1147                    // The two branches here return values that cannot be meaningfully compared with
1148                    // each other. However, we know that consistently for all executions of
1149                    // `alignment_group_key`, one or the other branch will be taken, so this is okay.
1150                    if let Some(pack) = pack {
1151                        // Return the packed alignment in bytes.
1152                        layout.align.abi.min(pack).bytes()
1153                    } else {
1154                        // Returns `log2(effective-align)`. The calculation assumes that size is an
1155                        // integer multiple of align, except for ZSTs.
1156                        let align = layout.align.bytes();
1157                        let size = layout.size.bytes();
1158                        let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1159                        // Group [u8; 4] with align-4 or [u8; 6] with align-2 fields.
1160                        let size_as_align = align.max(size).trailing_zeros();
1161                        let size_as_align = if largest_niche_size > 0 {
1162                            match niche_bias {
1163                                // Given `A(u8, [u8; 16])` and `B(bool, [u8; 16])` we want to bump the
1164                                // array to the front in the first case (for aligned loads) but keep
1165                                // the bool in front in the second case for its niches.
1166                                NicheBias::Start => {
1167                                    max_field_align.trailing_zeros().min(size_as_align)
1168                                }
1169                                // When moving niches towards the end of the struct then for
1170                                // A((u8, u8, u8, bool), (u8, bool, u8)) we want to keep the first tuple
1171                                // in the align-1 group because its bool can be moved closer to the end.
1172                                NicheBias::End if niche_size == largest_niche_size => {
1173                                    align.trailing_zeros()
1174                                }
1175                                NicheBias::End => size_as_align,
1176                            }
1177                        } else {
1178                            size_as_align
1179                        };
1180                        size_as_align as u64
1181                    }
1182                };
1183
1184                match kind {
1185                    StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1186                        // Currently `LayoutData` only exposes a single niche so sorting is usually
1187                        // sufficient to get one niche into the preferred position. If it ever
1188                        // supported multiple niches then a more advanced pick-and-pack approach could
1189                        // provide better results. But even for the single-niche cache it's not
1190                        // optimal. E.g. for A(u32, (bool, u8), u16) it would be possible to move the
1191                        // bool to the front but it would require packing the tuple together with the
1192                        // u16 to build a 4-byte group so that the u32 can be placed after it without
1193                        // padding. This kind of packing can't be achieved by sorting.
1194                        optimizing.sort_by_key(|&x| {
1195                            let f = &fields[x];
1196                            let field_size = f.size.bytes();
1197                            let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1198                            let niche_size_key = match niche_bias {
1199                                // large niche first
1200                                NicheBias::Start => !niche_size,
1201                                // large niche last
1202                                NicheBias::End => niche_size,
1203                            };
1204                            let inner_niche_offset_key = match niche_bias {
1205                                NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1206                                NicheBias::End => f.largest_niche.map_or(0, |n| {
1207                                    !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1208                                }),
1209                            };
1210
1211                            (
1212                                // Then place largest alignments first.
1213                                cmp::Reverse(alignment_group_key(f)),
1214                                // Then prioritize niche placement within alignment group according to
1215                                // `niche_bias_start`.
1216                                niche_size_key,
1217                                // Then among fields with equally-sized niches prefer the ones
1218                                // closer to the start/end of the field.
1219                                inner_niche_offset_key,
1220                            )
1221                        });
1222                    }
1223
1224                    StructKind::Prefixed(..) => {
1225                        // Sort in ascending alignment so that the layout stays optimal
1226                        // regardless of the prefix.
1227                        // And put the largest niche in an alignment group at the end
1228                        // so it can be used as discriminant in jagged enums
1229                        optimizing.sort_by_key(|&x| {
1230                            let f = &fields[x];
1231                            let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1232                            (alignment_group_key(f), niche_size)
1233                        });
1234                    }
1235                }
1236
1237                // FIXME(Kixiron): We can always shuffle fields within a given alignment class
1238                //                 regardless of the status of `-Z randomize-layout`
1239            }
1240        }
1241        // in_memory_order holds field indices by increasing memory offset.
1242        // That is, if field 5 has offset 0, the first element of in_memory_order is 5.
1243        // We now write field offsets to the corresponding offset slot;
1244        // field 5 with offset 0 puts 0 in offsets[5].
1245        let mut unsized_field = None::<&F>;
1246        let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1247        let mut offset = Size::ZERO;
1248        let mut largest_niche = None;
1249        let mut largest_niche_available = 0;
1250        if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1251            let prefix_align =
1252                if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1253            align = align.max(prefix_align);
1254            offset = prefix_size.align_to(prefix_align);
1255        }
1256        for &i in &in_memory_order {
1257            let field = &fields[i];
1258            if let Some(unsized_field) = unsized_field {
1259                return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1260            }
1261
1262            if field.is_unsized() {
1263                if let StructKind::MaybeUnsized = kind {
1264                    unsized_field = Some(field);
1265                } else {
1266                    return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1267                }
1268            }
1269
1270            // Invariant: offset < dl.obj_size_bound() <= 1<<61
1271            let field_align = if let Some(pack) = pack {
1272                field.align.min(AbiAlign::new(pack))
1273            } else {
1274                field.align
1275            };
1276            offset = offset.align_to(field_align.abi);
1277            align = align.max(field_align.abi);
1278            max_repr_align = max_repr_align.max(field.max_repr_align);
1279
1280            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:1280",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1280u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::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!("univariant offset: {0:?} field: {1:#?}",
                                                    offset, field) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("univariant offset: {:?} field: {:#?}", offset, field);
1281            offsets[i] = offset;
1282
1283            if let Some(mut niche) = field.largest_niche {
1284                let available = niche.available(dl);
1285                // Pick up larger niches.
1286                let prefer_new_niche = match niche_bias {
1287                    NicheBias::Start => available > largest_niche_available,
1288                    // if there are several niches of the same size then pick the last one
1289                    NicheBias::End => available >= largest_niche_available,
1290                };
1291                if prefer_new_niche {
1292                    largest_niche_available = available;
1293                    niche.offset += offset;
1294                    largest_niche = Some(niche);
1295                }
1296            }
1297
1298            offset =
1299                offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1300        }
1301
1302        // The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
1303        // See documentation on `LayoutData::unadjusted_abi_align`.
1304        let unadjusted_abi_align = align;
1305        if let Some(repr_align) = repr.align {
1306            align = align.max(repr_align);
1307        }
1308        // `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate.
1309        let align = align;
1310
1311        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:1311",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1311u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::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!("univariant min_size: {0:?}",
                                                    offset) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("univariant min_size: {:?}", offset);
1312        let min_size = offset;
1313        let size = min_size.align_to(align);
1314        // FIXME(oli-obk): deduplicate and harden these checks
1315        if size.bytes() >= dl.obj_size_bound() {
1316            return Err(LayoutCalculatorError::SizeOverflow);
1317        }
1318        let mut layout_of_single_non_zst_field = None;
1319        let sized = unsized_field.is_none();
1320        let mut abi = BackendRepr::Memory { sized };
1321
1322        let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1323
1324        // Try to make this a Scalar/ScalarPair.
1325        if sized && size.bytes() > 0 {
1326            // We skip *all* ZST here and later check if we are good in terms of alignment.
1327            // This lets us handle some cases involving aligned ZST.
1328            let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
1329
1330            match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1331                // We have exactly one non-ZST field.
1332                (Some((i, field)), None, None) => {
1333                    layout_of_single_non_zst_field = Some(field);
1334
1335                    // Field fills the struct and it has a scalar or scalar pair ABI.
1336                    if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1337                        match field.backend_repr {
1338                            // For plain scalars, or vectors of them, we can't unpack
1339                            // newtypes for `#[repr(C)]`, as that affects C ABIs.
1340                            BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1341                                if optimize_abi =>
1342                            {
1343                                abi = field.backend_repr;
1344                            }
1345                            // But scalar pairs are Rust-specific and get
1346                            // treated as aggregates by C ABIs anyway.
1347                            BackendRepr::ScalarPair { .. } => {
1348                                abi = field.backend_repr;
1349                            }
1350                            _ => {}
1351                        }
1352                    }
1353                }
1354
1355                // Two non-ZST fields, and they're both scalars.
1356                (Some((i, a)), Some((j, b)), None) => {
1357                    match (a.backend_repr, b.backend_repr) {
1358                        (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1359                            // Order by the memory placement, not source order.
1360                            let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1361                                ((i, a), (j, b))
1362                            } else {
1363                                ((j, b), (i, a))
1364                            };
1365                            let pair =
1366                                LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1367                            let pair_offsets = match pair.fields {
1368                                FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1369                                    {
    match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
        (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!(
1370                                        in_memory_order.raw,
1371                                        [FieldIdx::new(0), FieldIdx::new(1)]
1372                                    );
1373                                    offsets
1374                                }
1375                                FieldsShape::Primitive
1376                                | FieldsShape::Array { .. }
1377                                | FieldsShape::Union(..) => {
1378                                    {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")
1379                                }
1380                            };
1381                            if offsets[i] == pair_offsets[FieldIdx::new(0)]
1382                                && offsets[j] == pair_offsets[FieldIdx::new(1)]
1383                                && align == pair.align.abi
1384                                && size == pair.size
1385                            {
1386                                // We can use `ScalarPair` only when it matches our
1387                                // already computed layout (including `#[repr(C)]`).
1388                                abi = pair.backend_repr;
1389                            }
1390                        }
1391                        _ => {}
1392                    }
1393                }
1394
1395                _ => {}
1396            }
1397        }
1398        let uninhabited = fields.iter().any(|f| f.is_uninhabited());
1399
1400        let unadjusted_abi_align = if repr.transparent() {
1401            match layout_of_single_non_zst_field {
1402                Some(l) => l.unadjusted_abi_align,
1403                None => {
1404                    // `repr(transparent)` with all ZST fields.
1405                    align
1406                }
1407            }
1408        } else {
1409            unadjusted_abi_align
1410        };
1411
1412        let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
1413
1414        Ok(LayoutData {
1415            variants: Variants::Single { index: VariantIdx::new(0) },
1416            fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1417            backend_repr: abi,
1418            largest_niche,
1419            uninhabited,
1420            align: AbiAlign::new(align),
1421            size,
1422            max_repr_align,
1423            unadjusted_abi_align,
1424            randomization_seed: seed,
1425        })
1426    }
1427
1428    fn format_field_niches<'a, FieldIdx, VariantIdx, F>(
1429        &self,
1430        layout: &LayoutData<FieldIdx, VariantIdx>,
1431        fields: &IndexSlice<FieldIdx, F>,
1432    ) -> String
1433    where
1434        FieldIdx: Idx,
1435        VariantIdx: Idx,
1436        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1437    {
1438        let dl = self.cx.data_layout();
1439        let mut s = String::new();
1440        for i in layout.fields.index_by_increasing_offset() {
1441            let offset = layout.fields.offset(i);
1442            let f = &fields[FieldIdx::new(i)];
1443            s.write_fmt(format_args!("[o{0}a{1}s{2}", offset.bytes(), f.align.bytes(),
        f.size.bytes()))write!(s, "[o{}a{}s{}", offset.bytes(), f.align.bytes(), f.size.bytes()).unwrap();
1444            if let Some(n) = f.largest_niche {
1445                s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
        n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1446                    s,
1447                    " n{}b{}s{}",
1448                    n.offset.bytes(),
1449                    n.available(dl).ilog2(),
1450                    n.value.size(dl).bytes()
1451                )
1452                .unwrap();
1453            }
1454            s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1455        }
1456        s
1457    }
1458}
1459
1460enum SimdVectorKind {
1461    /// `#[rustc_scalable_vector]`
1462    Scalable(NumScalableVectors),
1463    /// `#[repr(simd, packed)]`
1464    PackedFixed,
1465    /// `#[repr(simd)]`
1466    Fixed,
1467}
1468
1469fn vector_type_layout<FieldIdx, VariantIdx, F>(
1470    kind: SimdVectorKind,
1471    dl: &TargetDataLayout,
1472    element: F,
1473    count: u64,
1474) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1475where
1476    FieldIdx: Idx,
1477    VariantIdx: Idx,
1478    F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1479{
1480    let elt = element.as_ref();
1481    let count = BackendLaneCount::new(count)?;
1482
1483    let BackendRepr::Scalar(element) = elt.backend_repr else {
1484        return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1485    };
1486
1487    // Compute the size and alignment of the vector
1488    let size =
1489        elt.size.checked_mul(count.as_u64(), dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1490    let (repr, size, align) = match kind {
1491        SimdVectorKind::Scalable(number_of_vectors) => (
1492            BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1493            size.checked_mul(number_of_vectors.0 as u64, dl)
1494                .ok_or(LayoutCalculatorError::SizeOverflow)?,
1495            dl.rust_vector_align(size),
1496        ),
1497        // Non-power-of-two vectors have padding up to the next power-of-two.
1498        // If we're a packed repr, remove the padding while keeping the alignment as close
1499        // to a vector as possible.
1500        SimdVectorKind::PackedFixed if !count.is_power_of_two() => {
1501            (BackendRepr::Memory { sized: true }, size, Align::max_aligned_factor(size))
1502        }
1503        SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
1504            (BackendRepr::SimdVector { element, count }, size, dl.rust_vector_align(size))
1505        }
1506    };
1507    let size = size.align_to(align);
1508
1509    Ok(LayoutData {
1510        variants: Variants::Single { index: VariantIdx::new(0) },
1511        fields: FieldsShape::Arbitrary {
1512            offsets: [Size::ZERO].into(),
1513            in_memory_order: [FieldIdx::new(0)].into(),
1514        },
1515        backend_repr: repr,
1516        largest_niche: elt.largest_niche,
1517        uninhabited: false,
1518        size,
1519        align: AbiAlign::new(align),
1520        max_repr_align: None,
1521        unadjusted_abi_align: elt.align.abi,
1522        randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count.as_u64())),
1523    })
1524}