]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/layout.rs
Rollup merge of #104647 - RalfJung:alloc-strict-provenance, r=thomcc
[rust.git] / compiler / rustc_ty_utils / src / layout.rs
1 use rustc_hir as hir;
2 use rustc_index::bit_set::BitSet;
3 use rustc_index::vec::{Idx, IndexVec};
4 use rustc_middle::mir::{GeneratorLayout, GeneratorSavedLocal};
5 use rustc_middle::ty::layout::{
6     IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
7 };
8 use rustc_middle::ty::{
9     self, subst::SubstsRef, EarlyBinder, ReprOptions, Ty, TyCtxt, TypeVisitable,
10 };
11 use rustc_session::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::DUMMY_SP;
14 use rustc_target::abi::*;
15
16 use std::cmp::{self, Ordering};
17 use std::iter;
18 use std::num::NonZeroUsize;
19 use std::ops::Bound;
20
21 use rand::{seq::SliceRandom, SeedableRng};
22 use rand_xoshiro::Xoshiro128StarStar;
23
24 use crate::layout_sanity_check::sanity_check_layout;
25
26 pub fn provide(providers: &mut ty::query::Providers) {
27     *providers = ty::query::Providers { layout_of, ..*providers };
28 }
29
30 #[instrument(skip(tcx, query), level = "debug")]
31 fn layout_of<'tcx>(
32     tcx: TyCtxt<'tcx>,
33     query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
34 ) -> Result<TyAndLayout<'tcx>, LayoutError<'tcx>> {
35     let (param_env, ty) = query.into_parts();
36     debug!(?ty);
37
38     let param_env = param_env.with_reveal_all_normalized(tcx);
39     let unnormalized_ty = ty;
40
41     // FIXME: We might want to have two different versions of `layout_of`:
42     // One that can be called after typecheck has completed and can use
43     // `normalize_erasing_regions` here and another one that can be called
44     // before typecheck has completed and uses `try_normalize_erasing_regions`.
45     let ty = match tcx.try_normalize_erasing_regions(param_env, ty) {
46         Ok(t) => t,
47         Err(normalization_error) => {
48             return Err(LayoutError::NormalizationFailure(ty, normalization_error));
49         }
50     };
51
52     if ty != unnormalized_ty {
53         // Ensure this layout is also cached for the normalized type.
54         return tcx.layout_of(param_env.and(ty));
55     }
56
57     let cx = LayoutCx { tcx, param_env };
58
59     let layout = layout_of_uncached(&cx, ty)?;
60     let layout = TyAndLayout { ty, layout };
61
62     record_layout_for_printing(&cx, layout);
63
64     sanity_check_layout(&cx, &layout);
65
66     Ok(layout)
67 }
68
69 #[derive(Copy, Clone, Debug)]
70 enum StructKind {
71     /// A tuple, closure, or univariant which cannot be coerced to unsized.
72     AlwaysSized,
73     /// A univariant, the last field of which may be coerced to unsized.
74     MaybeUnsized,
75     /// A univariant, but with a prefix of an arbitrary size & alignment (e.g., enum tag).
76     Prefixed(Size, Align),
77 }
78
79 // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`.
80 // This is used to go between `memory_index` (source field order to memory order)
81 // and `inverse_memory_index` (memory order to source field order).
82 // See also `FieldsShape::Arbitrary::memory_index` for more details.
83 // FIXME(eddyb) build a better abstraction for permutations, if possible.
84 fn invert_mapping(map: &[u32]) -> Vec<u32> {
85     let mut inverse = vec![0; map.len()];
86     for i in 0..map.len() {
87         inverse[map[i] as usize] = i as u32;
88     }
89     inverse
90 }
91
92 fn scalar_pair<'tcx>(cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, a: Scalar, b: Scalar) -> LayoutS<'tcx> {
93     let dl = cx.data_layout();
94     let b_align = b.align(dl);
95     let align = a.align(dl).max(b_align).max(dl.aggregate_align);
96     let b_offset = a.size(dl).align_to(b_align.abi);
97     let size = (b_offset + b.size(dl)).align_to(align.abi);
98
99     // HACK(nox): We iter on `b` and then `a` because `max_by_key`
100     // returns the last maximum.
101     let largest_niche = Niche::from_scalar(dl, b_offset, b)
102         .into_iter()
103         .chain(Niche::from_scalar(dl, Size::ZERO, a))
104         .max_by_key(|niche| niche.available(dl));
105
106     LayoutS {
107         variants: Variants::Single { index: VariantIdx::new(0) },
108         fields: FieldsShape::Arbitrary {
109             offsets: vec![Size::ZERO, b_offset],
110             memory_index: vec![0, 1],
111         },
112         abi: Abi::ScalarPair(a, b),
113         largest_niche,
114         align,
115         size,
116     }
117 }
118
119 fn univariant_uninterned<'tcx>(
120     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
121     ty: Ty<'tcx>,
122     fields: &[TyAndLayout<'_>],
123     repr: &ReprOptions,
124     kind: StructKind,
125 ) -> Result<LayoutS<'tcx>, LayoutError<'tcx>> {
126     let dl = cx.data_layout();
127     let pack = repr.pack;
128     if pack.is_some() && repr.align.is_some() {
129         cx.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned");
130         return Err(LayoutError::Unknown(ty));
131     }
132
133     let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
134
135     let mut inverse_memory_index: Vec<u32> = (0..fields.len() as u32).collect();
136
137     let optimize = !repr.inhibit_struct_field_reordering_opt();
138     if optimize {
139         let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
140         let optimizing = &mut inverse_memory_index[..end];
141         let field_align = |f: &TyAndLayout<'_>| {
142             if let Some(pack) = pack { f.align.abi.min(pack) } else { f.align.abi }
143         };
144
145         // If `-Z randomize-layout` was enabled for the type definition we can shuffle
146         // the field ordering to try and catch some code making assumptions about layouts
147         // we don't guarantee
148         if repr.can_randomize_type_layout() {
149             // `ReprOptions.layout_seed` is a deterministic seed that we can use to
150             // randomize field ordering with
151             let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed);
152
153             // Shuffle the ordering of the fields
154             optimizing.shuffle(&mut rng);
155
156             // Otherwise we just leave things alone and actually optimize the type's fields
157         } else {
158             match kind {
159                 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
160                     optimizing.sort_by_key(|&x| {
161                         // Place ZSTs first to avoid "interesting offsets",
162                         // especially with only one or two non-ZST fields.
163                         let f = &fields[x as usize];
164                         (!f.is_zst(), cmp::Reverse(field_align(f)))
165                     });
166                 }
167
168                 StructKind::Prefixed(..) => {
169                     // Sort in ascending alignment so that the layout stays optimal
170                     // regardless of the prefix
171                     optimizing.sort_by_key(|&x| field_align(&fields[x as usize]));
172                 }
173             }
174
175             // FIXME(Kixiron): We can always shuffle fields within a given alignment class
176             //                 regardless of the status of `-Z randomize-layout`
177         }
178     }
179
180     // inverse_memory_index holds field indices by increasing memory offset.
181     // That is, if field 5 has offset 0, the first element of inverse_memory_index is 5.
182     // We now write field offsets to the corresponding offset slot;
183     // field 5 with offset 0 puts 0 in offsets[5].
184     // At the bottom of this function, we invert `inverse_memory_index` to
185     // produce `memory_index` (see `invert_mapping`).
186
187     let mut sized = true;
188     let mut offsets = vec![Size::ZERO; fields.len()];
189     let mut offset = Size::ZERO;
190     let mut largest_niche = None;
191     let mut largest_niche_available = 0;
192
193     if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
194         let prefix_align =
195             if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
196         align = align.max(AbiAndPrefAlign::new(prefix_align));
197         offset = prefix_size.align_to(prefix_align);
198     }
199
200     for &i in &inverse_memory_index {
201         let field = fields[i as usize];
202         if !sized {
203             cx.tcx.sess.delay_span_bug(
204                 DUMMY_SP,
205                 &format!(
206                     "univariant: field #{} of `{}` comes after unsized field",
207                     offsets.len(),
208                     ty
209                 ),
210             );
211         }
212
213         if field.is_unsized() {
214             sized = false;
215         }
216
217         // Invariant: offset < dl.obj_size_bound() <= 1<<61
218         let field_align = if let Some(pack) = pack {
219             field.align.min(AbiAndPrefAlign::new(pack))
220         } else {
221             field.align
222         };
223         offset = offset.align_to(field_align.abi);
224         align = align.max(field_align);
225
226         debug!("univariant offset: {:?} field: {:#?}", offset, field);
227         offsets[i as usize] = offset;
228
229         if let Some(mut niche) = field.largest_niche {
230             let available = niche.available(dl);
231             if available > largest_niche_available {
232                 largest_niche_available = available;
233                 niche.offset += offset;
234                 largest_niche = Some(niche);
235             }
236         }
237
238         offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?;
239     }
240
241     if let Some(repr_align) = repr.align {
242         align = align.max(AbiAndPrefAlign::new(repr_align));
243     }
244
245     debug!("univariant min_size: {:?}", offset);
246     let min_size = offset;
247
248     // As stated above, inverse_memory_index holds field indices by increasing offset.
249     // This makes it an already-sorted view of the offsets vec.
250     // To invert it, consider:
251     // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
252     // Field 5 would be the first element, so memory_index is i:
253     // Note: if we didn't optimize, it's already right.
254
255     let memory_index =
256         if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index };
257
258     let size = min_size.align_to(align.abi);
259     let mut abi = Abi::Aggregate { sized };
260
261     // Unpack newtype ABIs and find scalar pairs.
262     if sized && size.bytes() > 0 {
263         // All other fields must be ZSTs.
264         let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst());
265
266         match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
267             // We have exactly one non-ZST field.
268             (Some((i, field)), None, None) => {
269                 // Field fills the struct and it has a scalar or scalar pair ABI.
270                 if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size {
271                     match field.abi {
272                         // For plain scalars, or vectors of them, we can't unpack
273                         // newtypes for `#[repr(C)]`, as that affects C ABIs.
274                         Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
275                             abi = field.abi;
276                         }
277                         // But scalar pairs are Rust-specific and get
278                         // treated as aggregates by C ABIs anyway.
279                         Abi::ScalarPair(..) => {
280                             abi = field.abi;
281                         }
282                         _ => {}
283                     }
284                 }
285             }
286
287             // Two non-ZST fields, and they're both scalars.
288             (Some((i, a)), Some((j, b)), None) => {
289                 match (a.abi, b.abi) {
290                     (Abi::Scalar(a), Abi::Scalar(b)) => {
291                         // Order by the memory placement, not source order.
292                         let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
293                             ((i, a), (j, b))
294                         } else {
295                             ((j, b), (i, a))
296                         };
297                         let pair = scalar_pair(cx, a, b);
298                         let pair_offsets = match pair.fields {
299                             FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
300                                 assert_eq!(memory_index, &[0, 1]);
301                                 offsets
302                             }
303                             _ => bug!(),
304                         };
305                         if offsets[i] == pair_offsets[0]
306                             && offsets[j] == pair_offsets[1]
307                             && align == pair.align
308                             && size == pair.size
309                         {
310                             // We can use `ScalarPair` only when it matches our
311                             // already computed layout (including `#[repr(C)]`).
312                             abi = pair.abi;
313                         }
314                     }
315                     _ => {}
316                 }
317             }
318
319             _ => {}
320         }
321     }
322
323     if fields.iter().any(|f| f.abi.is_uninhabited()) {
324         abi = Abi::Uninhabited;
325     }
326
327     Ok(LayoutS {
328         variants: Variants::Single { index: VariantIdx::new(0) },
329         fields: FieldsShape::Arbitrary { offsets, memory_index },
330         abi,
331         largest_niche,
332         align,
333         size,
334     })
335 }
336
337 fn layout_of_uncached<'tcx>(
338     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
339     ty: Ty<'tcx>,
340 ) -> Result<Layout<'tcx>, LayoutError<'tcx>> {
341     let tcx = cx.tcx;
342     let param_env = cx.param_env;
343     let dl = cx.data_layout();
344     let scalar_unit = |value: Primitive| {
345         let size = value.size(dl);
346         assert!(size.bits() <= 128);
347         Scalar::Initialized { value, valid_range: WrappingRange::full(size) }
348     };
349     let scalar = |value: Primitive| tcx.intern_layout(LayoutS::scalar(cx, scalar_unit(value)));
350
351     let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| {
352         Ok(tcx.intern_layout(univariant_uninterned(cx, ty, fields, repr, kind)?))
353     };
354     debug_assert!(!ty.has_non_region_infer());
355
356     Ok(match *ty.kind() {
357         // Basic scalars.
358         ty::Bool => tcx.intern_layout(LayoutS::scalar(
359             cx,
360             Scalar::Initialized {
361                 value: Int(I8, false),
362                 valid_range: WrappingRange { start: 0, end: 1 },
363             },
364         )),
365         ty::Char => tcx.intern_layout(LayoutS::scalar(
366             cx,
367             Scalar::Initialized {
368                 value: Int(I32, false),
369                 valid_range: WrappingRange { start: 0, end: 0x10FFFF },
370             },
371         )),
372         ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)),
373         ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)),
374         ty::Float(fty) => scalar(match fty {
375             ty::FloatTy::F32 => F32,
376             ty::FloatTy::F64 => F64,
377         }),
378         ty::FnPtr(_) => {
379             let mut ptr = scalar_unit(Pointer);
380             ptr.valid_range_mut().start = 1;
381             tcx.intern_layout(LayoutS::scalar(cx, ptr))
382         }
383
384         // The never type.
385         ty::Never => tcx.intern_layout(LayoutS {
386             variants: Variants::Single { index: VariantIdx::new(0) },
387             fields: FieldsShape::Primitive,
388             abi: Abi::Uninhabited,
389             largest_niche: None,
390             align: dl.i8_align,
391             size: Size::ZERO,
392         }),
393
394         // Potentially-wide pointers.
395         ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
396             let mut data_ptr = scalar_unit(Pointer);
397             if !ty.is_unsafe_ptr() {
398                 data_ptr.valid_range_mut().start = 1;
399             }
400
401             let pointee = tcx.normalize_erasing_regions(param_env, pointee);
402             if pointee.is_sized(tcx, param_env) {
403                 return Ok(tcx.intern_layout(LayoutS::scalar(cx, data_ptr)));
404             }
405
406             let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env);
407             let metadata = match unsized_part.kind() {
408                 ty::Foreign(..) => {
409                     return Ok(tcx.intern_layout(LayoutS::scalar(cx, data_ptr)));
410                 }
411                 ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)),
412                 ty::Dynamic(..) => {
413                     let mut vtable = scalar_unit(Pointer);
414                     vtable.valid_range_mut().start = 1;
415                     vtable
416                 }
417                 _ => return Err(LayoutError::Unknown(unsized_part)),
418             };
419
420             // Effectively a (ptr, meta) tuple.
421             tcx.intern_layout(scalar_pair(cx, data_ptr, metadata))
422         }
423
424         ty::Dynamic(_, _, ty::DynStar) => {
425             let mut data = scalar_unit(Int(dl.ptr_sized_integer(), false));
426             data.valid_range_mut().start = 0;
427             let mut vtable = scalar_unit(Pointer);
428             vtable.valid_range_mut().start = 1;
429             tcx.intern_layout(scalar_pair(cx, data, vtable))
430         }
431
432         // Arrays and slices.
433         ty::Array(element, mut count) => {
434             if count.has_projections() {
435                 count = tcx.normalize_erasing_regions(param_env, count);
436                 if count.has_projections() {
437                     return Err(LayoutError::Unknown(ty));
438                 }
439             }
440
441             let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?;
442             let element = cx.layout_of(element)?;
443             let size = element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?;
444
445             let abi = if count != 0 && ty.is_privately_uninhabited(tcx, param_env) {
446                 Abi::Uninhabited
447             } else {
448                 Abi::Aggregate { sized: true }
449             };
450
451             let largest_niche = if count != 0 { element.largest_niche } else { None };
452
453             tcx.intern_layout(LayoutS {
454                 variants: Variants::Single { index: VariantIdx::new(0) },
455                 fields: FieldsShape::Array { stride: element.size, count },
456                 abi,
457                 largest_niche,
458                 align: element.align,
459                 size,
460             })
461         }
462         ty::Slice(element) => {
463             let element = cx.layout_of(element)?;
464             tcx.intern_layout(LayoutS {
465                 variants: Variants::Single { index: VariantIdx::new(0) },
466                 fields: FieldsShape::Array { stride: element.size, count: 0 },
467                 abi: Abi::Aggregate { sized: false },
468                 largest_niche: None,
469                 align: element.align,
470                 size: Size::ZERO,
471             })
472         }
473         ty::Str => tcx.intern_layout(LayoutS {
474             variants: Variants::Single { index: VariantIdx::new(0) },
475             fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
476             abi: Abi::Aggregate { sized: false },
477             largest_niche: None,
478             align: dl.i8_align,
479             size: Size::ZERO,
480         }),
481
482         // Odd unit types.
483         ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?,
484         ty::Dynamic(_, _, ty::Dyn) | ty::Foreign(..) => {
485             let mut unit = univariant_uninterned(
486                 cx,
487                 ty,
488                 &[],
489                 &ReprOptions::default(),
490                 StructKind::AlwaysSized,
491             )?;
492             match unit.abi {
493                 Abi::Aggregate { ref mut sized } => *sized = false,
494                 _ => bug!(),
495             }
496             tcx.intern_layout(unit)
497         }
498
499         ty::Generator(def_id, substs, _) => generator_layout(cx, ty, def_id, substs)?,
500
501         ty::Closure(_, ref substs) => {
502             let tys = substs.as_closure().upvar_tys();
503             univariant(
504                 &tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
505                 &ReprOptions::default(),
506                 StructKind::AlwaysSized,
507             )?
508         }
509
510         ty::Tuple(tys) => {
511             let kind =
512                 if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized };
513
514             univariant(
515                 &tys.iter().map(|k| cx.layout_of(k)).collect::<Result<Vec<_>, _>>()?,
516                 &ReprOptions::default(),
517                 kind,
518             )?
519         }
520
521         // SIMD vector types.
522         ty::Adt(def, substs) if def.repr().simd() => {
523             if !def.is_struct() {
524                 // Should have yielded E0517 by now.
525                 tcx.sess.delay_span_bug(
526                     DUMMY_SP,
527                     "#[repr(simd)] was applied to an ADT that is not a struct",
528                 );
529                 return Err(LayoutError::Unknown(ty));
530             }
531
532             // Supported SIMD vectors are homogeneous ADTs with at least one field:
533             //
534             // * #[repr(simd)] struct S(T, T, T, T);
535             // * #[repr(simd)] struct S { x: T, y: T, z: T, w: T }
536             // * #[repr(simd)] struct S([T; 4])
537             //
538             // where T is a primitive scalar (integer/float/pointer).
539
540             // SIMD vectors with zero fields are not supported.
541             // (should be caught by typeck)
542             if def.non_enum_variant().fields.is_empty() {
543                 tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty));
544             }
545
546             // Type of the first ADT field:
547             let f0_ty = def.non_enum_variant().fields[0].ty(tcx, substs);
548
549             // Heterogeneous SIMD vectors are not supported:
550             // (should be caught by typeck)
551             for fi in &def.non_enum_variant().fields {
552                 if fi.ty(tcx, substs) != f0_ty {
553                     tcx.sess.fatal(&format!("monomorphising heterogeneous SIMD type `{}`", ty));
554                 }
555             }
556
557             // The element type and number of elements of the SIMD vector
558             // are obtained from:
559             //
560             // * the element type and length of the single array field, if
561             // the first field is of array type, or
562             //
563             // * the homogeneous field type and the number of fields.
564             let (e_ty, e_len, is_array) = if let ty::Array(e_ty, _) = f0_ty.kind() {
565                 // First ADT field is an array:
566
567                 // SIMD vectors with multiple array fields are not supported:
568                 // (should be caught by typeck)
569                 if def.non_enum_variant().fields.len() != 1 {
570                     tcx.sess.fatal(&format!(
571                         "monomorphising SIMD type `{}` with more than one array field",
572                         ty
573                     ));
574                 }
575
576                 // Extract the number of elements from the layout of the array field:
577                 let FieldsShape::Array { count, .. } = cx.layout_of(f0_ty)?.layout.fields() else {
578                         return Err(LayoutError::Unknown(ty));
579                     };
580
581                 (*e_ty, *count, true)
582             } else {
583                 // First ADT field is not an array:
584                 (f0_ty, def.non_enum_variant().fields.len() as _, false)
585             };
586
587             // SIMD vectors of zero length are not supported.
588             // Additionally, lengths are capped at 2^16 as a fixed maximum backends must
589             // support.
590             //
591             // Can't be caught in typeck if the array length is generic.
592             if e_len == 0 {
593                 tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty));
594             } else if e_len > MAX_SIMD_LANES {
595                 tcx.sess.fatal(&format!(
596                     "monomorphising SIMD type `{}` of length greater than {}",
597                     ty, MAX_SIMD_LANES,
598                 ));
599             }
600
601             // Compute the ABI of the element type:
602             let e_ly = cx.layout_of(e_ty)?;
603             let Abi::Scalar(e_abi) = e_ly.abi else {
604                     // This error isn't caught in typeck, e.g., if
605                     // the element type of the vector is generic.
606                     tcx.sess.fatal(&format!(
607                         "monomorphising SIMD type `{}` with a non-primitive-scalar \
608                         (integer/float/pointer) element type `{}`",
609                         ty, e_ty
610                     ))
611                 };
612
613             // Compute the size and alignment of the vector:
614             let size = e_ly.size.checked_mul(e_len, dl).ok_or(LayoutError::SizeOverflow(ty))?;
615             let align = dl.vector_align(size);
616             let size = size.align_to(align.abi);
617
618             // Compute the placement of the vector fields:
619             let fields = if is_array {
620                 FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] }
621             } else {
622                 FieldsShape::Array { stride: e_ly.size, count: e_len }
623             };
624
625             tcx.intern_layout(LayoutS {
626                 variants: Variants::Single { index: VariantIdx::new(0) },
627                 fields,
628                 abi: Abi::Vector { element: e_abi, count: e_len },
629                 largest_niche: e_ly.largest_niche,
630                 size,
631                 align,
632             })
633         }
634
635         // ADTs.
636         ty::Adt(def, substs) => {
637             // Cache the field layouts.
638             let variants = def
639                 .variants()
640                 .iter()
641                 .map(|v| {
642                     v.fields
643                         .iter()
644                         .map(|field| cx.layout_of(field.ty(tcx, substs)))
645                         .collect::<Result<Vec<_>, _>>()
646                 })
647                 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
648
649             if def.is_union() {
650                 if def.repr().pack.is_some() && def.repr().align.is_some() {
651                     cx.tcx.sess.delay_span_bug(
652                         tcx.def_span(def.did()),
653                         "union cannot be packed and aligned",
654                     );
655                     return Err(LayoutError::Unknown(ty));
656                 }
657
658                 let mut align =
659                     if def.repr().pack.is_some() { dl.i8_align } else { dl.aggregate_align };
660
661                 if let Some(repr_align) = def.repr().align {
662                     align = align.max(AbiAndPrefAlign::new(repr_align));
663                 }
664
665                 let optimize = !def.repr().inhibit_union_abi_opt();
666                 let mut size = Size::ZERO;
667                 let mut abi = Abi::Aggregate { sized: true };
668                 let index = VariantIdx::new(0);
669                 for field in &variants[index] {
670                     assert!(field.is_sized());
671                     align = align.max(field.align);
672
673                     // If all non-ZST fields have the same ABI, forward this ABI
674                     if optimize && !field.is_zst() {
675                         // Discard valid range information and allow undef
676                         let field_abi = match field.abi {
677                             Abi::Scalar(x) => Abi::Scalar(x.to_union()),
678                             Abi::ScalarPair(x, y) => Abi::ScalarPair(x.to_union(), y.to_union()),
679                             Abi::Vector { element: x, count } => {
680                                 Abi::Vector { element: x.to_union(), count }
681                             }
682                             Abi::Uninhabited | Abi::Aggregate { .. } => {
683                                 Abi::Aggregate { sized: true }
684                             }
685                         };
686
687                         if size == Size::ZERO {
688                             // first non ZST: initialize 'abi'
689                             abi = field_abi;
690                         } else if abi != field_abi {
691                             // different fields have different ABI: reset to Aggregate
692                             abi = Abi::Aggregate { sized: true };
693                         }
694                     }
695
696                     size = cmp::max(size, field.size);
697                 }
698
699                 if let Some(pack) = def.repr().pack {
700                     align = align.min(AbiAndPrefAlign::new(pack));
701                 }
702
703                 return Ok(tcx.intern_layout(LayoutS {
704                     variants: Variants::Single { index },
705                     fields: FieldsShape::Union(
706                         NonZeroUsize::new(variants[index].len()).ok_or(LayoutError::Unknown(ty))?,
707                     ),
708                     abi,
709                     largest_niche: None,
710                     align,
711                     size: size.align_to(align.abi),
712                 }));
713             }
714
715             // A variant is absent if it's uninhabited and only has ZST fields.
716             // Present uninhabited variants only require space for their fields,
717             // but *not* an encoding of the discriminant (e.g., a tag value).
718             // See issue #49298 for more details on the need to leave space
719             // for non-ZST uninhabited data (mostly partial initialization).
720             let absent = |fields: &[TyAndLayout<'_>]| {
721                 let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited());
722                 let is_zst = fields.iter().all(|f| f.is_zst());
723                 uninhabited && is_zst
724             };
725             let (present_first, present_second) = {
726                 let mut present_variants = variants
727                     .iter_enumerated()
728                     .filter_map(|(i, v)| if absent(v) { None } else { Some(i) });
729                 (present_variants.next(), present_variants.next())
730             };
731             let present_first = match present_first {
732                 Some(present_first) => present_first,
733                 // Uninhabited because it has no variants, or only absent ones.
734                 None if def.is_enum() => {
735                     return Ok(tcx.layout_of(param_env.and(tcx.types.never))?.layout);
736                 }
737                 // If it's a struct, still compute a layout so that we can still compute the
738                 // field offsets.
739                 None => VariantIdx::new(0),
740             };
741
742             let is_struct = !def.is_enum() ||
743                     // Only one variant is present.
744                     (present_second.is_none() &&
745                         // Representation optimizations are allowed.
746                         !def.repr().inhibit_enum_layout_opt());
747             if is_struct {
748                 // Struct, or univariant enum equivalent to a struct.
749                 // (Typechecking will reject discriminant-sizing attrs.)
750
751                 let v = present_first;
752                 let kind = if def.is_enum() || variants[v].is_empty() {
753                     StructKind::AlwaysSized
754                 } else {
755                     let param_env = tcx.param_env(def.did());
756                     let last_field = def.variant(v).fields.last().unwrap();
757                     let always_sized = tcx.type_of(last_field.did).is_sized(tcx, param_env);
758                     if !always_sized { StructKind::MaybeUnsized } else { StructKind::AlwaysSized }
759                 };
760
761                 let mut st = univariant_uninterned(cx, ty, &variants[v], &def.repr(), kind)?;
762                 st.variants = Variants::Single { index: v };
763
764                 if def.is_unsafe_cell() {
765                     let hide_niches = |scalar: &mut _| match scalar {
766                         Scalar::Initialized { value, valid_range } => {
767                             *valid_range = WrappingRange::full(value.size(dl))
768                         }
769                         // Already doesn't have any niches
770                         Scalar::Union { .. } => {}
771                     };
772                     match &mut st.abi {
773                         Abi::Uninhabited => {}
774                         Abi::Scalar(scalar) => hide_niches(scalar),
775                         Abi::ScalarPair(a, b) => {
776                             hide_niches(a);
777                             hide_niches(b);
778                         }
779                         Abi::Vector { element, count: _ } => hide_niches(element),
780                         Abi::Aggregate { sized: _ } => {}
781                     }
782                     st.largest_niche = None;
783                     return Ok(tcx.intern_layout(st));
784                 }
785
786                 let (start, end) = cx.tcx.layout_scalar_valid_range(def.did());
787                 match st.abi {
788                     Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => {
789                         // the asserts ensure that we are not using the
790                         // `#[rustc_layout_scalar_valid_range(n)]`
791                         // attribute to widen the range of anything as that would probably
792                         // result in UB somewhere
793                         // FIXME(eddyb) the asserts are probably not needed,
794                         // as larger validity ranges would result in missed
795                         // optimizations, *not* wrongly assuming the inner
796                         // value is valid. e.g. unions enlarge validity ranges,
797                         // because the values may be uninitialized.
798                         if let Bound::Included(start) = start {
799                             // FIXME(eddyb) this might be incorrect - it doesn't
800                             // account for wrap-around (end < start) ranges.
801                             let valid_range = scalar.valid_range_mut();
802                             assert!(valid_range.start <= start);
803                             valid_range.start = start;
804                         }
805                         if let Bound::Included(end) = end {
806                             // FIXME(eddyb) this might be incorrect - it doesn't
807                             // account for wrap-around (end < start) ranges.
808                             let valid_range = scalar.valid_range_mut();
809                             assert!(valid_range.end >= end);
810                             valid_range.end = end;
811                         }
812
813                         // Update `largest_niche` if we have introduced a larger niche.
814                         let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
815                         if let Some(niche) = niche {
816                             match st.largest_niche {
817                                 Some(largest_niche) => {
818                                     // Replace the existing niche even if they're equal,
819                                     // because this one is at a lower offset.
820                                     if largest_niche.available(dl) <= niche.available(dl) {
821                                         st.largest_niche = Some(niche);
822                                     }
823                                 }
824                                 None => st.largest_niche = Some(niche),
825                             }
826                         }
827                     }
828                     _ => assert!(
829                         start == Bound::Unbounded && end == Bound::Unbounded,
830                         "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}",
831                         def,
832                         st,
833                     ),
834                 }
835
836                 return Ok(tcx.intern_layout(st));
837             }
838
839             // At this point, we have handled all unions and
840             // structs. (We have also handled univariant enums
841             // that allow representation optimization.)
842             assert!(def.is_enum());
843
844             // Until we've decided whether to use the tagged or
845             // niche filling LayoutS, we don't want to intern the
846             // variant layouts, so we can't store them in the
847             // overall LayoutS. Store the overall LayoutS
848             // and the variant LayoutSs here until then.
849             struct TmpLayout<'tcx> {
850                 layout: LayoutS<'tcx>,
851                 variants: IndexVec<VariantIdx, LayoutS<'tcx>>,
852             }
853
854             let calculate_niche_filling_layout =
855                 || -> Result<Option<TmpLayout<'tcx>>, LayoutError<'tcx>> {
856                     // The current code for niche-filling relies on variant indices
857                     // instead of actual discriminants, so enums with
858                     // explicit discriminants (RFC #2363) would misbehave.
859                     if def.repr().inhibit_enum_layout_opt()
860                         || def
861                             .variants()
862                             .iter_enumerated()
863                             .any(|(i, v)| v.discr != ty::VariantDiscr::Relative(i.as_u32()))
864                     {
865                         return Ok(None);
866                     }
867
868                     if variants.len() < 2 {
869                         return Ok(None);
870                     }
871
872                     let mut align = dl.aggregate_align;
873                     let mut variant_layouts = variants
874                         .iter_enumerated()
875                         .map(|(j, v)| {
876                             let mut st = univariant_uninterned(
877                                 cx,
878                                 ty,
879                                 v,
880                                 &def.repr(),
881                                 StructKind::AlwaysSized,
882                             )?;
883                             st.variants = Variants::Single { index: j };
884
885                             align = align.max(st.align);
886
887                             Ok(st)
888                         })
889                         .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
890
891                     let largest_variant_index = match variant_layouts
892                         .iter_enumerated()
893                         .max_by_key(|(_i, layout)| layout.size.bytes())
894                         .map(|(i, _layout)| i)
895                     {
896                         None => return Ok(None),
897                         Some(i) => i,
898                     };
899
900                     let all_indices = VariantIdx::new(0)..=VariantIdx::new(variants.len() - 1);
901                     let needs_disc = |index: VariantIdx| {
902                         index != largest_variant_index && !absent(&variants[index])
903                     };
904                     let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
905                         ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
906
907                     let count = niche_variants.size_hint().1.unwrap() as u128;
908
909                     // Find the field with the largest niche
910                     let (field_index, niche, (niche_start, niche_scalar)) = match variants
911                         [largest_variant_index]
912                         .iter()
913                         .enumerate()
914                         .filter_map(|(j, field)| Some((j, field.largest_niche?)))
915                         .max_by_key(|(_, niche)| niche.available(dl))
916                         .and_then(|(j, niche)| Some((j, niche, niche.reserve(cx, count)?)))
917                     {
918                         None => return Ok(None),
919                         Some(x) => x,
920                     };
921
922                     let niche_offset = niche.offset
923                         + variant_layouts[largest_variant_index].fields.offset(field_index);
924                     let niche_size = niche.value.size(dl);
925                     let size = variant_layouts[largest_variant_index].size.align_to(align.abi);
926
927                     let all_variants_fit =
928                         variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
929                             if i == largest_variant_index {
930                                 return true;
931                             }
932
933                             layout.largest_niche = None;
934
935                             if layout.size <= niche_offset {
936                                 // This variant will fit before the niche.
937                                 return true;
938                             }
939
940                             // Determine if it'll fit after the niche.
941                             let this_align = layout.align.abi;
942                             let this_offset = (niche_offset + niche_size).align_to(this_align);
943
944                             if this_offset + layout.size > size {
945                                 return false;
946                             }
947
948                             // It'll fit, but we need to make some adjustments.
949                             match layout.fields {
950                                 FieldsShape::Arbitrary { ref mut offsets, .. } => {
951                                     for (j, offset) in offsets.iter_mut().enumerate() {
952                                         if !variants[i][j].is_zst() {
953                                             *offset += this_offset;
954                                         }
955                                     }
956                                 }
957                                 _ => {
958                                     panic!("Layout of fields should be Arbitrary for variants")
959                                 }
960                             }
961
962                             // It can't be a Scalar or ScalarPair because the offset isn't 0.
963                             if !layout.abi.is_uninhabited() {
964                                 layout.abi = Abi::Aggregate { sized: true };
965                             }
966                             layout.size += this_offset;
967
968                             true
969                         });
970
971                     if !all_variants_fit {
972                         return Ok(None);
973                     }
974
975                     let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
976
977                     let others_zst = variant_layouts
978                         .iter_enumerated()
979                         .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
980                     let same_size = size == variant_layouts[largest_variant_index].size;
981                     let same_align = align == variant_layouts[largest_variant_index].align;
982
983                     let abi = if variant_layouts.iter().all(|v| v.abi.is_uninhabited()) {
984                         Abi::Uninhabited
985                     } else if same_size && same_align && others_zst {
986                         match variant_layouts[largest_variant_index].abi {
987                             // When the total alignment and size match, we can use the
988                             // same ABI as the scalar variant with the reserved niche.
989                             Abi::Scalar(_) => Abi::Scalar(niche_scalar),
990                             Abi::ScalarPair(first, second) => {
991                                 // Only the niche is guaranteed to be initialised,
992                                 // so use union layouts for the other primitive.
993                                 if niche_offset == Size::ZERO {
994                                     Abi::ScalarPair(niche_scalar, second.to_union())
995                                 } else {
996                                     Abi::ScalarPair(first.to_union(), niche_scalar)
997                                 }
998                             }
999                             _ => Abi::Aggregate { sized: true },
1000                         }
1001                     } else {
1002                         Abi::Aggregate { sized: true }
1003                     };
1004
1005                     let layout = LayoutS {
1006                         variants: Variants::Multiple {
1007                             tag: niche_scalar,
1008                             tag_encoding: TagEncoding::Niche {
1009                                 untagged_variant: largest_variant_index,
1010                                 niche_variants,
1011                                 niche_start,
1012                             },
1013                             tag_field: 0,
1014                             variants: IndexVec::new(),
1015                         },
1016                         fields: FieldsShape::Arbitrary {
1017                             offsets: vec![niche_offset],
1018                             memory_index: vec![0],
1019                         },
1020                         abi,
1021                         largest_niche,
1022                         size,
1023                         align,
1024                     };
1025
1026                     Ok(Some(TmpLayout { layout, variants: variant_layouts }))
1027                 };
1028
1029             let niche_filling_layout = calculate_niche_filling_layout()?;
1030
1031             let (mut min, mut max) = (i128::MAX, i128::MIN);
1032             let discr_type = def.repr().discr_type();
1033             let bits = Integer::from_attr(cx, discr_type).size().bits();
1034             for (i, discr) in def.discriminants(tcx) {
1035                 if variants[i].iter().any(|f| f.abi.is_uninhabited()) {
1036                     continue;
1037                 }
1038                 let mut x = discr.val as i128;
1039                 if discr_type.is_signed() {
1040                     // sign extend the raw representation to be an i128
1041                     x = (x << (128 - bits)) >> (128 - bits);
1042                 }
1043                 if x < min {
1044                     min = x;
1045                 }
1046                 if x > max {
1047                     max = x;
1048                 }
1049             }
1050             // We might have no inhabited variants, so pretend there's at least one.
1051             if (min, max) == (i128::MAX, i128::MIN) {
1052                 min = 0;
1053                 max = 0;
1054             }
1055             assert!(min <= max, "discriminant range is {}...{}", min, max);
1056             let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr(), min, max);
1057
1058             let mut align = dl.aggregate_align;
1059             let mut size = Size::ZERO;
1060
1061             // We're interested in the smallest alignment, so start large.
1062             let mut start_align = Align::from_bytes(256).unwrap();
1063             assert_eq!(Integer::for_align(dl, start_align), None);
1064
1065             // repr(C) on an enum tells us to make a (tag, union) layout,
1066             // so we need to grow the prefix alignment to be at least
1067             // the alignment of the union. (This value is used both for
1068             // determining the alignment of the overall enum, and the
1069             // determining the alignment of the payload after the tag.)
1070             let mut prefix_align = min_ity.align(dl).abi;
1071             if def.repr().c() {
1072                 for fields in &variants {
1073                     for field in fields {
1074                         prefix_align = prefix_align.max(field.align.abi);
1075                     }
1076                 }
1077             }
1078
1079             // Create the set of structs that represent each variant.
1080             let mut layout_variants = variants
1081                 .iter_enumerated()
1082                 .map(|(i, field_layouts)| {
1083                     let mut st = univariant_uninterned(
1084                         cx,
1085                         ty,
1086                         &field_layouts,
1087                         &def.repr(),
1088                         StructKind::Prefixed(min_ity.size(), prefix_align),
1089                     )?;
1090                     st.variants = Variants::Single { index: i };
1091                     // Find the first field we can't move later
1092                     // to make room for a larger discriminant.
1093                     for field in st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) {
1094                         if !field.is_zst() || field.align.abi.bytes() != 1 {
1095                             start_align = start_align.min(field.align.abi);
1096                             break;
1097                         }
1098                     }
1099                     size = cmp::max(size, st.size);
1100                     align = align.max(st.align);
1101                     Ok(st)
1102                 })
1103                 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
1104
1105             // Align the maximum variant size to the largest alignment.
1106             size = size.align_to(align.abi);
1107
1108             if size.bytes() >= dl.obj_size_bound() {
1109                 return Err(LayoutError::SizeOverflow(ty));
1110             }
1111
1112             let typeck_ity = Integer::from_attr(dl, def.repr().discr_type());
1113             if typeck_ity < min_ity {
1114                 // It is a bug if Layout decided on a greater discriminant size than typeck for
1115                 // some reason at this point (based on values discriminant can take on). Mostly
1116                 // because this discriminant will be loaded, and then stored into variable of
1117                 // type calculated by typeck. Consider such case (a bug): typeck decided on
1118                 // byte-sized discriminant, but layout thinks we need a 16-bit to store all
1119                 // discriminant values. That would be a bug, because then, in codegen, in order
1120                 // to store this 16-bit discriminant into 8-bit sized temporary some of the
1121                 // space necessary to represent would have to be discarded (or layout is wrong
1122                 // on thinking it needs 16 bits)
1123                 bug!(
1124                     "layout decided on a larger discriminant type ({:?}) than typeck ({:?})",
1125                     min_ity,
1126                     typeck_ity
1127                 );
1128                 // However, it is fine to make discr type however large (as an optimisation)
1129                 // after this point â€“ we’ll just truncate the value we load in codegen.
1130             }
1131
1132             // Check to see if we should use a different type for the
1133             // discriminant. We can safely use a type with the same size
1134             // as the alignment of the first field of each variant.
1135             // We increase the size of the discriminant to avoid LLVM copying
1136             // padding when it doesn't need to. This normally causes unaligned
1137             // load/stores and excessive memcpy/memset operations. By using a
1138             // bigger integer size, LLVM can be sure about its contents and
1139             // won't be so conservative.
1140
1141             // Use the initial field alignment
1142             let mut ity = if def.repr().c() || def.repr().int.is_some() {
1143                 min_ity
1144             } else {
1145                 Integer::for_align(dl, start_align).unwrap_or(min_ity)
1146             };
1147
1148             // If the alignment is not larger than the chosen discriminant size,
1149             // don't use the alignment as the final size.
1150             if ity <= min_ity {
1151                 ity = min_ity;
1152             } else {
1153                 // Patch up the variants' first few fields.
1154                 let old_ity_size = min_ity.size();
1155                 let new_ity_size = ity.size();
1156                 for variant in &mut layout_variants {
1157                     match variant.fields {
1158                         FieldsShape::Arbitrary { ref mut offsets, .. } => {
1159                             for i in offsets {
1160                                 if *i <= old_ity_size {
1161                                     assert_eq!(*i, old_ity_size);
1162                                     *i = new_ity_size;
1163                                 }
1164                             }
1165                             // We might be making the struct larger.
1166                             if variant.size <= old_ity_size {
1167                                 variant.size = new_ity_size;
1168                             }
1169                         }
1170                         _ => bug!(),
1171                     }
1172                 }
1173             }
1174
1175             let tag_mask = ity.size().unsigned_int_max();
1176             let tag = Scalar::Initialized {
1177                 value: Int(ity, signed),
1178                 valid_range: WrappingRange {
1179                     start: (min as u128 & tag_mask),
1180                     end: (max as u128 & tag_mask),
1181                 },
1182             };
1183             let mut abi = Abi::Aggregate { sized: true };
1184
1185             if layout_variants.iter().all(|v| v.abi.is_uninhabited()) {
1186                 abi = Abi::Uninhabited;
1187             } else if tag.size(dl) == size {
1188                 // Make sure we only use scalar layout when the enum is entirely its
1189                 // own tag (i.e. it has no padding nor any non-ZST variant fields).
1190                 abi = Abi::Scalar(tag);
1191             } else {
1192                 // Try to use a ScalarPair for all tagged enums.
1193                 let mut common_prim = None;
1194                 let mut common_prim_initialized_in_all_variants = true;
1195                 for (field_layouts, layout_variant) in iter::zip(&variants, &layout_variants) {
1196                     let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
1197                             bug!();
1198                         };
1199                     let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
1200                     let (field, offset) = match (fields.next(), fields.next()) {
1201                         (None, None) => {
1202                             common_prim_initialized_in_all_variants = false;
1203                             continue;
1204                         }
1205                         (Some(pair), None) => pair,
1206                         _ => {
1207                             common_prim = None;
1208                             break;
1209                         }
1210                     };
1211                     let prim = match field.abi {
1212                         Abi::Scalar(scalar) => {
1213                             common_prim_initialized_in_all_variants &=
1214                                 matches!(scalar, Scalar::Initialized { .. });
1215                             scalar.primitive()
1216                         }
1217                         _ => {
1218                             common_prim = None;
1219                             break;
1220                         }
1221                     };
1222                     if let Some(pair) = common_prim {
1223                         // This is pretty conservative. We could go fancier
1224                         // by conflating things like i32 and u32, or even
1225                         // realising that (u8, u8) could just cohabit with
1226                         // u16 or even u32.
1227                         if pair != (prim, offset) {
1228                             common_prim = None;
1229                             break;
1230                         }
1231                     } else {
1232                         common_prim = Some((prim, offset));
1233                     }
1234                 }
1235                 if let Some((prim, offset)) = common_prim {
1236                     let prim_scalar = if common_prim_initialized_in_all_variants {
1237                         scalar_unit(prim)
1238                     } else {
1239                         // Common prim might be uninit.
1240                         Scalar::Union { value: prim }
1241                     };
1242                     let pair = scalar_pair(cx, tag, prim_scalar);
1243                     let pair_offsets = match pair.fields {
1244                         FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
1245                             assert_eq!(memory_index, &[0, 1]);
1246                             offsets
1247                         }
1248                         _ => bug!(),
1249                     };
1250                     if pair_offsets[0] == Size::ZERO
1251                         && pair_offsets[1] == *offset
1252                         && align == pair.align
1253                         && size == pair.size
1254                     {
1255                         // We can use `ScalarPair` only when it matches our
1256                         // already computed layout (including `#[repr(C)]`).
1257                         abi = pair.abi;
1258                     }
1259                 }
1260             }
1261
1262             // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1263             // variants to ensure they are consistent. This is because a downcast is
1264             // semantically a NOP, and thus should not affect layout.
1265             if matches!(abi, Abi::Scalar(..) | Abi::ScalarPair(..)) {
1266                 for variant in &mut layout_variants {
1267                     // We only do this for variants with fields; the others are not accessed anyway.
1268                     // Also do not overwrite any already existing "clever" ABIs.
1269                     if variant.fields.count() > 0 && matches!(variant.abi, Abi::Aggregate { .. }) {
1270                         variant.abi = abi;
1271                         // Also need to bump up the size and alignment, so that the entire value fits in here.
1272                         variant.size = cmp::max(variant.size, size);
1273                         variant.align.abi = cmp::max(variant.align.abi, align.abi);
1274                     }
1275                 }
1276             }
1277
1278             let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1279
1280             let tagged_layout = LayoutS {
1281                 variants: Variants::Multiple {
1282                     tag,
1283                     tag_encoding: TagEncoding::Direct,
1284                     tag_field: 0,
1285                     variants: IndexVec::new(),
1286                 },
1287                 fields: FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] },
1288                 largest_niche,
1289                 abi,
1290                 align,
1291                 size,
1292             };
1293
1294             let tagged_layout = TmpLayout { layout: tagged_layout, variants: layout_variants };
1295
1296             let mut best_layout = match (tagged_layout, niche_filling_layout) {
1297                 (tl, Some(nl)) => {
1298                     // Pick the smaller layout; otherwise,
1299                     // pick the layout with the larger niche; otherwise,
1300                     // pick tagged as it has simpler codegen.
1301                     use Ordering::*;
1302                     let niche_size = |tmp_l: &TmpLayout<'_>| {
1303                         tmp_l.layout.largest_niche.map_or(0, |n| n.available(dl))
1304                     };
1305                     match (
1306                         tl.layout.size.cmp(&nl.layout.size),
1307                         niche_size(&tl).cmp(&niche_size(&nl)),
1308                     ) {
1309                         (Greater, _) => nl,
1310                         (Equal, Less) => nl,
1311                         _ => tl,
1312                     }
1313                 }
1314                 (tl, None) => tl,
1315             };
1316
1317             // Now we can intern the variant layouts and store them in the enum layout.
1318             best_layout.layout.variants = match best_layout.layout.variants {
1319                 Variants::Multiple { tag, tag_encoding, tag_field, .. } => Variants::Multiple {
1320                     tag,
1321                     tag_encoding,
1322                     tag_field,
1323                     variants: best_layout
1324                         .variants
1325                         .into_iter()
1326                         .map(|layout| tcx.intern_layout(layout))
1327                         .collect(),
1328                 },
1329                 _ => bug!(),
1330             };
1331
1332             tcx.intern_layout(best_layout.layout)
1333         }
1334
1335         // Types with no meaningful known layout.
1336         ty::Projection(_) | ty::Opaque(..) => {
1337             // NOTE(eddyb) `layout_of` query should've normalized these away,
1338             // if that was possible, so there's no reason to try again here.
1339             return Err(LayoutError::Unknown(ty));
1340         }
1341
1342         ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => {
1343             bug!("Layout::compute: unexpected type `{}`", ty)
1344         }
1345
1346         ty::Bound(..) | ty::Param(_) | ty::Error(_) => {
1347             return Err(LayoutError::Unknown(ty));
1348         }
1349     })
1350 }
1351
1352 /// Overlap eligibility and variant assignment for each GeneratorSavedLocal.
1353 #[derive(Clone, Debug, PartialEq)]
1354 enum SavedLocalEligibility {
1355     Unassigned,
1356     Assigned(VariantIdx),
1357     // FIXME: Use newtype_index so we aren't wasting bytes
1358     Ineligible(Option<u32>),
1359 }
1360
1361 // When laying out generators, we divide our saved local fields into two
1362 // categories: overlap-eligible and overlap-ineligible.
1363 //
1364 // Those fields which are ineligible for overlap go in a "prefix" at the
1365 // beginning of the layout, and always have space reserved for them.
1366 //
1367 // Overlap-eligible fields are only assigned to one variant, so we lay
1368 // those fields out for each variant and put them right after the
1369 // prefix.
1370 //
1371 // Finally, in the layout details, we point to the fields from the
1372 // variants they are assigned to. It is possible for some fields to be
1373 // included in multiple variants. No field ever "moves around" in the
1374 // layout; its offset is always the same.
1375 //
1376 // Also included in the layout are the upvars and the discriminant.
1377 // These are included as fields on the "outer" layout; they are not part
1378 // of any variant.
1379
1380 /// Compute the eligibility and assignment of each local.
1381 fn generator_saved_local_eligibility<'tcx>(
1382     info: &GeneratorLayout<'tcx>,
1383 ) -> (BitSet<GeneratorSavedLocal>, IndexVec<GeneratorSavedLocal, SavedLocalEligibility>) {
1384     use SavedLocalEligibility::*;
1385
1386     let mut assignments: IndexVec<GeneratorSavedLocal, SavedLocalEligibility> =
1387         IndexVec::from_elem_n(Unassigned, info.field_tys.len());
1388
1389     // The saved locals not eligible for overlap. These will get
1390     // "promoted" to the prefix of our generator.
1391     let mut ineligible_locals = BitSet::new_empty(info.field_tys.len());
1392
1393     // Figure out which of our saved locals are fields in only
1394     // one variant. The rest are deemed ineligible for overlap.
1395     for (variant_index, fields) in info.variant_fields.iter_enumerated() {
1396         for local in fields {
1397             match assignments[*local] {
1398                 Unassigned => {
1399                     assignments[*local] = Assigned(variant_index);
1400                 }
1401                 Assigned(idx) => {
1402                     // We've already seen this local at another suspension
1403                     // point, so it is no longer a candidate.
1404                     trace!(
1405                         "removing local {:?} in >1 variant ({:?}, {:?})",
1406                         local,
1407                         variant_index,
1408                         idx
1409                     );
1410                     ineligible_locals.insert(*local);
1411                     assignments[*local] = Ineligible(None);
1412                 }
1413                 Ineligible(_) => {}
1414             }
1415         }
1416     }
1417
1418     // Next, check every pair of eligible locals to see if they
1419     // conflict.
1420     for local_a in info.storage_conflicts.rows() {
1421         let conflicts_a = info.storage_conflicts.count(local_a);
1422         if ineligible_locals.contains(local_a) {
1423             continue;
1424         }
1425
1426         for local_b in info.storage_conflicts.iter(local_a) {
1427             // local_a and local_b are storage live at the same time, therefore they
1428             // cannot overlap in the generator layout. The only way to guarantee
1429             // this is if they are in the same variant, or one is ineligible
1430             // (which means it is stored in every variant).
1431             if ineligible_locals.contains(local_b) || assignments[local_a] == assignments[local_b] {
1432                 continue;
1433             }
1434
1435             // If they conflict, we will choose one to make ineligible.
1436             // This is not always optimal; it's just a greedy heuristic that
1437             // seems to produce good results most of the time.
1438             let conflicts_b = info.storage_conflicts.count(local_b);
1439             let (remove, other) =
1440                 if conflicts_a > conflicts_b { (local_a, local_b) } else { (local_b, local_a) };
1441             ineligible_locals.insert(remove);
1442             assignments[remove] = Ineligible(None);
1443             trace!("removing local {:?} due to conflict with {:?}", remove, other);
1444         }
1445     }
1446
1447     // Count the number of variants in use. If only one of them, then it is
1448     // impossible to overlap any locals in our layout. In this case it's
1449     // always better to make the remaining locals ineligible, so we can
1450     // lay them out with the other locals in the prefix and eliminate
1451     // unnecessary padding bytes.
1452     {
1453         let mut used_variants = BitSet::new_empty(info.variant_fields.len());
1454         for assignment in &assignments {
1455             if let Assigned(idx) = assignment {
1456                 used_variants.insert(*idx);
1457             }
1458         }
1459         if used_variants.count() < 2 {
1460             for assignment in assignments.iter_mut() {
1461                 *assignment = Ineligible(None);
1462             }
1463             ineligible_locals.insert_all();
1464         }
1465     }
1466
1467     // Write down the order of our locals that will be promoted to the prefix.
1468     {
1469         for (idx, local) in ineligible_locals.iter().enumerate() {
1470             assignments[local] = Ineligible(Some(idx as u32));
1471         }
1472     }
1473     debug!("generator saved local assignments: {:?}", assignments);
1474
1475     (ineligible_locals, assignments)
1476 }
1477
1478 /// Compute the full generator layout.
1479 fn generator_layout<'tcx>(
1480     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
1481     ty: Ty<'tcx>,
1482     def_id: hir::def_id::DefId,
1483     substs: SubstsRef<'tcx>,
1484 ) -> Result<Layout<'tcx>, LayoutError<'tcx>> {
1485     use SavedLocalEligibility::*;
1486     let tcx = cx.tcx;
1487     let subst_field = |ty: Ty<'tcx>| EarlyBinder(ty).subst(tcx, substs);
1488
1489     let Some(info) = tcx.generator_layout(def_id) else {
1490             return Err(LayoutError::Unknown(ty));
1491         };
1492     let (ineligible_locals, assignments) = generator_saved_local_eligibility(&info);
1493
1494     // Build a prefix layout, including "promoting" all ineligible
1495     // locals as part of the prefix. We compute the layout of all of
1496     // these fields at once to get optimal packing.
1497     let tag_index = substs.as_generator().prefix_tys().count();
1498
1499     // `info.variant_fields` already accounts for the reserved variants, so no need to add them.
1500     let max_discr = (info.variant_fields.len() - 1) as u128;
1501     let discr_int = Integer::fit_unsigned(max_discr);
1502     let discr_int_ty = discr_int.to_ty(tcx, false);
1503     let tag = Scalar::Initialized {
1504         value: Primitive::Int(discr_int, false),
1505         valid_range: WrappingRange { start: 0, end: max_discr },
1506     };
1507     let tag_layout = cx.tcx.intern_layout(LayoutS::scalar(cx, tag));
1508     let tag_layout = TyAndLayout { ty: discr_int_ty, layout: tag_layout };
1509
1510     let promoted_layouts = ineligible_locals
1511         .iter()
1512         .map(|local| subst_field(info.field_tys[local]))
1513         .map(|ty| tcx.mk_maybe_uninit(ty))
1514         .map(|ty| cx.layout_of(ty));
1515     let prefix_layouts = substs
1516         .as_generator()
1517         .prefix_tys()
1518         .map(|ty| cx.layout_of(ty))
1519         .chain(iter::once(Ok(tag_layout)))
1520         .chain(promoted_layouts)
1521         .collect::<Result<Vec<_>, _>>()?;
1522     let prefix = univariant_uninterned(
1523         cx,
1524         ty,
1525         &prefix_layouts,
1526         &ReprOptions::default(),
1527         StructKind::AlwaysSized,
1528     )?;
1529
1530     let (prefix_size, prefix_align) = (prefix.size, prefix.align);
1531
1532     // Split the prefix layout into the "outer" fields (upvars and
1533     // discriminant) and the "promoted" fields. Promoted fields will
1534     // get included in each variant that requested them in
1535     // GeneratorLayout.
1536     debug!("prefix = {:#?}", prefix);
1537     let (outer_fields, promoted_offsets, promoted_memory_index) = match prefix.fields {
1538         FieldsShape::Arbitrary { mut offsets, memory_index } => {
1539             let mut inverse_memory_index = invert_mapping(&memory_index);
1540
1541             // "a" (`0..b_start`) and "b" (`b_start..`) correspond to
1542             // "outer" and "promoted" fields respectively.
1543             let b_start = (tag_index + 1) as u32;
1544             let offsets_b = offsets.split_off(b_start as usize);
1545             let offsets_a = offsets;
1546
1547             // Disentangle the "a" and "b" components of `inverse_memory_index`
1548             // by preserving the order but keeping only one disjoint "half" each.
1549             // FIXME(eddyb) build a better abstraction for permutations, if possible.
1550             let inverse_memory_index_b: Vec<_> =
1551                 inverse_memory_index.iter().filter_map(|&i| i.checked_sub(b_start)).collect();
1552             inverse_memory_index.retain(|&i| i < b_start);
1553             let inverse_memory_index_a = inverse_memory_index;
1554
1555             // Since `inverse_memory_index_{a,b}` each only refer to their
1556             // respective fields, they can be safely inverted
1557             let memory_index_a = invert_mapping(&inverse_memory_index_a);
1558             let memory_index_b = invert_mapping(&inverse_memory_index_b);
1559
1560             let outer_fields =
1561                 FieldsShape::Arbitrary { offsets: offsets_a, memory_index: memory_index_a };
1562             (outer_fields, offsets_b, memory_index_b)
1563         }
1564         _ => bug!(),
1565     };
1566
1567     let mut size = prefix.size;
1568     let mut align = prefix.align;
1569     let variants = info
1570         .variant_fields
1571         .iter_enumerated()
1572         .map(|(index, variant_fields)| {
1573             // Only include overlap-eligible fields when we compute our variant layout.
1574             let variant_only_tys = variant_fields
1575                 .iter()
1576                 .filter(|local| match assignments[**local] {
1577                     Unassigned => bug!(),
1578                     Assigned(v) if v == index => true,
1579                     Assigned(_) => bug!("assignment does not match variant"),
1580                     Ineligible(_) => false,
1581                 })
1582                 .map(|local| subst_field(info.field_tys[*local]));
1583
1584             let mut variant = univariant_uninterned(
1585                 cx,
1586                 ty,
1587                 &variant_only_tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
1588                 &ReprOptions::default(),
1589                 StructKind::Prefixed(prefix_size, prefix_align.abi),
1590             )?;
1591             variant.variants = Variants::Single { index };
1592
1593             let FieldsShape::Arbitrary { offsets, memory_index } = variant.fields else {
1594                     bug!();
1595                 };
1596
1597             // Now, stitch the promoted and variant-only fields back together in
1598             // the order they are mentioned by our GeneratorLayout.
1599             // Because we only use some subset (that can differ between variants)
1600             // of the promoted fields, we can't just pick those elements of the
1601             // `promoted_memory_index` (as we'd end up with gaps).
1602             // So instead, we build an "inverse memory_index", as if all of the
1603             // promoted fields were being used, but leave the elements not in the
1604             // subset as `INVALID_FIELD_IDX`, which we can filter out later to
1605             // obtain a valid (bijective) mapping.
1606             const INVALID_FIELD_IDX: u32 = !0;
1607             let mut combined_inverse_memory_index =
1608                 vec![INVALID_FIELD_IDX; promoted_memory_index.len() + memory_index.len()];
1609             let mut offsets_and_memory_index = iter::zip(offsets, memory_index);
1610             let combined_offsets = variant_fields
1611                 .iter()
1612                 .enumerate()
1613                 .map(|(i, local)| {
1614                     let (offset, memory_index) = match assignments[*local] {
1615                         Unassigned => bug!(),
1616                         Assigned(_) => {
1617                             let (offset, memory_index) = offsets_and_memory_index.next().unwrap();
1618                             (offset, promoted_memory_index.len() as u32 + memory_index)
1619                         }
1620                         Ineligible(field_idx) => {
1621                             let field_idx = field_idx.unwrap() as usize;
1622                             (promoted_offsets[field_idx], promoted_memory_index[field_idx])
1623                         }
1624                     };
1625                     combined_inverse_memory_index[memory_index as usize] = i as u32;
1626                     offset
1627                 })
1628                 .collect();
1629
1630             // Remove the unused slots and invert the mapping to obtain the
1631             // combined `memory_index` (also see previous comment).
1632             combined_inverse_memory_index.retain(|&i| i != INVALID_FIELD_IDX);
1633             let combined_memory_index = invert_mapping(&combined_inverse_memory_index);
1634
1635             variant.fields = FieldsShape::Arbitrary {
1636                 offsets: combined_offsets,
1637                 memory_index: combined_memory_index,
1638             };
1639
1640             size = size.max(variant.size);
1641             align = align.max(variant.align);
1642             Ok(tcx.intern_layout(variant))
1643         })
1644         .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
1645
1646     size = size.align_to(align.abi);
1647
1648     let abi = if prefix.abi.is_uninhabited() || variants.iter().all(|v| v.abi().is_uninhabited()) {
1649         Abi::Uninhabited
1650     } else {
1651         Abi::Aggregate { sized: true }
1652     };
1653
1654     let layout = tcx.intern_layout(LayoutS {
1655         variants: Variants::Multiple {
1656             tag,
1657             tag_encoding: TagEncoding::Direct,
1658             tag_field: tag_index,
1659             variants,
1660         },
1661         fields: outer_fields,
1662         abi,
1663         largest_niche: prefix.largest_niche,
1664         size,
1665         align,
1666     });
1667     debug!("generator layout ({:?}): {:#?}", ty, layout);
1668     Ok(layout)
1669 }
1670
1671 /// This is invoked by the `layout_of` query to record the final
1672 /// layout of each type.
1673 #[inline(always)]
1674 fn record_layout_for_printing<'tcx>(cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, layout: TyAndLayout<'tcx>) {
1675     // If we are running with `-Zprint-type-sizes`, maybe record layouts
1676     // for dumping later.
1677     if cx.tcx.sess.opts.unstable_opts.print_type_sizes {
1678         record_layout_for_printing_outlined(cx, layout)
1679     }
1680 }
1681
1682 fn record_layout_for_printing_outlined<'tcx>(
1683     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
1684     layout: TyAndLayout<'tcx>,
1685 ) {
1686     // Ignore layouts that are done with non-empty environments or
1687     // non-monomorphic layouts, as the user only wants to see the stuff
1688     // resulting from the final codegen session.
1689     if layout.ty.has_non_region_param() || !cx.param_env.caller_bounds().is_empty() {
1690         return;
1691     }
1692
1693     // (delay format until we actually need it)
1694     let record = |kind, packed, opt_discr_size, variants| {
1695         let type_desc = format!("{:?}", layout.ty);
1696         cx.tcx.sess.code_stats.record_type_size(
1697             kind,
1698             type_desc,
1699             layout.align.abi,
1700             layout.size,
1701             packed,
1702             opt_discr_size,
1703             variants,
1704         );
1705     };
1706
1707     let adt_def = match *layout.ty.kind() {
1708         ty::Adt(ref adt_def, _) => {
1709             debug!("print-type-size t: `{:?}` process adt", layout.ty);
1710             adt_def
1711         }
1712
1713         ty::Closure(..) => {
1714             debug!("print-type-size t: `{:?}` record closure", layout.ty);
1715             record(DataTypeKind::Closure, false, None, vec![]);
1716             return;
1717         }
1718
1719         _ => {
1720             debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
1721             return;
1722         }
1723     };
1724
1725     let adt_kind = adt_def.adt_kind();
1726     let adt_packed = adt_def.repr().pack.is_some();
1727
1728     let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| {
1729         let mut min_size = Size::ZERO;
1730         let field_info: Vec<_> = flds
1731             .iter()
1732             .enumerate()
1733             .map(|(i, &name)| {
1734                 let field_layout = layout.field(cx, i);
1735                 let offset = layout.fields.offset(i);
1736                 let field_end = offset + field_layout.size;
1737                 if min_size < field_end {
1738                     min_size = field_end;
1739                 }
1740                 FieldInfo {
1741                     name,
1742                     offset: offset.bytes(),
1743                     size: field_layout.size.bytes(),
1744                     align: field_layout.align.abi.bytes(),
1745                 }
1746             })
1747             .collect();
1748
1749         VariantInfo {
1750             name: n,
1751             kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
1752             align: layout.align.abi.bytes(),
1753             size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
1754             fields: field_info,
1755         }
1756     };
1757
1758     match layout.variants {
1759         Variants::Single { index } => {
1760             if !adt_def.variants().is_empty() && layout.fields != FieldsShape::Primitive {
1761                 debug!("print-type-size `{:#?}` variant {}", layout, adt_def.variant(index).name);
1762                 let variant_def = &adt_def.variant(index);
1763                 let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1764                 record(
1765                     adt_kind.into(),
1766                     adt_packed,
1767                     None,
1768                     vec![build_variant_info(Some(variant_def.name), &fields, layout)],
1769                 );
1770             } else {
1771                 // (This case arises for *empty* enums; so give it
1772                 // zero variants.)
1773                 record(adt_kind.into(), adt_packed, None, vec![]);
1774             }
1775         }
1776
1777         Variants::Multiple { tag, ref tag_encoding, .. } => {
1778             debug!(
1779                 "print-type-size `{:#?}` adt general variants def {}",
1780                 layout.ty,
1781                 adt_def.variants().len()
1782             );
1783             let variant_infos: Vec<_> = adt_def
1784                 .variants()
1785                 .iter_enumerated()
1786                 .map(|(i, variant_def)| {
1787                     let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1788                     build_variant_info(Some(variant_def.name), &fields, layout.for_variant(cx, i))
1789                 })
1790                 .collect();
1791             record(
1792                 adt_kind.into(),
1793                 adt_packed,
1794                 match tag_encoding {
1795                     TagEncoding::Direct => Some(tag.size(cx)),
1796                     _ => None,
1797                 },
1798                 variant_infos,
1799             );
1800         }
1801     }
1802 }