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