Skip to main content

rustc_abi/layout/
enum_layout.rs

1use std::ops::Deref;
2use std::range::{RangeFrom, RangeInclusive, RangeToInclusive};
3use std::{cmp, fmt, iter};
4
5use rustc_index::Idx;
6use tracing::trace;
7
8use super::{LayoutCalculator, LayoutCalculatorError, LayoutCalculatorResult, absent};
9use crate::{
10    Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer, LayoutData,
11    Niche, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding, TargetDataLayout,
12    VariantLayout, Variants, WrappingRange,
13};
14
15pub(super) fn layout_of_enum<'a, Cx: HasDataLayout, FieldIdx, VariantIdx, F>(
16    calculator: &LayoutCalculator<Cx>,
17    repr: &ReprOptions,
18    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
19    discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
20    discriminants: impl Iterator<Item = (VariantIdx, u128)>,
21) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
22where
23    FieldIdx: Idx,
24    VariantIdx: Idx,
25    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
26{
27    let dl = calculator.cx.data_layout();
28    // bail if the enum has an incoherent repr that cannot be computed
29    if repr.packed() {
30        return Err(LayoutCalculatorError::ReprConflict);
31    }
32
33    let niche_filling_layout = calculate_niche_filling_layout(calculator, repr, variants);
34
35    let tagged_layout =
36        calculate_tagged_layout(calculator, repr, variants, discr_range_of_repr, discriminants)?;
37
38    let Some(nl) = niche_filling_layout else {
39        return Ok(tagged_layout);
40    };
41
42    // Pick the smaller layout; otherwise,
43    // pick the layout with the larger niche; otherwise,
44    // pick tagged as it has simpler codegen.
45    use cmp::Ordering::*;
46    let niche_size =
47        |l: &LayoutData<FieldIdx, VariantIdx>| l.largest_niche.map_or(0, |n| n.available(dl));
48    let best_layout = match (
49        tagged_layout.size.cmp(&nl.size),
50        niche_size(&tagged_layout).cmp(&niche_size(&nl)),
51    ) {
52        (Greater, _) => nl,
53        (Equal, Less) => nl,
54        _ => tagged_layout,
55    };
56
57    Ok(best_layout)
58}
59
60struct CommonPrimitive {
61    primitive: Primitive,
62    offset: Size,
63    initialized_in_all_variants: bool,
64}
65
66fn calculate_common_primitive<'a, VariantIdx, FieldIdx, F>(
67    dl: &TargetDataLayout,
68    layout_variants: &IndexSlice<VariantIdx, VariantLayout<FieldIdx>>,
69    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
70) -> Option<CommonPrimitive>
71where
72    FieldIdx: Idx,
73    VariantIdx: Idx,
74    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
75{
76    // Try to use a ScalarPair for all tagged enums.
77    // That's possible only if we can find a common primitive type for all variants.
78    let mut common_prim = None;
79    let mut initialized_in_all_variants = true;
80    for (field_layouts, layout_variant) in iter::zip(variants, layout_variants) {
81        // We skip *all* ZST here and later check if we are good in terms of alignment.
82        // This lets us handle some cases involving aligned ZST.
83        let mut fields =
84            iter::zip(field_layouts, &layout_variant.field_offsets).filter(|p| !p.0.is_zst());
85        let (field, offset) = match (fields.next(), fields.next()) {
86            (None, None) => {
87                initialized_in_all_variants = false;
88                continue;
89            }
90            (Some(pair), None) => pair,
91            _ => {
92                return None;
93            }
94        };
95        let prim = match field.backend_repr {
96            BackendRepr::Scalar(scalar) => {
97                initialized_in_all_variants &= #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Initialized { .. } => true,
    _ => false,
}matches!(scalar, Scalar::Initialized { .. });
98                scalar.primitive()
99            }
100            _ => {
101                return None;
102            }
103        };
104        if let Some((old_prim, common_offset)) = common_prim {
105            // All variants must be at the same offset
106            if offset != common_offset {
107                return None;
108            }
109            // This is pretty conservative. We could go fancier
110            // by realising that (u8, u8) could just cohabit with
111            // u16 or even u32.
112            let new_prim = match (old_prim, prim) {
113                // Allow all identical primitives.
114                (x, y) if x == y => x,
115                // Allow integers of the same size with differing signedness.
116                // We arbitrarily choose the signedness of the first variant.
117                (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
118                // Allow booleans to unify with integers of size 1
119                (p @ Primitive::Int(Integer::I8, _), Primitive::Bool)
120                | (Primitive::Bool, p @ Primitive::Int(Integer::I8, _)) => p,
121                // Allow integers mixed with pointers of the same layout.
122                // We must represent this using a pointer, to avoid
123                // roundtripping pointers through ptrtoint/inttoptr.
124                (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
125                | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
126                    if p.size(dl) == i.size(dl) && p.default_align(dl) == i.default_align(dl) =>
127                {
128                    p
129                }
130                _ => {
131                    return None;
132                }
133            };
134            // We may be updating the primitive here, for example from int->ptr.
135            common_prim = Some((new_prim, common_offset));
136        } else {
137            common_prim = Some((prim, offset));
138        }
139    }
140    common_prim.map(|(primitive, offset)| CommonPrimitive {
141        primitive,
142        offset: *offset,
143        initialized_in_all_variants,
144    })
145}
146
147fn scalar_pair_repr<'a, Cx, VariantIdx, FieldIdx, F>(
148    calculator: &LayoutCalculator<Cx>,
149    layout_variants: &IndexSlice<VariantIdx, VariantLayout<FieldIdx>>,
150    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
151    size: Size,
152    align: Align,
153    tag: Scalar,
154) -> Option<BackendRepr>
155where
156    Cx: HasDataLayout,
157    FieldIdx: Idx,
158    VariantIdx: Idx,
159    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
160{
161    let CommonPrimitive { primitive, offset, initialized_in_all_variants } =
162        calculate_common_primitive(calculator.cx.data_layout(), layout_variants, variants)?;
163    let prim_scalar = if initialized_in_all_variants {
164        let size = primitive.size(calculator.cx.data_layout());
165        if !(size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
166        Scalar::Initialized { value: primitive, valid_range: WrappingRange::full(size) }
167    } else {
168        // Common prim might be uninit.
169        Scalar::Union { value: primitive }
170    };
171    let pair = LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&calculator.cx, tag, prim_scalar);
172    let pair_offsets = match pair.fields {
173        FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
174            {
    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)]);
175            offsets
176        }
177        _ => {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
178    };
179    if pair_offsets[FieldIdx::new(0)] == Size::ZERO
180        && pair_offsets[FieldIdx::new(1)] == offset
181        && align == pair.align
182        && size == pair.size
183    {
184        // We can use `ScalarPair` only when it matches our
185        // already computed layout (including `#[repr(C)]`).
186        Some(pair.backend_repr)
187    } else {
188        None
189    }
190}
191
192fn calculate_tagged_abi<'a, Cx, VariantIdx, FieldIdx, F>(
193    calculator: &LayoutCalculator<Cx>,
194    layout_variants: &IndexSlice<VariantIdx, VariantLayout<FieldIdx>>,
195    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
196    size: Size,
197    align: Align,
198    tag: Scalar,
199) -> BackendRepr
200where
201    Cx: HasDataLayout,
202    FieldIdx: Idx,
203    VariantIdx: Idx,
204    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
205{
206    if tag.size(calculator.cx.data_layout()) == size {
207        // Make sure we only use scalar layout when the enum is entirely its
208        // own tag (i.e. it has no padding nor any non-ZST variant fields).
209        BackendRepr::Scalar(tag)
210    } else if let Some(repr) =
211        scalar_pair_repr(calculator, layout_variants, variants, size, align, tag)
212    {
213        repr
214    } else {
215        BackendRepr::Memory { sized: true }
216    }
217}
218
219fn sanity_check_ity(dl: &TargetDataLayout, repr: &ReprOptions, min_ity: Integer) {
220    let typeck_ity = Integer::from_attr(dl, repr.discr_type());
221    if typeck_ity < min_ity {
222        // It is a bug if Layout decided on a greater discriminant size than typeck for
223        // some reason at this point (based on values discriminant can take on). Mostly
224        // because this discriminant will be loaded, and then stored into variable of
225        // type calculated by typeck. Consider such case (a bug): typeck decided on
226        // byte-sized discriminant, but layout thinks we need a 16-bit to store all
227        // discriminant values. That would be a bug, because then, in codegen, in order
228        // to store this 16-bit discriminant into 8-bit sized temporary some of the
229        // space necessary to represent would have to be discarded (or layout is wrong
230        // on thinking it needs 16 bits)
231        {
    ::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
            min_ity, typeck_ity));
};panic!(
232            "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
233        );
234    }
235}
236
237fn calculate_tagged_min_ity(
238    repr: &ReprOptions,
239    necessary_discriminants: &[u128],
240    discr_size: Size,
241    discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
242) -> (Integer, bool) {
243    // When picking the integer to use, we respect how the discriminants were written
244    // in the original rust code, rather than looking only at the bit pattern.
245    let (min_negative, max_positive): (i128, u128) = if repr.discr_type().is_signed() {
246        necessary_discriminants.iter().copied().map(|val| discr_size.sign_extend(val)).fold(
247            (0_i128, 0_u128),
248            |(min, max), val| {
249                if let Ok(val) = u128::try_from(val) {
250                    (min, max.max(val))
251                } else {
252                    (min.min(val), max)
253                }
254            },
255        )
256    } else {
257        // We might have no inhabited variants, so pretend there's at least one.
258        (0, necessary_discriminants.iter().copied().max().unwrap_or(0))
259    };
260    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_abi/src/layout/enum_layout.rs:260",
                        "rustc_abi::layout::enum_layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_abi/src/layout/enum_layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(260u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout::enum_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);
261
262    // Integer::discr_range_of_repr(tcx, ty, &repr, min, max);
263    discr_range_of_repr(RangeFrom { start: min_negative }, RangeToInclusive { last: max_positive })
264}
265
266fn finalize_tag_and_patch_variants<FieldIdx, VariantIdx>(
267    dl: &TargetDataLayout,
268    repr: &ReprOptions,
269    min_ity: Integer,
270    start_align: Align,
271    signed: bool,
272    necessary_discriminants: Vec<u128>,
273    layout_variants: &mut IndexSlice<VariantIdx, VariantLayout<FieldIdx>>,
274) -> Scalar
275where
276    FieldIdx: Idx,
277    VariantIdx: Idx,
278{
279    sanity_check_ity(dl, repr, min_ity);
280    // It is fine to make discr type however large (as an optimisation)
281    // after this point – we’ll just truncate the value we load in codegen.
282
283    // Check to see if we should use a different type for the
284    // discriminant. We can safely use a type with the same size
285    // as the alignment of the first field of each variant.
286    // We increase the size of the discriminant to avoid LLVM copying
287    // padding when it doesn't need to. This normally causes unaligned
288    // load/stores and excessive memcpy/memset operations. By using a
289    // bigger integer size, LLVM can be sure about its contents and
290    // won't be so conservative.
291
292    // Use the initial field alignment
293    let ity = if repr.c() {
294        min_ity
295    } else if let Some(ity) = repr.int {
296        Integer::from_attr(dl, ity)
297    } else {
298        Integer::for_align(dl, start_align)
299            .unwrap_or(min_ity)
300            // If the alignment is not larger than the chosen discriminant size,
301            // don't use the alignment as the final size.
302            .max(min_ity)
303    };
304
305    // If the alignment is not larger than the chosen discriminant size,
306    // don't use the alignment as the final size.
307    if ity > min_ity {
308        // Patch up the variants' first few fields.
309        let old_ity_size = min_ity.size();
310        let new_ity_size = ity.size();
311        for variant in layout_variants {
312            for i in &mut variant.field_offsets {
313                if *i <= old_ity_size {
314                    {
    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);
315                    *i = new_ity_size;
316                }
317            }
318            // We might be making the struct larger.
319            if variant.size <= old_ity_size {
320                variant.size = new_ity_size;
321            }
322        }
323    }
324
325    let tag_valid_range = {
326        let tag_size = ity.size();
327        let tags = necessary_discriminants.into_iter().map(|d| tag_size.truncate(d));
328        WrappingRange::smallest_range_containing(tags, tag_size)
329            // We might have no inhabited variants, so pretend there's at least one.
330            .unwrap_or(WrappingRange { start: 0, end: 0 })
331    };
332
333    // for an enum that does NOT have an explicit repr, and only has discriminants 0..=1, use Bool for it
334    if repr.int.is_none()
335        && !repr.c()
336        && #[allow(non_exhaustive_omitted_patterns)] match tag_valid_range {
    WrappingRange { start: 0, end: 1 } => true,
    _ => false,
}matches!(tag_valid_range, WrappingRange { start: 0, end: 1 })
337        && ity == Integer::I8
338    {
339        Scalar::Initialized { value: Primitive::Bool, valid_range: tag_valid_range }
340    } else {
341        Scalar::Initialized { value: Primitive::Int(ity, signed), valid_range: tag_valid_range }
342    }
343}
344
345fn variant_is_inhabited<'a, VariantIdx, FieldIdx, F>(variant: &IndexSlice<FieldIdx, F>) -> bool
346where
347    FieldIdx: Idx,
348    VariantIdx: Idx,
349    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
350{
351    variant.iter().all(|f| !f.is_uninhabited())
352}
353
354fn calculate_tagged_layout<'a, Cx: HasDataLayout, FieldIdx, VariantIdx, F>(
355    calculator: &LayoutCalculator<Cx>,
356    repr: &ReprOptions,
357    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
358    discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
359    discriminants: impl Iterator<Item = (VariantIdx, u128)>,
360) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
361where
362    FieldIdx: Idx,
363    VariantIdx: Idx,
364    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
365{
366    let dl = calculator.cx.data_layout();
367    let discr_size = Integer::from_attr(dl, repr.discr_type()).size();
368
369    let necessary_discriminants: Vec<u128> = discriminants
370        .filter(|&(i, _)| repr.c() || variant_is_inhabited(&variants[i]))
371        .map(|(_, val)| val)
372        .collect();
373
374    let (min_ity, signed) =
375        calculate_tagged_min_ity(repr, &necessary_discriminants, discr_size, discr_range_of_repr);
376
377    let mut align = dl.aggregate_align;
378    let mut max_repr_align = repr.align;
379    let mut unadjusted_abi_align = align;
380    let mut combined_seed = repr.field_shuffle_seed;
381
382    let mut size = Size::ZERO;
383
384    // We're interested in the smallest alignment, so start large.
385    let mut start_align = Align::from_bytes(256).unwrap();
386    {
    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);
387
388    // repr(C) on an enum tells us to make a (tag, union) layout,
389    // so we need to grow the prefix alignment to be at least
390    // the alignment of the union. (This value is used both for
391    // determining the alignment of the overall enum, and the
392    // determining the alignment of the payload after the tag.)
393    let prefix_align = if repr.c() {
394        variants
395            .iter()
396            .flatten()
397            .fold(min_ity.align(dl), |prefix_align, field| prefix_align.max(field.align))
398    } else {
399        min_ity.align(dl)
400    };
401
402    // Create the set of structs that represent each variant.
403    let mut layout_variants = variants
404        .iter()
405        .map(|field_layouts| {
406            let st = calculator.layout_of_univariant(
407                field_layouts,
408                repr,
409                StructKind::Prefixed(min_ity.size(), prefix_align),
410            )?;
411            // Find the first field we can't move later
412            // to make room for a larger discriminant.
413            for field_idx in st.fields.index_by_increasing_offset() {
414                let field = &field_layouts[FieldIdx::new(field_idx)];
415                if !field.is_1zst() {
416                    start_align = start_align.min(field.align);
417                    break;
418                }
419            }
420            size = cmp::max(size, st.size);
421            align = align.max(st.align);
422            max_repr_align = max_repr_align.max(st.max_repr_align);
423            unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
424            combined_seed = combined_seed.wrapping_add(st.randomization_seed);
425            Ok(VariantLayout::from_layout(st))
426        })
427        .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
428
429    // Align the maximum variant size to the largest alignment.
430    let size = size.align_to(align);
431
432    // FIXME(oli-obk): deduplicate and harden these checks
433    if size.bytes() >= dl.obj_size_bound() {
434        return Err(LayoutCalculatorError::SizeOverflow);
435    }
436
437    let tag = finalize_tag_and_patch_variants(
438        dl,
439        repr,
440        min_ity,
441        start_align,
442        signed,
443        necessary_discriminants,
444        &mut layout_variants,
445    );
446    let abi = calculate_tagged_abi(calculator, &layout_variants, variants, size, align, tag);
447
448    // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
449    // variants to ensure they are consistent. This is because a downcast is
450    // semantically a NOP, and thus should not affect layout.
451    if #[allow(non_exhaustive_omitted_patterns)] match abi {
    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } => true,
    _ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) {
452        for variant in &mut layout_variants {
453            // We only do this for variants with fields; the others are not accessed anyway.
454            // Also do not overwrite any already existing "clever" ABIs.
455            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()) {
456                variant.backend_repr = abi;
457                // Also need to bump up the size, so that the entire value fits in here.
458                variant.size = cmp::max(variant.size, size);
459            }
460        }
461    }
462
463    let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
464
465    Ok(LayoutData {
466        uninhabited: layout_variants.iter().all(|v| v.is_uninhabited()),
467        variants: Variants::Multiple {
468            tag,
469            tag_encoding: TagEncoding::Direct,
470            tag_field: FieldIdx::new(0),
471            variants: layout_variants,
472        },
473        fields: FieldsShape::Arbitrary {
474            offsets: [Size::ZERO].into(),
475            in_memory_order: [FieldIdx::new(0)].into(),
476        },
477        largest_niche,
478        backend_repr: abi,
479        align,
480        size,
481        max_repr_align,
482        unadjusted_abi_align,
483        repr_c: repr.c(),
484        randomization_seed: combined_seed,
485    })
486}
487
488struct VariantLayoutInfo {
489    align_abi: Align,
490}
491
492/// We are trying to add the tag at `niche_offset` with `niche_size` size in variants
493/// that are not `largest_variant_index`. The layout in these variants must be changed
494/// such that the data stored does not overlap with the tag.
495fn try_fit_variants_around_niche_tag<VariantIdx: Idx, FieldIdx: Idx>(
496    mut variant_layouts: IndexVec<VariantIdx, VariantLayout<FieldIdx>>,
497    variants_info: &IndexSlice<VariantIdx, VariantLayoutInfo>,
498    largest_variant_index: VariantIdx,
499    niche_offset: Size,
500    niche_size: Size,
501    size: Size,
502) -> Option<IndexVec<VariantIdx, VariantLayout<FieldIdx>>> {
503    for (i, layout) in variant_layouts.iter_enumerated_mut() {
504        if i == largest_variant_index {
505            continue;
506        }
507
508        layout.largest_niche = None;
509
510        if layout.size <= niche_offset {
511            // This variant will fit before the niche.
512            continue;
513        }
514
515        // Determine if it'll fit after the niche.
516        let this_align = variants_info[i].align_abi;
517        let this_offset = (niche_offset + niche_size).align_to(this_align);
518
519        if this_offset + layout.size > size {
520            return None;
521        }
522
523        // It'll fit, but we need to make some adjustments.
524        for offset in layout.field_offsets.iter_mut() {
525            *offset += this_offset;
526        }
527
528        // It can't be a Scalar or ScalarPair because the offset isn't 0.
529        if !layout.is_uninhabited() {
530            layout.backend_repr = BackendRepr::Memory { sized: true };
531        }
532        layout.size += this_offset;
533    }
534    Some(variant_layouts)
535}
536
537fn calculate_niche_abi<FieldIdx: Idx, VariantIdx: Idx>(
538    variant_layouts: &IndexSlice<VariantIdx, VariantLayout<FieldIdx>>,
539    variants_info: &IndexSlice<VariantIdx, VariantLayoutInfo>,
540    niche_scalar: Scalar,
541    largest_variant_index: VariantIdx,
542    size: Size,
543    align: Align,
544    niche_offset: Size,
545) -> BackendRepr {
546    let others_zst = variant_layouts
547        .iter_enumerated()
548        .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
549    let same_size = size == variant_layouts[largest_variant_index].size;
550    let same_align = align == variants_info[largest_variant_index].align_abi;
551
552    if same_size && same_align && others_zst {
553        match variant_layouts[largest_variant_index].backend_repr {
554            // When the total alignment and size match, we can use the
555            // same ABI as the scalar variant with the reserved niche.
556            BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
557            BackendRepr::ScalarPair { a: first, b: second, b_offset } => {
558                // Only the niche is guaranteed to be initialised,
559                // so use union layouts for the other primitive.
560                if niche_offset == Size::ZERO {
561                    BackendRepr::ScalarPair { a: niche_scalar, b: second.to_union(), b_offset }
562                } else {
563                    BackendRepr::ScalarPair { a: first.to_union(), b: niche_scalar, b_offset }
564                }
565            }
566            _ => BackendRepr::Memory { sized: true },
567        }
568    } else {
569        BackendRepr::Memory { sized: true }
570    }
571}
572
573fn calculate_niche_filling_layout<'a, Cx: HasDataLayout, FieldIdx, VariantIdx, F>(
574    calculator: &LayoutCalculator<Cx>,
575    repr: &ReprOptions,
576    variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
577) -> Option<LayoutData<FieldIdx, VariantIdx>>
578where
579    FieldIdx: Idx,
580    VariantIdx: Idx,
581    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
582{
583    let dl = calculator.cx.data_layout();
584    if repr.inhibit_enum_layout_opt() {
585        return None;
586    }
587
588    if variants.len() < 2 {
589        return None;
590    }
591
592    let mut align = dl.aggregate_align;
593    let mut max_repr_align = repr.align;
594    let mut unadjusted_abi_align = align;
595    let mut combined_seed = repr.field_shuffle_seed;
596
597    let mut variants_info = IndexVec::<VariantIdx, _>::with_capacity(variants.len());
598    let variant_layouts = variants
599        .iter()
600        .map(|v| {
601            let st = calculator.layout_of_univariant(v, repr, StructKind::AlwaysSized).ok()?;
602
603            variants_info.push(VariantLayoutInfo { align_abi: st.align });
604
605            align = align.max(st.align);
606            max_repr_align = max_repr_align.max(st.max_repr_align);
607            unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
608            combined_seed = combined_seed.wrapping_add(st.randomization_seed);
609
610            Some(VariantLayout::from_layout(st))
611        })
612        .collect::<Option<IndexVec<VariantIdx, _>>>()?;
613
614    let largest_variant_index = variant_layouts
615        .iter_enumerated()
616        .max_by_key(|(_i, layout)| layout.size.bytes())
617        .map(|(i, _layout)| i)?;
618
619    let needs_disc =
620        |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
621    let niche_variants = RangeInclusive {
622        start: variants.indices().find(|v| needs_disc(*v)).unwrap(),
623        last: variants.indices().rev().find(|v| needs_disc(*v)).unwrap(),
624    };
625
626    let count = (niche_variants.last.index() as u128 - niche_variants.start.index() as u128) + 1;
627
628    // Use the largest niche in the largest variant.
629    let niche = variant_layouts[largest_variant_index].largest_niche?;
630    let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
631    let size = variant_layouts[largest_variant_index].size.align_to(align);
632
633    let variant_layouts = try_fit_variants_around_niche_tag(
634        variant_layouts,
635        &variants_info,
636        largest_variant_index,
637        niche.offset,
638        niche.value.size(dl),
639        size,
640    )?;
641
642    let abi = calculate_niche_abi(
643        &variant_layouts,
644        &variants_info,
645        niche_scalar,
646        largest_variant_index,
647        size,
648        align,
649        niche.offset,
650    );
651
652    let layout = LayoutData {
653        uninhabited: variant_layouts.iter().all(|v| v.is_uninhabited()),
654        variants: Variants::Multiple {
655            tag: niche_scalar,
656            tag_encoding: TagEncoding::Niche {
657                untagged_variant: largest_variant_index,
658                niche_variants,
659                niche_start,
660            },
661            tag_field: FieldIdx::new(0),
662            variants: variant_layouts,
663        },
664        fields: FieldsShape::Arbitrary {
665            offsets: [niche.offset].into(),
666            in_memory_order: [FieldIdx::new(0)].into(),
667        },
668        backend_repr: abi,
669        largest_niche: Niche::from_scalar(dl, niche.offset, niche_scalar),
670        size,
671        align,
672        max_repr_align,
673        unadjusted_abi_align,
674        repr_c: repr.c(),
675        randomization_seed: combined_seed,
676    };
677
678    Some(layout)
679}