blob: cf03f434fbce455668f8537593b91cc5d265c5c0 [file]
use std::cmp;
use std::fmt::{self, Write};
use std::num::NonZero;
use std::ops::Deref;
use std::range::{RangeFrom, RangeToInclusive};
pub use coroutine::PackCoroutineLayout;
use rustc_hashes::Hash64;
use rustc_index::Idx;
use rustc_index::bit_set::BitMatrix;
use tracing::debug;
use crate::{
Align, BackendLaneCount, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec,
Integer, LayoutData, NicheOptimizations, NumScalableVectors, ReprOptions, Scalar, Size,
StructKind, TargetDataLayout, Variants, WrappingRange,
};
mod coroutine;
mod enum_layout;
mod simple;
#[cfg(feature = "nightly")]
mod ty;
#[cfg(feature = "nightly")]
pub use ty::{Layout, TyAbiInterface, TyAndLayout};
rustc_index::newtype_index! {
/// The *source-order* index of a field in a variant.
///
/// This is how most code after type checking refers to fields, rather than
/// using names (as names have hygiene complications and more complex lookup).
///
/// Particularly for `repr(Rust)` types, this may not be the same as *layout* order.
/// (It is for `repr(C)` `struct`s, however.)
///
/// For example, in the following types,
/// ```rust
/// # enum Never {}
/// # #[repr(u16)]
/// enum Demo1 {
/// Variant0 { a: Never, b: i32 } = 100,
/// Variant1 { c: u8, d: u64 } = 10,
/// }
/// struct Demo2 { e: u8, f: u16, g: u8 }
/// ```
/// `b` is `FieldIdx(1)` in `VariantIdx(0)`,
/// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and
/// `f` is `FieldIdx(1)` in `VariantIdx(0)`.
#[stable_hash]
#[encodable]
#[orderable]
#[gate_rustc_only]
pub struct FieldIdx {}
}
impl FieldIdx {
/// The second field, at index 1.
///
/// For use alongside [`FieldIdx::ZERO`], particularly with scalar pairs.
pub const ONE: FieldIdx = FieldIdx::from_u32(1);
}
rustc_index::newtype_index! {
/// The *source-order* index of a variant in a type.
///
/// For enums, these are always `0..variant_count`, regardless of any
/// custom discriminants that may have been defined, and including any
/// variants that may end up uninhabited due to field types. (Some of the
/// variants may not be present in a monomorphized ABI [`Variants`], but
/// those skipped variants are always counted when determining the *index*.)
///
/// `struct`s, `tuples`, and `unions`s are considered to have a single variant
/// with variant index zero, aka [`FIRST_VARIANT`].
#[stable_hash]
#[encodable]
#[orderable]
#[gate_rustc_only]
pub struct VariantIdx {
/// Equivalent to `VariantIdx(0)`.
const FIRST_VARIANT = 0;
}
}
// A variant is absent if it's uninhabited and only has ZST fields.
// Present uninhabited variants only require space for their fields,
// but *not* an encoding of the discriminant (e.g., a tag value).
// See issue #49298 for more details on the need to leave space
// for non-ZST uninhabited data (mostly partial initialization).
fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{
let uninhabited = fields.iter().any(|f| f.is_uninhabited());
// We cannot ignore alignment; that might lead us to entirely discard a variant and
// produce an enum that is less aligned than it should be!
let is_1zst = fields.iter().all(|f| f.is_1zst());
uninhabited && is_1zst
}
/// Determines towards which end of a struct layout optimizations will try to place the best niches.
enum NicheBias {
Start,
End,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LayoutCalculatorError<F> {
/// An unsized type was found in a location where a sized type was expected.
///
/// This is not always a compile error, for example if there is a `[T]: Sized`
/// bound in a where clause.
///
/// Contains the field that was unexpectedly unsized.
UnexpectedUnsized(F),
/// A type was too large for the target platform.
SizeOverflow,
/// A union had no fields.
EmptyUnion,
/// The fields or variants have irreconcilable reprs
ReprConflict,
/// The length of an SIMD type is zero
ZeroLengthSimdType,
/// The length of an SIMD type exceeds the maximum number of lanes
OversizedSimdType { max_lanes: usize },
/// An element type of an SIMD type isn't a primitive
NonPrimitiveSimdType(F),
}
impl<F> LayoutCalculatorError<F> {
pub fn without_payload(&self) -> LayoutCalculatorError<()> {
use LayoutCalculatorError::*;
match *self {
UnexpectedUnsized(_) => UnexpectedUnsized(()),
SizeOverflow => SizeOverflow,
EmptyUnion => EmptyUnion,
ReprConflict => ReprConflict,
ZeroLengthSimdType => ZeroLengthSimdType,
OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
}
}
/// Format an untranslated diagnostic for this type
///
/// Intended for use by rust-analyzer, as neither it nor `rustc_abi` depend on fluent infra.
pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use LayoutCalculatorError::*;
f.write_str(match self {
UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
SizeOverflow => "size overflow",
EmptyUnion => "type is a union with no fields",
ReprConflict => "type has an invalid repr",
ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
"invalid simd type definition"
}
})
}
}
type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
#[derive(Clone, Copy, Debug)]
pub struct LayoutCalculator<Cx> {
pub cx: Cx,
}
impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
pub fn new(cx: Cx) -> Self {
Self { cx }
}
pub fn layout_of_array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
&self,
element: &LayoutData<FieldIdx, VariantIdx>,
count_if_sized: Option<u64>, // None for slices
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
let count = count_if_sized.unwrap_or(0);
let size =
element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
Ok(LayoutData {
variants: Variants::Single { index: VariantIdx::new(0) },
fields: FieldsShape::Array { stride: element.size, count },
backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
largest_niche: element.largest_niche.filter(|_| count != 0),
uninhabited: element.uninhabited && count != 0,
align: element.align,
size,
max_repr_align: None,
unadjusted_abi_align: element.align,
repr_c: element.repr_c,
randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
})
}
pub fn layout_of_scalable_vector_type<FieldIdx, VariantIdx, F>(
&self,
element: F,
count: u64,
number_of_vectors: NumScalableVectors,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{
vector_type_layout(
SimdVectorKind::Scalable(number_of_vectors),
self.cx.data_layout(),
element,
count,
)
}
pub fn layout_of_simd_type<FieldIdx, VariantIdx, F>(
&self,
element: F,
count: u64,
repr_packed: bool,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{
let kind = if repr_packed { SimdVectorKind::PackedFixed } else { SimdVectorKind::Fixed };
vector_type_layout(kind, self.cx.data_layout(), element, count)
}
/// Compute the layout for a coroutine.
///
/// This uses dedicated code instead of [`Self::layout_of_struct_or_enum`], as coroutine
/// fields may be shared between multiple variants (see the [`coroutine`] module for details).
pub fn layout_of_coroutine<'a, F, VariantIdx, FieldIdx, LocalIdx>(
&self,
local_layouts: &IndexSlice<LocalIdx, F>,
prefix_layouts: IndexVec<FieldIdx, F>,
variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
tag_to_layout: impl Fn(Scalar) -> F,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
VariantIdx: Idx,
FieldIdx: Idx,
LocalIdx: Idx,
{
coroutine::layout(
self,
local_layouts,
prefix_layouts,
variant_fields,
storage_conflicts,
tag_to_layout,
)
}
/// Compute the layout for a univariant (see [`Variants::Single`]).
///
/// As a consumer of `rustc_abi`, you should only use this method for non-ADTs.
/// For structs and univariant enums, use [`Self::layout_of_struct`] instead
/// (it uses this function internally).
pub fn layout_of_univariant<'a, FieldIdx, VariantIdx, F>(
&self,
fields: &IndexSlice<FieldIdx, F>,
repr: &ReprOptions,
kind: StructKind,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
{
let dl = self.cx.data_layout();
let layout = self.layout_of_univariant_biased(fields, repr, kind, NicheBias::Start);
// Enums prefer niches close to the beginning or the end of the variants so that other
// (smaller) data-carrying variants can be packed into the space after/before the niche.
// If the default field ordering does not give us a niche at the front then we do a second
// run and bias niches to the right and then check which one is closer to one of the
// struct's edges.
if let Ok(layout) = &layout
// Don't try to calculate an end-biased layout for unsizable structs,
// otherwise we could end up with different layouts for
// Foo<Type> and Foo<dyn Trait> which would break unsizing.
&& !matches!(kind, StructKind::MaybeUnsized)
&& let Some(niche) = layout.largest_niche
&& let head_space = niche.offset.bytes()
&& let niche_len = niche.value.size(dl).bytes()
&& let tail_space = layout.size.bytes() - head_space - niche_len
// This may end up doing redundant work if the niche is already in the last
// field (e.g. a trailing bool) and there is tail padding. But it's non-trivial
// to get the unpadded size so we try anyway.
&& (fields.len() > 1 && head_space != 0 && tail_space > 0)
{
let alt_layout = self
.layout_of_univariant_biased(fields, repr, kind, NicheBias::End)
.expect("alt layout should always work");
let alt_niche = alt_layout
.largest_niche
.expect("alt layout should have a niche like the regular one");
let alt_head_space = alt_niche.offset.bytes();
let alt_niche_len = alt_niche.value.size(dl).bytes();
let alt_tail_space = alt_layout.size.bytes() - alt_head_space - alt_niche_len;
debug_assert_eq!(layout.size.bytes(), alt_layout.size.bytes());
let prefer_alt_layout = alt_head_space > head_space && alt_head_space > tail_space;
debug!(
"sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
layout: {}\n\
alt_layout: {}\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),
);
if prefer_alt_layout {
return Ok(alt_layout);
}
}
layout
}
pub fn layout_of_struct_or_enum<'a, FieldIdx, VariantIdx, F>(
&self,
repr: &ReprOptions,
variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
is_enum: bool,
niche_optimizations: NicheOptimizations,
discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
discriminants: impl Iterator<Item = (VariantIdx, u128)>,
always_sized: bool,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
{
let (present_first, present_second) = {
let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
});
(present_variants.next(), present_variants.next())
};
let present_first = match present_first {
Some(present_first) => present_first,
// Uninhabited because it has no variants, or only absent ones.
None if is_enum => {
return Ok(LayoutData::never_type());
}
// If it's a struct, still compute a layout so that we can still compute the
// field offsets.
None => VariantIdx::new(0),
};
// take the struct path if it is an actual struct
if !is_enum ||
// or for optimizing univariant enums
(present_second.is_none() && !repr.inhibit_enum_layout_opt())
{
self.layout_of_struct(
repr,
variants,
present_first,
is_enum,
niche_optimizations,
always_sized,
)
} else {
// At this point, we have handled all unions and
// structs. (We have also handled univariant enums
// that allow representation optimization.)
assert!(is_enum);
self::enum_layout::layout_of_enum(
self,
repr,
variants,
discr_range_of_repr,
discriminants,
)
}
}
pub fn layout_of_union<'a, FieldIdx, VariantIdx, F>(
&self,
repr: &ReprOptions,
variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
{
let dl = self.cx.data_layout();
let mut align = if repr.pack.is_some() { Align::ONE } else { dl.aggregate_align };
let mut max_repr_align = repr.align;
// If all the non-ZST fields have the same repr and union repr optimizations aren't
// disabled, we can use that common repr for the union as a whole.
struct AbiMismatch;
let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
// Can't optimize
Err(AbiMismatch)
} else {
Ok(None)
};
let mut size = Size::ZERO;
let only_variant_idx = VariantIdx::new(0);
let only_variant = &variants[only_variant_idx];
for field in only_variant {
if field.is_unsized() {
return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
}
align = align.max(field.align);
max_repr_align = max_repr_align.max(field.max_repr_align);
size = cmp::max(size, field.size);
if field.is_zst() {
// Nothing more to do for ZST fields
continue;
}
if let Ok(common) = common_non_zst_repr_and_align {
// Discard valid range information and allow undef
let field_abi = field.backend_repr.to_union();
if let Some((common_abi, common_align)) = common {
if common_abi != field_abi {
// Different fields have different ABI: disable opt
common_non_zst_repr_and_align = Err(AbiMismatch);
} else {
// Fields with the same non-Aggregate ABI should also
// have the same alignment
if !matches!(common_abi, BackendRepr::Memory { .. }) {
assert_eq!(
common_align, field.align,
"non-Aggregate field with matching ABI but differing alignment"
);
}
}
} else {
// First non-ZST field: record its ABI and alignment
common_non_zst_repr_and_align = Ok(Some((field_abi, field.align)));
}
}
}
if let Some(pack) = repr.pack {
align = align.min(pack);
}
// The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
// See documentation on `LayoutData::unadjusted_abi_align`.
let unadjusted_abi_align = align;
if let Some(repr_align) = repr.align {
align = align.max(repr_align);
}
// `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate.
let align = align;
// If all non-ZST fields have the same ABI, we may forward that ABI
// for the union as a whole, unless otherwise inhibited.
let backend_repr = match common_non_zst_repr_and_align {
Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
Ok(Some((repr, _))) => match repr {
// Mismatched alignment (e.g. union is #[repr(packed)]): disable opt
BackendRepr::Scalar(_) | BackendRepr::ScalarPair { .. }
if repr.scalar_platform_align(dl).unwrap() != align =>
{
BackendRepr::Memory { sized: true }
}
// Vectors require at least element alignment, else disable the opt
BackendRepr::SimdVector { element, count: _ }
if element.default_align(dl) > align =>
{
BackendRepr::Memory { sized: true }
}
// the alignment tests passed and we can use this
BackendRepr::Scalar(..)
| BackendRepr::ScalarPair { .. }
| BackendRepr::SimdVector { .. }
| BackendRepr::SimdScalableVector { .. }
| BackendRepr::Memory { .. } => repr,
},
};
let Some(union_field_count) = NonZero::new(only_variant.len()) else {
return Err(LayoutCalculatorError::EmptyUnion);
};
// We also need to check for a `repr(transparent)` wrapper around `repr(C)`
let repr_c =
repr.c() || (repr.transparent() && only_variant.iter().any(|field| field.repr_c));
let combined_seed = only_variant
.iter()
.map(|v| v.randomization_seed)
.fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
Ok(LayoutData {
variants: Variants::Single { index: only_variant_idx },
fields: FieldsShape::Union(union_field_count),
backend_repr,
largest_niche: None,
uninhabited: false,
align,
size: size.align_to(align),
max_repr_align,
unadjusted_abi_align,
repr_c,
randomization_seed: combined_seed,
})
}
/// Calculate the layout for a struct, or a single-variant enum.
///
/// They are the same thing, if you think about it
/// (Typechecking will reject discriminant-sizing attrs.)
fn layout_of_struct<'a, FieldIdx, VariantIdx, F>(
&self,
repr: &ReprOptions,
variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
variant_idx: VariantIdx,
is_enum: bool,
niche_optimizations: NicheOptimizations,
always_sized: bool,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
{
let dl = self.cx.data_layout();
let v = variant_idx;
let kind = if is_enum || variants[v].is_empty() || always_sized {
StructKind::AlwaysSized
} else {
StructKind::MaybeUnsized
};
let mut st = self.layout_of_univariant(&variants[v], repr, kind)?;
st.variants = Variants::Single { index: v };
if niche_optimizations == NicheOptimizations::Disabled {
let hide_niches = |scalar: &mut _| match scalar {
Scalar::Initialized { value, valid_range } => {
*valid_range = WrappingRange::full(value.size(dl))
}
// Already doesn't have any niches
Scalar::Union { .. } => {}
};
match &mut st.backend_repr {
BackendRepr::Scalar(scalar) => hide_niches(scalar),
BackendRepr::ScalarPair { a, b, b_offset: _ } => {
hide_niches(a);
hide_niches(b);
}
BackendRepr::SimdVector { element, .. }
| BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
BackendRepr::Memory { sized: _ } => {}
}
st.largest_niche = None;
return Ok(st);
}
Ok(st)
}
fn layout_of_univariant_biased<'a, FieldIdx, VariantIdx, F>(
&self,
fields: &IndexSlice<FieldIdx, F>,
repr: &ReprOptions,
kind: StructKind,
niche_bias: NicheBias,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
{
let dl = self.cx.data_layout();
let pack = repr.pack;
let mut align = if pack.is_some() { Align::ONE } else { dl.aggregate_align };
let mut max_repr_align = repr.align;
let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
let optimize_field_order = !repr.inhibit_struct_field_reordering();
let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
let optimizing = &mut in_memory_order.raw[..end];
let fields_excluding_tail = &fields.raw[..end];
// unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
let field_seed = fields_excluding_tail
.iter()
.fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
if optimize_field_order && fields.len() > 1 {
// If `-Z randomize-layout` was enabled for the type definition we can shuffle
// the field ordering to try and catch some code making assumptions about layouts
// we don't guarantee.
// In the future, we might do more than shuffle field order (e.g. introduce extra padding),
// but never for `repr(Rust)` structs with only zero-sized fields, single-variant
// `repr(Rust)` enums with only zero-sized fields, or zero-variant `repr(Rust)` enums,
// which must remain zero-sized as per T-lang decisions in
// https://github.com/rust-lang/reference/pull/2262 and https://github.com/rust-lang/reference/pull/2293
if repr.can_randomize_type_layout() && cfg!(feature = "randomize") {
#[cfg(feature = "randomize")]
{
use rand::SeedableRng;
use rand::seq::SliceRandom;
// `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
// ordering.
let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
);
// Shuffle the ordering of the fields.
optimizing.shuffle(&mut rng);
}
// Otherwise we just leave things alone and actually optimize the type's fields
} else {
// To allow unsizing `&Foo<Type>` -> `&Foo<dyn Trait>`, the layout of the struct must
// not depend on the layout of the tail.
let max_field_align =
fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
let largest_niche_size = fields_excluding_tail
.iter()
.filter_map(|f| f.largest_niche)
.map(|n| n.available(dl))
.max()
.unwrap_or(0);
// Calculates a sort key to group fields by their alignment or possibly some
// size-derived pseudo-alignment.
let alignment_group_key = |layout: &F| {
// The two branches here return values that cannot be meaningfully compared with
// each other. However, we know that consistently for all executions of
// `alignment_group_key`, one or the other branch will be taken, so this is okay.
if let Some(pack) = pack {
// Return the packed alignment in bytes.
layout.align.min(pack).bytes()
} else {
// Returns `log2(effective-align)`. The calculation assumes that size is an
// integer multiple of align, except for ZSTs.
let align = layout.align.bytes();
let size = layout.size.bytes();
let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
// Group [u8; 4] with align-4 or [u8; 6] with align-2 fields.
let size_as_align = align.max(size).trailing_zeros();
let size_as_align = if largest_niche_size > 0 {
match niche_bias {
// Given `A(u8, [u8; 16])` and `B(bool, [u8; 16])` we want to bump the
// array to the front in the first case (for aligned loads) but keep
// the bool in front in the second case for its niches.
NicheBias::Start => {
max_field_align.trailing_zeros().min(size_as_align)
}
// When moving niches towards the end of the struct then for
// A((u8, u8, u8, bool), (u8, bool, u8)) we want to keep the first tuple
// in the align-1 group because its bool can be moved closer to the end.
NicheBias::End if niche_size == largest_niche_size => {
align.trailing_zeros()
}
NicheBias::End => size_as_align,
}
} else {
size_as_align
};
size_as_align as u64
}
};
match kind {
StructKind::AlwaysSized | StructKind::MaybeUnsized => {
// Currently `LayoutData` only exposes a single niche so sorting is usually
// sufficient to get one niche into the preferred position. If it ever
// supported multiple niches then a more advanced pick-and-pack approach could
// provide better results. But even for the single-niche cache it's not
// optimal. E.g. for A(u32, (bool, u8), u16) it would be possible to move the
// bool to the front but it would require packing the tuple together with the
// u16 to build a 4-byte group so that the u32 can be placed after it without
// padding. This kind of packing can't be achieved by sorting.
optimizing.sort_by_key(|&x| {
let f = &fields[x];
let field_size = f.size.bytes();
let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
let niche_size_key = match niche_bias {
// large niche first
NicheBias::Start => !niche_size,
// large niche last
NicheBias::End => niche_size,
};
let inner_niche_offset_key = match niche_bias {
NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
NicheBias::End => f.largest_niche.map_or(0, |n| {
!(field_size - n.value.size(dl).bytes() - n.offset.bytes())
}),
};
(
// Then place largest alignments first.
cmp::Reverse(alignment_group_key(f)),
// Then prioritize niche placement within alignment group according to
// `niche_bias_start`.
niche_size_key,
// Then among fields with equally-sized niches prefer the ones
// closer to the start/end of the field.
inner_niche_offset_key,
)
});
}
StructKind::Prefixed(..) => {
// Sort in ascending alignment so that the layout stays optimal
// regardless of the prefix.
// And put the largest niche in an alignment group at the end
// so it can be used as discriminant in jagged enums
optimizing.sort_by_key(|&x| {
let f = &fields[x];
let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
(alignment_group_key(f), niche_size)
});
}
}
// FIXME(Kixiron): We can always shuffle fields within a given alignment class
// regardless of the status of `-Z randomize-layout`
}
}
// in_memory_order holds field indices by increasing memory offset.
// That is, if field 5 has offset 0, the first element of in_memory_order is 5.
// We now write field offsets to the corresponding offset slot;
// field 5 with offset 0 puts 0 in offsets[5].
let mut unsized_field = None::<&F>;
let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
let mut offset = Size::ZERO;
let mut largest_niche = None;
let mut largest_niche_available = 0;
if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
let prefix_align =
if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
align = align.max(prefix_align);
offset = prefix_size.align_to(prefix_align);
}
for &i in &in_memory_order {
let field = &fields[i];
if let Some(unsized_field) = unsized_field {
return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
}
if field.is_unsized() {
if let StructKind::MaybeUnsized = kind {
unsized_field = Some(field);
} else {
return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
}
}
// Invariant: offset < dl.obj_size_bound() <= 1<<61
let field_align =
if let Some(pack) = pack { field.align.min(pack) } else { field.align };
offset = offset.align_to(field_align);
align = align.max(field_align);
max_repr_align = max_repr_align.max(field.max_repr_align);
debug!("univariant offset: {:?} field: {:#?}", offset, field);
offsets[i] = offset;
if let Some(mut niche) = field.largest_niche {
let available = niche.available(dl);
// Pick up larger niches.
let prefer_new_niche = match niche_bias {
NicheBias::Start => available > largest_niche_available,
// if there are several niches of the same size then pick the last one
NicheBias::End => available >= largest_niche_available,
};
if prefer_new_niche {
largest_niche_available = available;
niche.offset += offset;
largest_niche = Some(niche);
}
}
offset =
offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
}
// The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
// See documentation on `LayoutData::unadjusted_abi_align`.
let unadjusted_abi_align = align;
if let Some(repr_align) = repr.align {
align = align.max(repr_align);
}
// `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate.
let align = align;
debug!("univariant min_size: {:?}", offset);
let min_size = offset;
let size = min_size.align_to(align);
// FIXME(oli-obk): deduplicate and harden these checks
if size.bytes() >= dl.obj_size_bound() {
return Err(LayoutCalculatorError::SizeOverflow);
}
let mut layout_of_single_non_zst_field = None;
let sized = unsized_field.is_none();
let mut abi = BackendRepr::Memory { sized };
let optimize_abi = !repr.inhibit_newtype_abi_optimization();
// Try to make this a Scalar/ScalarPair.
if sized && size.bytes() > 0 {
// We skip *all* ZST here and later check if we are good in terms of alignment.
// This lets us handle some cases involving aligned ZST.
let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
// We have exactly one non-ZST field.
(Some((i, field)), None, None) => {
layout_of_single_non_zst_field = Some(field);
// Field fills the struct and it has a scalar or scalar pair ABI.
if offsets[i].bytes() == 0 && align == field.align && size == field.size {
match field.backend_repr {
// For plain scalars, or vectors of them, we can't unpack
// newtypes for `#[repr(C)]`, as that affects C ABIs.
BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
if optimize_abi =>
{
abi = field.backend_repr;
}
// But scalar pairs are Rust-specific and get
// treated as aggregates by C ABIs anyway.
BackendRepr::ScalarPair { .. } => {
abi = field.backend_repr;
}
_ => {}
}
}
}
// Two non-ZST fields, and they're both scalars.
(Some((i, a)), Some((j, b)), None) => {
match (a.backend_repr, b.backend_repr) {
(BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
// Order by the memory placement, not source order.
let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
((i, a), (j, b))
} else {
((j, b), (i, a))
};
let pair =
LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
let pair_offsets = match pair.fields {
FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
assert_eq!(
in_memory_order.raw,
[FieldIdx::new(0), FieldIdx::new(1)]
);
offsets
}
FieldsShape::Primitive
| FieldsShape::Array { .. }
| FieldsShape::Union(..) => {
panic!("encountered a non-arbitrary layout during enum layout")
}
};
if offsets[i] == pair_offsets[FieldIdx::new(0)]
&& offsets[j] == pair_offsets[FieldIdx::new(1)]
&& align == pair.align
&& size == pair.size
{
// We can use `ScalarPair` only when it matches our
// already computed layout (including `#[repr(C)]`).
abi = pair.backend_repr;
}
}
_ => {}
}
}
_ => {}
}
}
let uninhabited = fields.iter().any(|f| f.is_uninhabited());
let unadjusted_abi_align = if repr.transparent() {
match layout_of_single_non_zst_field {
Some(l) => l.unadjusted_abi_align,
None => {
// `repr(transparent)` with all ZST fields.
align
}
}
} else {
unadjusted_abi_align
};
// We also need to check for a `repr(transparent)` wrapper around `repr(C)`
let repr_c = repr.c() || (repr.transparent() && fields.iter().any(|field| field.repr_c));
let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
Ok(LayoutData {
variants: Variants::Single { index: VariantIdx::new(0) },
fields: FieldsShape::Arbitrary { offsets, in_memory_order },
backend_repr: abi,
largest_niche,
uninhabited,
align,
size,
max_repr_align,
unadjusted_abi_align,
repr_c,
randomization_seed: seed,
})
}
fn format_field_niches<'a, FieldIdx, VariantIdx, F>(
&self,
layout: &LayoutData<FieldIdx, VariantIdx>,
fields: &IndexSlice<FieldIdx, F>,
) -> String
where
FieldIdx: Idx,
VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{
let dl = self.cx.data_layout();
let mut s = String::new();
for i in layout.fields.index_by_increasing_offset() {
let offset = layout.fields.offset(i);
let f = &fields[FieldIdx::new(i)];
write!(s, "[o{}a{}s{}", offset.bytes(), f.align.bytes(), f.size.bytes()).unwrap();
if let Some(n) = f.largest_niche {
write!(
s,
" n{}b{}s{}",
n.offset.bytes(),
n.available(dl).ilog2(),
n.value.size(dl).bytes()
)
.unwrap();
}
write!(s, "] ").unwrap();
}
s
}
}
enum SimdVectorKind {
/// `#[rustc_scalable_vector]`
Scalable(NumScalableVectors),
/// `#[repr(simd, packed)]`
PackedFixed,
/// `#[repr(simd)]`
Fixed,
}
fn vector_type_layout<FieldIdx, VariantIdx, F>(
kind: SimdVectorKind,
dl: &TargetDataLayout,
element: F,
count: u64,
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
where
FieldIdx: Idx,
VariantIdx: Idx,
F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{
let elt = element.as_ref();
let count = BackendLaneCount::new(count)?;
let BackendRepr::Scalar(element) = elt.backend_repr else {
return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
};
// Compute the size and alignment of the vector
let size =
elt.size.checked_mul(count.as_u64(), dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
let (repr, size, align) = match kind {
SimdVectorKind::Scalable(number_of_vectors) => (
BackendRepr::SimdScalableVector { element, count, number_of_vectors },
size.checked_mul(number_of_vectors.0 as u64, dl)
.ok_or(LayoutCalculatorError::SizeOverflow)?,
dl.rust_vector_align(size),
),
// Non-power-of-two vectors have padding up to the next power-of-two.
// If we're a packed repr, remove the padding while keeping the alignment as close
// to a vector as possible.
SimdVectorKind::PackedFixed if !count.is_power_of_two() => {
(BackendRepr::Memory { sized: true }, size, Align::max_aligned_factor(size))
}
SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
(BackendRepr::SimdVector { element, count }, size, dl.rust_vector_align(size))
}
};
let size = size.align_to(align);
Ok(LayoutData {
variants: Variants::Single { index: VariantIdx::new(0) },
fields: FieldsShape::Arbitrary {
offsets: [Size::ZERO].into(),
in_memory_order: [FieldIdx::new(0)].into(),
},
backend_repr: repr,
largest_niche: elt.largest_niche,
uninhabited: false,
size,
align,
max_repr_align: None,
unadjusted_abi_align: elt.align,
repr_c: false,
randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count.as_u64())),
})
}