1use std::collections::BTreeSet;
2use std::fmt::{self, Write};
3use std::ops::{Bound, Deref};
4use std::{cmp, iter};
56use rustc_hashes::Hash64;
7use rustc_index::Idx;
8use rustc_index::bit_set::BitMatrix;
9use tracing::{debug, trace};
1011use crate::{
12AbiAlign, Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer,
13LayoutData, Niche, NonZeroUsize, NumScalableVectors, Primitive, ReprOptions, Scalar, Size,
14StructKind, TagEncoding, TargetDataLayout, Variants, WrappingRange,
15};
1617mod coroutine;
18mod simple;
1920#[cfg(feature = "nightly")]
21mod ty;
2223#[cfg(feature = "nightly")]
24pub use ty::{Layout, TyAbiInterface, TyAndLayout};
2526impl ::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! {
27/// The *source-order* index of a field in a variant.
28 ///
29 /// This is how most code after type checking refers to fields, rather than
30 /// using names (as names have hygiene complications and more complex lookup).
31 ///
32 /// Particularly for `repr(Rust)` types, this may not be the same as *layout* order.
33 /// (It is for `repr(C)` `struct`s, however.)
34 ///
35 /// For example, in the following types,
36 /// ```rust
37 /// # enum Never {}
38 /// # #[repr(u16)]
39 /// enum Demo1 {
40 /// Variant0 { a: Never, b: i32 } = 100,
41 /// Variant1 { c: u8, d: u64 } = 10,
42 /// }
43 /// struct Demo2 { e: u8, f: u16, g: u8 }
44 /// ```
45 /// `b` is `FieldIdx(1)` in `VariantIdx(0)`,
46 /// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and
47 /// `f` is `FieldIdx(1)` in `VariantIdx(0)`.
48#[stable_hash_generic]
49 #[encodable]
50 #[orderable]
51 #[gate_rustc_only]
52pub struct FieldIdx {}
53}5455impl FieldIdx {
56/// The second field, at index 1.
57 ///
58 /// For use alongside [`FieldIdx::ZERO`], particularly with scalar pairs.
59pub const ONE: FieldIdx = FieldIdx::from_u32(1);
60}
6162impl ::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! {
63/// The *source-order* index of a variant in a type.
64 ///
65 /// For enums, these are always `0..variant_count`, regardless of any
66 /// custom discriminants that may have been defined, and including any
67 /// variants that may end up uninhabited due to field types. (Some of the
68 /// variants may not be present in a monomorphized ABI [`Variants`], but
69 /// those skipped variants are always counted when determining the *index*.)
70 ///
71 /// `struct`s, `tuples`, and `unions`s are considered to have a single variant
72 /// with variant index zero, aka [`FIRST_VARIANT`].
73#[stable_hash_generic]
74 #[encodable]
75 #[orderable]
76 #[gate_rustc_only]
77pub struct VariantIdx {
78/// Equivalent to `VariantIdx(0)`.
79const FIRST_VARIANT = 0;
80 }
81}8283// A variant is absent if it's uninhabited and only has ZST fields.
84// Present uninhabited variants only require space for their fields,
85// but *not* an encoding of the discriminant (e.g., a tag value).
86// See issue #49298 for more details on the need to leave space
87// for non-ZST uninhabited data (mostly partial initialization).
88fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool89where
90FieldIdx: Idx,
91 VariantIdx: Idx,
92 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
93{
94let uninhabited = fields.iter().any(|f| f.is_uninhabited());
95// We cannot ignore alignment; that might lead us to entirely discard a variant and
96 // produce an enum that is less aligned than it should be!
97let is_1zst = fields.iter().all(|f| f.is_1zst());
98uninhabited && is_1zst99}
100101/// Determines towards which end of a struct layout optimizations will try to place the best niches.
102enum NicheBias {
103 Start,
104 End,
105}
106107#[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) -> LayoutCalculatorError<F> {
match self {
LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
LayoutCalculatorError::UnexpectedUnsized(::core::clone::Clone::clone(__self_0)),
LayoutCalculatorError::SizeOverflow =>
LayoutCalculatorError::SizeOverflow,
LayoutCalculatorError::EmptyUnion =>
LayoutCalculatorError::EmptyUnion,
LayoutCalculatorError::ReprConflict =>
LayoutCalculatorError::ReprConflict,
LayoutCalculatorError::ZeroLengthSimdType =>
LayoutCalculatorError::ZeroLengthSimdType,
LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
=>
LayoutCalculatorError::OversizedSimdType {
max_lanes: ::core::clone::Clone::clone(__self_0),
},
LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
LayoutCalculatorError::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 {
LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UnexpectedUnsized", &__self_0),
LayoutCalculatorError::SizeOverflow =>
::core::fmt::Formatter::write_str(f, "SizeOverflow"),
LayoutCalculatorError::EmptyUnion =>
::core::fmt::Formatter::write_str(f, "EmptyUnion"),
LayoutCalculatorError::ReprConflict =>
::core::fmt::Formatter::write_str(f, "ReprConflict"),
LayoutCalculatorError::ZeroLengthSimdType =>
::core::fmt::Formatter::write_str(f, "ZeroLengthSimdType"),
LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
=>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OversizedSimdType", "max_lanes", &__self_0),
LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonPrimitiveSimdType", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
LayoutCalculatorError<F> {
#[inline]
fn eq(&self, other: &LayoutCalculatorError<F>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(LayoutCalculatorError::UnexpectedUnsized(__self_0),
LayoutCalculatorError::UnexpectedUnsized(__arg1_0)) =>
__self_0 == __arg1_0,
(LayoutCalculatorError::OversizedSimdType {
max_lanes: __self_0 },
LayoutCalculatorError::OversizedSimdType {
max_lanes: __arg1_0 }) => __self_0 == __arg1_0,
(LayoutCalculatorError::NonPrimitiveSimdType(__self_0),
LayoutCalculatorError::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<u64>;
}
}Eq)]
108pub enum LayoutCalculatorError<F> {
109/// An unsized type was found in a location where a sized type was expected.
110 ///
111 /// This is not always a compile error, for example if there is a `[T]: Sized`
112 /// bound in a where clause.
113 ///
114 /// Contains the field that was unexpectedly unsized.
115UnexpectedUnsized(F),
116117/// A type was too large for the target platform.
118SizeOverflow,
119120/// A union had no fields.
121EmptyUnion,
122123/// The fields or variants have irreconcilable reprs
124ReprConflict,
125126/// The length of an SIMD type is zero
127ZeroLengthSimdType,
128129/// The length of an SIMD type exceeds the maximum number of lanes
130OversizedSimdType { max_lanes: u64 },
131132/// An element type of an SIMD type isn't a primitive
133NonPrimitiveSimdType(F),
134}
135136impl<F> LayoutCalculatorError<F> {
137pub fn without_payload(&self) -> LayoutCalculatorError<()> {
138use LayoutCalculatorError::*;
139match *self {
140UnexpectedUnsized(_) => UnexpectedUnsized(()),
141SizeOverflow => SizeOverflow,
142EmptyUnion => EmptyUnion,
143ReprConflict => ReprConflict,
144ZeroLengthSimdType => ZeroLengthSimdType,
145OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
146NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
147 }
148 }
149150/// Format an untranslated diagnostic for this type
151 ///
152 /// Intended for use by rust-analyzer, as neither it nor `rustc_abi` depend on fluent infra.
153pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154use LayoutCalculatorError::*;
155f.write_str(match self {
156UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
157SizeOverflow => "size overflow",
158EmptyUnion => "type is a union with no fields",
159ReprConflict => "type has an invalid repr",
160ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
161"invalid simd type definition"
162}
163 })
164 }
165}
166167type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
168Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
169170#[derive(#[automatically_derived]
impl<Cx: ::core::clone::Clone> ::core::clone::Clone for LayoutCalculator<Cx> {
#[inline]
fn clone(&self) -> LayoutCalculator<Cx> {
LayoutCalculator { 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)]
171pub struct LayoutCalculator<Cx> {
172pub cx: Cx,
173}
174175impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
176pub fn new(cx: Cx) -> Self {
177Self { cx }
178 }
179180pub fn array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
181&self,
182 element: &LayoutData<FieldIdx, VariantIdx>,
183 count_if_sized: Option<u64>, // None for slices
184) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
185let count = count_if_sized.unwrap_or(0);
186let size =
187element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
188189Ok(LayoutData {
190 variants: Variants::Single { index: VariantIdx::new(0) },
191 fields: FieldsShape::Array { stride: element.size, count },
192 backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
193 largest_niche: element.largest_niche.filter(|_| count != 0),
194 uninhabited: element.uninhabited && count != 0,
195 align: element.align,
196size,
197 max_repr_align: None,
198 unadjusted_abi_align: element.align.abi,
199 randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
200 })
201 }
202203pub fn scalable_vector_type<FieldIdx, VariantIdx, F>(
204&self,
205 element: F,
206 count: u64,
207 number_of_vectors: NumScalableVectors,
208 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
209where
210FieldIdx: Idx,
211 VariantIdx: Idx,
212 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
213 {
214vector_type_layout(
215 SimdVectorKind::Scalable(number_of_vectors),
216self.cx.data_layout(),
217element,
218count,
219 )
220 }
221222pub fn simd_type<FieldIdx, VariantIdx, F>(
223&self,
224 element: F,
225 count: u64,
226 repr_packed: bool,
227 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
228where
229FieldIdx: Idx,
230 VariantIdx: Idx,
231 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
232 {
233let kind = if repr_packed { SimdVectorKind::PackedFixed } else { SimdVectorKind::Fixed };
234vector_type_layout(kind, self.cx.data_layout(), element, count)
235 }
236237/// Compute the layout for a coroutine.
238 ///
239 /// This uses dedicated code instead of [`Self::layout_of_struct_or_enum`], as coroutine
240 /// fields may be shared between multiple variants (see the [`coroutine`] module for details).
241pub fn coroutine<
242'a,
243 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
244 VariantIdx: Idx,
245 FieldIdx: Idx,
246 LocalIdx: Idx,
247 >(
248&self,
249 local_layouts: &IndexSlice<LocalIdx, F>,
250 prefix_layouts: IndexVec<FieldIdx, F>,
251 variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
252 storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
253 tag_to_layout: impl Fn(Scalar) -> F,
254 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
255 coroutine::layout(
256self,
257local_layouts,
258prefix_layouts,
259variant_fields,
260storage_conflicts,
261tag_to_layout,
262 )
263 }
264265pub fn univariant<
266'a,
267 FieldIdx: Idx,
268 VariantIdx: Idx,
269 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
270 >(
271&self,
272 fields: &IndexSlice<FieldIdx, F>,
273 repr: &ReprOptions,
274 kind: StructKind,
275 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
276let dl = self.cx.data_layout();
277let layout = self.univariant_biased(fields, repr, kind, NicheBias::Start);
278// Enums prefer niches close to the beginning or the end of the variants so that other
279 // (smaller) data-carrying variants can be packed into the space after/before the niche.
280 // If the default field ordering does not give us a niche at the front then we do a second
281 // run and bias niches to the right and then check which one is closer to one of the
282 // struct's edges.
283if let Ok(layout) = &layout {
284// Don't try to calculate an end-biased layout for unsizable structs,
285 // otherwise we could end up with different layouts for
286 // Foo<Type> and Foo<dyn Trait> which would break unsizing.
287if !#[allow(non_exhaustive_omitted_patterns)] match kind {
StructKind::MaybeUnsized => true,
_ => false,
}matches!(kind, StructKind::MaybeUnsized) {
288if let Some(niche) = layout.largest_niche {
289let head_space = niche.offset.bytes();
290let niche_len = niche.value.size(dl).bytes();
291let tail_space = layout.size.bytes() - head_space - niche_len;
292293// This may end up doing redundant work if the niche is already in the last
294 // field (e.g. a trailing bool) and there is tail padding. But it's non-trivial
295 // to get the unpadded size so we try anyway.
296if fields.len() > 1 && head_space != 0 && tail_space > 0 {
297let alt_layout = self298 .univariant_biased(fields, repr, kind, NicheBias::End)
299 .expect("alt layout should always work");
300let alt_niche = alt_layout301 .largest_niche
302 .expect("alt layout should have a niche like the regular one");
303let alt_head_space = alt_niche.offset.bytes();
304let alt_niche_len = alt_niche.value.size(dl).bytes();
305let alt_tail_space =
306alt_layout.size.bytes() - alt_head_space - alt_niche_len;
307308if 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());
309310let prefer_alt_layout =
311alt_head_space > head_space && alt_head_space > tail_space;
312313{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:313",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(313u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("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 Value))])
});
} else { ; }
};debug!(
314"sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
315 layout: {}\n\
316 alt_layout: {}\n",
317 layout.size.bytes(),
318 head_space,
319 niche_len,
320 tail_space,
321 alt_head_space,
322 alt_niche_len,
323 alt_tail_space,
324 layout.fields.count(),
325 prefer_alt_layout,
326self.format_field_niches(layout, fields),
327self.format_field_niches(&alt_layout, fields),
328 );
329330if prefer_alt_layout {
331return Ok(alt_layout);
332 }
333 }
334 }
335 }
336 }
337layout338 }
339340pub fn layout_of_struct_or_enum<
341'a,
342 FieldIdx: Idx,
343 VariantIdx: Idx,
344 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
345 >(
346&self,
347 repr: &ReprOptions,
348 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
349 is_enum: bool,
350 is_special_no_niche: bool,
351 scalar_valid_range: (Bound<u128>, Bound<u128>),
352 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
353 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
354 always_sized: bool,
355 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
356let (present_first, present_second) = {
357let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
358if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
359 });
360 (present_variants.next(), present_variants.next())
361 };
362let present_first = match present_first {
363Some(present_first) => present_first,
364// Uninhabited because it has no variants, or only absent ones.
365Noneif is_enum => {
366return Ok(LayoutData::never_type(&self.cx));
367 }
368// If it's a struct, still compute a layout so that we can still compute the
369 // field offsets.
370None => VariantIdx::new(0),
371 };
372373// take the struct path if it is an actual struct
374if !is_enum ||
375// or for optimizing univariant enums
376(present_second.is_none() && !repr.inhibit_enum_layout_opt())
377 {
378self.layout_of_struct(
379repr,
380variants,
381is_enum,
382is_special_no_niche,
383scalar_valid_range,
384always_sized,
385present_first,
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.)
391if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
392self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
393 }
394 }
395396pub fn layout_of_union<
397'a,
398 FieldIdx: Idx,
399 VariantIdx: Idx,
400 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
401 >(
402&self,
403 repr: &ReprOptions,
404 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
405 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
406let dl = self.cx.data_layout();
407let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
408let mut max_repr_align = repr.align;
409410// 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.
412struct AbiMismatch;
413let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
414// Can't optimize
415Err(AbiMismatch)
416 } else {
417Ok(None)
418 };
419420let mut size = Size::ZERO;
421let only_variant_idx = VariantIdx::new(0);
422let only_variant = &variants[only_variant_idx];
423for field in only_variant {
424if field.is_unsized() {
425return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
426 }
427428 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);
431432if field.is_zst() {
433// Nothing more to do for ZST fields
434continue;
435 }
436437if let Ok(common) = common_non_zst_repr_and_align {
438// Discard valid range information and allow undef
439let field_abi = field.backend_repr.to_union();
440441if let Some((common_abi, common_align)) = common {
442if common_abi != field_abi {
443// Different fields have different ABI: disable opt
444common_non_zst_repr_and_align = Err(AbiMismatch);
445 } else {
446// Fields with the same non-Aggregate ABI should also
447 // have the same alignment
448if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
449match (&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
457common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
458 }
459 }
460 }
461462if let Some(pack) = repr.pack {
463align = 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`.
467let unadjusted_abi_align = align;
468if let Some(repr_align) = repr.align {
469align = align.max(repr_align);
470 }
471// `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate.
472let align = align;
473474// If all non-ZST fields have the same ABI, we may forward that ABI
475 // for the union as a whole, unless otherwise inhibited.
476let backend_repr = match common_non_zst_repr_and_align {
477Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
478Ok(Some((repr, _))) => match repr {
479// Mismatched alignment (e.g. union is #[repr(packed)]): disable opt
480BackendRepr::Scalar(_) | BackendRepr::ScalarPair(_, _)
481if repr.scalar_align(dl).unwrap() != align =>
482 {
483 BackendRepr::Memory { sized: true }
484 }
485// Vectors require at least element alignment, else disable the opt
486BackendRepr::SimdVector { element, count: _ } if element.align(dl).abi > align => {
487 BackendRepr::Memory { sized: true }
488 }
489// the alignment tests passed and we can use this
490BackendRepr::Scalar(..)
491 | BackendRepr::ScalarPair(..)
492 | BackendRepr::SimdVector { .. }
493 | BackendRepr::SimdScalableVector { .. }
494 | BackendRepr::Memory { .. } => repr,
495 },
496 };
497498let Some(union_field_count) = NonZeroUsize::new(only_variant.len()) else {
499return Err(LayoutCalculatorError::EmptyUnion);
500 };
501502let combined_seed = only_variant503 .iter()
504 .map(|v| v.randomization_seed)
505 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
506507Ok(LayoutData {
508 variants: Variants::Single { index: only_variant_idx },
509 fields: FieldsShape::Union(union_field_count),
510backend_repr,
511 largest_niche: None,
512 uninhabited: false,
513 align: AbiAlign::new(align),
514 size: size.align_to(align),
515max_repr_align,
516unadjusted_abi_align,
517 randomization_seed: combined_seed,
518 })
519 }
520521/// single-variant enums are just structs, if you think about it
522fn layout_of_struct<
523'a,
524 FieldIdx: Idx,
525 VariantIdx: Idx,
526 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
527 >(
528&self,
529 repr: &ReprOptions,
530 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
531 is_enum: bool,
532 is_special_no_niche: bool,
533 scalar_valid_range: (Bound<u128>, Bound<u128>),
534 always_sized: bool,
535 present_first: VariantIdx,
536 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
537// Struct, or univariant enum equivalent to a struct.
538 // (Typechecking will reject discriminant-sizing attrs.)
539540let dl = self.cx.data_layout();
541let v = present_first;
542let kind = if is_enum || variants[v].is_empty() || always_sized {
543 StructKind::AlwaysSized544 } else {
545 StructKind::MaybeUnsized546 };
547548let mut st = self.univariant(&variants[v], repr, kind)?;
549st.variants = Variants::Single { index: v };
550551if is_special_no_niche {
552let hide_niches = |scalar: &mut _| match scalar {
553 Scalar::Initialized { value, valid_range } => {
554*valid_range = WrappingRange::full(value.size(dl))
555 }
556// Already doesn't have any niches
557Scalar::Union { .. } => {}
558 };
559match &mut st.backend_repr {
560 BackendRepr::Scalar(scalar) => hide_niches(scalar),
561 BackendRepr::ScalarPair(a, b) => {
562hide_niches(a);
563hide_niches(b);
564 }
565 BackendRepr::SimdVector { element, .. }
566 | BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
567 BackendRepr::Memory { sized: _ } => {}
568 }
569st.largest_niche = None;
570return Ok(st);
571 }
572573let (start, end) = scalar_valid_range;
574match st.backend_repr {
575 BackendRepr::Scalar(ref mut scalar) | BackendRepr::ScalarPair(ref mut scalar, _) => {
576// Enlarging validity ranges would result in missed
577 // optimizations, *not* wrongly assuming the inner
578 // value is valid. e.g. unions already enlarge validity ranges,
579 // because the values may be uninitialized.
580 //
581 // Because of that we only check that the start and end
582 // of the range is representable with this scalar type.
583584let max_value = scalar.size(dl).unsigned_int_max();
585if let Bound::Included(start) = start {
586// FIXME(eddyb) this might be incorrect - it doesn't
587 // account for wrap-around (end < start) ranges.
588if !(start <= max_value) {
{
::core::panicking::panic_fmt(format_args!("{0} > {1}", start,
max_value));
}
};assert!(start <= max_value, "{start} > {max_value}");
589scalar.valid_range_mut().start = start;
590 }
591if let Bound::Included(end) = end {
592// FIXME(eddyb) this might be incorrect - it doesn't
593 // account for wrap-around (end < start) ranges.
594if !(end <= max_value) {
{
::core::panicking::panic_fmt(format_args!("{0} > {1}", end,
max_value));
}
};assert!(end <= max_value, "{end} > {max_value}");
595scalar.valid_range_mut().end = end;
596 }
597598// Update `largest_niche` if we have introduced a larger niche.
599let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
600if let Some(niche) = niche {
601match st.largest_niche {
602Some(largest_niche) => {
603// Replace the existing niche even if they're equal,
604 // because this one is at a lower offset.
605if largest_niche.available(dl) <= niche.available(dl) {
606st.largest_niche = Some(niche);
607 }
608 }
609None => st.largest_niche = Some(niche),
610 }
611 }
612 }
613_ => if !(start == Bound::Unbounded && end == Bound::Unbounded) {
{
::core::panicking::panic_fmt(format_args!("nonscalar layout for layout_scalar_valid_range type: {0:#?}",
st));
}
}assert!(
614 start == Bound::Unbounded && end == Bound::Unbounded,
615"nonscalar layout for layout_scalar_valid_range type: {st:#?}",
616 ),
617 }
618619Ok(st)
620 }
621622fn layout_of_enum<
623'a,
624 FieldIdx: Idx,
625 VariantIdx: Idx,
626 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
627 >(
628&self,
629 repr: &ReprOptions,
630 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
631 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
632 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
633 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
634let dl = self.cx.data_layout();
635// bail if the enum has an incoherent repr that cannot be computed
636if repr.packed() {
637return Err(LayoutCalculatorError::ReprConflict);
638 }
639640let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
641if repr.inhibit_enum_layout_opt() {
642return None;
643 }
644645if variants.len() < 2 {
646return None;
647 }
648649let mut align = dl.aggregate_align;
650let mut max_repr_align = repr.align;
651let mut unadjusted_abi_align = align;
652653let mut variant_layouts = variants654 .iter_enumerated()
655 .map(|(j, v)| {
656let mut st = self.univariant(v, repr, StructKind::AlwaysSized).ok()?;
657st.variants = Variants::Single { index: j };
658659align = align.max(st.align.abi);
660max_repr_align = max_repr_align.max(st.max_repr_align);
661unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
662663Some(st)
664 })
665 .collect::<Option<IndexVec<VariantIdx, _>>>()?;
666667let largest_variant_index = variant_layouts668 .iter_enumerated()
669 .max_by_key(|(_i, layout)| layout.size.bytes())
670 .map(|(i, _layout)| i)?;
671672let all_indices = variants.indices();
673let needs_disc =
674 |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
675let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
676 ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
677678let count =
679 (niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1;
680681// Use the largest niche in the largest variant.
682let niche = variant_layouts[largest_variant_index].largest_niche?;
683let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
684let niche_offset = niche.offset;
685let niche_size = niche.value.size(dl);
686let size = variant_layouts[largest_variant_index].size.align_to(align);
687688let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
689if i == largest_variant_index {
690return true;
691 }
692693layout.largest_niche = None;
694695if layout.size <= niche_offset {
696// This variant will fit before the niche.
697return true;
698 }
699700// Determine if it'll fit after the niche.
701let this_align = layout.align.abi;
702let this_offset = (niche_offset + niche_size).align_to(this_align);
703704if this_offset + layout.size > size {
705return false;
706 }
707708// It'll fit, but we need to make some adjustments.
709match layout.fields {
710 FieldsShape::Arbitrary { ref mut offsets, .. } => {
711for offset in offsets.iter_mut() {
712*offset += this_offset;
713 }
714 }
715 FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
716{
::core::panicking::panic_fmt(format_args!("Layout of fields should be Arbitrary for variants"));
}panic!("Layout of fields should be Arbitrary for variants")717 }
718 }
719720// It can't be a Scalar or ScalarPair because the offset isn't 0.
721if !layout.is_uninhabited() {
722layout.backend_repr = BackendRepr::Memory { sized: true };
723 }
724layout.size += this_offset;
725726true
727});
728729if !all_variants_fit {
730return None;
731 }
732733let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
734735let others_zst = variant_layouts736 .iter_enumerated()
737 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
738let same_size = size == variant_layouts[largest_variant_index].size;
739let same_align = align == variant_layouts[largest_variant_index].align.abi;
740741let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
742let abi = if same_size && same_align && others_zst {
743match variant_layouts[largest_variant_index].backend_repr {
744// When the total alignment and size match, we can use the
745 // same ABI as the scalar variant with the reserved niche.
746BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
747 BackendRepr::ScalarPair(first, second) => {
748// Only the niche is guaranteed to be initialised,
749 // so use union layouts for the other primitive.
750if niche_offset == Size::ZERO {
751 BackendRepr::ScalarPair(niche_scalar, second.to_union())
752 } else {
753 BackendRepr::ScalarPair(first.to_union(), niche_scalar)
754 }
755 }
756_ => BackendRepr::Memory { sized: true },
757 }
758 } else {
759 BackendRepr::Memory { sized: true }
760 };
761762let combined_seed = variant_layouts763 .iter()
764 .map(|v| v.randomization_seed)
765 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
766767let layout = LayoutData {
768 variants: Variants::Multiple {
769 tag: niche_scalar,
770 tag_encoding: TagEncoding::Niche {
771 untagged_variant: largest_variant_index,
772niche_variants,
773niche_start,
774 },
775 tag_field: FieldIdx::new(0),
776 variants: variant_layouts,
777 },
778 fields: FieldsShape::Arbitrary {
779 offsets: [niche_offset].into(),
780 in_memory_order: [FieldIdx::new(0)].into(),
781 },
782 backend_repr: abi,
783largest_niche,
784uninhabited,
785size,
786 align: AbiAlign::new(align),
787max_repr_align,
788unadjusted_abi_align,
789 randomization_seed: combined_seed,
790 };
791792Some(layout)
793 };
794795let niche_filling_layout = calculate_niche_filling_layout();
796797let discr_type = repr.discr_type();
798let discr_int = Integer::from_attr(dl, discr_type);
799// Because we can only represent one range of valid values, we'll look for the
800 // largest range of invalid values and pick everything else as the range of valid
801 // values.
802803 // First we need to sort the possible discriminant values so that we can look for the largest gap:
804let valid_discriminants: BTreeSet<i128> = discriminants805 .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
806 .map(|(_, val)| {
807if discr_type.is_signed() {
808// sign extend the raw representation to be an i128
809 // FIXME: do this at the discriminant iterator creation sites
810discr_int.size().sign_extend(valas u128)
811 } else {
812val813 }
814 })
815 .collect();
816{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:816",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(816u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["valid_discriminants"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&valid_discriminants)
as &dyn Value))])
});
} else { ; }
};trace!(?valid_discriminants);
817let discriminants = valid_discriminants.iter().copied();
818//let next_discriminants = discriminants.clone().cycle().skip(1);
819let next_discriminants =
820discriminants.clone().chain(valid_discriminants.first().copied()).skip(1);
821// Iterate over pairs of each discriminant together with the next one.
822 // Since they were sorted, we can now compute the niche sizes and pick the largest.
823let discriminants = discriminants.zip(next_discriminants);
824let largest_niche = discriminants.max_by_key(|&(start, end)| {
825{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:825",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(825u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["start", "end"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&start) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&end) as
&dyn Value))])
});
} else { ; }
};trace!(?start, ?end);
826// If this is a wraparound range, the niche size is `MAX - abs(diff)`, as the diff between
827 // the two end points is actually the size of the valid discriminants.
828let dist = if start > end {
829// Overflow can happen for 128 bit discriminants if `end` is negative.
830 // But in that case casting to `u128` still gets us the right value,
831 // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
832let dist = start.wrapping_sub(end);
833if discr_type.is_signed() {
834discr_int.signed_max().wrapping_sub(dist) as u128835 } else {
836discr_int.size().unsigned_int_max() - distas u128837 }
838 } else {
839// Overflow can happen for 128 bit discriminants if `start` is negative.
840 // But in that case casting to `u128` still gets us the right value,
841 // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
842end.wrapping_sub(start) as u128843 };
844{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:844",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(844u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["dist"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&dist) as
&dyn Value))])
});
} else { ; }
};trace!(?dist);
845dist846 });
847{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:847",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(847u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["largest_niche"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&largest_niche)
as &dyn Value))])
});
} else { ; }
};trace!(?largest_niche);
848849// `max` is the last valid discriminant before the largest niche
850 // `min` is the first valid discriminant after the largest niche
851let (max, min) = largest_niche852// We might have no inhabited variants, so pretend there's at least one.
853.unwrap_or((0, 0));
854let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::discr_range_of_repr(tcx, ty, &repr, min, max);
855856let mut align = dl.aggregate_align;
857let mut max_repr_align = repr.align;
858let mut unadjusted_abi_align = align;
859860let mut size = Size::ZERO;
861862// We're interested in the smallest alignment, so start large.
863let mut start_align = Align::from_bytes(256).unwrap();
864match (&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);
865866// repr(C) on an enum tells us to make a (tag, union) layout,
867 // so we need to grow the prefix alignment to be at least
868 // the alignment of the union. (This value is used both for
869 // determining the alignment of the overall enum, and the
870 // determining the alignment of the payload after the tag.)
871let mut prefix_align = min_ity.align(dl).abi;
872if repr.c() {
873for fields in variants {
874for field in fields {
875 prefix_align = prefix_align.max(field.align.abi);
876 }
877 }
878 }
879880// Create the set of structs that represent each variant.
881let mut layout_variants = variants882 .iter_enumerated()
883 .map(|(i, field_layouts)| {
884let mut st = self.univariant(
885field_layouts,
886repr,
887 StructKind::Prefixed(min_ity.size(), prefix_align),
888 )?;
889st.variants = Variants::Single { index: i };
890// Find the first field we can't move later
891 // to make room for a larger discriminant.
892for field_idx in st.fields.index_by_increasing_offset() {
893let field = &field_layouts[FieldIdx::new(field_idx)];
894if !field.is_1zst() {
895 start_align = start_align.min(field.align.abi);
896break;
897 }
898 }
899size = cmp::max(size, st.size);
900align = align.max(st.align.abi);
901max_repr_align = max_repr_align.max(st.max_repr_align);
902unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
903Ok(st)
904 })
905 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
906907// Align the maximum variant size to the largest alignment.
908size = size.align_to(align);
909910// FIXME(oli-obk): deduplicate and harden these checks
911if size.bytes() >= dl.obj_size_bound() {
912return Err(LayoutCalculatorError::SizeOverflow);
913 }
914915let typeck_ity = Integer::from_attr(dl, repr.discr_type());
916if typeck_ity < min_ity {
917// It is a bug if Layout decided on a greater discriminant size than typeck for
918 // some reason at this point (based on values discriminant can take on). Mostly
919 // because this discriminant will be loaded, and then stored into variable of
920 // type calculated by typeck. Consider such case (a bug): typeck decided on
921 // byte-sized discriminant, but layout thinks we need a 16-bit to store all
922 // discriminant values. That would be a bug, because then, in codegen, in order
923 // to store this 16-bit discriminant into 8-bit sized temporary some of the
924 // space necessary to represent would have to be discarded (or layout is wrong
925 // on thinking it needs 16 bits)
926{
::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
min_ity, typeck_ity));
};panic!(
927"layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
928);
929// However, it is fine to make discr type however large (as an optimisation)
930 // after this point – we’ll just truncate the value we load in codegen.
931}
932933// Check to see if we should use a different type for the
934 // discriminant. We can safely use a type with the same size
935 // as the alignment of the first field of each variant.
936 // We increase the size of the discriminant to avoid LLVM copying
937 // padding when it doesn't need to. This normally causes unaligned
938 // load/stores and excessive memcpy/memset operations. By using a
939 // bigger integer size, LLVM can be sure about its contents and
940 // won't be so conservative.
941942 // Use the initial field alignment
943let mut ity = if repr.c() || repr.int.is_some() {
944min_ity945 } else {
946Integer::for_align(dl, start_align).unwrap_or(min_ity)
947 };
948949// If the alignment is not larger than the chosen discriminant size,
950 // don't use the alignment as the final size.
951if ity <= min_ity {
952ity = min_ity;
953 } else {
954// Patch up the variants' first few fields.
955let old_ity_size = min_ity.size();
956let new_ity_size = ity.size();
957for variant in &mut layout_variants {
958match variant.fields {
959 FieldsShape::Arbitrary { ref mut offsets, .. } => {
960for i in offsets {
961if *i <= old_ity_size {
962match (&*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);
963*i = new_ity_size;
964 }
965 }
966// We might be making the struct larger.
967if variant.size <= old_ity_size {
968 variant.size = new_ity_size;
969 }
970 }
971 FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
972{
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")973 }
974 }
975 }
976 }
977978let tag_mask = ity.size().unsigned_int_max();
979let tag = Scalar::Initialized {
980 value: Primitive::Int(ity, signed),
981 valid_range: WrappingRange {
982 start: (minas u128 & tag_mask),
983 end: (maxas u128 & tag_mask),
984 },
985 };
986let mut abi = BackendRepr::Memory { sized: true };
987988let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
989if tag.size(dl) == size {
990// Make sure we only use scalar layout when the enum is entirely its
991 // own tag (i.e. it has no padding nor any non-ZST variant fields).
992abi = BackendRepr::Scalar(tag);
993 } else {
994// Try to use a ScalarPair for all tagged enums.
995 // That's possible only if we can find a common primitive type for all variants.
996let mut common_prim = None;
997let mut common_prim_initialized_in_all_variants = true;
998for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
999let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
1000{
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
};panic!("encountered a non-arbitrary layout during enum layout");
1001 };
1002// We skip *all* ZST here and later check if we are good in terms of alignment.
1003 // This lets us handle some cases involving aligned ZST.
1004let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
1005let (field, offset) = match (fields.next(), fields.next()) {
1006 (None, None) => {
1007 common_prim_initialized_in_all_variants = false;
1008continue;
1009 }
1010 (Some(pair), None) => pair,
1011_ => {
1012 common_prim = None;
1013break;
1014 }
1015 };
1016let prim = match field.backend_repr {
1017 BackendRepr::Scalar(scalar) => {
1018 common_prim_initialized_in_all_variants &=
1019#[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Initialized { .. } => true,
_ => false,
}matches!(scalar, Scalar::Initialized { .. });
1020 scalar.primitive()
1021 }
1022_ => {
1023 common_prim = None;
1024break;
1025 }
1026 };
1027if let Some((old_prim, common_offset)) = common_prim {
1028// All variants must be at the same offset
1029if offset != common_offset {
1030 common_prim = None;
1031break;
1032 }
1033// This is pretty conservative. We could go fancier
1034 // by realising that (u8, u8) could just cohabit with
1035 // u16 or even u32.
1036let new_prim = match (old_prim, prim) {
1037// Allow all identical primitives.
1038(x, y) if x == y => x,
1039// Allow integers of the same size with differing signedness.
1040 // We arbitrarily choose the signedness of the first variant.
1041(p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
1042// Allow integers mixed with pointers of the same layout.
1043 // We must represent this using a pointer, to avoid
1044 // roundtripping pointers through ptrtoint/inttoptr.
1045(p @ Primitive::Pointer(_), i @ Primitive::Int(..))
1046 | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
1047if p.size(dl) == i.size(dl) && p.align(dl) == i.align(dl) =>
1048 {
1049 p
1050 }
1051_ => {
1052 common_prim = None;
1053break;
1054 }
1055 };
1056// We may be updating the primitive here, for example from int->ptr.
1057common_prim = Some((new_prim, common_offset));
1058 } else {
1059 common_prim = Some((prim, offset));
1060 }
1061 }
1062if let Some((prim, offset)) = common_prim {
1063let prim_scalar = if common_prim_initialized_in_all_variants {
1064let size = prim.size(dl);
1065if !(size.bits() <= 128) {
::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
1066 Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
1067 } else {
1068// Common prim might be uninit.
1069Scalar::Union { value: prim }
1070 };
1071let pair =
1072 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1073let pair_offsets = match pair.fields {
1074 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1075match (&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)]);
1076offsets1077 }
1078_ => {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1079 };
1080if pair_offsets[FieldIdx::new(0)] == Size::ZERO1081 && pair_offsets[FieldIdx::new(1)] == *offset1082 && align == pair.align.abi
1083 && size == pair.size
1084 {
1085// We can use `ScalarPair` only when it matches our
1086 // already computed layout (including `#[repr(C)]`).
1087abi = pair.backend_repr;
1088 }
1089 }
1090 }
10911092// If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1093 // variants to ensure they are consistent. This is because a downcast is
1094 // semantically a NOP, and thus should not affect layout.
1095if #[allow(non_exhaustive_omitted_patterns)] match abi {
BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..) => true,
_ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1096for variant in &mut layout_variants {
1097// We only do this for variants with fields; the others are not accessed anyway.
1098 // Also do not overwrite any already existing "clever" ABIs.
1099if variant.fields.count() > 0
1100 && #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. })1101 {
1102 variant.backend_repr = abi;
1103// Also need to bump up the size and alignment, so that the entire value fits
1104 // in here.
1105variant.size = cmp::max(variant.size, size);
1106 variant.align.abi = cmp::max(variant.align.abi, align);
1107 }
1108 }
1109 }
11101111let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
11121113let combined_seed = layout_variants1114 .iter()
1115 .map(|v| v.randomization_seed)
1116 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
11171118let tagged_layout = LayoutData {
1119 variants: Variants::Multiple {
1120tag,
1121 tag_encoding: TagEncoding::Direct,
1122 tag_field: FieldIdx::new(0),
1123 variants: layout_variants,
1124 },
1125 fields: FieldsShape::Arbitrary {
1126 offsets: [Size::ZERO].into(),
1127 in_memory_order: [FieldIdx::new(0)].into(),
1128 },
1129largest_niche,
1130uninhabited,
1131 backend_repr: abi,
1132 align: AbiAlign::new(align),
1133size,
1134max_repr_align,
1135unadjusted_abi_align,
1136 randomization_seed: combined_seed,
1137 };
11381139let best_layout = match (tagged_layout, niche_filling_layout) {
1140 (tl, Some(nl)) => {
1141// Pick the smaller layout; otherwise,
1142 // pick the layout with the larger niche; otherwise,
1143 // pick tagged as it has simpler codegen.
1144use cmp::Ordering::*;
1145let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1146l.largest_niche.map_or(0, |n| n.available(dl))
1147 };
1148match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1149 (Greater, _) => nl,
1150 (Equal, Less) => nl,
1151_ => tl,
1152 }
1153 }
1154 (tl, None) => tl,
1155 };
11561157Ok(best_layout)
1158 }
11591160fn univariant_biased<
1161'a,
1162 FieldIdx: Idx,
1163 VariantIdx: Idx,
1164 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1165 >(
1166&self,
1167 fields: &IndexSlice<FieldIdx, F>,
1168 repr: &ReprOptions,
1169 kind: StructKind,
1170 niche_bias: NicheBias,
1171 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
1172let dl = self.cx.data_layout();
1173let pack = repr.pack;
1174let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1175let mut max_repr_align = repr.align;
1176let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1177let optimize_field_order = !repr.inhibit_struct_field_reordering();
1178let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1179let optimizing = &mut in_memory_order.raw[..end];
1180let fields_excluding_tail = &fields.raw[..end];
1181// unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
1182let field_seed = fields_excluding_tail1183 .iter()
1184 .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
11851186if optimize_field_order && fields.len() > 1 {
1187// If `-Z randomize-layout` was enabled for the type definition we can shuffle
1188 // the field ordering to try and catch some code making assumptions about layouts
1189 // we don't guarantee.
1190if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1191#[cfg(feature = "randomize")]
1192{
1193use rand::SeedableRng;
1194use rand::seq::SliceRandom;
1195// `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
1196 // ordering.
1197let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1198field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1199 );
12001201// Shuffle the ordering of the fields.
1202optimizing.shuffle(&mut rng);
1203 }
1204// Otherwise we just leave things alone and actually optimize the type's fields
1205} else {
1206// To allow unsizing `&Foo<Type>` -> `&Foo<dyn Trait>`, the layout of the struct must
1207 // not depend on the layout of the tail.
1208let max_field_align =
1209fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1210let largest_niche_size = fields_excluding_tail1211 .iter()
1212 .filter_map(|f| f.largest_niche)
1213 .map(|n| n.available(dl))
1214 .max()
1215 .unwrap_or(0);
12161217// Calculates a sort key to group fields by their alignment or possibly some
1218 // size-derived pseudo-alignment.
1219let alignment_group_key = |layout: &F| {
1220// The two branches here return values that cannot be meaningfully compared with
1221 // each other. However, we know that consistently for all executions of
1222 // `alignment_group_key`, one or the other branch will be taken, so this is okay.
1223if let Some(pack) = pack {
1224// Return the packed alignment in bytes.
1225layout.align.abi.min(pack).bytes()
1226 } else {
1227// Returns `log2(effective-align)`. The calculation assumes that size is an
1228 // integer multiple of align, except for ZSTs.
1229let align = layout.align.bytes();
1230let size = layout.size.bytes();
1231let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1232// Group [u8; 4] with align-4 or [u8; 6] with align-2 fields.
1233let size_as_align = align.max(size).trailing_zeros();
1234let size_as_align = if largest_niche_size > 0 {
1235match niche_bias {
1236// Given `A(u8, [u8; 16])` and `B(bool, [u8; 16])` we want to bump the
1237 // array to the front in the first case (for aligned loads) but keep
1238 // the bool in front in the second case for its niches.
1239NicheBias::Start => {
1240max_field_align.trailing_zeros().min(size_as_align)
1241 }
1242// When moving niches towards the end of the struct then for
1243 // A((u8, u8, u8, bool), (u8, bool, u8)) we want to keep the first tuple
1244 // in the align-1 group because its bool can be moved closer to the end.
1245NicheBias::Endif niche_size == largest_niche_size => {
1246align.trailing_zeros()
1247 }
1248 NicheBias::End => size_as_align,
1249 }
1250 } else {
1251size_as_align1252 };
1253size_as_alignas u641254 }
1255 };
12561257match kind {
1258 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1259// Currently `LayoutData` only exposes a single niche so sorting is usually
1260 // sufficient to get one niche into the preferred position. If it ever
1261 // supported multiple niches then a more advanced pick-and-pack approach could
1262 // provide better results. But even for the single-niche cache it's not
1263 // optimal. E.g. for A(u32, (bool, u8), u16) it would be possible to move the
1264 // bool to the front but it would require packing the tuple together with the
1265 // u16 to build a 4-byte group so that the u32 can be placed after it without
1266 // padding. This kind of packing can't be achieved by sorting.
1267optimizing.sort_by_key(|&x| {
1268let f = &fields[x];
1269let field_size = f.size.bytes();
1270let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1271let niche_size_key = match niche_bias {
1272// large niche first
1273NicheBias::Start => !niche_size,
1274// large niche last
1275NicheBias::End => niche_size,
1276 };
1277let inner_niche_offset_key = match niche_bias {
1278 NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1279 NicheBias::End => f.largest_niche.map_or(0, |n| {
1280 !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1281 }),
1282 };
12831284 (
1285// Then place largest alignments first.
1286cmp::Reverse(alignment_group_key(f)),
1287// Then prioritize niche placement within alignment group according to
1288 // `niche_bias_start`.
1289niche_size_key,
1290// Then among fields with equally-sized niches prefer the ones
1291 // closer to the start/end of the field.
1292inner_niche_offset_key,
1293 )
1294 });
1295 }
12961297 StructKind::Prefixed(..) => {
1298// Sort in ascending alignment so that the layout stays optimal
1299 // regardless of the prefix.
1300 // And put the largest niche in an alignment group at the end
1301 // so it can be used as discriminant in jagged enums
1302optimizing.sort_by_key(|&x| {
1303let f = &fields[x];
1304let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1305 (alignment_group_key(f), niche_size)
1306 });
1307 }
1308 }
13091310// FIXME(Kixiron): We can always shuffle fields within a given alignment class
1311 // regardless of the status of `-Z randomize-layout`
1312}
1313 }
1314// in_memory_order holds field indices by increasing memory offset.
1315 // That is, if field 5 has offset 0, the first element of in_memory_order is 5.
1316 // We now write field offsets to the corresponding offset slot;
1317 // field 5 with offset 0 puts 0 in offsets[5].
1318let mut unsized_field = None::<&F>;
1319let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1320let mut offset = Size::ZERO;
1321let mut largest_niche = None;
1322let mut largest_niche_available = 0;
1323if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1324let prefix_align =
1325if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1326align = align.max(prefix_align);
1327offset = prefix_size.align_to(prefix_align);
1328 }
1329for &i in &in_memory_order {
1330let field = &fields[i];
1331if let Some(unsized_field) = unsized_field {
1332return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1333 }
13341335if field.is_unsized() {
1336if let StructKind::MaybeUnsized = kind {
1337 unsized_field = Some(field);
1338 } else {
1339return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1340 }
1341 }
13421343// Invariant: offset < dl.obj_size_bound() <= 1<<61
1344let field_align = if let Some(pack) = pack {
1345 field.align.min(AbiAlign::new(pack))
1346 } else {
1347 field.align
1348 };
1349 offset = offset.align_to(field_align.abi);
1350 align = align.max(field_align.abi);
1351 max_repr_align = max_repr_align.max(field.max_repr_align);
13521353{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1353",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1353u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("univariant offset: {0:?} field: {1:#?}",
offset, field) as &dyn Value))])
});
} else { ; }
};debug!("univariant offset: {:?} field: {:#?}", offset, field);
1354 offsets[i] = offset;
13551356if let Some(mut niche) = field.largest_niche {
1357let available = niche.available(dl);
1358// Pick up larger niches.
1359let prefer_new_niche = match niche_bias {
1360 NicheBias::Start => available > largest_niche_available,
1361// if there are several niches of the same size then pick the last one
1362NicheBias::End => available >= largest_niche_available,
1363 };
1364if prefer_new_niche {
1365 largest_niche_available = available;
1366 niche.offset += offset;
1367 largest_niche = Some(niche);
1368 }
1369 }
13701371 offset =
1372 offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1373 }
13741375// The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
1376 // See documentation on `LayoutData::unadjusted_abi_align`.
1377let unadjusted_abi_align = align;
1378if let Some(repr_align) = repr.align {
1379align = align.max(repr_align);
1380 }
1381// `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate.
1382let align = align;
13831384{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1384",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1384u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("univariant min_size: {0:?}",
offset) as &dyn Value))])
});
} else { ; }
};debug!("univariant min_size: {:?}", offset);
1385let min_size = offset;
1386let size = min_size.align_to(align);
1387// FIXME(oli-obk): deduplicate and harden these checks
1388if size.bytes() >= dl.obj_size_bound() {
1389return Err(LayoutCalculatorError::SizeOverflow);
1390 }
1391let mut layout_of_single_non_zst_field = None;
1392let sized = unsized_field.is_none();
1393let mut abi = BackendRepr::Memory { sized };
13941395let optimize_abi = !repr.inhibit_newtype_abi_optimization();
13961397// Try to make this a Scalar/ScalarPair.
1398if sized && size.bytes() > 0 {
1399// We skip *all* ZST here and later check if we are good in terms of alignment.
1400 // This lets us handle some cases involving aligned ZST.
1401let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
14021403match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1404// We have exactly one non-ZST field.
1405(Some((i, field)), None, None) => {
1406layout_of_single_non_zst_field = Some(field);
14071408// Field fills the struct and it has a scalar or scalar pair ABI.
1409if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1410match field.backend_repr {
1411// For plain scalars, or vectors of them, we can't unpack
1412 // newtypes for `#[repr(C)]`, as that affects C ABIs.
1413BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1414if optimize_abi =>
1415 {
1416abi = field.backend_repr;
1417 }
1418// But scalar pairs are Rust-specific and get
1419 // treated as aggregates by C ABIs anyway.
1420BackendRepr::ScalarPair(..) => {
1421abi = field.backend_repr;
1422 }
1423_ => {}
1424 }
1425 }
1426 }
14271428// Two non-ZST fields, and they're both scalars.
1429(Some((i, a)), Some((j, b)), None) => {
1430match (a.backend_repr, b.backend_repr) {
1431 (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1432// Order by the memory placement, not source order.
1433let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1434 ((i, a), (j, b))
1435 } else {
1436 ((j, b), (i, a))
1437 };
1438let pair =
1439 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1440let pair_offsets = match pair.fields {
1441 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1442match (&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!(
1443 in_memory_order.raw,
1444 [FieldIdx::new(0), FieldIdx::new(1)]
1445 );
1446offsets1447 }
1448 FieldsShape::Primitive1449 | FieldsShape::Array { .. }
1450 | FieldsShape::Union(..) => {
1451{
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")1452 }
1453 };
1454if offsets[i] == pair_offsets[FieldIdx::new(0)]
1455 && offsets[j] == pair_offsets[FieldIdx::new(1)]
1456 && align == pair.align.abi
1457 && size == pair.size
1458 {
1459// We can use `ScalarPair` only when it matches our
1460 // already computed layout (including `#[repr(C)]`).
1461abi = pair.backend_repr;
1462 }
1463 }
1464_ => {}
1465 }
1466 }
14671468_ => {}
1469 }
1470 }
1471let uninhabited = fields.iter().any(|f| f.is_uninhabited());
14721473let unadjusted_abi_align = if repr.transparent() {
1474match layout_of_single_non_zst_field {
1475Some(l) => l.unadjusted_abi_align,
1476None => {
1477// `repr(transparent)` with all ZST fields.
1478align1479 }
1480 }
1481 } else {
1482unadjusted_abi_align1483 };
14841485let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
14861487Ok(LayoutData {
1488 variants: Variants::Single { index: VariantIdx::new(0) },
1489 fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1490 backend_repr: abi,
1491largest_niche,
1492uninhabited,
1493 align: AbiAlign::new(align),
1494size,
1495max_repr_align,
1496unadjusted_abi_align,
1497 randomization_seed: seed,
1498 })
1499 }
15001501fn format_field_niches<
1502'a,
1503 FieldIdx: Idx,
1504 VariantIdx: Idx,
1505 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1506 >(
1507&self,
1508 layout: &LayoutData<FieldIdx, VariantIdx>,
1509 fields: &IndexSlice<FieldIdx, F>,
1510 ) -> String {
1511let dl = self.cx.data_layout();
1512let mut s = String::new();
1513for i in layout.fields.index_by_increasing_offset() {
1514let offset = layout.fields.offset(i);
1515let f = &fields[FieldIdx::new(i)];
1516s.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();
1517if let Some(n) = f.largest_niche {
1518s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1519 s,
1520" n{}b{}s{}",
1521 n.offset.bytes(),
1522 n.available(dl).ilog2(),
1523 n.value.size(dl).bytes()
1524 )1525 .unwrap();
1526 }
1527s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1528 }
1529s1530 }
1531}
15321533enum SimdVectorKind {
1534/// `#[rustc_scalable_vector]`
1535Scalable(NumScalableVectors),
1536/// `#[repr(simd, packed)]`
1537PackedFixed,
1538/// `#[repr(simd)]`
1539Fixed,
1540}
15411542fn vector_type_layout<FieldIdx, VariantIdx, F>(
1543 kind: SimdVectorKind,
1544 dl: &TargetDataLayout,
1545 element: F,
1546 count: u64,
1547) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1548where
1549FieldIdx: Idx,
1550 VariantIdx: Idx,
1551 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1552{
1553let elt = element.as_ref();
1554if count == 0 {
1555return Err(LayoutCalculatorError::ZeroLengthSimdType);
1556 } else if count > crate::MAX_SIMD_LANES {
1557return Err(LayoutCalculatorError::OversizedSimdType { max_lanes: crate::MAX_SIMD_LANES });
1558 }
15591560let BackendRepr::Scalar(element) = elt.backend_repr else {
1561return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1562 };
15631564// Compute the size and alignment of the vector
1565let size =
1566elt.size.checked_mul(count, dl).ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
1567let (repr, align) = match kind {
1568 SimdVectorKind::Scalable(number_of_vectors) => (
1569 BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1570dl.llvmlike_vector_align(size),
1571 ),
1572// Non-power-of-two vectors have padding up to the next power-of-two.
1573 // If we're a packed repr, remove the padding while keeping the alignment as close
1574 // to a vector as possible.
1575SimdVectorKind::PackedFixedif !count.is_power_of_two() => {
1576 (BackendRepr::Memory { sized: true }, Align::max_aligned_factor(size))
1577 }
1578 SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
1579 (BackendRepr::SimdVector { element, count }, dl.llvmlike_vector_align(size))
1580 }
1581 };
1582let size = size.align_to(align);
15831584Ok(LayoutData {
1585 variants: Variants::Single { index: VariantIdx::new(0) },
1586 fields: FieldsShape::Arbitrary {
1587 offsets: [Size::ZERO].into(),
1588 in_memory_order: [FieldIdx::new(0)].into(),
1589 },
1590 backend_repr: repr,
1591 largest_niche: elt.largest_niche,
1592 uninhabited: false,
1593size,
1594 align: AbiAlign::new(align),
1595 max_repr_align: None,
1596 unadjusted_abi_align: elt.align.abi,
1597 randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count)),
1598 })
1599}