1use std::collections::BTreeSet;
2use std::fmt::{self, Write};
3use std::ops::{Bound, Deref};
4use std::{cmp, iter};
5
6use rustc_hashes::Hash64;
7use rustc_index::Idx;
8use rustc_index::bit_set::BitMatrix;
9use tracing::{debug, trace};
10
11use crate::{
12 AbiAlign, Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer,
13 LayoutData, Niche, NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding,
14 Variants, WrappingRange,
15};
16
17mod coroutine;
18mod simple;
19
20#[cfg(feature = "nightly")]
21mod ty;
22
23#[cfg(feature = "nightly")]
24pub use ty::{FIRST_VARIANT, FieldIdx, Layout, TyAbiInterface, TyAndLayout, VariantIdx};
25
26fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
32where
33 FieldIdx: Idx,
34 VariantIdx: Idx,
35 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
36{
37 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
38 let is_1zst = fields.iter().all(|f| f.is_1zst());
41 uninhabited && is_1zst
42}
43
44enum NicheBias {
46 Start,
47 End,
48}
49
50#[derive(Copy, Clone, Debug, PartialEq, Eq)]
51pub enum LayoutCalculatorError<F> {
52 UnexpectedUnsized(F),
59
60 SizeOverflow,
62
63 EmptyUnion,
65
66 ReprConflict,
68
69 ZeroLengthSimdType,
71
72 OversizedSimdType { max_lanes: u64 },
74
75 NonPrimitiveSimdType(F),
77}
78
79impl<F> LayoutCalculatorError<F> {
80 pub fn without_payload(&self) -> LayoutCalculatorError<()> {
81 use LayoutCalculatorError::*;
82 match *self {
83 UnexpectedUnsized(_) => UnexpectedUnsized(()),
84 SizeOverflow => SizeOverflow,
85 EmptyUnion => EmptyUnion,
86 ReprConflict => ReprConflict,
87 ZeroLengthSimdType => ZeroLengthSimdType,
88 OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
89 NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
90 }
91 }
92
93 pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 use LayoutCalculatorError::*;
98 f.write_str(match self {
99 UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
100 SizeOverflow => "size overflow",
101 EmptyUnion => "type is a union with no fields",
102 ReprConflict => "type has an invalid repr",
103 ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
104 "invalid simd type definition"
105 }
106 })
107 }
108}
109
110type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
111 Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
112
113#[derive(Clone, Copy, Debug)]
114pub struct LayoutCalculator<Cx> {
115 pub cx: Cx,
116}
117
118impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
119 pub fn new(cx: Cx) -> Self {
120 Self { cx }
121 }
122
123 pub fn array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
124 &self,
125 element: &LayoutData<FieldIdx, VariantIdx>,
126 count_if_sized: Option<u64>, ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
128 let count = count_if_sized.unwrap_or(0);
129 let size =
130 element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
131
132 Ok(LayoutData {
133 variants: Variants::Single { index: VariantIdx::new(0) },
134 fields: FieldsShape::Array { stride: element.size, count },
135 backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
136 largest_niche: element.largest_niche.filter(|_| count != 0),
137 uninhabited: element.uninhabited && count != 0,
138 align: element.align,
139 size,
140 max_repr_align: None,
141 unadjusted_abi_align: element.align.abi,
142 randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
143 })
144 }
145
146 pub fn simd_type<
147 FieldIdx: Idx,
148 VariantIdx: Idx,
149 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
150 >(
151 &self,
152 element: F,
153 count: u64,
154 repr_packed: bool,
155 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
156 let elt = element.as_ref();
157 if count == 0 {
158 return Err(LayoutCalculatorError::ZeroLengthSimdType);
159 } else if count > crate::MAX_SIMD_LANES {
160 return Err(LayoutCalculatorError::OversizedSimdType {
161 max_lanes: crate::MAX_SIMD_LANES,
162 });
163 }
164
165 let BackendRepr::Scalar(e_repr) = elt.backend_repr else {
166 return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
167 };
168
169 let dl = self.cx.data_layout();
171 let size =
172 elt.size.checked_mul(count, dl).ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
173 let (repr, align) = if repr_packed && !count.is_power_of_two() {
174 (BackendRepr::Memory { sized: true }, AbiAlign { abi: Align::max_aligned_factor(size) })
178 } else {
179 (BackendRepr::SimdVector { element: e_repr, count }, dl.llvmlike_vector_align(size))
180 };
181 let size = size.align_to(align.abi);
182
183 Ok(LayoutData {
184 variants: Variants::Single { index: VariantIdx::new(0) },
185 fields: FieldsShape::Arbitrary {
186 offsets: [Size::ZERO].into(),
187 memory_index: [0].into(),
188 },
189 backend_repr: repr,
190 largest_niche: elt.largest_niche,
191 uninhabited: false,
192 size,
193 align,
194 max_repr_align: None,
195 unadjusted_abi_align: elt.align.abi,
196 randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count)),
197 })
198 }
199
200 pub fn coroutine<
205 'a,
206 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
207 VariantIdx: Idx,
208 FieldIdx: Idx,
209 LocalIdx: Idx,
210 >(
211 &self,
212 local_layouts: &IndexSlice<LocalIdx, F>,
213 prefix_layouts: IndexVec<FieldIdx, F>,
214 variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
215 storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
216 tag_to_layout: impl Fn(Scalar) -> F,
217 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
218 coroutine::layout(
219 self,
220 local_layouts,
221 prefix_layouts,
222 variant_fields,
223 storage_conflicts,
224 tag_to_layout,
225 )
226 }
227
228 pub fn univariant<
229 'a,
230 FieldIdx: Idx,
231 VariantIdx: Idx,
232 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
233 >(
234 &self,
235 fields: &IndexSlice<FieldIdx, F>,
236 repr: &ReprOptions,
237 kind: StructKind,
238 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
239 let dl = self.cx.data_layout();
240 let layout = self.univariant_biased(fields, repr, kind, NicheBias::Start);
241 if let Ok(layout) = &layout {
247 if !matches!(kind, StructKind::MaybeUnsized) {
251 if let Some(niche) = layout.largest_niche {
252 let head_space = niche.offset.bytes();
253 let niche_len = niche.value.size(dl).bytes();
254 let tail_space = layout.size.bytes() - head_space - niche_len;
255
256 if fields.len() > 1 && head_space != 0 && tail_space > 0 {
260 let alt_layout = self
261 .univariant_biased(fields, repr, kind, NicheBias::End)
262 .expect("alt layout should always work");
263 let alt_niche = alt_layout
264 .largest_niche
265 .expect("alt layout should have a niche like the regular one");
266 let alt_head_space = alt_niche.offset.bytes();
267 let alt_niche_len = alt_niche.value.size(dl).bytes();
268 let alt_tail_space =
269 alt_layout.size.bytes() - alt_head_space - alt_niche_len;
270
271 debug_assert_eq!(layout.size.bytes(), alt_layout.size.bytes());
272
273 let prefer_alt_layout =
274 alt_head_space > head_space && alt_head_space > tail_space;
275
276 debug!(
277 "sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
278 layout: {}\n\
279 alt_layout: {}\n",
280 layout.size.bytes(),
281 head_space,
282 niche_len,
283 tail_space,
284 alt_head_space,
285 alt_niche_len,
286 alt_tail_space,
287 layout.fields.count(),
288 prefer_alt_layout,
289 self.format_field_niches(layout, fields),
290 self.format_field_niches(&alt_layout, fields),
291 );
292
293 if prefer_alt_layout {
294 return Ok(alt_layout);
295 }
296 }
297 }
298 }
299 }
300 layout
301 }
302
303 pub fn layout_of_struct_or_enum<
304 'a,
305 FieldIdx: Idx,
306 VariantIdx: Idx,
307 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
308 >(
309 &self,
310 repr: &ReprOptions,
311 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
312 is_enum: bool,
313 is_special_no_niche: bool,
314 scalar_valid_range: (Bound<u128>, Bound<u128>),
315 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
316 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
317 always_sized: bool,
318 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
319 let (present_first, present_second) = {
320 let mut present_variants = variants
321 .iter_enumerated()
322 .filter_map(|(i, v)| if !repr.c() && absent(v) { None } else { Some(i) });
323 (present_variants.next(), present_variants.next())
324 };
325 let present_first = match present_first {
326 Some(present_first) => present_first,
327 None if is_enum => {
329 return Ok(LayoutData::never_type(&self.cx));
330 }
331 None => VariantIdx::new(0),
334 };
335
336 if !is_enum ||
338 (present_second.is_none() && !repr.inhibit_enum_layout_opt())
340 {
341 self.layout_of_struct(
342 repr,
343 variants,
344 is_enum,
345 is_special_no_niche,
346 scalar_valid_range,
347 always_sized,
348 present_first,
349 )
350 } else {
351 assert!(is_enum);
355 self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
356 }
357 }
358
359 pub fn layout_of_union<
360 'a,
361 FieldIdx: Idx,
362 VariantIdx: Idx,
363 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
364 >(
365 &self,
366 repr: &ReprOptions,
367 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
368 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
369 let dl = self.cx.data_layout();
370 let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
371 let mut max_repr_align = repr.align;
372
373 struct AbiMismatch;
376 let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
377 Err(AbiMismatch)
379 } else {
380 Ok(None)
381 };
382
383 let mut size = Size::ZERO;
384 let only_variant_idx = VariantIdx::new(0);
385 let only_variant = &variants[only_variant_idx];
386 for field in only_variant {
387 if field.is_unsized() {
388 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
389 }
390
391 align = align.max(field.align);
392 max_repr_align = max_repr_align.max(field.max_repr_align);
393 size = cmp::max(size, field.size);
394
395 if field.is_zst() {
396 continue;
398 }
399
400 if let Ok(common) = common_non_zst_repr_and_align {
401 let field_abi = field.backend_repr.to_union();
403
404 if let Some((common_abi, common_align)) = common {
405 if common_abi != field_abi {
406 common_non_zst_repr_and_align = Err(AbiMismatch);
408 } else {
409 if !matches!(common_abi, BackendRepr::Memory { .. }) {
412 assert_eq!(
413 common_align, field.align.abi,
414 "non-Aggregate field with matching ABI but differing alignment"
415 );
416 }
417 }
418 } else {
419 common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
421 }
422 }
423 }
424
425 if let Some(pack) = repr.pack {
426 align = align.min(AbiAlign::new(pack));
427 }
428 let unadjusted_abi_align = align.abi;
431 if let Some(repr_align) = repr.align {
432 align = align.max(AbiAlign::new(repr_align));
433 }
434 let align = align;
436
437 let backend_repr = match common_non_zst_repr_and_align {
440 Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
441 Ok(Some((repr, _))) => match repr {
442 BackendRepr::Scalar(_) | BackendRepr::ScalarPair(_, _)
444 if repr.scalar_align(dl).unwrap() != align.abi =>
445 {
446 BackendRepr::Memory { sized: true }
447 }
448 BackendRepr::SimdVector { element, count: _ }
450 if element.align(dl).abi > align.abi =>
451 {
452 BackendRepr::Memory { sized: true }
453 }
454 BackendRepr::Scalar(..)
456 | BackendRepr::ScalarPair(..)
457 | BackendRepr::SimdVector { .. }
458 | BackendRepr::Memory { .. } => repr,
459 },
460 };
461
462 let Some(union_field_count) = NonZeroUsize::new(only_variant.len()) else {
463 return Err(LayoutCalculatorError::EmptyUnion);
464 };
465
466 let combined_seed = only_variant
467 .iter()
468 .map(|v| v.randomization_seed)
469 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
470
471 Ok(LayoutData {
472 variants: Variants::Single { index: only_variant_idx },
473 fields: FieldsShape::Union(union_field_count),
474 backend_repr,
475 largest_niche: None,
476 uninhabited: false,
477 align,
478 size: size.align_to(align.abi),
479 max_repr_align,
480 unadjusted_abi_align,
481 randomization_seed: combined_seed,
482 })
483 }
484
485 fn layout_of_struct<
487 'a,
488 FieldIdx: Idx,
489 VariantIdx: Idx,
490 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
491 >(
492 &self,
493 repr: &ReprOptions,
494 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
495 is_enum: bool,
496 is_special_no_niche: bool,
497 scalar_valid_range: (Bound<u128>, Bound<u128>),
498 always_sized: bool,
499 present_first: VariantIdx,
500 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
501 let dl = self.cx.data_layout();
505 let v = present_first;
506 let kind = if is_enum || variants[v].is_empty() || always_sized {
507 StructKind::AlwaysSized
508 } else {
509 StructKind::MaybeUnsized
510 };
511
512 let mut st = self.univariant(&variants[v], repr, kind)?;
513 st.variants = Variants::Single { index: v };
514
515 if is_special_no_niche {
516 let hide_niches = |scalar: &mut _| match scalar {
517 Scalar::Initialized { value, valid_range } => {
518 *valid_range = WrappingRange::full(value.size(dl))
519 }
520 Scalar::Union { .. } => {}
522 };
523 match &mut st.backend_repr {
524 BackendRepr::Scalar(scalar) => hide_niches(scalar),
525 BackendRepr::ScalarPair(a, b) => {
526 hide_niches(a);
527 hide_niches(b);
528 }
529 BackendRepr::SimdVector { element, count: _ } => hide_niches(element),
530 BackendRepr::Memory { sized: _ } => {}
531 }
532 st.largest_niche = None;
533 return Ok(st);
534 }
535
536 let (start, end) = scalar_valid_range;
537 match st.backend_repr {
538 BackendRepr::Scalar(ref mut scalar) | BackendRepr::ScalarPair(ref mut scalar, _) => {
539 let max_value = scalar.size(dl).unsigned_int_max();
548 if let Bound::Included(start) = start {
549 assert!(start <= max_value, "{start} > {max_value}");
552 scalar.valid_range_mut().start = start;
553 }
554 if let Bound::Included(end) = end {
555 assert!(end <= max_value, "{end} > {max_value}");
558 scalar.valid_range_mut().end = end;
559 }
560
561 let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
563 if let Some(niche) = niche {
564 match st.largest_niche {
565 Some(largest_niche) => {
566 if largest_niche.available(dl) <= niche.available(dl) {
569 st.largest_niche = Some(niche);
570 }
571 }
572 None => st.largest_niche = Some(niche),
573 }
574 }
575 }
576 _ => assert!(
577 start == Bound::Unbounded && end == Bound::Unbounded,
578 "nonscalar layout for layout_scalar_valid_range type: {st:#?}",
579 ),
580 }
581
582 Ok(st)
583 }
584
585 fn layout_of_enum<
586 'a,
587 FieldIdx: Idx,
588 VariantIdx: Idx,
589 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
590 >(
591 &self,
592 repr: &ReprOptions,
593 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
594 discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
595 discriminants: impl Iterator<Item = (VariantIdx, i128)>,
596 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
597 let dl = self.cx.data_layout();
598 if repr.packed() {
600 return Err(LayoutCalculatorError::ReprConflict);
601 }
602
603 let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
604 if repr.inhibit_enum_layout_opt() {
605 return None;
606 }
607
608 if variants.len() < 2 {
609 return None;
610 }
611
612 let mut align = dl.aggregate_align;
613 let mut max_repr_align = repr.align;
614 let mut unadjusted_abi_align = align.abi;
615
616 let mut variant_layouts = variants
617 .iter_enumerated()
618 .map(|(j, v)| {
619 let mut st = self.univariant(v, repr, StructKind::AlwaysSized).ok()?;
620 st.variants = Variants::Single { index: j };
621
622 align = align.max(st.align);
623 max_repr_align = max_repr_align.max(st.max_repr_align);
624 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
625
626 Some(st)
627 })
628 .collect::<Option<IndexVec<VariantIdx, _>>>()?;
629
630 let largest_variant_index = variant_layouts
631 .iter_enumerated()
632 .max_by_key(|(_i, layout)| layout.size.bytes())
633 .map(|(i, _layout)| i)?;
634
635 let all_indices = variants.indices();
636 let needs_disc =
637 |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
638 let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
639 ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
640
641 let count =
642 (niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1;
643
644 let niche = variant_layouts[largest_variant_index].largest_niche?;
646 let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
647 let niche_offset = niche.offset;
648 let niche_size = niche.value.size(dl);
649 let size = variant_layouts[largest_variant_index].size.align_to(align.abi);
650
651 let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
652 if i == largest_variant_index {
653 return true;
654 }
655
656 layout.largest_niche = None;
657
658 if layout.size <= niche_offset {
659 return true;
661 }
662
663 let this_align = layout.align.abi;
665 let this_offset = (niche_offset + niche_size).align_to(this_align);
666
667 if this_offset + layout.size > size {
668 return false;
669 }
670
671 match layout.fields {
673 FieldsShape::Arbitrary { ref mut offsets, .. } => {
674 for offset in offsets.iter_mut() {
675 *offset += this_offset;
676 }
677 }
678 FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
679 panic!("Layout of fields should be Arbitrary for variants")
680 }
681 }
682
683 if !layout.is_uninhabited() {
685 layout.backend_repr = BackendRepr::Memory { sized: true };
686 }
687 layout.size += this_offset;
688
689 true
690 });
691
692 if !all_variants_fit {
693 return None;
694 }
695
696 let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
697
698 let others_zst = variant_layouts
699 .iter_enumerated()
700 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
701 let same_size = size == variant_layouts[largest_variant_index].size;
702 let same_align = align == variant_layouts[largest_variant_index].align;
703
704 let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
705 let abi = if same_size && same_align && others_zst {
706 match variant_layouts[largest_variant_index].backend_repr {
707 BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
710 BackendRepr::ScalarPair(first, second) => {
711 if niche_offset == Size::ZERO {
714 BackendRepr::ScalarPair(niche_scalar, second.to_union())
715 } else {
716 BackendRepr::ScalarPair(first.to_union(), niche_scalar)
717 }
718 }
719 _ => BackendRepr::Memory { sized: true },
720 }
721 } else {
722 BackendRepr::Memory { sized: true }
723 };
724
725 let combined_seed = variant_layouts
726 .iter()
727 .map(|v| v.randomization_seed)
728 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
729
730 let layout = LayoutData {
731 variants: Variants::Multiple {
732 tag: niche_scalar,
733 tag_encoding: TagEncoding::Niche {
734 untagged_variant: largest_variant_index,
735 niche_variants,
736 niche_start,
737 },
738 tag_field: FieldIdx::new(0),
739 variants: variant_layouts,
740 },
741 fields: FieldsShape::Arbitrary {
742 offsets: [niche_offset].into(),
743 memory_index: [0].into(),
744 },
745 backend_repr: abi,
746 largest_niche,
747 uninhabited,
748 size,
749 align,
750 max_repr_align,
751 unadjusted_abi_align,
752 randomization_seed: combined_seed,
753 };
754
755 Some(layout)
756 };
757
758 let niche_filling_layout = calculate_niche_filling_layout();
759
760 let discr_type = repr.discr_type();
761 let discr_int = Integer::from_attr(dl, discr_type);
762 let valid_discriminants: BTreeSet<i128> = discriminants
768 .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
769 .map(|(_, val)| {
770 if discr_type.is_signed() {
771 discr_int.size().sign_extend(val as u128)
774 } else {
775 val
776 }
777 })
778 .collect();
779 trace!(?valid_discriminants);
780 let discriminants = valid_discriminants.iter().copied();
781 let next_discriminants =
783 discriminants.clone().chain(valid_discriminants.first().copied()).skip(1);
784 let discriminants = discriminants.zip(next_discriminants);
787 let largest_niche = discriminants.max_by_key(|&(start, end)| {
788 trace!(?start, ?end);
789 let dist = if start > end {
792 let dist = start.wrapping_sub(end);
796 if discr_type.is_signed() {
797 discr_int.signed_max().wrapping_sub(dist) as u128
798 } else {
799 discr_int.size().unsigned_int_max() - dist as u128
800 }
801 } else {
802 end.wrapping_sub(start) as u128
806 };
807 trace!(?dist);
808 dist
809 });
810 trace!(?largest_niche);
811
812 let (max, min) = largest_niche
815 .unwrap_or((0, 0));
817 let (min_ity, signed) = discr_range_of_repr(min, max); let mut align = dl.aggregate_align;
820 let mut max_repr_align = repr.align;
821 let mut unadjusted_abi_align = align.abi;
822
823 let mut size = Size::ZERO;
824
825 let mut start_align = Align::from_bytes(256).unwrap();
827 assert_eq!(Integer::for_align(dl, start_align), None);
828
829 let mut prefix_align = min_ity.align(dl).abi;
835 if repr.c() {
836 for fields in variants {
837 for field in fields {
838 prefix_align = prefix_align.max(field.align.abi);
839 }
840 }
841 }
842
843 let mut layout_variants = variants
845 .iter_enumerated()
846 .map(|(i, field_layouts)| {
847 let mut st = self.univariant(
848 field_layouts,
849 repr,
850 StructKind::Prefixed(min_ity.size(), prefix_align),
851 )?;
852 st.variants = Variants::Single { index: i };
853 for field_idx in st.fields.index_by_increasing_offset() {
856 let field = &field_layouts[FieldIdx::new(field_idx)];
857 if !field.is_1zst() {
858 start_align = start_align.min(field.align.abi);
859 break;
860 }
861 }
862 size = cmp::max(size, st.size);
863 align = align.max(st.align);
864 max_repr_align = max_repr_align.max(st.max_repr_align);
865 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
866 Ok(st)
867 })
868 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
869
870 size = size.align_to(align.abi);
872
873 if size.bytes() >= dl.obj_size_bound() {
875 return Err(LayoutCalculatorError::SizeOverflow);
876 }
877
878 let typeck_ity = Integer::from_attr(dl, repr.discr_type());
879 if typeck_ity < min_ity {
880 panic!(
890 "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
891 );
892 }
895
896 let mut ity = if repr.c() || repr.int.is_some() {
907 min_ity
908 } else {
909 Integer::for_align(dl, start_align).unwrap_or(min_ity)
910 };
911
912 if ity <= min_ity {
915 ity = min_ity;
916 } else {
917 let old_ity_size = min_ity.size();
919 let new_ity_size = ity.size();
920 for variant in &mut layout_variants {
921 match variant.fields {
922 FieldsShape::Arbitrary { ref mut offsets, .. } => {
923 for i in offsets {
924 if *i <= old_ity_size {
925 assert_eq!(*i, old_ity_size);
926 *i = new_ity_size;
927 }
928 }
929 if variant.size <= old_ity_size {
931 variant.size = new_ity_size;
932 }
933 }
934 FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
935 panic!("encountered a non-arbitrary layout during enum layout")
936 }
937 }
938 }
939 }
940
941 let tag_mask = ity.size().unsigned_int_max();
942 let tag = Scalar::Initialized {
943 value: Primitive::Int(ity, signed),
944 valid_range: WrappingRange {
945 start: (min as u128 & tag_mask),
946 end: (max as u128 & tag_mask),
947 },
948 };
949 let mut abi = BackendRepr::Memory { sized: true };
950
951 let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
952 if tag.size(dl) == size {
953 abi = BackendRepr::Scalar(tag);
956 } else {
957 let mut common_prim = None;
960 let mut common_prim_initialized_in_all_variants = true;
961 for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
962 let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
963 panic!("encountered a non-arbitrary layout during enum layout");
964 };
965 let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
968 let (field, offset) = match (fields.next(), fields.next()) {
969 (None, None) => {
970 common_prim_initialized_in_all_variants = false;
971 continue;
972 }
973 (Some(pair), None) => pair,
974 _ => {
975 common_prim = None;
976 break;
977 }
978 };
979 let prim = match field.backend_repr {
980 BackendRepr::Scalar(scalar) => {
981 common_prim_initialized_in_all_variants &=
982 matches!(scalar, Scalar::Initialized { .. });
983 scalar.primitive()
984 }
985 _ => {
986 common_prim = None;
987 break;
988 }
989 };
990 if let Some((old_prim, common_offset)) = common_prim {
991 if offset != common_offset {
993 common_prim = None;
994 break;
995 }
996 let new_prim = match (old_prim, prim) {
1000 (x, y) if x == y => x,
1002 (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
1005 (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
1009 | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
1010 if p.size(dl) == i.size(dl) && p.align(dl) == i.align(dl) =>
1011 {
1012 p
1013 }
1014 _ => {
1015 common_prim = None;
1016 break;
1017 }
1018 };
1019 common_prim = Some((new_prim, common_offset));
1021 } else {
1022 common_prim = Some((prim, offset));
1023 }
1024 }
1025 if let Some((prim, offset)) = common_prim {
1026 let prim_scalar = if common_prim_initialized_in_all_variants {
1027 let size = prim.size(dl);
1028 assert!(size.bits() <= 128);
1029 Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
1030 } else {
1031 Scalar::Union { value: prim }
1033 };
1034 let pair =
1035 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1036 let pair_offsets = match pair.fields {
1037 FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
1038 assert_eq!(memory_index.raw, [0, 1]);
1039 offsets
1040 }
1041 _ => panic!("encountered a non-arbitrary layout during enum layout"),
1042 };
1043 if pair_offsets[FieldIdx::new(0)] == Size::ZERO
1044 && pair_offsets[FieldIdx::new(1)] == *offset
1045 && align == pair.align
1046 && size == pair.size
1047 {
1048 abi = pair.backend_repr;
1051 }
1052 }
1053 }
1054
1055 if matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1059 for variant in &mut layout_variants {
1060 if variant.fields.count() > 0
1063 && matches!(variant.backend_repr, BackendRepr::Memory { .. })
1064 {
1065 variant.backend_repr = abi;
1066 variant.size = cmp::max(variant.size, size);
1069 variant.align.abi = cmp::max(variant.align.abi, align.abi);
1070 }
1071 }
1072 }
1073
1074 let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1075
1076 let combined_seed = layout_variants
1077 .iter()
1078 .map(|v| v.randomization_seed)
1079 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
1080
1081 let tagged_layout = LayoutData {
1082 variants: Variants::Multiple {
1083 tag,
1084 tag_encoding: TagEncoding::Direct,
1085 tag_field: FieldIdx::new(0),
1086 variants: layout_variants,
1087 },
1088 fields: FieldsShape::Arbitrary {
1089 offsets: [Size::ZERO].into(),
1090 memory_index: [0].into(),
1091 },
1092 largest_niche,
1093 uninhabited,
1094 backend_repr: abi,
1095 align,
1096 size,
1097 max_repr_align,
1098 unadjusted_abi_align,
1099 randomization_seed: combined_seed,
1100 };
1101
1102 let best_layout = match (tagged_layout, niche_filling_layout) {
1103 (tl, Some(nl)) => {
1104 use cmp::Ordering::*;
1108 let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1109 l.largest_niche.map_or(0, |n| n.available(dl))
1110 };
1111 match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1112 (Greater, _) => nl,
1113 (Equal, Less) => nl,
1114 _ => tl,
1115 }
1116 }
1117 (tl, None) => tl,
1118 };
1119
1120 Ok(best_layout)
1121 }
1122
1123 fn univariant_biased<
1124 'a,
1125 FieldIdx: Idx,
1126 VariantIdx: Idx,
1127 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1128 >(
1129 &self,
1130 fields: &IndexSlice<FieldIdx, F>,
1131 repr: &ReprOptions,
1132 kind: StructKind,
1133 niche_bias: NicheBias,
1134 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
1135 let dl = self.cx.data_layout();
1136 let pack = repr.pack;
1137 let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1138 let mut max_repr_align = repr.align;
1139 let mut inverse_memory_index: IndexVec<u32, FieldIdx> = fields.indices().collect();
1140 let optimize_field_order = !repr.inhibit_struct_field_reordering();
1141 let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1142 let optimizing = &mut inverse_memory_index.raw[..end];
1143 let fields_excluding_tail = &fields.raw[..end];
1144 let field_seed = fields_excluding_tail
1146 .iter()
1147 .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
1148
1149 if optimize_field_order && fields.len() > 1 {
1150 if repr.can_randomize_type_layout() && cfg!(feature = "randomize") {
1154 #[cfg(feature = "randomize")]
1155 {
1156 use rand::SeedableRng;
1157 use rand::seq::SliceRandom;
1158 let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1161 field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1162 );
1163
1164 optimizing.shuffle(&mut rng);
1166 }
1167 } else {
1169 let max_field_align =
1172 fields_excluding_tail.iter().map(|f| f.align.abi.bytes()).max().unwrap_or(1);
1173 let largest_niche_size = fields_excluding_tail
1174 .iter()
1175 .filter_map(|f| f.largest_niche)
1176 .map(|n| n.available(dl))
1177 .max()
1178 .unwrap_or(0);
1179
1180 let alignment_group_key = |layout: &F| {
1183 if let Some(pack) = pack {
1187 layout.align.abi.min(pack).bytes()
1189 } else {
1190 let align = layout.align.abi.bytes();
1193 let size = layout.size.bytes();
1194 let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1195 let size_as_align = align.max(size).trailing_zeros();
1197 let size_as_align = if largest_niche_size > 0 {
1198 match niche_bias {
1199 NicheBias::Start => {
1203 max_field_align.trailing_zeros().min(size_as_align)
1204 }
1205 NicheBias::End if niche_size == largest_niche_size => {
1209 align.trailing_zeros()
1210 }
1211 NicheBias::End => size_as_align,
1212 }
1213 } else {
1214 size_as_align
1215 };
1216 size_as_align as u64
1217 }
1218 };
1219
1220 match kind {
1221 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1222 optimizing.sort_by_key(|&x| {
1231 let f = &fields[x];
1232 let field_size = f.size.bytes();
1233 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1234 let niche_size_key = match niche_bias {
1235 NicheBias::Start => !niche_size,
1237 NicheBias::End => niche_size,
1239 };
1240 let inner_niche_offset_key = match niche_bias {
1241 NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1242 NicheBias::End => f.largest_niche.map_or(0, |n| {
1243 !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1244 }),
1245 };
1246
1247 (
1248 cmp::Reverse(alignment_group_key(f)),
1250 niche_size_key,
1253 inner_niche_offset_key,
1256 )
1257 });
1258 }
1259
1260 StructKind::Prefixed(..) => {
1261 optimizing.sort_by_key(|&x| {
1266 let f = &fields[x];
1267 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1268 (alignment_group_key(f), niche_size)
1269 });
1270 }
1271 }
1272
1273 }
1276 }
1277 let mut unsized_field = None::<&F>;
1284 let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1285 let mut offset = Size::ZERO;
1286 let mut largest_niche = None;
1287 let mut largest_niche_available = 0;
1288 if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1289 let prefix_align =
1290 if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1291 align = align.max(AbiAlign::new(prefix_align));
1292 offset = prefix_size.align_to(prefix_align);
1293 }
1294 for &i in &inverse_memory_index {
1295 let field = &fields[i];
1296 if let Some(unsized_field) = unsized_field {
1297 return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1298 }
1299
1300 if field.is_unsized() {
1301 if let StructKind::MaybeUnsized = kind {
1302 unsized_field = Some(field);
1303 } else {
1304 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1305 }
1306 }
1307
1308 let field_align = if let Some(pack) = pack {
1310 field.align.min(AbiAlign::new(pack))
1311 } else {
1312 field.align
1313 };
1314 offset = offset.align_to(field_align.abi);
1315 align = align.max(field_align);
1316 max_repr_align = max_repr_align.max(field.max_repr_align);
1317
1318 debug!("univariant offset: {:?} field: {:#?}", offset, field);
1319 offsets[i] = offset;
1320
1321 if let Some(mut niche) = field.largest_niche {
1322 let available = niche.available(dl);
1323 let prefer_new_niche = match niche_bias {
1325 NicheBias::Start => available > largest_niche_available,
1326 NicheBias::End => available >= largest_niche_available,
1328 };
1329 if prefer_new_niche {
1330 largest_niche_available = available;
1331 niche.offset += offset;
1332 largest_niche = Some(niche);
1333 }
1334 }
1335
1336 offset =
1337 offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1338 }
1339
1340 let unadjusted_abi_align = align.abi;
1343 if let Some(repr_align) = repr.align {
1344 align = align.max(AbiAlign::new(repr_align));
1345 }
1346 let align = align;
1348
1349 debug!("univariant min_size: {:?}", offset);
1350 let min_size = offset;
1351 let memory_index = if optimize_field_order {
1358 inverse_memory_index.invert_bijective_mapping()
1359 } else {
1360 debug_assert!(inverse_memory_index.iter().copied().eq(fields.indices()));
1361 inverse_memory_index.into_iter().map(|it| it.index() as u32).collect()
1362 };
1363 let size = min_size.align_to(align.abi);
1364 if size.bytes() >= dl.obj_size_bound() {
1366 return Err(LayoutCalculatorError::SizeOverflow);
1367 }
1368 let mut layout_of_single_non_zst_field = None;
1369 let sized = unsized_field.is_none();
1370 let mut abi = BackendRepr::Memory { sized };
1371
1372 let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1373
1374 if sized && size.bytes() > 0 {
1376 let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
1379
1380 match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1381 (Some((i, field)), None, None) => {
1383 layout_of_single_non_zst_field = Some(field);
1384
1385 if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size
1387 {
1388 match field.backend_repr {
1389 BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1392 if optimize_abi =>
1393 {
1394 abi = field.backend_repr;
1395 }
1396 BackendRepr::ScalarPair(..) => {
1399 abi = field.backend_repr;
1400 }
1401 _ => {}
1402 }
1403 }
1404 }
1405
1406 (Some((i, a)), Some((j, b)), None) => {
1408 match (a.backend_repr, b.backend_repr) {
1409 (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1410 let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1412 ((i, a), (j, b))
1413 } else {
1414 ((j, b), (i, a))
1415 };
1416 let pair =
1417 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1418 let pair_offsets = match pair.fields {
1419 FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
1420 assert_eq!(memory_index.raw, [0, 1]);
1421 offsets
1422 }
1423 FieldsShape::Primitive
1424 | FieldsShape::Array { .. }
1425 | FieldsShape::Union(..) => {
1426 panic!("encountered a non-arbitrary layout during enum layout")
1427 }
1428 };
1429 if offsets[i] == pair_offsets[FieldIdx::new(0)]
1430 && offsets[j] == pair_offsets[FieldIdx::new(1)]
1431 && align == pair.align
1432 && size == pair.size
1433 {
1434 abi = pair.backend_repr;
1437 }
1438 }
1439 _ => {}
1440 }
1441 }
1442
1443 _ => {}
1444 }
1445 }
1446 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
1447
1448 let unadjusted_abi_align = if repr.transparent() {
1449 match layout_of_single_non_zst_field {
1450 Some(l) => l.unadjusted_abi_align,
1451 None => {
1452 align.abi
1454 }
1455 }
1456 } else {
1457 unadjusted_abi_align
1458 };
1459
1460 let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
1461
1462 Ok(LayoutData {
1463 variants: Variants::Single { index: VariantIdx::new(0) },
1464 fields: FieldsShape::Arbitrary { offsets, memory_index },
1465 backend_repr: abi,
1466 largest_niche,
1467 uninhabited,
1468 align,
1469 size,
1470 max_repr_align,
1471 unadjusted_abi_align,
1472 randomization_seed: seed,
1473 })
1474 }
1475
1476 fn format_field_niches<
1477 'a,
1478 FieldIdx: Idx,
1479 VariantIdx: Idx,
1480 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1481 >(
1482 &self,
1483 layout: &LayoutData<FieldIdx, VariantIdx>,
1484 fields: &IndexSlice<FieldIdx, F>,
1485 ) -> String {
1486 let dl = self.cx.data_layout();
1487 let mut s = String::new();
1488 for i in layout.fields.index_by_increasing_offset() {
1489 let offset = layout.fields.offset(i);
1490 let f = &fields[FieldIdx::new(i)];
1491 write!(s, "[o{}a{}s{}", offset.bytes(), f.align.abi.bytes(), f.size.bytes()).unwrap();
1492 if let Some(n) = f.largest_niche {
1493 write!(
1494 s,
1495 " n{}b{}s{}",
1496 n.offset.bytes(),
1497 n.available(dl).ilog2(),
1498 n.value.size(dl).bytes()
1499 )
1500 .unwrap();
1501 }
1502 write!(s, "] ").unwrap();
1503 }
1504 s
1505 }
1506}