]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs
move InitMask to its own module
[rust.git] / compiler / rustc_middle / src / mir / interpret / allocation / init_mask.rs
1 use std::hash;
2 use std::iter;
3 use std::ops::Range;
4
5 use rustc_target::abi::Size;
6
7 use super::AllocRange;
8
9 type Block = u64;
10
11 /// A bitmask where each bit refers to the byte with the same index. If the bit is `true`, the byte
12 /// is initialized. If it is `false` the byte is uninitialized.
13 // Note: for performance reasons when interning, some of the `InitMask` fields can be partially
14 // hashed. (see the `Hash` impl below for more details), so the impl is not derived.
15 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable)]
16 #[derive(HashStable)]
17 pub struct InitMask {
18     blocks: Vec<Block>,
19     len: Size,
20 }
21
22 // Const allocations are only hashed for interning. However, they can be large, making the hashing
23 // expensive especially since it uses `FxHash`: it's better suited to short keys, not potentially
24 // big buffers like the allocation's init mask. We can partially hash some fields when they're
25 // large.
26 impl hash::Hash for InitMask {
27     fn hash<H: hash::Hasher>(&self, state: &mut H) {
28         const MAX_BLOCKS_TO_HASH: usize = super::MAX_BYTES_TO_HASH / std::mem::size_of::<Block>();
29         const MAX_BLOCKS_LEN: usize = super::MAX_HASHED_BUFFER_LEN / std::mem::size_of::<Block>();
30
31         // Partially hash the `blocks` buffer when it is large. To limit collisions with common
32         // prefixes and suffixes, we hash the length and some slices of the buffer.
33         let block_count = self.blocks.len();
34         if block_count > MAX_BLOCKS_LEN {
35             // Hash the buffer's length.
36             block_count.hash(state);
37
38             // And its head and tail.
39             self.blocks[..MAX_BLOCKS_TO_HASH].hash(state);
40             self.blocks[block_count - MAX_BLOCKS_TO_HASH..].hash(state);
41         } else {
42             self.blocks.hash(state);
43         }
44
45         // Hash the other fields as usual.
46         self.len.hash(state);
47     }
48 }
49
50 impl InitMask {
51     pub const BLOCK_SIZE: u64 = 64;
52
53     pub fn new(size: Size, state: bool) -> Self {
54         let mut m = InitMask { blocks: vec![], len: Size::ZERO };
55         m.grow(size, state);
56         m
57     }
58
59     #[inline]
60     fn bit_index(bits: Size) -> (usize, usize) {
61         // BLOCK_SIZE is the number of bits that can fit in a `Block`.
62         // Each bit in a `Block` represents the initialization state of one byte of an allocation,
63         // so we use `.bytes()` here.
64         let bits = bits.bytes();
65         let a = bits / InitMask::BLOCK_SIZE;
66         let b = bits % InitMask::BLOCK_SIZE;
67         (usize::try_from(a).unwrap(), usize::try_from(b).unwrap())
68     }
69
70     #[inline]
71     fn size_from_bit_index(block: impl TryInto<u64>, bit: impl TryInto<u64>) -> Size {
72         let block = block.try_into().ok().unwrap();
73         let bit = bit.try_into().ok().unwrap();
74         Size::from_bytes(block * InitMask::BLOCK_SIZE + bit)
75     }
76
77     /// Checks whether the `range` is entirely initialized.
78     ///
79     /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte
80     /// indexes for the first contiguous span of the uninitialized access.
81     #[inline]
82     pub fn is_range_initialized(&self, range: AllocRange) -> Result<(), AllocRange> {
83         let end = range.end();
84         if end > self.len {
85             return Err(AllocRange::from(self.len..end));
86         }
87
88         let uninit_start = self.find_bit(range.start, end, false);
89
90         match uninit_start {
91             Some(uninit_start) => {
92                 let uninit_end = self.find_bit(uninit_start, end, true).unwrap_or(end);
93                 Err(AllocRange::from(uninit_start..uninit_end))
94             }
95             None => Ok(()),
96         }
97     }
98
99     pub fn set_range(&mut self, range: AllocRange, new_state: bool) {
100         let end = range.end();
101         let len = self.len;
102         if end > len {
103             self.grow(end - len, new_state);
104         }
105         self.set_range_inbounds(range.start, end, new_state);
106     }
107
108     fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
109         let (blocka, bita) = Self::bit_index(start);
110         let (blockb, bitb) = Self::bit_index(end);
111         if blocka == blockb {
112             // First set all bits except the first `bita`,
113             // then unset the last `64 - bitb` bits.
114             let range = if bitb == 0 {
115                 u64::MAX << bita
116             } else {
117                 (u64::MAX << bita) & (u64::MAX >> (64 - bitb))
118             };
119             if new_state {
120                 self.blocks[blocka] |= range;
121             } else {
122                 self.blocks[blocka] &= !range;
123             }
124             return;
125         }
126         // across block boundaries
127         if new_state {
128             // Set `bita..64` to `1`.
129             self.blocks[blocka] |= u64::MAX << bita;
130             // Set `0..bitb` to `1`.
131             if bitb != 0 {
132                 self.blocks[blockb] |= u64::MAX >> (64 - bitb);
133             }
134             // Fill in all the other blocks (much faster than one bit at a time).
135             for block in (blocka + 1)..blockb {
136                 self.blocks[block] = u64::MAX;
137             }
138         } else {
139             // Set `bita..64` to `0`.
140             self.blocks[blocka] &= !(u64::MAX << bita);
141             // Set `0..bitb` to `0`.
142             if bitb != 0 {
143                 self.blocks[blockb] &= !(u64::MAX >> (64 - bitb));
144             }
145             // Fill in all the other blocks (much faster than one bit at a time).
146             for block in (blocka + 1)..blockb {
147                 self.blocks[block] = 0;
148             }
149         }
150     }
151
152     #[inline]
153     fn get(&self, i: Size) -> bool {
154         let (block, bit) = Self::bit_index(i);
155         (self.blocks[block] & (1 << bit)) != 0
156     }
157
158     fn grow(&mut self, amount: Size, new_state: bool) {
159         if amount.bytes() == 0 {
160             return;
161         }
162         let unused_trailing_bits =
163             u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes();
164         if amount.bytes() > unused_trailing_bits {
165             let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
166             self.blocks.extend(
167                 // FIXME(oli-obk): optimize this by repeating `new_state as Block`.
168                 iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()),
169             );
170         }
171         let start = self.len;
172         self.len += amount;
173         self.set_range_inbounds(start, start + amount, new_state); // `Size` operation
174     }
175
176     /// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init.
177     fn find_bit(&self, start: Size, end: Size, is_init: bool) -> Option<Size> {
178         /// A fast implementation of `find_bit`,
179         /// which skips over an entire block at a time if it's all 0s (resp. 1s),
180         /// and finds the first 1 (resp. 0) bit inside a block using `trailing_zeros` instead of a loop.
181         ///
182         /// Note that all examples below are written with 8 (instead of 64) bit blocks for simplicity,
183         /// and with the least significant bit (and lowest block) first:
184         /// ```text
185         ///        00000000|00000000
186         ///        ^      ^ ^      ^
187         /// index: 0      7 8      15
188         /// ```
189         /// Also, if not stated, assume that `is_init = true`, that is, we are searching for the first 1 bit.
190         fn find_bit_fast(
191             init_mask: &InitMask,
192             start: Size,
193             end: Size,
194             is_init: bool,
195         ) -> Option<Size> {
196             /// Search one block, returning the index of the first bit equal to `is_init`.
197             fn search_block(
198                 bits: Block,
199                 block: usize,
200                 start_bit: usize,
201                 is_init: bool,
202             ) -> Option<Size> {
203                 // For the following examples, assume this function was called with:
204                 //   bits = 0b00111011
205                 //   start_bit = 3
206                 //   is_init = false
207                 // Note that, for the examples in this function, the most significant bit is written first,
208                 // which is backwards compared to the comments in `find_bit`/`find_bit_fast`.
209
210                 // Invert bits so we're always looking for the first set bit.
211                 //        ! 0b00111011
212                 //   bits = 0b11000100
213                 let bits = if is_init { bits } else { !bits };
214                 // Mask off unused start bits.
215                 //          0b11000100
216                 //        & 0b11111000
217                 //   bits = 0b11000000
218                 let bits = bits & (!0 << start_bit);
219                 // Find set bit, if any.
220                 //   bit = trailing_zeros(0b11000000)
221                 //   bit = 6
222                 if bits == 0 {
223                     None
224                 } else {
225                     let bit = bits.trailing_zeros();
226                     Some(InitMask::size_from_bit_index(block, bit))
227                 }
228             }
229
230             if start >= end {
231                 return None;
232             }
233
234             // Convert `start` and `end` to block indexes and bit indexes within each block.
235             // We must convert `end` to an inclusive bound to handle block boundaries correctly.
236             //
237             // For example:
238             //
239             //   (a) 00000000|00000000    (b) 00000000|
240             //       ^~~~~~~~~~~^             ^~~~~~~~~^
241             //     start       end          start     end
242             //
243             // In both cases, the block index of `end` is 1.
244             // But we do want to search block 1 in (a), and we don't in (b).
245             //
246             // We subtract 1 from both end positions to make them inclusive:
247             //
248             //   (a) 00000000|00000000    (b) 00000000|
249             //       ^~~~~~~~~~^              ^~~~~~~^
250             //     start    end_inclusive   start end_inclusive
251             //
252             // For (a), the block index of `end_inclusive` is 1, and for (b), it's 0.
253             // This provides the desired behavior of searching blocks 0 and 1 for (a),
254             // and searching only block 0 for (b).
255             // There is no concern of overflows since we checked for `start >= end` above.
256             let (start_block, start_bit) = InitMask::bit_index(start);
257             let end_inclusive = Size::from_bytes(end.bytes() - 1);
258             let (end_block_inclusive, _) = InitMask::bit_index(end_inclusive);
259
260             // Handle first block: need to skip `start_bit` bits.
261             //
262             // We need to handle the first block separately,
263             // because there may be bits earlier in the block that should be ignored,
264             // such as the bit marked (1) in this example:
265             //
266             //       (1)
267             //       -|------
268             //   (c) 01000000|00000000|00000001
269             //          ^~~~~~~~~~~~~~~~~~^
270             //        start              end
271             if let Some(i) =
272                 search_block(init_mask.blocks[start_block], start_block, start_bit, is_init)
273             {
274                 // If the range is less than a block, we may find a matching bit after `end`.
275                 //
276                 // For example, we shouldn't successfully find bit (2), because it's after `end`:
277                 //
278                 //             (2)
279                 //       -------|
280                 //   (d) 00000001|00000000|00000001
281                 //        ^~~~~^
282                 //      start end
283                 //
284                 // An alternative would be to mask off end bits in the same way as we do for start bits,
285                 // but performing this check afterwards is faster and simpler to implement.
286                 if i < end {
287                     return Some(i);
288                 } else {
289                     return None;
290                 }
291             }
292
293             // Handle remaining blocks.
294             //
295             // We can skip over an entire block at once if it's all 0s (resp. 1s).
296             // The block marked (3) in this example is the first block that will be handled by this loop,
297             // and it will be skipped for that reason:
298             //
299             //                   (3)
300             //                --------
301             //   (e) 01000000|00000000|00000001
302             //          ^~~~~~~~~~~~~~~~~~^
303             //        start              end
304             if start_block < end_block_inclusive {
305                 // This loop is written in a specific way for performance.
306                 // Notably: `..end_block_inclusive + 1` is used for an inclusive range instead of `..=end_block_inclusive`,
307                 // and `.zip(start_block + 1..)` is used to track the index instead of `.enumerate().skip().take()`,
308                 // because both alternatives result in significantly worse codegen.
309                 // `end_block_inclusive + 1` is guaranteed not to wrap, because `end_block_inclusive <= end / BLOCK_SIZE`,
310                 // and `BLOCK_SIZE` (the number of bits per block) will always be at least 8 (1 byte).
311                 for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1]
312                     .iter()
313                     .zip(start_block + 1..)
314                 {
315                     if let Some(i) = search_block(bits, block, 0, is_init) {
316                         // If this is the last block, we may find a matching bit after `end`.
317                         //
318                         // For example, we shouldn't successfully find bit (4), because it's after `end`:
319                         //
320                         //                               (4)
321                         //                         -------|
322                         //   (f) 00000001|00000000|00000001
323                         //          ^~~~~~~~~~~~~~~~~~^
324                         //        start              end
325                         //
326                         // As above with example (d), we could handle the end block separately and mask off end bits,
327                         // but unconditionally searching an entire block at once and performing this check afterwards
328                         // is faster and much simpler to implement.
329                         if i < end {
330                             return Some(i);
331                         } else {
332                             return None;
333                         }
334                     }
335                 }
336             }
337
338             None
339         }
340
341         #[cfg_attr(not(debug_assertions), allow(dead_code))]
342         fn find_bit_slow(
343             init_mask: &InitMask,
344             start: Size,
345             end: Size,
346             is_init: bool,
347         ) -> Option<Size> {
348             (start..end).find(|&i| init_mask.get(i) == is_init)
349         }
350
351         let result = find_bit_fast(self, start, end, is_init);
352
353         debug_assert_eq!(
354             result,
355             find_bit_slow(self, start, end, is_init),
356             "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}",
357             start,
358             end,
359             is_init,
360             self
361         );
362
363         result
364     }
365 }
366
367 /// A contiguous chunk of initialized or uninitialized memory.
368 pub enum InitChunk {
369     Init(Range<Size>),
370     Uninit(Range<Size>),
371 }
372
373 impl InitChunk {
374     #[inline]
375     pub fn is_init(&self) -> bool {
376         match self {
377             Self::Init(_) => true,
378             Self::Uninit(_) => false,
379         }
380     }
381
382     #[inline]
383     pub fn range(&self) -> Range<Size> {
384         match self {
385             Self::Init(r) => r.clone(),
386             Self::Uninit(r) => r.clone(),
387         }
388     }
389 }
390
391 impl InitMask {
392     /// Returns an iterator, yielding a range of byte indexes for each contiguous region
393     /// of initialized or uninitialized bytes inside the range `start..end` (end-exclusive).
394     ///
395     /// The iterator guarantees the following:
396     /// - Chunks are nonempty.
397     /// - Chunks are adjacent (each range's start is equal to the previous range's end).
398     /// - Chunks span exactly `start..end` (the first starts at `start`, the last ends at `end`).
399     /// - Chunks alternate between [`InitChunk::Init`] and [`InitChunk::Uninit`].
400     #[inline]
401     pub fn range_as_init_chunks(&self, range: AllocRange) -> InitChunkIter<'_> {
402         let start = range.start;
403         let end = range.end();
404         assert!(end <= self.len);
405
406         let is_init = if start < end {
407             self.get(start)
408         } else {
409             // `start..end` is empty: there are no chunks, so use some arbitrary value
410             false
411         };
412
413         InitChunkIter { init_mask: self, is_init, start, end }
414     }
415 }
416
417 /// Yields [`InitChunk`]s. See [`InitMask::range_as_init_chunks`].
418 #[derive(Clone)]
419 pub struct InitChunkIter<'a> {
420     init_mask: &'a InitMask,
421     /// Whether the next chunk we will return is initialized.
422     /// If there are no more chunks, contains some arbitrary value.
423     is_init: bool,
424     /// The current byte index into `init_mask`.
425     start: Size,
426     /// The end byte index into `init_mask`.
427     end: Size,
428 }
429
430 impl<'a> Iterator for InitChunkIter<'a> {
431     type Item = InitChunk;
432
433     #[inline]
434     fn next(&mut self) -> Option<Self::Item> {
435         if self.start >= self.end {
436             return None;
437         }
438
439         let end_of_chunk =
440             self.init_mask.find_bit(self.start, self.end, !self.is_init).unwrap_or(self.end);
441         let range = self.start..end_of_chunk;
442
443         let ret =
444             Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) });
445
446         self.is_init = !self.is_init;
447         self.start = end_of_chunk;
448
449         ret
450     }
451 }
452
453 /// Run-length encoding of the uninit mask.
454 /// Used to copy parts of a mask multiple times to another allocation.
455 pub struct InitCopy {
456     /// Whether the first range is initialized.
457     initial: bool,
458     /// The lengths of ranges that are run-length encoded.
459     /// The initialization state of the ranges alternate starting with `initial`.
460     ranges: smallvec::SmallVec<[u64; 1]>,
461 }
462
463 impl InitCopy {
464     pub fn no_bytes_init(&self) -> bool {
465         // The `ranges` are run-length encoded and of alternating initialization state.
466         // So if `ranges.len() > 1` then the second block is an initialized range.
467         !self.initial && self.ranges.len() == 1
468     }
469 }
470
471 /// Transferring the initialization mask to other allocations.
472 impl InitMask {
473     /// Creates a run-length encoding of the initialization mask; panics if range is empty.
474     ///
475     /// This is essentially a more space-efficient version of
476     /// `InitMask::range_as_init_chunks(...).collect::<Vec<_>>()`.
477     pub fn prepare_copy(&self, range: AllocRange) -> InitCopy {
478         // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
479         // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from
480         // the source and write it to the destination. Even if we optimized the memory accesses,
481         // we'd be doing all of this `repeat` times.
482         // Therefore we precompute a compressed version of the initialization mask of the source value and
483         // then write it back `repeat` times without computing any more information from the source.
484
485         // A precomputed cache for ranges of initialized / uninitialized bits
486         // 0000010010001110 will become
487         // `[5, 1, 2, 1, 3, 3, 1]`,
488         // where each element toggles the state.
489
490         let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
491
492         let mut chunks = self.range_as_init_chunks(range).peekable();
493
494         let initial = chunks.peek().expect("range should be nonempty").is_init();
495
496         // Here we rely on `range_as_init_chunks` to yield alternating init/uninit chunks.
497         for chunk in chunks {
498             let len = chunk.range().end.bytes() - chunk.range().start.bytes();
499             ranges.push(len);
500         }
501
502         InitCopy { ranges, initial }
503     }
504
505     /// Applies multiple instances of the run-length encoding to the initialization mask.
506     pub fn apply_copy(&mut self, defined: InitCopy, range: AllocRange, repeat: u64) {
507         // An optimization where we can just overwrite an entire range of initialization
508         // bits if they are going to be uniformly `1` or `0`.
509         if defined.ranges.len() <= 1 {
510             self.set_range_inbounds(
511                 range.start,
512                 range.start + range.size * repeat, // `Size` operations
513                 defined.initial,
514             );
515             return;
516         }
517
518         for mut j in 0..repeat {
519             j *= range.size.bytes();
520             j += range.start.bytes();
521             let mut cur = defined.initial;
522             for range in &defined.ranges {
523                 let old_j = j;
524                 j += range;
525                 self.set_range_inbounds(Size::from_bytes(old_j), Size::from_bytes(j), cur);
526                 cur = !cur;
527             }
528         }
529     }
530 }