]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/table.rs
Auto merge of #97802 - Enselic:add-no_ignore_sigkill-feature, r=joshtriplett
[rust.git] / compiler / rustc_metadata / src / rmeta / table.rs
1 use crate::rmeta::*;
2
3 use rustc_data_structures::fingerprint::Fingerprint;
4 use rustc_hir::def::{CtorKind, CtorOf};
5 use rustc_index::vec::Idx;
6 use rustc_middle::ty::ParameterizedOverTcx;
7 use rustc_serialize::opaque::FileEncoder;
8 use rustc_serialize::Encoder as _;
9 use rustc_span::hygiene::MacroKind;
10 use std::convert::TryInto;
11 use std::marker::PhantomData;
12 use std::num::NonZeroUsize;
13
14 /// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
15 /// Used mainly for Lazy positions and lengths.
16 /// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
17 /// but this has no impact on safety.
18 pub(super) trait FixedSizeEncoding: Default {
19     /// This should be `[u8; BYTE_LEN]`;
20     type ByteArray;
21
22     fn from_bytes(b: &Self::ByteArray) -> Self;
23     fn write_to_bytes(self, b: &mut Self::ByteArray);
24 }
25
26 impl FixedSizeEncoding for u32 {
27     type ByteArray = [u8; 4];
28
29     #[inline]
30     fn from_bytes(b: &[u8; 4]) -> Self {
31         Self::from_le_bytes(*b)
32     }
33
34     #[inline]
35     fn write_to_bytes(self, b: &mut [u8; 4]) {
36         *b = self.to_le_bytes();
37     }
38 }
39
40 macro_rules! fixed_size_enum {
41     ($ty:ty { $(($($pat:tt)*))* }) => {
42         impl FixedSizeEncoding for Option<$ty> {
43             type ByteArray = [u8;1];
44
45             #[inline]
46             fn from_bytes(b: &[u8;1]) -> Self {
47                 use $ty::*;
48                 if b[0] == 0 {
49                     return None;
50                 }
51                 match b[0] - 1 {
52                     $(${index()} => Some($($pat)*),)*
53                     _ => panic!("Unexpected {} code: {:?}", stringify!($ty), b[0]),
54                 }
55             }
56
57             #[inline]
58             fn write_to_bytes(self, b: &mut [u8;1]) {
59                 use $ty::*;
60                 b[0] = match self {
61                     None => 0,
62                     $(Some($($pat)*) => 1 + ${index()},)*
63                 }
64             }
65         }
66     }
67 }
68
69 fixed_size_enum! {
70     DefKind {
71         ( Mod                                      )
72         ( Struct                                   )
73         ( Union                                    )
74         ( Enum                                     )
75         ( Variant                                  )
76         ( Trait                                    )
77         ( TyAlias                                  )
78         ( ForeignTy                                )
79         ( TraitAlias                               )
80         ( AssocTy                                  )
81         ( TyParam                                  )
82         ( Fn                                       )
83         ( Const                                    )
84         ( ConstParam                               )
85         ( AssocFn                                  )
86         ( AssocConst                               )
87         ( ExternCrate                              )
88         ( Use                                      )
89         ( ForeignMod                               )
90         ( AnonConst                                )
91         ( InlineConst                              )
92         ( OpaqueTy                                 )
93         ( Field                                    )
94         ( LifetimeParam                            )
95         ( GlobalAsm                                )
96         ( Impl                                     )
97         ( Closure                                  )
98         ( Generator                                )
99         ( Static(ast::Mutability::Not)             )
100         ( Static(ast::Mutability::Mut)             )
101         ( Ctor(CtorOf::Struct, CtorKind::Fn)       )
102         ( Ctor(CtorOf::Struct, CtorKind::Const)    )
103         ( Ctor(CtorOf::Struct, CtorKind::Fictive)  )
104         ( Ctor(CtorOf::Variant, CtorKind::Fn)      )
105         ( Ctor(CtorOf::Variant, CtorKind::Const)   )
106         ( Ctor(CtorOf::Variant, CtorKind::Fictive) )
107         ( Macro(MacroKind::Bang)                   )
108         ( Macro(MacroKind::Attr)                   )
109         ( Macro(MacroKind::Derive)                 )
110     }
111 }
112
113 fixed_size_enum! {
114     ty::ImplPolarity {
115         ( Positive    )
116         ( Negative    )
117         ( Reservation )
118     }
119 }
120
121 fixed_size_enum! {
122     hir::Constness {
123         ( NotConst )
124         ( Const    )
125     }
126 }
127
128 fixed_size_enum! {
129     hir::Defaultness {
130         ( Final                        )
131         ( Default { has_value: false } )
132         ( Default { has_value: true }  )
133     }
134 }
135
136 fixed_size_enum! {
137     hir::IsAsync {
138         ( NotAsync )
139         ( Async    )
140     }
141 }
142
143 fixed_size_enum! {
144     ty::AssocItemContainer {
145         ( TraitContainer )
146         ( ImplContainer  )
147     }
148 }
149
150 fixed_size_enum! {
151     MacroKind {
152         ( Attr   )
153         ( Bang   )
154         ( Derive )
155     }
156 }
157
158 // We directly encode `DefPathHash` because a `LazyValue` would incur a 25% cost.
159 impl FixedSizeEncoding for Option<DefPathHash> {
160     type ByteArray = [u8; 16];
161
162     #[inline]
163     fn from_bytes(b: &[u8; 16]) -> Self {
164         Some(DefPathHash(Fingerprint::from_le_bytes(*b)))
165     }
166
167     #[inline]
168     fn write_to_bytes(self, b: &mut [u8; 16]) {
169         let Some(DefPathHash(fingerprint)) = self else {
170             panic!("Trying to encode absent DefPathHash.")
171         };
172         *b = fingerprint.to_le_bytes();
173     }
174 }
175
176 // We directly encode RawDefId because using a `LazyValue` would incur a 50% overhead in the worst case.
177 impl FixedSizeEncoding for Option<RawDefId> {
178     type ByteArray = [u8; 8];
179
180     #[inline]
181     fn from_bytes(b: &[u8; 8]) -> Self {
182         let krate = u32::from_le_bytes(b[0..4].try_into().unwrap());
183         let index = u32::from_le_bytes(b[4..8].try_into().unwrap());
184         if krate == 0 {
185             return None;
186         }
187         Some(RawDefId { krate: krate - 1, index })
188     }
189
190     #[inline]
191     fn write_to_bytes(self, b: &mut [u8; 8]) {
192         match self {
193             None => *b = [0; 8],
194             Some(RawDefId { krate, index }) => {
195                 // CrateNum is less than `CrateNum::MAX_AS_U32`.
196                 debug_assert!(krate < u32::MAX);
197                 b[0..4].copy_from_slice(&(1 + krate).to_le_bytes());
198                 b[4..8].copy_from_slice(&index.to_le_bytes());
199             }
200         }
201     }
202 }
203
204 impl FixedSizeEncoding for Option<()> {
205     type ByteArray = [u8; 1];
206
207     #[inline]
208     fn from_bytes(b: &[u8; 1]) -> Self {
209         (b[0] != 0).then(|| ())
210     }
211
212     #[inline]
213     fn write_to_bytes(self, b: &mut [u8; 1]) {
214         b[0] = self.is_some() as u8
215     }
216 }
217
218 // NOTE(eddyb) there could be an impl for `usize`, which would enable a more
219 // generic `LazyValue<T>` impl, but in the general case we might not need / want
220 // to fit every `usize` in `u32`.
221 impl<T> FixedSizeEncoding for Option<LazyValue<T>> {
222     type ByteArray = [u8; 4];
223
224     #[inline]
225     fn from_bytes(b: &[u8; 4]) -> Self {
226         let position = NonZeroUsize::new(u32::from_bytes(b) as usize)?;
227         Some(LazyValue::from_position(position))
228     }
229
230     #[inline]
231     fn write_to_bytes(self, b: &mut [u8; 4]) {
232         let position = self.map_or(0, |lazy| lazy.position.get());
233         let position: u32 = position.try_into().unwrap();
234         position.write_to_bytes(b)
235     }
236 }
237
238 impl<T> FixedSizeEncoding for Option<LazyArray<T>> {
239     type ByteArray = [u8; 8];
240
241     #[inline]
242     fn from_bytes(b: &[u8; 8]) -> Self {
243         let ([ref position_bytes, ref meta_bytes],[])= b.as_chunks::<4>() else { panic!() };
244         let position = NonZeroUsize::new(u32::from_bytes(position_bytes) as usize)?;
245         let len = u32::from_bytes(meta_bytes) as usize;
246         Some(LazyArray::from_position_and_num_elems(position, len))
247     }
248
249     #[inline]
250     fn write_to_bytes(self, b: &mut [u8; 8]) {
251         let ([ref mut position_bytes, ref mut meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() };
252
253         let position = self.map_or(0, |lazy| lazy.position.get());
254         let position: u32 = position.try_into().unwrap();
255         position.write_to_bytes(position_bytes);
256
257         let len = self.map_or(0, |lazy| lazy.num_elems);
258         let len: u32 = len.try_into().unwrap();
259         len.write_to_bytes(meta_bytes);
260     }
261 }
262
263 /// Helper for constructing a table's serialization (also see `Table`).
264 pub(super) struct TableBuilder<I: Idx, T>
265 where
266     Option<T>: FixedSizeEncoding,
267 {
268     blocks: IndexVec<I, <Option<T> as FixedSizeEncoding>::ByteArray>,
269     _marker: PhantomData<T>,
270 }
271
272 impl<I: Idx, T> Default for TableBuilder<I, T>
273 where
274     Option<T>: FixedSizeEncoding,
275 {
276     fn default() -> Self {
277         TableBuilder { blocks: Default::default(), _marker: PhantomData }
278     }
279 }
280
281 impl<I: Idx, T> TableBuilder<I, T>
282 where
283     Option<T>: FixedSizeEncoding,
284 {
285     pub(crate) fn set<const N: usize>(&mut self, i: I, value: T)
286     where
287         Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
288     {
289         // FIXME(eddyb) investigate more compact encodings for sparse tables.
290         // On the PR @michaelwoerister mentioned:
291         // > Space requirements could perhaps be optimized by using the HAMT `popcnt`
292         // > trick (i.e. divide things into buckets of 32 or 64 items and then
293         // > store bit-masks of which item in each bucket is actually serialized).
294         self.blocks.ensure_contains_elem(i, || [0; N]);
295         Some(value).write_to_bytes(&mut self.blocks[i]);
296     }
297
298     pub(crate) fn encode<const N: usize>(&self, buf: &mut FileEncoder) -> LazyTable<I, T>
299     where
300         Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
301     {
302         let pos = buf.position();
303         for block in &self.blocks {
304             buf.emit_raw_bytes(block);
305         }
306         let num_bytes = self.blocks.len() * N;
307         LazyTable::from_position_and_encoded_size(
308             NonZeroUsize::new(pos as usize).unwrap(),
309             num_bytes,
310         )
311     }
312 }
313
314 impl<I: Idx, T: ParameterizedOverTcx> LazyTable<I, T>
315 where
316     Option<T>: FixedSizeEncoding,
317 {
318     /// Given the metadata, extract out the value at a particular index (if any).
319     #[inline(never)]
320     pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>, const N: usize>(
321         &self,
322         metadata: M,
323         i: I,
324     ) -> Option<T::Value<'tcx>>
325     where
326         Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
327     {
328         debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
329
330         let start = self.position.get();
331         let bytes = &metadata.blob()[start..start + self.encoded_size];
332         let (bytes, []) = bytes.as_chunks::<N>() else { panic!() };
333         let bytes = bytes.get(i.index())?;
334         FixedSizeEncoding::from_bytes(bytes)
335     }
336
337     /// Size of the table in entries, including possible gaps.
338     pub(super) fn size<const N: usize>(&self) -> usize
339     where
340         for<'tcx> Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
341     {
342         self.encoded_size / N
343     }
344 }