Skip to main content

rustc_ty_utils/
layout.rs

1use hir::def_id::DefId;
2use rustc_abi as abi;
3use rustc_abi::Integer::{I8, I32};
4use rustc_abi::Primitive::{self, Float, Int, Pointer};
5use rustc_abi::{
6    AddressSpace, BackendRepr, FIRST_VARIANT, FieldIdx, FieldsShape, HasDataLayout, Layout,
7    LayoutCalculatorError, LayoutData, Niche, ReprOptions, Scalar, Size, StructKind, TagEncoding,
8    VariantIdx, Variants, WrappingRange,
9};
10use rustc_hashes::Hash64;
11use rustc_hir as hir;
12use rustc_hir::find_attr;
13use rustc_index::{Idx as _, IndexVec};
14use rustc_middle::bug;
15use rustc_middle::query::Providers;
16use rustc_middle::traits::ObligationCause;
17use rustc_middle::ty::layout::{
18    FloatExt, HasTyCtxt, IntegerExt, LayoutCx, LayoutError, LayoutOf, SimdLayoutError, TyAndLayout,
19};
20use rustc_middle::ty::print::with_no_trimmed_paths;
21use rustc_middle::ty::{
22    self, AdtDef, CoroutineArgsExt, EarlyBinder, PseudoCanonicalInput, Ty, TyCtxt, TypeVisitableExt,
23};
24use rustc_session::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
25use rustc_span::{Symbol, sym};
26use tracing::{debug, instrument};
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#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("layout_of",
                                    "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(36u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let PseudoCanonicalInput { typing_env, value: ty } = query;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:42",
                                    "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(42u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                                    ::tracing_core::field::FieldSet::new(&["ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let typing_env = typing_env.with_post_analysis_normalized(tcx);
            let unnormalized_ty = ty;
            let ty =
                match tcx.try_normalize_erasing_regions(typing_env, ty) {
                    Ok(t) => t,
                    Err(normalization_error) => {
                        return Err(tcx.arena.alloc(LayoutError::NormalizationFailure(ty,
                                        normalization_error)));
                    }
                };
            if ty != unnormalized_ty {
                return tcx.layout_of(typing_env.as_query_input(ty));
            }
            let cx = LayoutCx::new(tcx, typing_env);
            let layout = layout_of_uncached(&cx, ty)?;
            let layout = TyAndLayout { ty, layout };
            if cx.tcx().sess.opts.unstable_opts.print_type_sizes {
                record_layout_for_printing(&cx, layout);
            }
            invariant::layout_sanity_check(&cx, &layout);
            Ok(layout)
        }
    }
}#[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            if !field.layout.is_unsized() {
    {
        ::core::panicking::panic_fmt(format_args!("invalid layout error {0:#?}",
                err));
    }
};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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered unexpected unsized field in layout of {0:?}: {1:#?}",
                ty, field))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("computed layout of empty union: {0:?}",
                ty))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("computed impossible repr (packed enum?): {0:?}",
                ty))
    })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                ::rustc_middle::util::bug::bug_fmt(format_args!("failed to normalize const, but it is not generic: {0:?}",
        ct));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            ::rustc_middle::util::bug::bug_fmt(format_args!("layout_of: unexpected const: {0:?}",
        ct));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        if !(size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: size.bits() <= 128")
};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    if true {
    if !!ty.has_non_region_infer() {
        ::core::panicking::panic("assertion failed: !ty.has_non_region_infer()")
    };
};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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pattern type ranges cannot wrap: {0}..={1}",
                start, end))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pattern type ranges cannot wrap: {0}..={1}",
                range.start, range.end))
    })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                        ::rustc_middle::util::bug::bug_fmt(format_args!("pattern type with range but not scalar layout: {0:?}, {1:?}",
        ty, layout))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                        ::rustc_middle::util::bug::bug_fmt(format_args!("pattern type with `!null` pattern but not scalar/pair layout: {0:?}, {1:?}",
        ty, layout))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                                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("mixed or patterns are not allowed")));
}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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only signed integer base types are allowed for or-pattern pattern types at present"))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the only or-pattern types allowed are two range patterns that are directly connected at their overflow site"))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only non-overlapping pattern type ranges are allowed at present"))
    })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(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("one pattern needs to end at `{1}::MAX`, but was {0} instead",
                second.1, ty))
    })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                            ::rustc_middle::util::bug::bug_fmt(format_args!("pattern type with range but not scalar layout: {0:?}, {1:?}",
        ty, layout))bug!(
363                                "pattern type with range but not scalar layout: {ty:?}, {layout:?}"
364                            )
365                        }
366                    }
367                    ty::PatternKind::NotNull => ::rustc_middle::util::bug::bug_fmt(format_args!("or patterns can\'t contain `!null` patterns"))bug!("or patterns can't contain `!null` patterns"),
368                    ty::PatternKind::Or(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("patterns cannot have nested or patterns"))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                in_memory_order: [FieldIdx::new(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 = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::FnDef(..) => true,
    _ => false,
}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                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:551",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(551u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coroutine layout ({0:?}): {1:#?}",
                                                    ty, layout) as &dyn Value))])
            });
    } else { ; }
};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        // Scalable vector types
571        //
572        // ```rust (ignore, example)
573        // #[rustc_scalable_vector(3)]
574        // struct svuint32_t(u32);
575        //
576        // #[rustc_scalable_vector]
577        // struct svuint32x2_t(svuint32_t, svuint32_t);
578        // ```
579        ty::Adt(def, _args) if def.repr().scalable() => {
580            let Some((element_count, element_ty, number_of_vectors)) =
581                ty.scalable_vector_parts(tcx)
582            else {
583                let guar = tcx
584                    .dcx()
585                    .delayed_bug("`#[rustc_scalable_vector]` was applied to an invalid type");
586                return Err(error(cx, LayoutError::ReferencesError(guar)));
587            };
588
589            let element_layout = cx.layout_of(element_ty)?;
590            map_layout(cx.calc.scalable_vector_type(
591                element_layout,
592                element_count as u64,
593                number_of_vectors,
594            ))?
595        }
596
597        // SIMD vector types.
598        ty::Adt(def, args) if def.repr().simd() => {
599            // Supported SIMD vectors are ADTs with a single array field:
600            //
601            // * #[repr(simd)] struct S([T; 4])
602            //
603            // where T is a primitive scalar (integer/float/pointer).
604            let Some(ty::Array(e_ty, e_len)) = def
605                .is_struct()
606                .then(|| &def.variant(FIRST_VARIANT).fields)
607                .filter(|fields| fields.len() == 1)
608                .map(|fields| *fields[FieldIdx::ZERO].ty(tcx, args).kind())
609            else {
610                // Invalid SIMD types should have been caught by typeck by now.
611                let guar = tcx.dcx().delayed_bug("#[repr(simd)] was applied to an invalid ADT");
612                return Err(error(cx, LayoutError::ReferencesError(guar)));
613            };
614
615            let e_len = extract_const_value(cx, ty, e_len)?
616                .try_to_target_usize(tcx)
617                .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
618
619            let e_ly = cx.layout_of(e_ty)?;
620
621            // Check for the rustc_simd_monomorphize_lane_limit attribute and check the lane limit
622            if let Some(limit) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def.did(), &tcx)
                {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcSimdMonomorphizeLaneLimit(limit))
                        => {
                        break 'done Some(limit);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(
623                tcx, def.did(),
624                RustcSimdMonomorphizeLaneLimit(limit) => limit
625            ) {
626                if !limit.value_within_limit(e_len as usize) {
627                    return Err(map_error(
628                        &cx,
629                        ty,
630                        rustc_abi::LayoutCalculatorError::OversizedSimdType {
631                            max_lanes: limit.0 as u64,
632                        },
633                    ));
634                }
635            }
636
637            map_layout(cx.calc.simd_type(e_ly, e_len, def.repr().packed()))?
638        }
639
640        // ADTs.
641        ty::Adt(def, args) => {
642            // Cache the field layouts.
643            let variants = def
644                .variants()
645                .iter()
646                .map(|v| {
647                    v.fields
648                        .iter()
649                        .map(|field| cx.layout_of(field.ty(tcx, args)))
650                        .try_collect::<IndexVec<_, _>>()
651                })
652                .try_collect::<IndexVec<VariantIdx, _>>()?;
653
654            if def.is_union() {
655                if def.repr().pack.is_some() && def.repr().align.is_some() {
656                    let guar = tcx.dcx().span_delayed_bug(
657                        tcx.def_span(def.did()),
658                        "union cannot be packed and aligned",
659                    );
660                    return Err(error(cx, LayoutError::ReferencesError(guar)));
661                }
662
663                return map_layout(cx.calc.layout_of_union(&def.repr(), &variants));
664            }
665
666            // UnsafeCell and UnsafePinned both disable niche optimizations
667            let is_special_no_niche = def.is_unsafe_cell() || def.is_unsafe_pinned();
668
669            let discr_range_of_repr =
670                |min, max| abi::Integer::discr_range_of_repr(tcx, ty, &def.repr(), min, max);
671
672            let discriminants_iter = || {
673                def.is_enum()
674                    .then(|| def.discriminants(tcx).map(|(v, d)| (v, d.val as i128)))
675                    .into_iter()
676                    .flatten()
677            };
678
679            let maybe_unsized = def.is_struct()
680                && def.non_enum_variant().tail_opt().is_some_and(|last_field| {
681                    let typing_env = ty::TypingEnv::post_analysis(tcx, def.did());
682                    !tcx.type_of(last_field.did).instantiate_identity().is_sized(tcx, typing_env)
683                });
684
685            let layout = cx
686                .calc
687                .layout_of_struct_or_enum(
688                    &def.repr(),
689                    &variants,
690                    def.is_enum(),
691                    is_special_no_niche,
692                    tcx.layout_scalar_valid_range(def.did()),
693                    discr_range_of_repr,
694                    discriminants_iter(),
695                    !maybe_unsized,
696                )
697                .map_err(|err| map_error(cx, ty, err))?;
698
699            if !maybe_unsized && layout.is_unsized() {
700                ::rustc_middle::util::bug::bug_fmt(format_args!("got unsized layout for type that cannot be unsized {0:?}: {1:#?}",
        ty, layout));bug!("got unsized layout for type that cannot be unsized {ty:?}: {layout:#?}");
701            }
702
703            // If the struct tail is sized and can be unsized, check that unsizing doesn't move the fields around.
704            if truecfg!(debug_assertions)
705                && maybe_unsized
706                && def.non_enum_variant().tail().ty(tcx, args).is_sized(tcx, cx.typing_env)
707            {
708                let mut variants = variants;
709                let tail_replacement = cx.layout_of(Ty::new_slice(tcx, tcx.types.u8)).unwrap();
710                *variants[FIRST_VARIANT].raw.last_mut().unwrap() = tail_replacement;
711
712                let Ok(unsized_layout) = cx.calc.layout_of_struct_or_enum(
713                    &def.repr(),
714                    &variants,
715                    def.is_enum(),
716                    is_special_no_niche,
717                    tcx.layout_scalar_valid_range(def.did()),
718                    discr_range_of_repr,
719                    discriminants_iter(),
720                    !maybe_unsized,
721                ) else {
722                    ::rustc_middle::util::bug::bug_fmt(format_args!("failed to compute unsized layout of {0:?}",
        ty));bug!("failed to compute unsized layout of {ty:?}");
723                };
724
725                let FieldsShape::Arbitrary { offsets: sized_offsets, .. } = &layout.fields else {
726                    ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected FieldsShape for sized layout of {1:?}: {0:?}",
        layout.fields, ty));bug!("unexpected FieldsShape for sized layout of {ty:?}: {:?}", layout.fields);
727                };
728                let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } =
729                    &unsized_layout.fields
730                else {
731                    ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected FieldsShape for unsized layout of {1:?}: {0:?}",
        unsized_layout.fields, ty));bug!(
732                        "unexpected FieldsShape for unsized layout of {ty:?}: {:?}",
733                        unsized_layout.fields
734                    );
735                };
736
737                let (sized_tail, sized_fields) = sized_offsets.raw.split_last().unwrap();
738                let (unsized_tail, unsized_fields) = unsized_offsets.raw.split_last().unwrap();
739
740                if sized_fields != unsized_fields {
741                    ::rustc_middle::util::bug::bug_fmt(format_args!("unsizing {0:?} changed field order!\n{1:?}\n{2:?}",
        ty, layout, unsized_layout));bug!("unsizing {ty:?} changed field order!\n{layout:?}\n{unsized_layout:?}");
742                }
743
744                if sized_tail < unsized_tail {
745                    ::rustc_middle::util::bug::bug_fmt(format_args!("unsizing {0:?} moved tail backwards!\n{1:?}\n{2:?}",
        ty, layout, unsized_layout));bug!("unsizing {ty:?} moved tail backwards!\n{layout:?}\n{unsized_layout:?}");
746                }
747            }
748
749            tcx.mk_layout(layout)
750        }
751
752        ty::UnsafeBinder(bound_ty) => {
753            let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
754            cx.layout_of(ty)?.layout
755        }
756
757        // Types with no meaningful known layout.
758        ty::Param(_) | ty::Placeholder(..) => {
759            return Err(error(cx, LayoutError::TooGeneric(ty)));
760        }
761
762        ty::Alias(..) => {
763            // In case we're still in a generic context, aliases might be rigid. E.g.
764            // if we've got a `T: Trait` where-bound, `T::Assoc` cannot be normalized
765            // in the current context.
766            //
767            // For some builtin traits, generic aliases can be rigid even in an empty environment,
768            // e.g. `<T as Pointee>::Metadata`.
769            //
770            // Due to trivial bounds, this can even be the case if the alias does not reference
771            // any generic parameters, e.g. a `for<'a> u32: Trait<'a>` where-bound means that
772            // `<u32 as Trait<'static>>::Assoc` is rigid.
773            let err = if ty.has_param() || !cx.typing_env.param_env.caller_bounds().is_empty() {
774                LayoutError::TooGeneric(ty)
775            } else {
776                LayoutError::ReferencesError(cx.tcx().dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected rigid alias in layout_of after normalization: {0:?}",
                ty))
    })format!(
777                    "unexpected rigid alias in layout_of after normalization: {ty:?}"
778                )))
779            };
780            return Err(error(cx, err));
781        }
782
783        ty::Bound(..) | ty::CoroutineWitness(..) | ty::Infer(_) | ty::Error(_) => {
784            // `ty::Error` is handled at the top of this function.
785            ::rustc_middle::util::bug::bug_fmt(format_args!("layout_of: unexpected type `{0}`",
        ty))bug!("layout_of: unexpected type `{ty}`")
786        }
787    })
788}
789
790fn record_layout_for_printing<'tcx>(cx: &LayoutCx<'tcx>, layout: TyAndLayout<'tcx>) {
791    // Ignore layouts that are done with non-empty environments or
792    // non-monomorphic layouts, as the user only wants to see the stuff
793    // resulting from the final codegen session.
794    if layout.ty.has_non_region_param() || !cx.typing_env.param_env.caller_bounds().is_empty() {
795        return;
796    }
797
798    // (delay format until we actually need it)
799    let record = |kind, packed, opt_discr_size, variants| {
800        let type_desc = {
    let _guard = NoTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("{0}", layout.ty))
        })
}with_no_trimmed_paths!(format!("{}", layout.ty));
801        cx.tcx().sess.code_stats.record_type_size(
802            kind,
803            type_desc,
804            layout.align.abi,
805            layout.size,
806            packed,
807            opt_discr_size,
808            variants,
809        );
810    };
811
812    match *layout.ty.kind() {
813        ty::Adt(adt_def, _) => {
814            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:814",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(814u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size t: `{0:?}` process adt",
                                                    layout.ty) as &dyn Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` process adt", layout.ty);
815            let adt_kind = adt_def.adt_kind();
816            let adt_packed = adt_def.repr().pack.is_some();
817            let (variant_infos, opt_discr_size) = variant_info_for_adt(cx, layout, adt_def);
818            record(adt_kind.into(), adt_packed, opt_discr_size, variant_infos);
819        }
820
821        ty::Coroutine(def_id, args) => {
822            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:822",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(822u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size t: `{0:?}` record coroutine",
                                                    layout.ty) as &dyn Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` record coroutine", layout.ty);
823            // Coroutines always have a begin/poisoned/end state with additional suspend points
824            let (variant_infos, opt_discr_size) =
825                variant_info_for_coroutine(cx, layout, def_id, args);
826            record(DataTypeKind::Coroutine, false, opt_discr_size, variant_infos);
827        }
828
829        ty::Closure(..) => {
830            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:830",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(830u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size t: `{0:?}` record closure",
                                                    layout.ty) as &dyn Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` record closure", layout.ty);
831            record(DataTypeKind::Closure, false, None, ::alloc::vec::Vec::new()vec![]);
832        }
833
834        _ => {
835            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:835",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(835u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size t: `{0:?}` skip non-nominal",
                                                    layout.ty) as &dyn Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
836        }
837    };
838}
839
840fn variant_info_for_adt<'tcx>(
841    cx: &LayoutCx<'tcx>,
842    layout: TyAndLayout<'tcx>,
843    adt_def: AdtDef<'tcx>,
844) -> (Vec<VariantInfo>, Option<Size>) {
845    let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| {
846        let mut min_size = Size::ZERO;
847        let field_info: Vec<_> = flds
848            .iter()
849            .enumerate()
850            .map(|(i, &name)| {
851                let field_layout = layout.field(cx, i);
852                let offset = layout.fields.offset(i);
853                min_size = min_size.max(offset + field_layout.size);
854                FieldInfo {
855                    kind: FieldKind::AdtField,
856                    name,
857                    offset: offset.bytes(),
858                    size: field_layout.size.bytes(),
859                    align: field_layout.align.bytes(),
860                    type_name: None,
861                }
862            })
863            .collect();
864
865        VariantInfo {
866            name: n,
867            kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
868            align: layout.align.bytes(),
869            size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
870            fields: field_info,
871        }
872    };
873
874    match layout.variants {
875        Variants::Empty => (::alloc::vec::Vec::new()vec![], None),
876
877        Variants::Single { index } => {
878            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:878",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(878u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size `{0:#?}` variant {1}",
                                                    layout, adt_def.variant(index).name) as &dyn Value))])
            });
    } else { ; }
};debug!("print-type-size `{:#?}` variant {}", layout, adt_def.variant(index).name);
879            let variant_def = &adt_def.variant(index);
880            let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
881            (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [build_variant_info(Some(variant_def.name), &fields, layout)]))vec![build_variant_info(Some(variant_def.name), &fields, layout)], None)
882        }
883
884        Variants::Multiple { tag, ref tag_encoding, .. } => {
885            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/layout.rs:885",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(885u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("print-type-size `{0:#?}` adt general variants def {1}",
                                                    layout.ty, adt_def.variants().len()) as &dyn Value))])
            });
    } else { ; }
};debug!(
886                "print-type-size `{:#?}` adt general variants def {}",
887                layout.ty,
888                adt_def.variants().len()
889            );
890            let variant_infos: Vec<_> = adt_def
891                .variants()
892                .iter_enumerated()
893                .map(|(i, variant_def)| {
894                    let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
895                    build_variant_info(Some(variant_def.name), &fields, layout.for_variant(cx, i))
896                })
897                .collect();
898
899            (
900                variant_infos,
901                match tag_encoding {
902                    TagEncoding::Direct => Some(tag.size(cx)),
903                    _ => None,
904                },
905            )
906        }
907    }
908}
909
910fn variant_info_for_coroutine<'tcx>(
911    cx: &LayoutCx<'tcx>,
912    layout: TyAndLayout<'tcx>,
913    def_id: DefId,
914    args: ty::GenericArgsRef<'tcx>,
915) -> (Vec<VariantInfo>, Option<Size>) {
916    use itertools::Itertools;
917
918    let Variants::Multiple { tag, ref tag_encoding, tag_field, .. } = layout.variants else {
919        return (::alloc::vec::Vec::new()vec![], None);
920    };
921
922    let coroutine = cx.tcx().coroutine_layout(def_id, args).unwrap();
923    let upvar_names = cx.tcx().closure_saved_names_of_captured_variables(def_id);
924
925    let mut upvars_size = Size::ZERO;
926    let upvar_fields: Vec<_> = args
927        .as_coroutine()
928        .upvar_tys()
929        .iter()
930        .zip_eq(upvar_names)
931        .enumerate()
932        .map(|(field_idx, (_, name))| {
933            let field_layout = layout.field(cx, field_idx);
934            let offset = layout.fields.offset(field_idx);
935            upvars_size = upvars_size.max(offset + field_layout.size);
936            FieldInfo {
937                kind: FieldKind::Upvar,
938                name: *name,
939                offset: offset.bytes(),
940                size: field_layout.size.bytes(),
941                align: field_layout.align.bytes(),
942                type_name: None,
943            }
944        })
945        .collect();
946
947    let mut variant_infos: Vec<_> = coroutine
948        .variant_fields
949        .iter_enumerated()
950        .map(|(variant_idx, variant_def)| {
951            let variant_layout = layout.for_variant(cx, variant_idx);
952            let mut variant_size = Size::ZERO;
953            let fields = variant_def
954                .iter()
955                .enumerate()
956                .map(|(field_idx, local)| {
957                    let field_name = coroutine.field_names[*local];
958                    let field_layout = variant_layout.field(cx, field_idx);
959                    let offset = variant_layout.fields.offset(field_idx);
960                    // The struct is as large as the last field's end
961                    variant_size = variant_size.max(offset + field_layout.size);
962                    FieldInfo {
963                        kind: FieldKind::CoroutineLocal,
964                        name: field_name.unwrap_or_else(|| {
965                            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".coroutine_field{0}",
                local.as_usize()))
    })format!(".coroutine_field{}", local.as_usize()))
966                        }),
967                        offset: offset.bytes(),
968                        size: field_layout.size.bytes(),
969                        align: field_layout.align.bytes(),
970                        // Include the type name if there is no field name, or if the name is the
971                        // __awaitee placeholder symbol which means a child future being `.await`ed.
972                        type_name: (field_name.is_none() || field_name == Some(sym::__awaitee))
973                            .then(|| Symbol::intern(&field_layout.ty.to_string())),
974                    }
975                })
976                .chain(upvar_fields.iter().copied())
977                .collect();
978
979            // If the variant has no state-specific fields, then it's the size of the upvars.
980            if variant_size == Size::ZERO {
981                variant_size = upvars_size;
982            }
983
984            // This `if` deserves some explanation.
985            //
986            // The layout code has a choice of where to place the discriminant of this coroutine.
987            // If the discriminant of the coroutine is placed early in the layout (before the
988            // variant's own fields), then it'll implicitly be counted towards the size of the
989            // variant, since we use the maximum offset to calculate size.
990            //    (side-note: I know this is a bit problematic given upvars placement, etc).
991            //
992            // This is important, since the layout printing code always subtracts this discriminant
993            // size from the variant size if the struct is "enum"-like, so failing to account for it
994            // will either lead to numerical underflow, or an underreported variant size...
995            //
996            // However, if the discriminant is placed past the end of the variant, then we need
997            // to factor in the size of the discriminant manually. This really should be refactored
998            // better, but this "works" for now.
999            if layout.fields.offset(tag_field.as_usize()) >= variant_size {
1000                variant_size += match tag_encoding {
1001                    TagEncoding::Direct => tag.size(cx),
1002                    _ => Size::ZERO,
1003                };
1004            }
1005
1006            VariantInfo {
1007                name: Some(Symbol::intern(&ty::CoroutineArgs::variant_name(variant_idx))),
1008                kind: SizeKind::Exact,
1009                size: variant_size.bytes(),
1010                align: variant_layout.align.bytes(),
1011                fields,
1012            }
1013        })
1014        .collect();
1015
1016    // The first three variants are hardcoded to be `UNRESUMED`, `RETURNED` and `POISONED`.
1017    // We will move the `RETURNED` and `POISONED` elements to the end so we
1018    // are left with a sorting order according to the coroutines yield points:
1019    // First `Unresumed`, then the `SuspendN` followed by `Returned` and `Panicked` (POISONED).
1020    let end_states = variant_infos.drain(1..=2);
1021    let end_states: Vec<_> = end_states.collect();
1022    variant_infos.extend(end_states);
1023
1024    (
1025        variant_infos,
1026        match tag_encoding {
1027            TagEncoding::Direct => Some(tag.size(cx)),
1028            _ => None,
1029        },
1030    )
1031}