1use std::collections::BTreeSet;
2use std::fmt::{self, Write};
3use std::ops::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, VariantLayout, 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]
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]
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 =
187 element.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 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
352 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
353 always_sized: bool,
354 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
355let (present_first, present_second) = {
356let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
357if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
358 });
359 (present_variants.next(), present_variants.next())
360 };
361let present_first = match present_first {
362Some(present_first) => present_first,
363// Uninhabited because it has no variants, or only absent ones.
364Noneif is_enum => {
365return Ok(LayoutData::never_type(&self.cx));
366 }
367// If it's a struct, still compute a layout so that we can still compute the
368 // field offsets.
369None => VariantIdx::new(0),
370 };
371372// take the struct path if it is an actual struct
373if !is_enum ||
374// or for optimizing univariant enums
375(present_second.is_none() && !repr.inhibit_enum_layout_opt())
376 {
377self.layout_of_struct(
378repr,
379variants,
380is_enum,
381is_special_no_niche,
382always_sized,
383present_first,
384 )
385 } else {
386// At this point, we have handled all unions and
387 // structs. (We have also handled univariant enums
388 // that allow representation optimization.)
389if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
390self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
391 }
392 }
393394pub fn layout_of_union<
395'a,
396 FieldIdx: Idx,
397 VariantIdx: Idx,
398 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
399 >(
400&self,
401 repr: &ReprOptions,
402 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
403 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
404let dl = self.cx.data_layout();
405let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
406let mut max_repr_align = repr.align;
407408// If all the non-ZST fields have the same repr and union repr optimizations aren't
409 // disabled, we can use that common repr for the union as a whole.
410struct AbiMismatch;
411let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
412// Can't optimize
413Err(AbiMismatch)
414 } else {
415Ok(None)
416 };
417418let mut size = Size::ZERO;
419let only_variant_idx = VariantIdx::new(0);
420let only_variant = &variants[only_variant_idx];
421for field in only_variant {
422if field.is_unsized() {
423return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
424 }
425426 align = align.max(field.align.abi);
427 max_repr_align = max_repr_align.max(field.max_repr_align);
428 size = cmp::max(size, field.size);
429430if field.is_zst() {
431// Nothing more to do for ZST fields
432continue;
433 }
434435if let Ok(common) = common_non_zst_repr_and_align {
436// Discard valid range information and allow undef
437let field_abi = field.backend_repr.to_union();
438439if let Some((common_abi, common_align)) = common {
440if common_abi != field_abi {
441// Different fields have different ABI: disable opt
442common_non_zst_repr_and_align = Err(AbiMismatch);
443 } else {
444// Fields with the same non-Aggregate ABI should also
445 // have the same alignment
446if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
447match (&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!(
448 common_align, field.align.abi,
449"non-Aggregate field with matching ABI but differing alignment"
450);
451 }
452 }
453 } else {
454// First non-ZST field: record its ABI and alignment
455common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
456 }
457 }
458 }
459460if let Some(pack) = repr.pack {
461align = align.min(pack);
462 }
463// The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
464 // See documentation on `LayoutData::unadjusted_abi_align`.
465let unadjusted_abi_align = align;
466if let Some(repr_align) = repr.align {
467align = align.max(repr_align);
468 }
469// `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate.
470let align = align;
471472// If all non-ZST fields have the same ABI, we may forward that ABI
473 // for the union as a whole, unless otherwise inhibited.
474let backend_repr = match common_non_zst_repr_and_align {
475Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
476Ok(Some((repr, _))) => match repr {
477// Mismatched alignment (e.g. union is #[repr(packed)]): disable opt
478BackendRepr::Scalar(_) | BackendRepr::ScalarPair(_, _)
479if repr.scalar_align(dl).unwrap() != align =>
480 {
481 BackendRepr::Memory { sized: true }
482 }
483// Vectors require at least element alignment, else disable the opt
484BackendRepr::SimdVector { element, count: _ } if element.align(dl).abi > align => {
485 BackendRepr::Memory { sized: true }
486 }
487// the alignment tests passed and we can use this
488BackendRepr::Scalar(..)
489 | BackendRepr::ScalarPair(..)
490 | BackendRepr::SimdVector { .. }
491 | BackendRepr::SimdScalableVector { .. }
492 | BackendRepr::Memory { .. } => repr,
493 },
494 };
495496let Some(union_field_count) = NonZeroUsize::new(only_variant.len()) else {
497return Err(LayoutCalculatorError::EmptyUnion);
498 };
499500let combined_seed = only_variant501 .iter()
502 .map(|v| v.randomization_seed)
503 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
504505Ok(LayoutData {
506 variants: Variants::Single { index: only_variant_idx },
507 fields: FieldsShape::Union(union_field_count),
508backend_repr,
509 largest_niche: None,
510 uninhabited: false,
511 align: AbiAlign::new(align),
512 size: size.align_to(align),
513max_repr_align,
514unadjusted_abi_align,
515 randomization_seed: combined_seed,
516 })
517 }
518519/// single-variant enums are just structs, if you think about it
520fn layout_of_struct<
521'a,
522 FieldIdx: Idx,
523 VariantIdx: Idx,
524 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
525 >(
526&self,
527 repr: &ReprOptions,
528 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
529 is_enum: bool,
530 is_special_no_niche: bool,
531 always_sized: bool,
532 present_first: VariantIdx,
533 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
534// Struct, or univariant enum equivalent to a struct.
535 // (Typechecking will reject discriminant-sizing attrs.)
536537let dl = self.cx.data_layout();
538let v = present_first;
539let kind = if is_enum || variants[v].is_empty() || always_sized {
540 StructKind::AlwaysSized541 } else {
542 StructKind::MaybeUnsized543 };
544545let mut st = self.univariant(&variants[v], repr, kind)?;
546st.variants = Variants::Single { index: v };
547548if is_special_no_niche {
549let hide_niches = |scalar: &mut _| match scalar {
550 Scalar::Initialized { value, valid_range } => {
551*valid_range = WrappingRange::full(value.size(dl))
552 }
553// Already doesn't have any niches
554Scalar::Union { .. } => {}
555 };
556match &mut st.backend_repr {
557 BackendRepr::Scalar(scalar) => hide_niches(scalar),
558 BackendRepr::ScalarPair(a, b) => {
559hide_niches(a);
560hide_niches(b);
561 }
562 BackendRepr::SimdVector { element, .. }
563 | BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
564 BackendRepr::Memory { sized: _ } => {}
565 }
566st.largest_niche = None;
567return Ok(st);
568 }
569570Ok(st)
571 }
572573fn layout_of_enum<
574'a,
575 FieldIdx: Idx,
576 VariantIdx: Idx,
577 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
578 >(
579&self,
580 repr: &ReprOptions,
581 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
582 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
583 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
584 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
585let dl = self.cx.data_layout();
586// bail if the enum has an incoherent repr that cannot be computed
587if repr.packed() {
588return Err(LayoutCalculatorError::ReprConflict);
589 }
590591let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
592struct VariantLayoutInfo {
593 align_abi: Align,
594 }
595596if repr.inhibit_enum_layout_opt() {
597return None;
598 }
599600if variants.len() < 2 {
601return None;
602 }
603604let mut align = dl.aggregate_align;
605let mut max_repr_align = repr.align;
606let mut unadjusted_abi_align = align;
607let mut combined_seed = repr.field_shuffle_seed;
608609let mut variants_info = IndexVec::<VariantIdx, _>::with_capacity(variants.len());
610let mut variant_layouts = variants
611 .iter()
612 .map(|v| {
613let st = self.univariant(v, repr, StructKind::AlwaysSized).ok()?;
614615 variants_info.push(VariantLayoutInfo { align_abi: st.align.abi });
616617 align = align.max(st.align.abi);
618 max_repr_align = max_repr_align.max(st.max_repr_align);
619 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
620 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
621622Some(VariantLayout::from_layout(st))
623 })
624 .collect::<Option<IndexVec<VariantIdx, _>>>()?;
625626let largest_variant_index = variant_layouts
627 .iter_enumerated()
628 .max_by_key(|(_i, layout)| layout.size.bytes())
629 .map(|(i, _layout)| i)?;
630631let all_indices = variants.indices();
632let needs_disc =
633 |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
634let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
635 ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
636637let count =
638 (niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1;
639640// Use the largest niche in the largest variant.
641let niche = variant_layouts[largest_variant_index].largest_niche?;
642let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
643let niche_offset = niche.offset;
644let niche_size = niche.value.size(dl);
645let size = variant_layouts[largest_variant_index].size.align_to(align);
646647let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
648if i == largest_variant_index {
649return true;
650 }
651652layout.largest_niche = None;
653654if layout.size <= niche_offset {
655// This variant will fit before the niche.
656return true;
657 }
658659// Determine if it'll fit after the niche.
660let this_align = variants_info[i].align_abi;
661let this_offset = (niche_offset + niche_size).align_to(this_align);
662663if this_offset + layout.size > size {
664return false;
665 }
666667// It'll fit, but we need to make some adjustments.
668for offset in layout.field_offsets.iter_mut() {
669*offset += this_offset;
670 }
671672// It can't be a Scalar or ScalarPair because the offset isn't 0.
673if !layout.is_uninhabited() {
674layout.backend_repr = BackendRepr::Memory { sized: true };
675 }
676layout.size += this_offset;
677678true
679});
680681if !all_variants_fit {
682return None;
683 }
684685let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
686687let others_zst = variant_layouts688 .iter_enumerated()
689 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
690let same_size = size == variant_layouts[largest_variant_index].size;
691let same_align = align == variants_info[largest_variant_index].align_abi;
692693let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
694let abi = if same_size && same_align && others_zst {
695match variant_layouts[largest_variant_index].backend_repr {
696// When the total alignment and size match, we can use the
697 // same ABI as the scalar variant with the reserved niche.
698BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
699 BackendRepr::ScalarPair(first, second) => {
700// Only the niche is guaranteed to be initialised,
701 // so use union layouts for the other primitive.
702if niche_offset == Size::ZERO {
703 BackendRepr::ScalarPair(niche_scalar, second.to_union())
704 } else {
705 BackendRepr::ScalarPair(first.to_union(), niche_scalar)
706 }
707 }
708_ => BackendRepr::Memory { sized: true },
709 }
710 } else {
711 BackendRepr::Memory { sized: true }
712 };
713714let layout = LayoutData {
715 variants: Variants::Multiple {
716 tag: niche_scalar,
717 tag_encoding: TagEncoding::Niche {
718 untagged_variant: largest_variant_index,
719niche_variants,
720niche_start,
721 },
722 tag_field: FieldIdx::new(0),
723 variants: variant_layouts,
724 },
725 fields: FieldsShape::Arbitrary {
726 offsets: [niche_offset].into(),
727 in_memory_order: [FieldIdx::new(0)].into(),
728 },
729 backend_repr: abi,
730largest_niche,
731uninhabited,
732size,
733 align: AbiAlign::new(align),
734max_repr_align,
735unadjusted_abi_align,
736 randomization_seed: combined_seed,
737 };
738739Some(layout)
740 };
741742let niche_filling_layout = calculate_niche_filling_layout();
743744let discr_type = repr.discr_type();
745let discr_int = Integer::from_attr(dl, discr_type);
746// Because we can only represent one range of valid values, we'll look for the
747 // largest range of invalid values and pick everything else as the range of valid
748 // values.
749750 // First we need to sort the possible discriminant values so that we can look for the largest gap:
751let valid_discriminants: BTreeSet<i128> = discriminants752 .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
753 .map(|(_, val)| {
754if discr_type.is_signed() {
755// sign extend the raw representation to be an i128
756 // FIXME: do this at the discriminant iterator creation sites
757discr_int.size().sign_extend(valas u128)
758 } else {
759val760 }
761 })
762 .collect();
763{
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:763",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(763u32),
::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);
764let discriminants = valid_discriminants.iter().copied();
765//let next_discriminants = discriminants.clone().cycle().skip(1);
766let next_discriminants =
767discriminants.clone().chain(valid_discriminants.first().copied()).skip(1);
768// Iterate over pairs of each discriminant together with the next one.
769 // Since they were sorted, we can now compute the niche sizes and pick the largest.
770let discriminants = discriminants.zip(next_discriminants);
771let largest_niche = discriminants.max_by_key(|&(start, end)| {
772{
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:772",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(772u32),
::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);
773// If this is a wraparound range, the niche size is `MAX - abs(diff)`, as the diff between
774 // the two end points is actually the size of the valid discriminants.
775let dist = if start > end {
776// Overflow can happen for 128 bit discriminants if `end` is negative.
777 // But in that case casting to `u128` still gets us the right value,
778 // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
779let dist = start.wrapping_sub(end);
780if discr_type.is_signed() {
781discr_int.signed_max().wrapping_sub(dist) as u128782 } else {
783discr_int.size().unsigned_int_max() - distas u128784 }
785 } else {
786// Overflow can happen for 128 bit discriminants if `start` is negative.
787 // But in that case casting to `u128` still gets us the right value,
788 // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
789end.wrapping_sub(start) as u128790 };
791{
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:791",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(791u32),
::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);
792dist793 });
794{
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:794",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(794u32),
::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);
795796// `max` is the last valid discriminant before the largest niche
797 // `min` is the first valid discriminant after the largest niche
798let (max, min) = largest_niche799// We might have no inhabited variants, so pretend there's at least one.
800.unwrap_or((0, 0));
801let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::discr_range_of_repr(tcx, ty, &repr, min, max);
802803let mut align = dl.aggregate_align;
804let mut max_repr_align = repr.align;
805let mut unadjusted_abi_align = align;
806let mut combined_seed = repr.field_shuffle_seed;
807808let mut size = Size::ZERO;
809810// We're interested in the smallest alignment, so start large.
811let mut start_align = Align::from_bytes(256).unwrap();
812match (&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);
813814// repr(C) on an enum tells us to make a (tag, union) layout,
815 // so we need to grow the prefix alignment to be at least
816 // the alignment of the union. (This value is used both for
817 // determining the alignment of the overall enum, and the
818 // determining the alignment of the payload after the tag.)
819let mut prefix_align = min_ity.align(dl).abi;
820if repr.c() {
821for fields in variants {
822for field in fields {
823 prefix_align = prefix_align.max(field.align.abi);
824 }
825 }
826 }
827828// Create the set of structs that represent each variant.
829let mut layout_variants = variants
830 .iter()
831 .map(|field_layouts| {
832let st = self.univariant(
833 field_layouts,
834 repr,
835 StructKind::Prefixed(min_ity.size(), prefix_align),
836 )?;
837// Find the first field we can't move later
838 // to make room for a larger discriminant.
839for field_idx in st.fields.index_by_increasing_offset() {
840let field = &field_layouts[FieldIdx::new(field_idx)];
841if !field.is_1zst() {
842 start_align = start_align.min(field.align.abi);
843break;
844 }
845 }
846 size = cmp::max(size, st.size);
847 align = align.max(st.align.abi);
848 max_repr_align = max_repr_align.max(st.max_repr_align);
849 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
850 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
851Ok(VariantLayout::from_layout(st))
852 })
853 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
854855// Align the maximum variant size to the largest alignment.
856size = size.align_to(align);
857858// FIXME(oli-obk): deduplicate and harden these checks
859if size.bytes() >= dl.obj_size_bound() {
860return Err(LayoutCalculatorError::SizeOverflow);
861 }
862863let typeck_ity = Integer::from_attr(dl, repr.discr_type());
864if typeck_ity < min_ity {
865// It is a bug if Layout decided on a greater discriminant size than typeck for
866 // some reason at this point (based on values discriminant can take on). Mostly
867 // because this discriminant will be loaded, and then stored into variable of
868 // type calculated by typeck. Consider such case (a bug): typeck decided on
869 // byte-sized discriminant, but layout thinks we need a 16-bit to store all
870 // discriminant values. That would be a bug, because then, in codegen, in order
871 // to store this 16-bit discriminant into 8-bit sized temporary some of the
872 // space necessary to represent would have to be discarded (or layout is wrong
873 // on thinking it needs 16 bits)
874{
::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
min_ity, typeck_ity));
};panic!(
875"layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
876);
877// However, it is fine to make discr type however large (as an optimisation)
878 // after this point – we’ll just truncate the value we load in codegen.
879}
880881// Check to see if we should use a different type for the
882 // discriminant. We can safely use a type with the same size
883 // as the alignment of the first field of each variant.
884 // We increase the size of the discriminant to avoid LLVM copying
885 // padding when it doesn't need to. This normally causes unaligned
886 // load/stores and excessive memcpy/memset operations. By using a
887 // bigger integer size, LLVM can be sure about its contents and
888 // won't be so conservative.
889890 // Use the initial field alignment
891let mut ity = if repr.c() || repr.int.is_some() {
892min_ity893 } else {
894Integer::for_align(dl, start_align).unwrap_or(min_ity)
895 };
896897// If the alignment is not larger than the chosen discriminant size,
898 // don't use the alignment as the final size.
899if ity <= min_ity {
900ity = min_ity;
901 } else {
902// Patch up the variants' first few fields.
903let old_ity_size = min_ity.size();
904let new_ity_size = ity.size();
905for variant in &mut layout_variants {
906for i in &mut variant.field_offsets {
907if *i <= old_ity_size {
908match (&*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);
909*i = new_ity_size;
910 }
911 }
912// We might be making the struct larger.
913if variant.size <= old_ity_size {
914 variant.size = new_ity_size;
915 }
916 }
917 }
918919let tag_mask = ity.size().unsigned_int_max();
920let tag = Scalar::Initialized {
921 value: Primitive::Int(ity, signed),
922 valid_range: WrappingRange {
923 start: (minas u128 & tag_mask),
924 end: (maxas u128 & tag_mask),
925 },
926 };
927let mut abi = BackendRepr::Memory { sized: true };
928929let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
930if tag.size(dl) == size {
931// Make sure we only use scalar layout when the enum is entirely its
932 // own tag (i.e. it has no padding nor any non-ZST variant fields).
933abi = BackendRepr::Scalar(tag);
934 } else {
935// Try to use a ScalarPair for all tagged enums.
936 // That's possible only if we can find a common primitive type for all variants.
937let mut common_prim = None;
938let mut common_prim_initialized_in_all_variants = true;
939for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
940// We skip *all* ZST here and later check if we are good in terms of alignment.
941 // This lets us handle some cases involving aligned ZST.
942let mut fields = iter::zip(field_layouts, &layout_variant.field_offsets)
943 .filter(|p| !p.0.is_zst());
944let (field, offset) = match (fields.next(), fields.next()) {
945 (None, None) => {
946 common_prim_initialized_in_all_variants = false;
947continue;
948 }
949 (Some(pair), None) => pair,
950_ => {
951 common_prim = None;
952break;
953 }
954 };
955let prim = match field.backend_repr {
956 BackendRepr::Scalar(scalar) => {
957 common_prim_initialized_in_all_variants &=
958#[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Initialized { .. } => true,
_ => false,
}matches!(scalar, Scalar::Initialized { .. });
959 scalar.primitive()
960 }
961_ => {
962 common_prim = None;
963break;
964 }
965 };
966if let Some((old_prim, common_offset)) = common_prim {
967// All variants must be at the same offset
968if offset != common_offset {
969 common_prim = None;
970break;
971 }
972// This is pretty conservative. We could go fancier
973 // by realising that (u8, u8) could just cohabit with
974 // u16 or even u32.
975let new_prim = match (old_prim, prim) {
976// Allow all identical primitives.
977(x, y) if x == y => x,
978// Allow integers of the same size with differing signedness.
979 // We arbitrarily choose the signedness of the first variant.
980(p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
981// Allow integers mixed with pointers of the same layout.
982 // We must represent this using a pointer, to avoid
983 // roundtripping pointers through ptrtoint/inttoptr.
984(p @ Primitive::Pointer(_), i @ Primitive::Int(..))
985 | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
986if p.size(dl) == i.size(dl) && p.align(dl) == i.align(dl) =>
987 {
988 p
989 }
990_ => {
991 common_prim = None;
992break;
993 }
994 };
995// We may be updating the primitive here, for example from int->ptr.
996common_prim = Some((new_prim, common_offset));
997 } else {
998 common_prim = Some((prim, offset));
999 }
1000 }
1001if let Some((prim, offset)) = common_prim {
1002let prim_scalar = if common_prim_initialized_in_all_variants {
1003let size = prim.size(dl);
1004if !(size.bits() <= 128) {
::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
1005 Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
1006 } else {
1007// Common prim might be uninit.
1008Scalar::Union { value: prim }
1009 };
1010let pair =
1011LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1012let pair_offsets = match pair.fields {
1013 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1014match (&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)]);
1015offsets1016 }
1017_ => {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1018 };
1019if pair_offsets[FieldIdx::new(0)] == Size::ZERO1020 && pair_offsets[FieldIdx::new(1)] == *offset1021 && align == pair.align.abi
1022 && size == pair.size
1023 {
1024// We can use `ScalarPair` only when it matches our
1025 // already computed layout (including `#[repr(C)]`).
1026abi = pair.backend_repr;
1027 }
1028 }
1029 }
10301031// If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1032 // variants to ensure they are consistent. This is because a downcast is
1033 // semantically a NOP, and thus should not affect layout.
1034if #[allow(non_exhaustive_omitted_patterns)] match abi {
BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..) => true,
_ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1035for variant in &mut layout_variants {
1036// We only do this for variants with fields; the others are not accessed anyway.
1037 // Also do not overwrite any already existing "clever" ABIs.
1038if #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
BackendRepr::Memory { .. } if variant.has_fields() => true,
_ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. } if variant.has_fields())1039 {
1040 variant.backend_repr = abi;
1041// Also need to bump up the size, so that the entire value fits in here.
1042variant.size = cmp::max(variant.size, size);
1043 }
1044 }
1045 }
10461047let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
10481049let tagged_layout = LayoutData {
1050 variants: Variants::Multiple {
1051tag,
1052 tag_encoding: TagEncoding::Direct,
1053 tag_field: FieldIdx::new(0),
1054 variants: layout_variants,
1055 },
1056 fields: FieldsShape::Arbitrary {
1057 offsets: [Size::ZERO].into(),
1058 in_memory_order: [FieldIdx::new(0)].into(),
1059 },
1060largest_niche,
1061uninhabited,
1062 backend_repr: abi,
1063 align: AbiAlign::new(align),
1064size,
1065max_repr_align,
1066unadjusted_abi_align,
1067 randomization_seed: combined_seed,
1068 };
10691070let best_layout = match (tagged_layout, niche_filling_layout) {
1071 (tl, Some(nl)) => {
1072// Pick the smaller layout; otherwise,
1073 // pick the layout with the larger niche; otherwise,
1074 // pick tagged as it has simpler codegen.
1075use cmp::Ordering::*;
1076let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1077l.largest_niche.map_or(0, |n| n.available(dl))
1078 };
1079match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1080 (Greater, _) => nl,
1081 (Equal, Less) => nl,
1082_ => tl,
1083 }
1084 }
1085 (tl, None) => tl,
1086 };
10871088Ok(best_layout)
1089 }
10901091fn univariant_biased<
1092'a,
1093 FieldIdx: Idx,
1094 VariantIdx: Idx,
1095 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1096 >(
1097&self,
1098 fields: &IndexSlice<FieldIdx, F>,
1099 repr: &ReprOptions,
1100 kind: StructKind,
1101 niche_bias: NicheBias,
1102 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
1103let dl = self.cx.data_layout();
1104let pack = repr.pack;
1105let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1106let mut max_repr_align = repr.align;
1107let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1108let optimize_field_order = !repr.inhibit_struct_field_reordering();
1109let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1110let optimizing = &mut in_memory_order.raw[..end];
1111let fields_excluding_tail = &fields.raw[..end];
1112// unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
1113let field_seed = fields_excluding_tail1114 .iter()
1115 .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
11161117if optimize_field_order && fields.len() > 1 {
1118// If `-Z randomize-layout` was enabled for the type definition we can shuffle
1119 // the field ordering to try and catch some code making assumptions about layouts
1120 // we don't guarantee.
1121if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1122#[cfg(feature = "randomize")]
1123{
1124use rand::SeedableRng;
1125use rand::seq::SliceRandom;
1126// `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
1127 // ordering.
1128let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1129field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1130 );
11311132// Shuffle the ordering of the fields.
1133optimizing.shuffle(&mut rng);
1134 }
1135// Otherwise we just leave things alone and actually optimize the type's fields
1136} else {
1137// To allow unsizing `&Foo<Type>` -> `&Foo<dyn Trait>`, the layout of the struct must
1138 // not depend on the layout of the tail.
1139let max_field_align =
1140fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1141let largest_niche_size = fields_excluding_tail1142 .iter()
1143 .filter_map(|f| f.largest_niche)
1144 .map(|n| n.available(dl))
1145 .max()
1146 .unwrap_or(0);
11471148// Calculates a sort key to group fields by their alignment or possibly some
1149 // size-derived pseudo-alignment.
1150let alignment_group_key = |layout: &F| {
1151// The two branches here return values that cannot be meaningfully compared with
1152 // each other. However, we know that consistently for all executions of
1153 // `alignment_group_key`, one or the other branch will be taken, so this is okay.
1154if let Some(pack) = pack {
1155// Return the packed alignment in bytes.
1156layout.align.abi.min(pack).bytes()
1157 } else {
1158// Returns `log2(effective-align)`. The calculation assumes that size is an
1159 // integer multiple of align, except for ZSTs.
1160let align = layout.align.bytes();
1161let size = layout.size.bytes();
1162let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1163// Group [u8; 4] with align-4 or [u8; 6] with align-2 fields.
1164let size_as_align = align.max(size).trailing_zeros();
1165let size_as_align = if largest_niche_size > 0 {
1166match niche_bias {
1167// Given `A(u8, [u8; 16])` and `B(bool, [u8; 16])` we want to bump the
1168 // array to the front in the first case (for aligned loads) but keep
1169 // the bool in front in the second case for its niches.
1170NicheBias::Start => {
1171max_field_align.trailing_zeros().min(size_as_align)
1172 }
1173// When moving niches towards the end of the struct then for
1174 // A((u8, u8, u8, bool), (u8, bool, u8)) we want to keep the first tuple
1175 // in the align-1 group because its bool can be moved closer to the end.
1176NicheBias::Endif niche_size == largest_niche_size => {
1177align.trailing_zeros()
1178 }
1179 NicheBias::End => size_as_align,
1180 }
1181 } else {
1182size_as_align1183 };
1184size_as_alignas u641185 }
1186 };
11871188match kind {
1189 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1190// Currently `LayoutData` only exposes a single niche so sorting is usually
1191 // sufficient to get one niche into the preferred position. If it ever
1192 // supported multiple niches then a more advanced pick-and-pack approach could
1193 // provide better results. But even for the single-niche cache it's not
1194 // optimal. E.g. for A(u32, (bool, u8), u16) it would be possible to move the
1195 // bool to the front but it would require packing the tuple together with the
1196 // u16 to build a 4-byte group so that the u32 can be placed after it without
1197 // padding. This kind of packing can't be achieved by sorting.
1198optimizing.sort_by_key(|&x| {
1199let f = &fields[x];
1200let field_size = f.size.bytes();
1201let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1202let niche_size_key = match niche_bias {
1203// large niche first
1204NicheBias::Start => !niche_size,
1205// large niche last
1206NicheBias::End => niche_size,
1207 };
1208let inner_niche_offset_key = match niche_bias {
1209 NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1210 NicheBias::End => f.largest_niche.map_or(0, |n| {
1211 !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1212 }),
1213 };
12141215 (
1216// Then place largest alignments first.
1217cmp::Reverse(alignment_group_key(f)),
1218// Then prioritize niche placement within alignment group according to
1219 // `niche_bias_start`.
1220niche_size_key,
1221// Then among fields with equally-sized niches prefer the ones
1222 // closer to the start/end of the field.
1223inner_niche_offset_key,
1224 )
1225 });
1226 }
12271228 StructKind::Prefixed(..) => {
1229// Sort in ascending alignment so that the layout stays optimal
1230 // regardless of the prefix.
1231 // And put the largest niche in an alignment group at the end
1232 // so it can be used as discriminant in jagged enums
1233optimizing.sort_by_key(|&x| {
1234let f = &fields[x];
1235let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1236 (alignment_group_key(f), niche_size)
1237 });
1238 }
1239 }
12401241// FIXME(Kixiron): We can always shuffle fields within a given alignment class
1242 // regardless of the status of `-Z randomize-layout`
1243}
1244 }
1245// in_memory_order holds field indices by increasing memory offset.
1246 // That is, if field 5 has offset 0, the first element of in_memory_order is 5.
1247 // We now write field offsets to the corresponding offset slot;
1248 // field 5 with offset 0 puts 0 in offsets[5].
1249let mut unsized_field = None::<&F>;
1250let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1251let mut offset = Size::ZERO;
1252let mut largest_niche = None;
1253let mut largest_niche_available = 0;
1254if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1255let prefix_align =
1256if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1257align = align.max(prefix_align);
1258offset = prefix_size.align_to(prefix_align);
1259 }
1260for &i in &in_memory_order {
1261let field = &fields[i];
1262if let Some(unsized_field) = unsized_field {
1263return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1264 }
12651266if field.is_unsized() {
1267if let StructKind::MaybeUnsized = kind {
1268 unsized_field = Some(field);
1269 } else {
1270return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1271 }
1272 }
12731274// Invariant: offset < dl.obj_size_bound() <= 1<<61
1275let field_align = if let Some(pack) = pack {
1276 field.align.min(AbiAlign::new(pack))
1277 } else {
1278 field.align
1279 };
1280 offset = offset.align_to(field_align.abi);
1281 align = align.max(field_align.abi);
1282 max_repr_align = max_repr_align.max(field.max_repr_align);
12831284{
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:1284",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1284u32),
::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);
1285 offsets[i] = offset;
12861287if let Some(mut niche) = field.largest_niche {
1288let available = niche.available(dl);
1289// Pick up larger niches.
1290let prefer_new_niche = match niche_bias {
1291 NicheBias::Start => available > largest_niche_available,
1292// if there are several niches of the same size then pick the last one
1293NicheBias::End => available >= largest_niche_available,
1294 };
1295if prefer_new_niche {
1296 largest_niche_available = available;
1297 niche.offset += offset;
1298 largest_niche = Some(niche);
1299 }
1300 }
13011302 offset =
1303 offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1304 }
13051306// The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
1307 // See documentation on `LayoutData::unadjusted_abi_align`.
1308let unadjusted_abi_align = align;
1309if let Some(repr_align) = repr.align {
1310align = align.max(repr_align);
1311 }
1312// `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate.
1313let align = align;
13141315{
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:1315",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1315u32),
::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);
1316let min_size = offset;
1317let size = min_size.align_to(align);
1318// FIXME(oli-obk): deduplicate and harden these checks
1319if size.bytes() >= dl.obj_size_bound() {
1320return Err(LayoutCalculatorError::SizeOverflow);
1321 }
1322let mut layout_of_single_non_zst_field = None;
1323let sized = unsized_field.is_none();
1324let mut abi = BackendRepr::Memory { sized };
13251326let optimize_abi = !repr.inhibit_newtype_abi_optimization();
13271328// Try to make this a Scalar/ScalarPair.
1329if sized && size.bytes() > 0 {
1330// We skip *all* ZST here and later check if we are good in terms of alignment.
1331 // This lets us handle some cases involving aligned ZST.
1332let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
13331334match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1335// We have exactly one non-ZST field.
1336(Some((i, field)), None, None) => {
1337layout_of_single_non_zst_field = Some(field);
13381339// Field fills the struct and it has a scalar or scalar pair ABI.
1340if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1341match field.backend_repr {
1342// For plain scalars, or vectors of them, we can't unpack
1343 // newtypes for `#[repr(C)]`, as that affects C ABIs.
1344BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1345if optimize_abi =>
1346 {
1347abi = field.backend_repr;
1348 }
1349// But scalar pairs are Rust-specific and get
1350 // treated as aggregates by C ABIs anyway.
1351BackendRepr::ScalarPair(..) => {
1352abi = field.backend_repr;
1353 }
1354_ => {}
1355 }
1356 }
1357 }
13581359// Two non-ZST fields, and they're both scalars.
1360(Some((i, a)), Some((j, b)), None) => {
1361match (a.backend_repr, b.backend_repr) {
1362 (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1363// Order by the memory placement, not source order.
1364let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1365 ((i, a), (j, b))
1366 } else {
1367 ((j, b), (i, a))
1368 };
1369let pair =
1370LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1371let pair_offsets = match pair.fields {
1372 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1373match (&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!(
1374 in_memory_order.raw,
1375 [FieldIdx::new(0), FieldIdx::new(1)]
1376 );
1377offsets1378 }
1379 FieldsShape::Primitive1380 | FieldsShape::Array { .. }
1381 | FieldsShape::Union(..) => {
1382{
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")1383 }
1384 };
1385if offsets[i] == pair_offsets[FieldIdx::new(0)]
1386 && offsets[j] == pair_offsets[FieldIdx::new(1)]
1387 && align == pair.align.abi
1388 && size == pair.size
1389 {
1390// We can use `ScalarPair` only when it matches our
1391 // already computed layout (including `#[repr(C)]`).
1392abi = pair.backend_repr;
1393 }
1394 }
1395_ => {}
1396 }
1397 }
13981399_ => {}
1400 }
1401 }
1402let uninhabited = fields.iter().any(|f| f.is_uninhabited());
14031404let unadjusted_abi_align = if repr.transparent() {
1405match layout_of_single_non_zst_field {
1406Some(l) => l.unadjusted_abi_align,
1407None => {
1408// `repr(transparent)` with all ZST fields.
1409align1410 }
1411 }
1412 } else {
1413unadjusted_abi_align1414 };
14151416let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
14171418Ok(LayoutData {
1419 variants: Variants::Single { index: VariantIdx::new(0) },
1420 fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1421 backend_repr: abi,
1422largest_niche,
1423uninhabited,
1424 align: AbiAlign::new(align),
1425size,
1426max_repr_align,
1427unadjusted_abi_align,
1428 randomization_seed: seed,
1429 })
1430 }
14311432fn format_field_niches<
1433'a,
1434 FieldIdx: Idx,
1435 VariantIdx: Idx,
1436 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1437 >(
1438&self,
1439 layout: &LayoutData<FieldIdx, VariantIdx>,
1440 fields: &IndexSlice<FieldIdx, F>,
1441 ) -> String {
1442let dl = self.cx.data_layout();
1443let mut s = String::new();
1444for i in layout.fields.index_by_increasing_offset() {
1445let offset = layout.fields.offset(i);
1446let f = &fields[FieldIdx::new(i)];
1447s.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();
1448if let Some(n) = f.largest_niche {
1449s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1450 s,
1451" n{}b{}s{}",
1452 n.offset.bytes(),
1453 n.available(dl).ilog2(),
1454 n.value.size(dl).bytes()
1455 )1456 .unwrap();
1457 }
1458s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1459 }
1460s1461 }
1462}
14631464enum SimdVectorKind {
1465/// `#[rustc_scalable_vector]`
1466Scalable(NumScalableVectors),
1467/// `#[repr(simd, packed)]`
1468PackedFixed,
1469/// `#[repr(simd)]`
1470Fixed,
1471}
14721473fn vector_type_layout<FieldIdx, VariantIdx, F>(
1474 kind: SimdVectorKind,
1475 dl: &TargetDataLayout,
1476 element: F,
1477 count: u64,
1478) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1479where
1480FieldIdx: Idx,
1481 VariantIdx: Idx,
1482 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1483{
1484let elt = element.as_ref();
1485if count == 0 {
1486return Err(LayoutCalculatorError::ZeroLengthSimdType);
1487 } else if count > crate::MAX_SIMD_LANES {
1488return Err(LayoutCalculatorError::OversizedSimdType { max_lanes: crate::MAX_SIMD_LANES });
1489 }
14901491let BackendRepr::Scalar(element) = elt.backend_repr else {
1492return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1493 };
14941495// Compute the size and alignment of the vector
1496let size =
1497 elt.size.checked_mul(count, dl).ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
1498let (repr, align) = match kind {
1499 SimdVectorKind::Scalable(number_of_vectors) => (
1500 BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1501dl.llvmlike_vector_align(size),
1502 ),
1503// Non-power-of-two vectors have padding up to the next power-of-two.
1504 // If we're a packed repr, remove the padding while keeping the alignment as close
1505 // to a vector as possible.
1506SimdVectorKind::PackedFixedif !count.is_power_of_two() => {
1507 (BackendRepr::Memory { sized: true }, Align::max_aligned_factor(size))
1508 }
1509 SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
1510 (BackendRepr::SimdVector { element, count }, dl.llvmlike_vector_align(size))
1511 }
1512 };
1513let size = size.align_to(align);
15141515Ok(LayoutData {
1516 variants: Variants::Single { index: VariantIdx::new(0) },
1517 fields: FieldsShape::Arbitrary {
1518 offsets: [Size::ZERO].into(),
1519 in_memory_order: [FieldIdx::new(0)].into(),
1520 },
1521 backend_repr: repr,
1522 largest_niche: elt.largest_niche,
1523 uninhabited: false,
1524size,
1525 align: AbiAlign::new(align),
1526 max_repr_align: None,
1527 unadjusted_abi_align: elt.align.abi,
1528 randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count)),
1529 })
1530}