Skip to main content

rustc_ty_utils/layout/
invariant.rs

1use rustc_abi::{BackendRepr, FieldsShape, Scalar, Size, TagEncoding, Variants};
2use rustc_data_structures::assert_matches;
3use rustc_middle::bug;
4use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, TyAndLayout};
5
6/// Enforce some basic invariants on layouts.
7pub(super) fn layout_sanity_check<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLayout<'tcx>) {
8    let tcx = cx.tcx();
9
10    if !layout.size.bytes().is_multiple_of(layout.align.bytes()) {
11        ::rustc_middle::util::bug::bug_fmt(format_args!("size is not a multiple of align, in the following layout:\n{0:#?}",
        layout));bug!("size is not a multiple of align, in the following layout:\n{layout:#?}");
12    }
13    if layout.size.bytes() >= tcx.data_layout.obj_size_bound() {
14        ::rustc_middle::util::bug::bug_fmt(format_args!("size is too large, in the following layout:\n{0:#?}",
        layout));bug!("size is too large, in the following layout:\n{layout:#?}");
15    }
16    // FIXME(#124403): Once `repr_c_enums_larger_than_int` is a hard error, we could assert
17    // here that a repr(c) enum discriminant is never larger than a c_int.
18
19    if !truecfg!(debug_assertions) {
20        // Stop here, the rest is kind of expensive.
21        return;
22    }
23
24    // Type-level uninhabitedness should always imply ABI uninhabitedness. This can be expensive on
25    // big non-exhaustive types, and is [hard to
26    // fix](https://github.com/rust-lang/rust/issues/141006#issuecomment-2883415000) in general.
27    // Only doing this sanity check when debug assertions are turned on avoids the issue for the
28    // very specific case of #140944.
29    if layout.ty.is_privately_uninhabited(tcx, cx.typing_env) {
30        if !layout.is_uninhabited() {
    {
        ::core::panicking::panic_fmt(format_args!("{0:?} is type-level uninhabited but not ABI-uninhabited?",
                layout.ty));
    }
};assert!(
31            layout.is_uninhabited(),
32            "{:?} is type-level uninhabited but not ABI-uninhabited?",
33            layout.ty
34        );
35    }
36
37    /// Yields non-ZST fields of the type
38    fn non_zst_fields<'tcx, 'a>(
39        cx: &'a LayoutCx<'tcx>,
40        layout: &'a TyAndLayout<'tcx>,
41    ) -> impl Iterator<Item = (Size, TyAndLayout<'tcx>)> {
42        (0..layout.layout.fields().count()).filter_map(|i| {
43            let field = layout.field(cx, i);
44            // Also checking `align == 1` here leads to test failures in
45            // `layout/zero-sized-array-union.rs`, where a type has a zero-size field with
46            // alignment 4 that still gets ignored during layout computation (which is okay
47            // since other fields already force alignment 4).
48            let zst = field.is_zst();
49            (!zst).then(|| (layout.fields.offset(i), field))
50        })
51    }
52
53    fn skip_newtypes<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLayout<'tcx>) -> TyAndLayout<'tcx> {
54        if #[allow(non_exhaustive_omitted_patterns)] match layout.layout.variants() {
    Variants::Multiple { .. } => true,
    _ => false,
}matches!(layout.layout.variants(), Variants::Multiple { .. }) {
55            // Definitely not a newtype of anything.
56            return *layout;
57        }
58        let mut fields = non_zst_fields(cx, layout);
59        let Some(first) = fields.next() else {
60            // No fields here, so this could be a primitive or enum -- either way it's not a newtype around a thing
61            return *layout;
62        };
63        if fields.next().is_none() {
64            let (offset, first) = first;
65            if offset == Size::ZERO && first.layout.size() == layout.size {
66                // This is a newtype, so keep recursing.
67                // FIXME(RalfJung): I don't think it would be correct to do any checks for
68                // alignment here, so we don't. Is that correct?
69                return skip_newtypes(cx, &first);
70            }
71        }
72        // No more newtypes here.
73        *layout
74    }
75
76    fn check_layout_abi<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLayout<'tcx>) {
77        // Verify the ABI-mandated alignment and size for scalars.
78        let align = layout.backend_repr.scalar_align(cx);
79        let size = layout.backend_repr.scalar_size(cx);
80        if let Some(align) = align {
81            match (&layout.layout.align().abi, &align) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("alignment mismatch between ABI and layout in {0:#?}",
                        layout)));
        }
    }
};assert_eq!(
82                layout.layout.align().abi,
83                align,
84                "alignment mismatch between ABI and layout in {layout:#?}"
85            );
86        }
87        if let Some(size) = size {
88            match (&layout.layout.size(), &size) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("size mismatch between ABI and layout in {0:#?}",
                        layout)));
        }
    }
};assert_eq!(
89                layout.layout.size(),
90                size,
91                "size mismatch between ABI and layout in {layout:#?}"
92            );
93        }
94
95        // Verify per-ABI invariants
96        match layout.layout.backend_repr() {
97            BackendRepr::Scalar(_) => {
98                // These must always be present for `Scalar` types.
99                let align = align.unwrap();
100                let size = size.unwrap();
101                // Check that this matches the underlying field.
102                let inner = skip_newtypes(cx, layout);
103                if !#[allow(non_exhaustive_omitted_patterns)] match inner.layout.backend_repr()
            {
            BackendRepr::Scalar(_) => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("`Scalar` type {0} is newtype around non-`Scalar` type {1}",
                layout.ty, inner.ty));
    }
};assert!(
104                    matches!(inner.layout.backend_repr(), BackendRepr::Scalar(_)),
105                    "`Scalar` type {} is newtype around non-`Scalar` type {}",
106                    layout.ty,
107                    inner.ty
108                );
109                match inner.layout.fields() {
110                    FieldsShape::Primitive => {
111                        // Fine.
112                    }
113                    FieldsShape::Union(..) => {
114                        // FIXME: I guess we could also check something here? Like, look at all fields?
115                        return;
116                    }
117                    FieldsShape::Arbitrary { .. } => {
118                        // Should be an enum, the only field is the discriminant.
119                        if !inner.ty.is_enum() {
    {
        ::core::panicking::panic_fmt(format_args!("`Scalar` layout for non-primitive non-enum type {0}",
                inner.ty));
    }
};assert!(
120                            inner.ty.is_enum(),
121                            "`Scalar` layout for non-primitive non-enum type {}",
122                            inner.ty
123                        );
124                        match (&inner.layout.fields().count(), &1) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`Scalar` layout for multiple-field type in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
125                            inner.layout.fields().count(),
126                            1,
127                            "`Scalar` layout for multiple-field type in {inner:#?}",
128                        );
129                        let offset = inner.layout.fields().offset(0);
130                        let field = inner.field(cx, 0);
131                        // The field should be at the right offset, and match the `scalar` layout.
132                        match (&offset, &Size::ZERO) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`Scalar` field at non-0 offset in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
133                            offset,
134                            Size::ZERO,
135                            "`Scalar` field at non-0 offset in {inner:#?}",
136                        );
137                        match (&field.size, &size) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`Scalar` field with bad size in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(field.size, size, "`Scalar` field with bad size in {inner:#?}",);
138                        match (&field.align.abi, &align) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`Scalar` field with bad align in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
139                            field.align.abi, align,
140                            "`Scalar` field with bad align in {inner:#?}",
141                        );
142                        if !#[allow(non_exhaustive_omitted_patterns)] match field.backend_repr {
            BackendRepr::Scalar(_) => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("`Scalar` field with bad ABI in {0:#?}",
                inner));
    }
};assert!(
143                            matches!(field.backend_repr, BackendRepr::Scalar(_)),
144                            "`Scalar` field with bad ABI in {inner:#?}",
145                        );
146                    }
147                    _ => {
148                        {
    ::core::panicking::panic_fmt(format_args!("`Scalar` layout for non-primitive non-enum type {0}",
            inner.ty));
};panic!("`Scalar` layout for non-primitive non-enum type {}", inner.ty);
149                    }
150                }
151            }
152            BackendRepr::ScalarPair(scalar1, scalar2) => {
153                // Check that the underlying pair of fields matches.
154                let inner = skip_newtypes(cx, layout);
155                if !#[allow(non_exhaustive_omitted_patterns)] match inner.layout.backend_repr()
            {
            BackendRepr::ScalarPair(..) => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("`ScalarPair` type {0} is newtype around non-`ScalarPair` type {1}",
                layout.ty, inner.ty));
    }
};assert!(
156                    matches!(inner.layout.backend_repr(), BackendRepr::ScalarPair(..)),
157                    "`ScalarPair` type {} is newtype around non-`ScalarPair` type {}",
158                    layout.ty,
159                    inner.ty
160                );
161                if #[allow(non_exhaustive_omitted_patterns)] match inner.layout.variants() {
    Variants::Multiple { .. } => true,
    _ => false,
}matches!(inner.layout.variants(), Variants::Multiple { .. }) {
162                    // FIXME: ScalarPair for enums is enormously complicated and it is very hard
163                    // to check anything about them.
164                    return;
165                }
166                match inner.layout.fields() {
167                    FieldsShape::Arbitrary { .. } => {
168                        // Checked below.
169                    }
170                    FieldsShape::Union(..) => {
171                        // FIXME: I guess we could also check something here? Like, look at all fields?
172                        return;
173                    }
174                    _ => {
175                        {
    ::core::panicking::panic_fmt(format_args!("`ScalarPair` layout with unexpected field shape in {0:#?}",
            inner));
};panic!("`ScalarPair` layout with unexpected field shape in {inner:#?}");
176                    }
177                }
178                let mut fields = non_zst_fields(cx, &inner);
179                let (offset1, field1) = fields.next().unwrap_or_else(|| {
180                    {
    ::core::panicking::panic_fmt(format_args!("`ScalarPair` layout for type with not even one non-ZST field: {0:#?}",
            inner));
}panic!(
181                        "`ScalarPair` layout for type with not even one non-ZST field: {inner:#?}"
182                    )
183                });
184                let (offset2, field2) = fields.next().unwrap_or_else(|| {
185                    {
    ::core::panicking::panic_fmt(format_args!("`ScalarPair` layout for type with less than two non-ZST fields: {0:#?}",
            inner));
}panic!(
186                        "`ScalarPair` layout for type with less than two non-ZST fields: {inner:#?}"
187                    )
188                });
189                match fields.next() {
    None => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val, "None",
            ::core::option::Option::Some(format_args!("`ScalarPair` layout for type with at least three non-ZST fields: {0:#?}",
                    inner)));
    }
};assert_matches!(
190                    fields.next(),
191                    None,
192                    "`ScalarPair` layout for type with at least three non-ZST fields: {inner:#?}"
193                );
194                // The fields might be in opposite order.
195                let (offset1, field1, offset2, field2) = if offset1 <= offset2 {
196                    (offset1, field1, offset2, field2)
197                } else {
198                    (offset2, field2, offset1, field1)
199                };
200                // The fields should be at the right offset, and match the `scalar` layout.
201                let size1 = scalar1.size(cx);
202                let align1 = scalar1.align(cx).abi;
203                let size2 = scalar2.size(cx);
204                let align2 = scalar2.align(cx).abi;
205                match (&offset1, &Size::ZERO) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` first field at non-0 offset in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
206                    offset1,
207                    Size::ZERO,
208                    "`ScalarPair` first field at non-0 offset in {inner:#?}",
209                );
210                match (&field1.size, &size1) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` first field with bad size in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
211                    field1.size, size1,
212                    "`ScalarPair` first field with bad size in {inner:#?}",
213                );
214                match (&field1.align.abi, &align1) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` first field with bad align in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
215                    field1.align.abi, align1,
216                    "`ScalarPair` first field with bad align in {inner:#?}",
217                );
218                match field1.backend_repr {
    BackendRepr::Scalar(_) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "BackendRepr::Scalar(_)",
            ::core::option::Option::Some(format_args!("`ScalarPair` first field with bad ABI in {0:#?}",
                    inner)));
    }
};assert_matches!(
219                    field1.backend_repr,
220                    BackendRepr::Scalar(_),
221                    "`ScalarPair` first field with bad ABI in {inner:#?}",
222                );
223                let field2_offset = size1.align_to(align2);
224                match (&offset2, &field2_offset) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` second field at bad offset in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
225                    offset2, field2_offset,
226                    "`ScalarPair` second field at bad offset in {inner:#?}",
227                );
228                match (&field2.size, &size2) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` second field with bad size in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
229                    field2.size, size2,
230                    "`ScalarPair` second field with bad size in {inner:#?}",
231                );
232                match (&field2.align.abi, &align2) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("`ScalarPair` second field with bad align in {0:#?}",
                        inner)));
        }
    }
};assert_eq!(
233                    field2.align.abi, align2,
234                    "`ScalarPair` second field with bad align in {inner:#?}",
235                );
236                match field2.backend_repr {
    BackendRepr::Scalar(_) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "BackendRepr::Scalar(_)",
            ::core::option::Option::Some(format_args!("`ScalarPair` second field with bad ABI in {0:#?}",
                    inner)));
    }
};assert_matches!(
237                    field2.backend_repr,
238                    BackendRepr::Scalar(_),
239                    "`ScalarPair` second field with bad ABI in {inner:#?}",
240                );
241            }
242            BackendRepr::SimdVector { element, count } => {
243                let align = layout.align.abi;
244                let size = layout.size;
245                let element_align = element.align(cx).abi;
246                let element_size = element.size(cx);
247                // Currently, vectors must always be aligned to at least their elements:
248                if !(align >= element_align) {
    ::core::panicking::panic("assertion failed: align >= element_align")
};assert!(align >= element_align);
249                // And the size has to be element * count plus alignment padding, of course
250                if !(size == (element_size * count).align_to(align)) {
    ::core::panicking::panic("assertion failed: size == (element_size * count).align_to(align)")
};assert!(size == (element_size * count).align_to(align));
251            }
252            BackendRepr::Memory { .. } | BackendRepr::ScalableVector { .. } => {} // Nothing to check.
253        }
254    }
255
256    check_layout_abi(cx, layout);
257
258    match &layout.variants {
259        Variants::Empty => {
260            if !layout.is_uninhabited() {
    ::core::panicking::panic("assertion failed: layout.is_uninhabited()")
};assert!(layout.is_uninhabited());
261        }
262        Variants::Single { index } => {
263            if let Some(variants) = layout.ty.variant_range(tcx) {
264                if !variants.contains(index) {
    ::core::panicking::panic("assertion failed: variants.contains(index)")
};assert!(variants.contains(index));
265            } else {
266                // Types without variants use `0` as dummy variant index.
267                if !(index.as_u32() == 0) {
    ::core::panicking::panic("assertion failed: index.as_u32() == 0")
};assert!(index.as_u32() == 0);
268            }
269        }
270        Variants::Multiple { variants, tag, tag_encoding, .. } => {
271            if let TagEncoding::Niche { niche_start, untagged_variant, niche_variants } =
272                tag_encoding
273            {
274                let niche_size = tag.size(cx);
275                if !(*niche_start <= niche_size.unsigned_int_max()) {
    ::core::panicking::panic("assertion failed: *niche_start <= niche_size.unsigned_int_max()")
};assert!(*niche_start <= niche_size.unsigned_int_max());
276                for (idx, variant) in variants.iter_enumerated() {
277                    // Ensure all inhabited variants are accounted for.
278                    if !variant.is_uninhabited() {
279                        if !(idx == *untagged_variant || niche_variants.contains(&idx)) {
    ::core::panicking::panic("assertion failed: idx == *untagged_variant || niche_variants.contains(&idx)")
};assert!(idx == *untagged_variant || niche_variants.contains(&idx));
280                    }
281
282                    // Ensure that for niche encoded tags the discriminant coincides with the variant index.
283                    let val = layout.ty.discriminant_for_variant(tcx, idx).unwrap().val;
284                    if val != u128::from(idx.as_u32()) {
285                        let adt_def = layout.ty.ty_adt_def().unwrap();
286                        cx.tcx().dcx().span_delayed_bug(
287                            cx.tcx().def_span(adt_def.did()),
288                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("variant {0:?} has discriminant {1:?} in niche-encoded type",
                idx, val))
    })format!(
289                                "variant {idx:?} has discriminant {val:?} in niche-encoded type"
290                            ),
291                        );
292                    }
293                }
294            }
295            for variant in variants.iter() {
296                // No nested "multiple".
297                match variant.variants {
    Variants::Single { .. } => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "Variants::Single { .. }", ::core::option::Option::None);
    }
};assert_matches!(variant.variants, Variants::Single { .. });
298                // Variants should have the same or a smaller size as the full thing,
299                // and same for alignment.
300                if variant.size > layout.size {
301                    ::rustc_middle::util::bug::bug_fmt(format_args!("Type with size {0} bytes has variant with size {1} bytes: {2:#?}",
        layout.size.bytes(), variant.size.bytes(), layout))bug!(
302                        "Type with size {} bytes has variant with size {} bytes: {layout:#?}",
303                        layout.size.bytes(),
304                        variant.size.bytes(),
305                    )
306                }
307                if variant.align.abi > layout.align.abi {
308                    ::rustc_middle::util::bug::bug_fmt(format_args!("Type with alignment {0} bytes has variant with alignment {1} bytes: {2:#?}",
        layout.align.bytes(), variant.align.bytes(), layout))bug!(
309                        "Type with alignment {} bytes has variant with alignment {} bytes: {layout:#?}",
310                        layout.align.bytes(),
311                        variant.align.bytes(),
312                    )
313                }
314                // Skip empty variants.
315                if variant.size == Size::ZERO
316                    || variant.fields.count() == 0
317                    || variant.is_uninhabited()
318                {
319                    // These are never actually accessed anyway, so we can skip the coherence check
320                    // for them. They also fail that check, since they may have
321                    // a different ABI even when the main type is
322                    // `Scalar`/`ScalarPair`. (Note that sometimes, variants with fields have size
323                    // 0, and sometimes, variants without fields have non-0 size.)
324                    continue;
325                }
326                // The top-level ABI and the ABI of the variants should be coherent.
327                let scalar_coherent = |s1: Scalar, s2: Scalar| {
328                    s1.size(cx) == s2.size(cx) && s1.align(cx) == s2.align(cx)
329                };
330                let abi_coherent = match (layout.backend_repr, variant.backend_repr) {
331                    (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => scalar_coherent(s1, s2),
332                    (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
333                        scalar_coherent(a1, a2) && scalar_coherent(b1, b2)
334                    }
335                    (BackendRepr::Memory { .. }, _) => true,
336                    _ => false,
337                };
338                if !abi_coherent {
339                    ::rustc_middle::util::bug::bug_fmt(format_args!("Variant ABI is incompatible with top-level ABI:\nvariant={0:#?}\nTop-level: {1:#?}",
        variant, layout));bug!(
340                        "Variant ABI is incompatible with top-level ABI:\nvariant={:#?}\nTop-level: {layout:#?}",
341                        variant
342                    );
343                }
344            }
345        }
346    }
347}