Skip to main content

rustc_abi/layout/
simple.rs

1use std::num::NonZero;
2
3use rustc_hashes::Hash64;
4use rustc_index::{Idx, IndexVec};
5
6use crate::{
7    Align, BackendRepr, FieldsShape, HasDataLayout, LayoutData, Niche, Primitive, Scalar, Size,
8    Variants,
9};
10
11/// "Simple" layout constructors that cannot fail.
12impl<FieldIdx: Idx, VariantIdx: Idx> LayoutData<FieldIdx, VariantIdx> {
13    pub fn unit(sized: bool) -> Self {
14        LayoutData {
15            variants: Variants::Single { index: VariantIdx::new(0) },
16            fields: FieldsShape::Arbitrary {
17                offsets: IndexVec::new(),
18                in_memory_order: IndexVec::new(),
19            },
20            backend_repr: BackendRepr::Memory { sized },
21            largest_niche: None,
22            uninhabited: false,
23            align: Align::ONE,
24            size: Size::ZERO,
25            max_repr_align: None,
26            unadjusted_abi_align: Align::ONE,
27            repr_c: false,
28            randomization_seed: Hash64::new(0),
29        }
30    }
31
32    pub fn never_type() -> Self {
33        // This is also used for uninhabited enums, so we use `Variants::Empty`.
34        LayoutData {
35            variants: Variants::Empty,
36            fields: FieldsShape::Primitive,
37            backend_repr: BackendRepr::Memory { sized: true },
38            largest_niche: None,
39            uninhabited: true,
40            align: Align::ONE,
41            size: Size::ZERO,
42            max_repr_align: None,
43            unadjusted_abi_align: Align::ONE,
44            repr_c: false,
45            randomization_seed: Hash64::ZERO,
46        }
47    }
48
49    pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
50        let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar);
51        let size = scalar.size(cx);
52        let align = scalar.default_align(cx);
53
54        let range = scalar.valid_range(cx);
55
56        // All primitive types for which we don't have subtype coercions should get a distinct seed,
57        // so that types wrapping them can use randomization to arrive at distinct layouts.
58        //
59        // Some type information is already lost at this point, so as an approximation we derive
60        // the seed from what remains. For example on 64-bit targets usize and u64 can no longer
61        // be distinguished.
62        let randomization_seed = size
63            .bytes()
64            .wrapping_add(
65                match scalar.primitive() {
66                    Primitive::Int(_, true) => 1,
67                    Primitive::Int(_, false) => 2,
68                    Primitive::Float(_) => 3,
69                    Primitive::Pointer(_) => 4,
70                } << 32,
71            )
72            // distinguishes references from pointers
73            .wrapping_add((range.start as u64).rotate_right(16))
74            // distinguishes char from u32 and bool from u8
75            .wrapping_add((range.end as u64).rotate_right(16));
76
77        LayoutData {
78            variants: Variants::Single { index: VariantIdx::new(0) },
79            fields: FieldsShape::Primitive,
80            backend_repr: BackendRepr::Scalar(scalar),
81            largest_niche,
82            uninhabited: false,
83            size,
84            align,
85            max_repr_align: None,
86            unadjusted_abi_align: align,
87            repr_c: false,
88            randomization_seed: Hash64::new(randomization_seed),
89        }
90    }
91
92    pub fn scalar_pair<C: HasDataLayout>(cx: &C, a: Scalar, b: Scalar) -> Self {
93        let dl = cx.data_layout();
94        let b_align = b.default_align(dl);
95        let align = a.default_align(dl).max(b_align).max(dl.aggregate_align);
96        let b_offset = a.size(dl).align_to(b_align);
97        let size = (b_offset + b.size(dl)).align_to(align);
98
99        // HACK(nox): We iter on `b` and then `a` because `max_by_key`
100        // returns the last maximum.
101        let largest_niche = Niche::from_scalar(dl, b_offset, b)
102            .into_iter()
103            .chain(Niche::from_scalar(dl, Size::ZERO, a))
104            .max_by_key(|niche| niche.available(dl));
105
106        let combined_seed = a.size(dl).bytes().wrapping_add(b.size(dl).bytes());
107
108        LayoutData {
109            variants: Variants::Single { index: VariantIdx::new(0) },
110            fields: FieldsShape::Arbitrary {
111                offsets: [Size::ZERO, b_offset].into(),
112                in_memory_order: [FieldIdx::new(0), FieldIdx::new(1)].into(),
113            },
114            backend_repr: BackendRepr::ScalarPair { a, b, b_offset },
115            largest_niche,
116            uninhabited: false,
117            align,
118            size,
119            max_repr_align: None,
120            unadjusted_abi_align: align,
121            repr_c: false,
122            randomization_seed: Hash64::new(combined_seed),
123        }
124    }
125
126    /// Returns a dummy layout for an uninhabited variant.
127    ///
128    /// Uninhabited variants get pruned as part of the layout calculation,
129    /// so this can be used after the fact to reconstitute a layout.
130    pub fn uninhabited_variant(index: VariantIdx, fields: usize) -> Self {
131        LayoutData {
132            variants: Variants::Single { index },
133            fields: match NonZero::new(fields) {
134                Some(fields) => FieldsShape::Union(fields),
135                None => FieldsShape::Arbitrary {
136                    offsets: IndexVec::new(),
137                    in_memory_order: IndexVec::new(),
138                },
139            },
140            backend_repr: BackendRepr::Memory { sized: true },
141            largest_niche: None,
142            uninhabited: true,
143            align: Align::ONE,
144            size: Size::ZERO,
145            max_repr_align: None,
146            unadjusted_abi_align: Align::ONE,
147            repr_c: false,
148            // Variant layouts never flow back into actual layout computations,
149            // so dummy values are fine here.
150            randomization_seed: Hash64::ZERO,
151        }
152    }
153
154    /// Returns a layout for an inhabited variant.
155    pub fn for_variant(parent: &Self, index: VariantIdx) -> Self {
156        let layout = match &parent.variants {
157            Variants::Multiple { variants, .. } => &variants[index],
158            _ => {
    ::core::panicking::panic_fmt(format_args!("Expected multi-variant layout in `Layout::for_variant`"));
}panic!("Expected multi-variant layout in `Layout::for_variant`"),
159        };
160
161        Self {
162            fields: FieldsShape::Arbitrary {
163                offsets: layout.field_offsets.clone(),
164                in_memory_order: layout.fields_in_memory_order.clone(),
165            },
166            variants: Variants::Single { index },
167            backend_repr: layout.backend_repr,
168            largest_niche: layout.largest_niche,
169            uninhabited: layout.uninhabited,
170            size: layout.size,
171            align: parent.align,
172            max_repr_align: parent.max_repr_align,
173            unadjusted_abi_align: parent.unadjusted_abi_align,
174            repr_c: parent.repr_c,
175            // Variant layouts never flow back into actual layout computations,
176            // so dummy values are fine here.
177            randomization_seed: Hash64::ZERO,
178        }
179    }
180}