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