rustc_ty_utils/
layout.rs

1use hir::def_id::DefId;
2use rustc_abi::Integer::{I8, I32};
3use rustc_abi::Primitive::{self, Float, Int, Pointer};
4use rustc_abi::{
5    AddressSpace, BackendRepr, FIRST_VARIANT, FieldIdx, FieldsShape, HasDataLayout, Layout,
6    LayoutCalculatorError, LayoutData, Niche, ReprOptions, Scalar, Size, StructKind, TagEncoding,
7    VariantIdx, Variants, WrappingRange,
8};
9use rustc_hashes::Hash64;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::find_attr;
12use rustc_index::IndexVec;
13use rustc_middle::bug;
14use rustc_middle::query::Providers;
15use rustc_middle::traits::ObligationCause;
16use rustc_middle::ty::layout::{
17    FloatExt, HasTyCtxt, IntegerExt, LayoutCx, LayoutError, LayoutOf, SimdLayoutError, TyAndLayout,
18};
19use rustc_middle::ty::print::with_no_trimmed_paths;
20use rustc_middle::ty::{
21    self, AdtDef, CoroutineArgsExt, EarlyBinder, PseudoCanonicalInput, Ty, TyCtxt, TypeVisitableExt,
22};
23use rustc_session::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
24use rustc_span::{Symbol, sym};
25use tracing::{debug, instrument};
26use {rustc_abi as abi, rustc_hir as hir};
27
28use crate::errors::NonPrimitiveSimdType;
29
30mod invariant;
31
32pub(crate) fn provide(providers: &mut Providers) {
33    *providers = Providers { layout_of, ..*providers };
34}
35
36#[instrument(skip(tcx, query), level = "debug")]
37fn layout_of<'tcx>(
38    tcx: TyCtxt<'tcx>,
39    query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
40) -> Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>> {
41    let PseudoCanonicalInput { typing_env, value: ty } = query;
42    debug!(?ty);
43
44    // Optimization: We convert to TypingMode::PostAnalysis and convert opaque types in
45    // the where bounds to their hidden types. This reduces overall uncached invocations
46    // of `layout_of` and is thus a small performance improvement.
47    let typing_env = typing_env.with_post_analysis_normalized(tcx);
48    let unnormalized_ty = ty;
49
50    // FIXME: We might want to have two different versions of `layout_of`:
51    // One that can be called after typecheck has completed and can use
52    // `normalize_erasing_regions` here and another one that can be called
53    // before typecheck has completed and uses `try_normalize_erasing_regions`.
54    let ty = match tcx.try_normalize_erasing_regions(typing_env, ty) {
55        Ok(t) => t,
56        Err(normalization_error) => {
57            return Err(tcx
58                .arena
59                .alloc(LayoutError::NormalizationFailure(ty, normalization_error)));
60        }
61    };
62
63    if ty != unnormalized_ty {
64        // Ensure this layout is also cached for the normalized type.
65        return tcx.layout_of(typing_env.as_query_input(ty));
66    }
67
68    let cx = LayoutCx::new(tcx, typing_env);
69
70    let layout = layout_of_uncached(&cx, ty)?;
71    let layout = TyAndLayout { ty, layout };
72
73    // If we are running with `-Zprint-type-sizes`, maybe record layouts
74    // for dumping later.
75    if cx.tcx().sess.opts.unstable_opts.print_type_sizes {
76        record_layout_for_printing(&cx, layout);
77    }
78
79    invariant::layout_sanity_check(&cx, &layout);
80
81    Ok(layout)
82}
83
84fn error<'tcx>(cx: &LayoutCx<'tcx>, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
85    cx.tcx().arena.alloc(err)
86}
87
88fn map_error<'tcx>(
89    cx: &LayoutCx<'tcx>,
90    ty: Ty<'tcx>,
91    err: LayoutCalculatorError<TyAndLayout<'tcx>>,
92) -> &'tcx LayoutError<'tcx> {
93    let err = match err {
94        LayoutCalculatorError::SizeOverflow => {
95            // This is sometimes not a compile error in `check` builds.
96            // See `tests/ui/limits/huge-enum.rs` for an example.
97            LayoutError::SizeOverflow(ty)
98        }
99        LayoutCalculatorError::UnexpectedUnsized(field) => {
100            // This is sometimes not a compile error if there are trivially false where clauses.
101            // See `tests/ui/layout/trivial-bounds-sized.rs` for an example.
102            assert!(field.layout.is_unsized(), "invalid layout error {err:#?}");
103            if cx.typing_env.param_env.caller_bounds().is_empty() {
104                cx.tcx().dcx().delayed_bug(format!(
105                    "encountered unexpected unsized field in layout of {ty:?}: {field:#?}"
106                ));
107            }
108            LayoutError::Unknown(ty)
109        }
110        LayoutCalculatorError::EmptyUnion => {
111            // This is always a compile error.
112            let guar =
113                cx.tcx().dcx().delayed_bug(format!("computed layout of empty union: {ty:?}"));
114            LayoutError::ReferencesError(guar)
115        }
116        LayoutCalculatorError::ReprConflict => {
117            // packed enums are the only known trigger of this, but others might arise
118            let guar = cx
119                .tcx()
120                .dcx()
121                .delayed_bug(format!("computed impossible repr (packed enum?): {ty:?}"));
122            LayoutError::ReferencesError(guar)
123        }
124        LayoutCalculatorError::ZeroLengthSimdType => {
125            // Can't be caught in typeck if the array length is generic.
126            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength }
127        }
128        LayoutCalculatorError::OversizedSimdType { max_lanes } => {
129            // Can't be caught in typeck if the array length is generic.
130            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) }
131        }
132        LayoutCalculatorError::NonPrimitiveSimdType(field) => {
133            // This error isn't caught in typeck, e.g., if
134            // the element type of the vector is generic.
135            cx.tcx().dcx().emit_fatal(NonPrimitiveSimdType { ty, e_ty: field.ty })
136        }
137    };
138    error(cx, err)
139}
140
141fn extract_const_value<'tcx>(
142    cx: &LayoutCx<'tcx>,
143    ty: Ty<'tcx>,
144    ct: ty::Const<'tcx>,
145) -> Result<ty::Value<'tcx>, &'tcx LayoutError<'tcx>> {
146    match ct.kind() {
147        ty::ConstKind::Value(cv) => Ok(cv),
148        ty::ConstKind::Param(_) | ty::ConstKind::Expr(_) => {
149            if !ct.has_param() {
150                bug!("failed to normalize const, but it is not generic: {ct:?}");
151            }
152            Err(error(cx, LayoutError::TooGeneric(ty)))
153        }
154        ty::ConstKind::Unevaluated(_) => {
155            let err = if ct.has_param() {
156                LayoutError::TooGeneric(ty)
157            } else {
158                // This case is reachable with unsatisfiable predicates and GCE (which will
159                // cause anon consts to inherit the unsatisfiable predicates). For example
160                // if we have an unsatisfiable `u8: Trait` bound, then it's not a compile
161                // error to mention `[u8; <u8 as Trait>::CONST]`, but we can't compute its
162                // layout.
163                LayoutError::Unknown(ty)
164            };
165            Err(error(cx, err))
166        }
167        ty::ConstKind::Infer(_)
168        | ty::ConstKind::Bound(..)
169        | ty::ConstKind::Placeholder(_)
170        | ty::ConstKind::Error(_) => {
171            // `ty::ConstKind::Error` is handled at the top of `layout_of_uncached`
172            // (via `ty.error_reported()`).
173            bug!("layout_of: unexpected const: {ct:?}");
174        }
175    }
176}
177
178fn layout_of_uncached<'tcx>(
179    cx: &LayoutCx<'tcx>,
180    ty: Ty<'tcx>,
181) -> Result<Layout<'tcx>, &'tcx LayoutError<'tcx>> {
182    // Types that reference `ty::Error` pessimistically don't have a meaningful layout.
183    // The only side-effect of this is possibly worse diagnostics in case the layout
184    // was actually computable (like if the `ty::Error` showed up only in a `PhantomData`).
185    if let Err(guar) = ty.error_reported() {
186        return Err(error(cx, LayoutError::ReferencesError(guar)));
187    }
188
189    let tcx = cx.tcx();
190
191    // layout of `async_drop_in_place<T>::{closure}` in case,
192    // when T is a coroutine, contains this internal coroutine's ref
193
194    let dl = cx.data_layout();
195    let map_layout = |result: Result<_, _>| match result {
196        Ok(layout) => Ok(tcx.mk_layout(layout)),
197        Err(err) => Err(map_error(cx, ty, err)),
198    };
199    let scalar_unit = |value: Primitive| {
200        let size = value.size(dl);
201        assert!(size.bits() <= 128);
202        Scalar::Initialized { value, valid_range: WrappingRange::full(size) }
203    };
204    let scalar = |value: Primitive| tcx.mk_layout(LayoutData::scalar(cx, scalar_unit(value)));
205
206    let univariant = |tys: &[Ty<'tcx>], kind| {
207        let fields = tys.iter().map(|ty| cx.layout_of(*ty)).try_collect::<IndexVec<_, _>>()?;
208        let repr = ReprOptions::default();
209        map_layout(cx.calc.univariant(&fields, &repr, kind))
210    };
211    debug_assert!(!ty.has_non_region_infer());
212
213    Ok(match *ty.kind() {
214        ty::Pat(ty, pat) => {
215            let layout = cx.layout_of(ty)?.layout;
216            let mut layout = LayoutData::clone(&layout.0);
217            match *pat {
218                ty::PatternKind::Range { start, end } => {
219                    if let BackendRepr::Scalar(scalar) = &mut layout.backend_repr {
220                        scalar.valid_range_mut().start = extract_const_value(cx, ty, start)?
221                            .try_to_bits(tcx, cx.typing_env)
222                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
223
224                        scalar.valid_range_mut().end = extract_const_value(cx, ty, end)?
225                            .try_to_bits(tcx, cx.typing_env)
226                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
227
228                        // FIXME(pattern_types): create implied bounds from pattern types in signatures
229                        // that require that the range end is >= the range start so that we can't hit
230                        // this error anymore without first having hit a trait solver error.
231                        // Very fuzzy on the details here, but pattern types are an internal impl detail,
232                        // so we can just go with this for now
233                        if scalar.is_signed() {
234                            let range = scalar.valid_range_mut();
235                            let start = layout.size.sign_extend(range.start);
236                            let end = layout.size.sign_extend(range.end);
237                            if end < start {
238                                let guar = tcx.dcx().err(format!(
239                                    "pattern type ranges cannot wrap: {start}..={end}"
240                                ));
241
242                                return Err(error(cx, LayoutError::ReferencesError(guar)));
243                            }
244                        } else {
245                            let range = scalar.valid_range_mut();
246                            if range.end < range.start {
247                                let guar = tcx.dcx().err(format!(
248                                    "pattern type ranges cannot wrap: {}..={}",
249                                    range.start, range.end
250                                ));
251
252                                return Err(error(cx, LayoutError::ReferencesError(guar)));
253                            }
254                        };
255
256                        let niche = Niche {
257                            offset: Size::ZERO,
258                            value: scalar.primitive(),
259                            valid_range: scalar.valid_range(cx),
260                        };
261
262                        layout.largest_niche = Some(niche);
263                    } else {
264                        bug!("pattern type with range but not scalar layout: {ty:?}, {layout:?}")
265                    }
266                }
267                ty::PatternKind::NotNull => {
268                    if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair(scalar, _) =
269                        &mut layout.backend_repr
270                    {
271                        scalar.valid_range_mut().start = 1;
272                        let niche = Niche {
273                            offset: Size::ZERO,
274                            value: scalar.primitive(),
275                            valid_range: scalar.valid_range(cx),
276                        };
277
278                        layout.largest_niche = Some(niche);
279                    } else {
280                        bug!(
281                            "pattern type with `!null` pattern but not scalar/pair layout: {ty:?}, {layout:?}"
282                        )
283                    }
284                }
285
286                ty::PatternKind::Or(variants) => match *variants[0] {
287                    ty::PatternKind::Range { .. } => {
288                        if let BackendRepr::Scalar(scalar) = &mut layout.backend_repr {
289                            let variants: Result<Vec<_>, _> = variants
290                                .iter()
291                                .map(|pat| match *pat {
292                                    ty::PatternKind::Range { start, end } => Ok((
293                                        extract_const_value(cx, ty, start)
294                                            .unwrap()
295                                            .try_to_bits(tcx, cx.typing_env)
296                                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?,
297                                        extract_const_value(cx, ty, end)
298                                            .unwrap()
299                                            .try_to_bits(tcx, cx.typing_env)
300                                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?,
301                                    )),
302                                    ty::PatternKind::NotNull | ty::PatternKind::Or(_) => {
303                                        unreachable!("mixed or patterns are not allowed")
304                                    }
305                                })
306                                .collect();
307                            let mut variants = variants?;
308                            if !scalar.is_signed() {
309                                let guar = tcx.dcx().err(format!(
310                                    "only signed integer base types are allowed for or-pattern pattern types at present"
311                                ));
312
313                                return Err(error(cx, LayoutError::ReferencesError(guar)));
314                            }
315                            variants.sort();
316                            if variants.len() != 2 {
317                                let guar = tcx
318                                .dcx()
319                                .err(format!("the only or-pattern types allowed are two range patterns that are directly connected at their overflow site"));
320
321                                return Err(error(cx, LayoutError::ReferencesError(guar)));
322                            }
323
324                            // first is the one starting at the signed in range min
325                            let mut first = variants[0];
326                            let mut second = variants[1];
327                            if second.0
328                                == layout.size.truncate(layout.size.signed_int_min() as u128)
329                            {
330                                (second, first) = (first, second);
331                            }
332
333                            if layout.size.sign_extend(first.1) >= layout.size.sign_extend(second.0)
334                            {
335                                let guar = tcx.dcx().err(format!(
336                                    "only non-overlapping pattern type ranges are allowed at present"
337                                ));
338
339                                return Err(error(cx, LayoutError::ReferencesError(guar)));
340                            }
341                            if layout.size.signed_int_max() as u128 != second.1 {
342                                let guar = tcx.dcx().err(format!(
343                                    "one pattern needs to end at `{ty}::MAX`, but was {} instead",
344                                    second.1
345                                ));
346
347                                return Err(error(cx, LayoutError::ReferencesError(guar)));
348                            }
349
350                            // Now generate a wrapping range (which aren't allowed in surface syntax).
351                            scalar.valid_range_mut().start = second.0;
352                            scalar.valid_range_mut().end = first.1;
353
354                            let niche = Niche {
355                                offset: Size::ZERO,
356                                value: scalar.primitive(),
357                                valid_range: scalar.valid_range(cx),
358                            };
359
360                            layout.largest_niche = Some(niche);
361                        } else {
362                            bug!(
363                                "pattern type with range but not scalar layout: {ty:?}, {layout:?}"
364                            )
365                        }
366                    }
367                    ty::PatternKind::NotNull => bug!("or patterns can't contain `!null` patterns"),
368                    ty::PatternKind::Or(..) => bug!("patterns cannot have nested or patterns"),
369                },
370            }
371            // Pattern types contain their base as their sole field.
372            // This allows the rest of the compiler to process pattern types just like
373            // single field transparent Adts, and only the parts of the compiler that
374            // specifically care about pattern types will have to handle it.
375            layout.fields = FieldsShape::Arbitrary {
376                offsets: [Size::ZERO].into_iter().collect(),
377                memory_index: [0].into_iter().collect(),
378            };
379            tcx.mk_layout(layout)
380        }
381
382        // Basic scalars.
383        ty::Bool => tcx.mk_layout(LayoutData::scalar(
384            cx,
385            Scalar::Initialized {
386                value: Int(I8, false),
387                valid_range: WrappingRange { start: 0, end: 1 },
388            },
389        )),
390        ty::Char => tcx.mk_layout(LayoutData::scalar(
391            cx,
392            Scalar::Initialized {
393                value: Int(I32, false),
394                valid_range: WrappingRange { start: 0, end: 0x10FFFF },
395            },
396        )),
397        ty::Int(ity) => scalar(Int(abi::Integer::from_int_ty(dl, ity), true)),
398        ty::Uint(ity) => scalar(Int(abi::Integer::from_uint_ty(dl, ity), false)),
399        ty::Float(fty) => scalar(Float(abi::Float::from_float_ty(fty))),
400        ty::FnPtr(..) => {
401            let mut ptr = scalar_unit(Pointer(dl.instruction_address_space));
402            ptr.valid_range_mut().start = 1;
403            tcx.mk_layout(LayoutData::scalar(cx, ptr))
404        }
405
406        // The never type.
407        ty::Never => tcx.mk_layout(LayoutData::never_type(cx)),
408
409        // Potentially-wide pointers.
410        ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
411            let mut data_ptr = scalar_unit(Pointer(AddressSpace::ZERO));
412            if !ty.is_raw_ptr() {
413                data_ptr.valid_range_mut().start = 1;
414            }
415
416            if pointee.is_sized(tcx, cx.typing_env) {
417                return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
418            }
419
420            let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type() {
421                let pointee_metadata = Ty::new_projection(tcx, metadata_def_id, [pointee]);
422                let metadata_ty = match tcx
423                    .try_normalize_erasing_regions(cx.typing_env, pointee_metadata)
424                {
425                    Ok(metadata_ty) => metadata_ty,
426                    Err(mut err) => {
427                        // Usually `<Ty as Pointee>::Metadata` can't be normalized because
428                        // its struct tail cannot be normalized either, so try to get a
429                        // more descriptive layout error here, which will lead to less confusing
430                        // diagnostics.
431                        //
432                        // We use the raw struct tail function here to get the first tail
433                        // that is an alias, which is likely the cause of the normalization
434                        // error.
435                        match tcx.try_normalize_erasing_regions(
436                            cx.typing_env,
437                            tcx.struct_tail_raw(pointee, &ObligationCause::dummy(), |ty| ty, || {}),
438                        ) {
439                            Ok(_) => {}
440                            Err(better_err) => {
441                                err = better_err;
442                            }
443                        }
444                        return Err(error(cx, LayoutError::NormalizationFailure(pointee, err)));
445                    }
446                };
447
448                let metadata_layout = cx.layout_of(metadata_ty)?;
449                // If the metadata is a 1-zst, then the pointer is thin.
450                if metadata_layout.is_1zst() {
451                    return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
452                }
453
454                let BackendRepr::Scalar(metadata) = metadata_layout.backend_repr else {
455                    return Err(error(cx, LayoutError::Unknown(pointee)));
456                };
457
458                metadata
459            } else {
460                let unsized_part = tcx.struct_tail_for_codegen(pointee, cx.typing_env);
461
462                match unsized_part.kind() {
463                    ty::Foreign(..) => {
464                        return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
465                    }
466                    ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)),
467                    ty::Dynamic(..) => {
468                        let mut vtable = scalar_unit(Pointer(AddressSpace::ZERO));
469                        vtable.valid_range_mut().start = 1;
470                        vtable
471                    }
472                    _ => {
473                        return Err(error(cx, LayoutError::Unknown(pointee)));
474                    }
475                }
476            };
477
478            // Effectively a (ptr, meta) tuple.
479            tcx.mk_layout(LayoutData::scalar_pair(cx, data_ptr, metadata))
480        }
481
482        // Arrays and slices.
483        ty::Array(element, count) => {
484            let count = extract_const_value(cx, ty, count)?
485                .try_to_target_usize(tcx)
486                .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
487
488            let element = cx.layout_of(element)?;
489            map_layout(cx.calc.array_like(&element, Some(count)))?
490        }
491        ty::Slice(element) => {
492            let element = cx.layout_of(element)?;
493            map_layout(cx.calc.array_like(&element, None).map(|mut layout| {
494                // a randomly chosen value to distinguish slices
495                layout.randomization_seed = Hash64::new(0x2dcba99c39784102);
496                layout
497            }))?
498        }
499        ty::Str => {
500            let element = scalar(Int(I8, false));
501            map_layout(cx.calc.array_like(&element, None).map(|mut layout| {
502                // another random value
503                layout.randomization_seed = Hash64::new(0xc1325f37d127be22);
504                layout
505            }))?
506        }
507
508        // Odd unit types.
509        ty::FnDef(..) | ty::Dynamic(_, _) | ty::Foreign(..) => {
510            let sized = matches!(ty.kind(), ty::FnDef(..));
511            tcx.mk_layout(LayoutData::unit(cx, sized))
512        }
513
514        ty::Coroutine(def_id, args) => {
515            use rustc_middle::ty::layout::PrimitiveExt as _;
516
517            let info = tcx.coroutine_layout(def_id, args)?;
518
519            let local_layouts = info
520                .field_tys
521                .iter()
522                .map(|local| {
523                    let field_ty = EarlyBinder::bind(local.ty);
524                    let uninit_ty = Ty::new_maybe_uninit(tcx, field_ty.instantiate(tcx, args));
525                    cx.spanned_layout_of(uninit_ty, local.source_info.span)
526                })
527                .try_collect::<IndexVec<_, _>>()?;
528
529            let prefix_layouts = args
530                .as_coroutine()
531                .prefix_tys()
532                .iter()
533                .map(|ty| cx.layout_of(ty))
534                .try_collect::<IndexVec<_, _>>()?;
535
536            let layout = cx
537                .calc
538                .coroutine(
539                    &local_layouts,
540                    prefix_layouts,
541                    &info.variant_fields,
542                    &info.storage_conflicts,
543                    |tag| TyAndLayout {
544                        ty: tag.primitive().to_ty(tcx),
545                        layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
546                    },
547                )
548                .map(|mut layout| {
549                    // this is similar to how ReprOptions populates its field_shuffle_seed
550                    layout.randomization_seed = tcx.def_path_hash(def_id).0.to_smaller_hash();
551                    debug!("coroutine layout ({:?}): {:#?}", ty, layout);
552                    layout
553                });
554            map_layout(layout)?
555        }
556
557        ty::Closure(_, args) => univariant(args.as_closure().upvar_tys(), StructKind::AlwaysSized)?,
558
559        ty::CoroutineClosure(_, args) => {
560            univariant(args.as_coroutine_closure().upvar_tys(), StructKind::AlwaysSized)?
561        }
562
563        ty::Tuple(tys) => {
564            let kind =
565                if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized };
566
567            univariant(tys, kind)?
568        }
569
570        // SIMD vector types.
571        ty::Adt(def, args) if def.repr().simd() => {
572            // Supported SIMD vectors are ADTs with a single array field:
573            //
574            // * #[repr(simd)] struct S([T; 4])
575            //
576            // where T is a primitive scalar (integer/float/pointer).
577            let Some(ty::Array(e_ty, e_len)) = def
578                .is_struct()
579                .then(|| &def.variant(FIRST_VARIANT).fields)
580                .filter(|fields| fields.len() == 1)
581                .map(|fields| *fields[FieldIdx::ZERO].ty(tcx, args).kind())
582            else {
583                // Invalid SIMD types should have been caught by typeck by now.
584                let guar = tcx.dcx().delayed_bug("#[repr(simd)] was applied to an invalid ADT");
585                return Err(error(cx, LayoutError::ReferencesError(guar)));
586            };
587
588            let e_len = extract_const_value(cx, ty, e_len)?
589                .try_to_target_usize(tcx)
590                .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
591
592            let e_ly = cx.layout_of(e_ty)?;
593
594            // Check for the rustc_simd_monomorphize_lane_limit attribute and check the lane limit
595            if let Some(limit) = find_attr!(
596                tcx.get_all_attrs(def.did()),
597                AttributeKind::RustcSimdMonomorphizeLaneLimit(limit) => limit
598            ) {
599                if !limit.value_within_limit(e_len as usize) {
600                    return Err(map_error(
601                        &cx,
602                        ty,
603                        rustc_abi::LayoutCalculatorError::OversizedSimdType {
604                            max_lanes: limit.0 as u64,
605                        },
606                    ));
607                }
608            }
609
610            map_layout(cx.calc.simd_type(e_ly, e_len, def.repr().packed()))?
611        }
612
613        // ADTs.
614        ty::Adt(def, args) => {
615            // Cache the field layouts.
616            let variants = def
617                .variants()
618                .iter()
619                .map(|v| {
620                    v.fields
621                        .iter()
622                        .map(|field| cx.layout_of(field.ty(tcx, args)))
623                        .try_collect::<IndexVec<_, _>>()
624                })
625                .try_collect::<IndexVec<VariantIdx, _>>()?;
626
627            if def.is_union() {
628                if def.repr().pack.is_some() && def.repr().align.is_some() {
629                    let guar = tcx.dcx().span_delayed_bug(
630                        tcx.def_span(def.did()),
631                        "union cannot be packed and aligned",
632                    );
633                    return Err(error(cx, LayoutError::ReferencesError(guar)));
634                }
635
636                return map_layout(cx.calc.layout_of_union(&def.repr(), &variants));
637            }
638
639            // UnsafeCell and UnsafePinned both disable niche optimizations
640            let is_special_no_niche = def.is_unsafe_cell() || def.is_unsafe_pinned();
641
642            let get_discriminant_type =
643                |min, max| abi::Integer::repr_discr(tcx, ty, &def.repr(), min, max);
644
645            let discriminants_iter = || {
646                def.is_enum()
647                    .then(|| def.discriminants(tcx).map(|(v, d)| (v, d.val as i128)))
648                    .into_iter()
649                    .flatten()
650            };
651
652            let maybe_unsized = def.is_struct()
653                && def.non_enum_variant().tail_opt().is_some_and(|last_field| {
654                    let typing_env = ty::TypingEnv::post_analysis(tcx, def.did());
655                    !tcx.type_of(last_field.did).instantiate_identity().is_sized(tcx, typing_env)
656                });
657
658            let layout = cx
659                .calc
660                .layout_of_struct_or_enum(
661                    &def.repr(),
662                    &variants,
663                    def.is_enum(),
664                    is_special_no_niche,
665                    tcx.layout_scalar_valid_range(def.did()),
666                    get_discriminant_type,
667                    discriminants_iter(),
668                    !maybe_unsized,
669                )
670                .map_err(|err| map_error(cx, ty, err))?;
671
672            if !maybe_unsized && layout.is_unsized() {
673                bug!("got unsized layout for type that cannot be unsized {ty:?}: {layout:#?}");
674            }
675
676            // If the struct tail is sized and can be unsized, check that unsizing doesn't move the fields around.
677            if cfg!(debug_assertions)
678                && maybe_unsized
679                && def.non_enum_variant().tail().ty(tcx, args).is_sized(tcx, cx.typing_env)
680            {
681                let mut variants = variants;
682                let tail_replacement = cx.layout_of(Ty::new_slice(tcx, tcx.types.u8)).unwrap();
683                *variants[FIRST_VARIANT].raw.last_mut().unwrap() = tail_replacement;
684
685                let Ok(unsized_layout) = cx.calc.layout_of_struct_or_enum(
686                    &def.repr(),
687                    &variants,
688                    def.is_enum(),
689                    is_special_no_niche,
690                    tcx.layout_scalar_valid_range(def.did()),
691                    get_discriminant_type,
692                    discriminants_iter(),
693                    !maybe_unsized,
694                ) else {
695                    bug!("failed to compute unsized layout of {ty:?}");
696                };
697
698                let FieldsShape::Arbitrary { offsets: sized_offsets, .. } = &layout.fields else {
699                    bug!("unexpected FieldsShape for sized layout of {ty:?}: {:?}", layout.fields);
700                };
701                let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } =
702                    &unsized_layout.fields
703                else {
704                    bug!(
705                        "unexpected FieldsShape for unsized layout of {ty:?}: {:?}",
706                        unsized_layout.fields
707                    );
708                };
709
710                let (sized_tail, sized_fields) = sized_offsets.raw.split_last().unwrap();
711                let (unsized_tail, unsized_fields) = unsized_offsets.raw.split_last().unwrap();
712
713                if sized_fields != unsized_fields {
714                    bug!("unsizing {ty:?} changed field order!\n{layout:?}\n{unsized_layout:?}");
715                }
716
717                if sized_tail < unsized_tail {
718                    bug!("unsizing {ty:?} moved tail backwards!\n{layout:?}\n{unsized_layout:?}");
719                }
720            }
721
722            tcx.mk_layout(layout)
723        }
724
725        ty::UnsafeBinder(bound_ty) => {
726            let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
727            cx.layout_of(ty)?.layout
728        }
729
730        // Types with no meaningful known layout.
731        ty::Param(_) | ty::Placeholder(..) => {
732            return Err(error(cx, LayoutError::TooGeneric(ty)));
733        }
734
735        ty::Alias(..) => {
736            // NOTE(eddyb) `layout_of` query should've normalized these away,
737            // if that was possible, so there's no reason to try again here.
738            let err = if ty.has_param() {
739                LayoutError::TooGeneric(ty)
740            } else {
741                // This is only reachable with unsatisfiable predicates. For example, if we have
742                // `u8: Iterator`, then we can't compute the layout of `<u8 as Iterator>::Item`.
743                LayoutError::Unknown(ty)
744            };
745            return Err(error(cx, err));
746        }
747
748        ty::Bound(..) | ty::CoroutineWitness(..) | ty::Infer(_) | ty::Error(_) => {
749            // `ty::Error` is handled at the top of this function.
750            bug!("layout_of: unexpected type `{ty}`")
751        }
752    })
753}
754
755fn record_layout_for_printing<'tcx>(cx: &LayoutCx<'tcx>, layout: TyAndLayout<'tcx>) {
756    // Ignore layouts that are done with non-empty environments or
757    // non-monomorphic layouts, as the user only wants to see the stuff
758    // resulting from the final codegen session.
759    if layout.ty.has_non_region_param() || !cx.typing_env.param_env.caller_bounds().is_empty() {
760        return;
761    }
762
763    // (delay format until we actually need it)
764    let record = |kind, packed, opt_discr_size, variants| {
765        let type_desc = with_no_trimmed_paths!(format!("{}", layout.ty));
766        cx.tcx().sess.code_stats.record_type_size(
767            kind,
768            type_desc,
769            layout.align.abi,
770            layout.size,
771            packed,
772            opt_discr_size,
773            variants,
774        );
775    };
776
777    match *layout.ty.kind() {
778        ty::Adt(adt_def, _) => {
779            debug!("print-type-size t: `{:?}` process adt", layout.ty);
780            let adt_kind = adt_def.adt_kind();
781            let adt_packed = adt_def.repr().pack.is_some();
782            let (variant_infos, opt_discr_size) = variant_info_for_adt(cx, layout, adt_def);
783            record(adt_kind.into(), adt_packed, opt_discr_size, variant_infos);
784        }
785
786        ty::Coroutine(def_id, args) => {
787            debug!("print-type-size t: `{:?}` record coroutine", layout.ty);
788            // Coroutines always have a begin/poisoned/end state with additional suspend points
789            let (variant_infos, opt_discr_size) =
790                variant_info_for_coroutine(cx, layout, def_id, args);
791            record(DataTypeKind::Coroutine, false, opt_discr_size, variant_infos);
792        }
793
794        ty::Closure(..) => {
795            debug!("print-type-size t: `{:?}` record closure", layout.ty);
796            record(DataTypeKind::Closure, false, None, vec![]);
797        }
798
799        _ => {
800            debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
801        }
802    };
803}
804
805fn variant_info_for_adt<'tcx>(
806    cx: &LayoutCx<'tcx>,
807    layout: TyAndLayout<'tcx>,
808    adt_def: AdtDef<'tcx>,
809) -> (Vec<VariantInfo>, Option<Size>) {
810    let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| {
811        let mut min_size = Size::ZERO;
812        let field_info: Vec<_> = flds
813            .iter()
814            .enumerate()
815            .map(|(i, &name)| {
816                let field_layout = layout.field(cx, i);
817                let offset = layout.fields.offset(i);
818                min_size = min_size.max(offset + field_layout.size);
819                FieldInfo {
820                    kind: FieldKind::AdtField,
821                    name,
822                    offset: offset.bytes(),
823                    size: field_layout.size.bytes(),
824                    align: field_layout.align.bytes(),
825                    type_name: None,
826                }
827            })
828            .collect();
829
830        VariantInfo {
831            name: n,
832            kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
833            align: layout.align.bytes(),
834            size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
835            fields: field_info,
836        }
837    };
838
839    match layout.variants {
840        Variants::Empty => (vec![], None),
841
842        Variants::Single { index } => {
843            debug!("print-type-size `{:#?}` variant {}", layout, adt_def.variant(index).name);
844            let variant_def = &adt_def.variant(index);
845            let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
846            (vec![build_variant_info(Some(variant_def.name), &fields, layout)], None)
847        }
848
849        Variants::Multiple { tag, ref tag_encoding, .. } => {
850            debug!(
851                "print-type-size `{:#?}` adt general variants def {}",
852                layout.ty,
853                adt_def.variants().len()
854            );
855            let variant_infos: Vec<_> = adt_def
856                .variants()
857                .iter_enumerated()
858                .map(|(i, variant_def)| {
859                    let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
860                    build_variant_info(Some(variant_def.name), &fields, layout.for_variant(cx, i))
861                })
862                .collect();
863
864            (
865                variant_infos,
866                match tag_encoding {
867                    TagEncoding::Direct => Some(tag.size(cx)),
868                    _ => None,
869                },
870            )
871        }
872    }
873}
874
875fn variant_info_for_coroutine<'tcx>(
876    cx: &LayoutCx<'tcx>,
877    layout: TyAndLayout<'tcx>,
878    def_id: DefId,
879    args: ty::GenericArgsRef<'tcx>,
880) -> (Vec<VariantInfo>, Option<Size>) {
881    use itertools::Itertools;
882
883    let Variants::Multiple { tag, ref tag_encoding, tag_field, .. } = layout.variants else {
884        return (vec![], None);
885    };
886
887    let coroutine = cx.tcx().coroutine_layout(def_id, args).unwrap();
888    let upvar_names = cx.tcx().closure_saved_names_of_captured_variables(def_id);
889
890    let mut upvars_size = Size::ZERO;
891    let upvar_fields: Vec<_> = args
892        .as_coroutine()
893        .upvar_tys()
894        .iter()
895        .zip_eq(upvar_names)
896        .enumerate()
897        .map(|(field_idx, (_, name))| {
898            let field_layout = layout.field(cx, field_idx);
899            let offset = layout.fields.offset(field_idx);
900            upvars_size = upvars_size.max(offset + field_layout.size);
901            FieldInfo {
902                kind: FieldKind::Upvar,
903                name: *name,
904                offset: offset.bytes(),
905                size: field_layout.size.bytes(),
906                align: field_layout.align.bytes(),
907                type_name: None,
908            }
909        })
910        .collect();
911
912    let mut variant_infos: Vec<_> = coroutine
913        .variant_fields
914        .iter_enumerated()
915        .map(|(variant_idx, variant_def)| {
916            let variant_layout = layout.for_variant(cx, variant_idx);
917            let mut variant_size = Size::ZERO;
918            let fields = variant_def
919                .iter()
920                .enumerate()
921                .map(|(field_idx, local)| {
922                    let field_name = coroutine.field_names[*local];
923                    let field_layout = variant_layout.field(cx, field_idx);
924                    let offset = variant_layout.fields.offset(field_idx);
925                    // The struct is as large as the last field's end
926                    variant_size = variant_size.max(offset + field_layout.size);
927                    FieldInfo {
928                        kind: FieldKind::CoroutineLocal,
929                        name: field_name.unwrap_or_else(|| {
930                            Symbol::intern(&format!(".coroutine_field{}", local.as_usize()))
931                        }),
932                        offset: offset.bytes(),
933                        size: field_layout.size.bytes(),
934                        align: field_layout.align.bytes(),
935                        // Include the type name if there is no field name, or if the name is the
936                        // __awaitee placeholder symbol which means a child future being `.await`ed.
937                        type_name: (field_name.is_none() || field_name == Some(sym::__awaitee))
938                            .then(|| Symbol::intern(&field_layout.ty.to_string())),
939                    }
940                })
941                .chain(upvar_fields.iter().copied())
942                .collect();
943
944            // If the variant has no state-specific fields, then it's the size of the upvars.
945            if variant_size == Size::ZERO {
946                variant_size = upvars_size;
947            }
948
949            // This `if` deserves some explanation.
950            //
951            // The layout code has a choice of where to place the discriminant of this coroutine.
952            // If the discriminant of the coroutine is placed early in the layout (before the
953            // variant's own fields), then it'll implicitly be counted towards the size of the
954            // variant, since we use the maximum offset to calculate size.
955            //    (side-note: I know this is a bit problematic given upvars placement, etc).
956            //
957            // This is important, since the layout printing code always subtracts this discriminant
958            // size from the variant size if the struct is "enum"-like, so failing to account for it
959            // will either lead to numerical underflow, or an underreported variant size...
960            //
961            // However, if the discriminant is placed past the end of the variant, then we need
962            // to factor in the size of the discriminant manually. This really should be refactored
963            // better, but this "works" for now.
964            if layout.fields.offset(tag_field.as_usize()) >= variant_size {
965                variant_size += match tag_encoding {
966                    TagEncoding::Direct => tag.size(cx),
967                    _ => Size::ZERO,
968                };
969            }
970
971            VariantInfo {
972                name: Some(Symbol::intern(&ty::CoroutineArgs::variant_name(variant_idx))),
973                kind: SizeKind::Exact,
974                size: variant_size.bytes(),
975                align: variant_layout.align.bytes(),
976                fields,
977            }
978        })
979        .collect();
980
981    // The first three variants are hardcoded to be `UNRESUMED`, `RETURNED` and `POISONED`.
982    // We will move the `RETURNED` and `POISONED` elements to the end so we
983    // are left with a sorting order according to the coroutines yield points:
984    // First `Unresumed`, then the `SuspendN` followed by `Returned` and `Panicked` (POISONED).
985    let end_states = variant_infos.drain(1..=2);
986    let end_states: Vec<_> = end_states.collect();
987    variant_infos.extend(end_states);
988
989    (
990        variant_infos,
991        match tag_encoding {
992            TagEncoding::Direct => Some(tag.size(cx)),
993            _ => None,
994        },
995    )
996}