5 use rustc_target::abi::Size;
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)]
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
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>();
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);
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);
42 self.blocks.hash(state);
45 // Hash the other fields as usual.
51 pub const BLOCK_SIZE: u64 = 64;
53 pub fn new(size: Size, state: bool) -> Self {
54 let mut m = InitMask { blocks: vec![], len: Size::ZERO };
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())
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)
77 /// Checks whether the `range` is entirely initialized.
79 /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte
80 /// indexes for the first contiguous span of the uninitialized access.
82 pub fn is_range_initialized(&self, range: AllocRange) -> Result<(), AllocRange> {
83 let end = range.end();
85 return Err(AllocRange::from(self.len..end));
88 let uninit_start = self.find_bit(range.start, end, false);
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))
99 pub fn set_range(&mut self, range: AllocRange, new_state: bool) {
100 let end = range.end();
103 self.grow(end - len, new_state);
105 self.set_range_inbounds(range.start, end, new_state);
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 {
117 (u64::MAX << bita) & (u64::MAX >> (64 - bitb))
120 self.blocks[blocka] |= range;
122 self.blocks[blocka] &= !range;
126 // across block boundaries
128 // Set `bita..64` to `1`.
129 self.blocks[blocka] |= u64::MAX << bita;
130 // Set `0..bitb` to `1`.
132 self.blocks[blockb] |= u64::MAX >> (64 - bitb);
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;
139 // Set `bita..64` to `0`.
140 self.blocks[blocka] &= !(u64::MAX << bita);
141 // Set `0..bitb` to `0`.
143 self.blocks[blockb] &= !(u64::MAX >> (64 - bitb));
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;
153 fn get(&self, i: Size) -> bool {
154 let (block, bit) = Self::bit_index(i);
155 (self.blocks[block] & (1 << bit)) != 0
158 fn grow(&mut self, amount: Size, new_state: bool) {
159 if amount.bytes() == 0 {
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;
167 // FIXME(oli-obk): optimize this by repeating `new_state as Block`.
168 iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()),
171 let start = self.len;
173 self.set_range_inbounds(start, start + amount, new_state); // `Size` operation
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.
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:
185 /// 00000000|00000000
189 /// Also, if not stated, assume that `is_init = true`, that is, we are searching for the first 1 bit.
191 init_mask: &InitMask,
196 /// Search one block, returning the index of the first bit equal to `is_init`.
203 // For the following examples, assume this function was called with:
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`.
210 // Invert bits so we're always looking for the first set bit.
213 let bits = if is_init { bits } else { !bits };
214 // Mask off unused start bits.
218 let bits = bits & (!0 << start_bit);
219 // Find set bit, if any.
220 // bit = trailing_zeros(0b11000000)
225 let bit = bits.trailing_zeros();
226 Some(InitMask::size_from_bit_index(block, bit))
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.
239 // (a) 00000000|00000000 (b) 00000000|
240 // ^~~~~~~~~~~^ ^~~~~~~~~^
241 // start end start end
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).
246 // We subtract 1 from both end positions to make them inclusive:
248 // (a) 00000000|00000000 (b) 00000000|
249 // ^~~~~~~~~~^ ^~~~~~~^
250 // start end_inclusive start end_inclusive
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);
260 // Handle first block: need to skip `start_bit` bits.
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:
268 // (c) 01000000|00000000|00000001
269 // ^~~~~~~~~~~~~~~~~~^
272 search_block(init_mask.blocks[start_block], start_block, start_bit, is_init)
274 // If the range is less than a block, we may find a matching bit after `end`.
276 // For example, we shouldn't successfully find bit (2), because it's after `end`:
280 // (d) 00000001|00000000|00000001
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.
293 // Handle remaining blocks.
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:
301 // (e) 01000000|00000000|00000001
302 // ^~~~~~~~~~~~~~~~~~^
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]
313 .zip(start_block + 1..)
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`.
318 // For example, we shouldn't successfully find bit (4), because it's after `end`:
322 // (f) 00000001|00000000|00000001
323 // ^~~~~~~~~~~~~~~~~~^
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.
341 #[cfg_attr(not(debug_assertions), allow(dead_code))]
343 init_mask: &InitMask,
348 (start..end).find(|&i| init_mask.get(i) == is_init)
351 let result = find_bit_fast(self, start, end, is_init);
355 find_bit_slow(self, start, end, is_init),
356 "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}",
367 /// A contiguous chunk of initialized or uninitialized memory.
375 pub fn is_init(&self) -> bool {
377 Self::Init(_) => true,
378 Self::Uninit(_) => false,
383 pub fn range(&self) -> Range<Size> {
385 Self::Init(r) => r.clone(),
386 Self::Uninit(r) => r.clone(),
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).
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`].
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);
406 let is_init = if start < end {
409 // `start..end` is empty: there are no chunks, so use some arbitrary value
413 InitChunkIter { init_mask: self, is_init, start, end }
417 /// Yields [`InitChunk`]s. See [`InitMask::range_as_init_chunks`].
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.
424 /// The current byte index into `init_mask`.
426 /// The end byte index into `init_mask`.
430 impl<'a> Iterator for InitChunkIter<'a> {
431 type Item = InitChunk;
434 fn next(&mut self) -> Option<Self::Item> {
435 if self.start >= self.end {
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;
444 Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) });
446 self.is_init = !self.is_init;
447 self.start = end_of_chunk;
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.
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]>,
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
471 /// Transferring the initialization mask to other allocations.
473 /// Creates a run-length encoding of the initialization mask; panics if range is empty.
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.
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.
490 let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
492 let mut chunks = self.range_as_init_chunks(range).peekable();
494 let initial = chunks.peek().expect("range should be nonempty").is_init();
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();
502 InitCopy { ranges, initial }
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(
512 range.start + range.size * repeat, // `Size` operations
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 {
525 self.set_range_inbounds(Size::from_bytes(old_j), Size::from_bytes(j), cur);