1#[cfg(test)]
2mod tests;
34use std::ops::Range;
5use std::{hash, iter};
67use rustc_abi::Size;
8use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable};
9use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
1011use super::AllocRange;
1213type Block = u64;
1415/// A bitmask where each bit refers to the byte with the same index. If the bit is `true`, the byte
16/// is initialized. If it is `false` the byte is uninitialized.
17/// The actual bits are only materialized when needed, and we try to keep this data lazy as long as
18/// possible. Currently, if all the blocks have the same value, then the mask represents either a
19/// fully initialized or fully uninitialized const allocation, so we can only store that single
20/// value.
21#[derive(#[automatically_derived]
impl ::core::clone::Clone for InitMask {
#[inline]
fn clone(&self) -> InitMask {
InitMask {
blocks: ::core::clone::Clone::clone(&self.blocks),
len: ::core::clone::Clone::clone(&self.len),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InitMask {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InitMask",
"blocks", &self.blocks, "len", &&self.len)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for InitMask {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<InitMaskBlocks>;
let _: ::core::cmp::AssertParamIsEq<Size>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for InitMask {
#[inline]
fn eq(&self, other: &InitMask) -> bool {
self.blocks == other.blocks && self.len == other.len
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_serialize::Encoder>
::rustc_serialize::Encodable<__E> for InitMask {
fn encode(&self, __encoder: &mut __E) {
match *self {
InitMask { blocks: ref __binding_0, len: ref __binding_1 }
=> {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable_NoContext, const _: () =
{
impl<__D: ::rustc_serialize::Decoder>
::rustc_serialize::Decodable<__D> for InitMask {
fn decode(__decoder: &mut __D) -> Self {
InitMask {
blocks: ::rustc_serialize::Decodable::decode(__decoder),
len: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable_NoContext, #[automatically_derived]
impl ::core::hash::Hash for InitMask {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.blocks, state);
::core::hash::Hash::hash(&self.len, state)
}
}Hash, const _: () =
{
impl<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
for InitMask {
#[inline]
fn hash_stable(&self,
__hcx:
&mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self {
InitMask { blocks: ref __binding_0, len: ref __binding_1 }
=> {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable)]
22pub struct InitMask {
23 blocks: InitMaskBlocks,
24 len: Size,
25}
2627#[derive(#[automatically_derived]
impl ::core::clone::Clone for InitMaskBlocks {
#[inline]
fn clone(&self) -> InitMaskBlocks {
match self {
InitMaskBlocks::Lazy { state: __self_0 } =>
InitMaskBlocks::Lazy {
state: ::core::clone::Clone::clone(__self_0),
},
InitMaskBlocks::Materialized(__self_0) =>
InitMaskBlocks::Materialized(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InitMaskBlocks {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InitMaskBlocks::Lazy { state: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Lazy",
"state", &__self_0),
InitMaskBlocks::Materialized(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Materialized", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for InitMaskBlocks {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
let _: ::core::cmp::AssertParamIsEq<InitMaskMaterialized>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for InitMaskBlocks {
#[inline]
fn eq(&self, other: &InitMaskBlocks) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(InitMaskBlocks::Lazy { state: __self_0 },
InitMaskBlocks::Lazy { state: __arg1_0 }) =>
__self_0 == __arg1_0,
(InitMaskBlocks::Materialized(__self_0),
InitMaskBlocks::Materialized(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_serialize::Encoder>
::rustc_serialize::Encodable<__E> for InitMaskBlocks {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
InitMaskBlocks::Lazy { state: ref __binding_0 } => {
0usize
}
InitMaskBlocks::Materialized(ref __binding_0) => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
InitMaskBlocks::Lazy { state: ref __binding_0 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
InitMaskBlocks::Materialized(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable_NoContext, const _: () =
{
impl<__D: ::rustc_serialize::Decoder>
::rustc_serialize::Decodable<__D> for InitMaskBlocks {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
InitMaskBlocks::Lazy {
state: ::rustc_serialize::Decodable::decode(__decoder),
}
}
1usize => {
InitMaskBlocks::Materialized(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `InitMaskBlocks`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable_NoContext, #[automatically_derived]
impl ::core::hash::Hash for InitMaskBlocks {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
InitMaskBlocks::Lazy { state: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
InitMaskBlocks::Materialized(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, const _: () =
{
impl<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
for InitMaskBlocks {
#[inline]
fn hash_stable(&self,
__hcx:
&mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
InitMaskBlocks::Lazy { state: ref __binding_0 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
InitMaskBlocks::Materialized(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable)]
28enum InitMaskBlocks {
29 Lazy {
30/// Whether the lazy init mask is fully initialized or uninitialized.
31state: bool,
32 },
33 Materialized(InitMaskMaterialized),
34}
3536impl InitMask {
37pub fn new(size: Size, state: bool) -> Self {
38// Blocks start lazily allocated, until we have to materialize them.
39let blocks = InitMaskBlocks::Lazy { state };
40InitMask { len: size, blocks }
41 }
4243/// Checks whether the `range` is entirely initialized.
44 ///
45 /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte
46 /// indexes for the first contiguous span of the uninitialized access.
47#[inline]
48pub fn is_range_initialized(&self, range: AllocRange) -> Result<(), AllocRange> {
49let end = range.end();
50if end > self.len {
51return Err(AllocRange::from(self.len..end));
52 }
5354match self.blocks {
55 InitMaskBlocks::Lazy { state } => {
56// Lazily allocated blocks represent the full mask, and cover the requested range by
57 // definition.
58if state { Ok(()) } else { Err(range) }
59 }
60 InitMaskBlocks::Materialized(ref blocks) => {
61blocks.is_range_initialized(range.start, end)
62 }
63 }
64 }
6566/// Sets a specified range to a value. If the range is out-of-bounds, the mask will grow to
67 /// accommodate it entirely.
68pub fn set_range(&mut self, range: AllocRange, new_state: bool) {
69let start = range.start;
70let end = range.end();
7172let is_full_overwrite = start == Size::ZERO && end >= self.len;
7374// Optimize the cases of a full init/uninit state, while handling growth if needed.
75match self.blocks {
76 InitMaskBlocks::Lazy { ref mut state } if is_full_overwrite => {
77// This is fully overwriting the mask, and we'll still have a single initialization
78 // state: the blocks can stay lazy.
79*state = new_state;
80self.len = end;
81 }
82 InitMaskBlocks::Materialized(_) if is_full_overwrite => {
83// This is also fully overwriting materialized blocks with a single initialization
84 // state: we'll have no need for these blocks anymore and can make them lazy.
85self.blocks = InitMaskBlocks::Lazy { state: new_state };
86self.len = end;
87 }
88 InitMaskBlocks::Lazy { state } if state == new_state => {
89// Here we're partially overwriting the mask but the initialization state doesn't
90 // change: the blocks can stay lazy.
91if end > self.len {
92self.len = end;
93 }
94 }
95_ => {
96// Otherwise, we have a partial overwrite that can result in a mix of initialization
97 // states, so we'll need materialized blocks.
98let len = self.len;
99let blocks = self.materialize_blocks();
100101// There are 3 cases of interest here, if we have:
102 //
103 // [--------]
104 // ^ ^
105 // 0 len
106 //
107 // 1) the range to set can be in-bounds:
108 //
109 // xxxx = [start, end]
110 // [--------]
111 // ^ ^
112 // 0 len
113 //
114 // Here, we'll simply set the single `start` to `end` range.
115 //
116 // 2) the range to set can be partially out-of-bounds:
117 //
118 // xxxx = [start, end]
119 // [--------]
120 // ^ ^
121 // 0 len
122 //
123 // We have 2 subranges to handle:
124 // - we'll set the existing `start` to `len` range.
125 // - we'll grow and set the `len` to `end` range.
126 //
127 // 3) the range to set can be fully out-of-bounds:
128 //
129 // ---xxxx = [start, end]
130 // [--------]
131 // ^ ^
132 // 0 len
133 //
134 // Since we're growing the mask to a single `new_state` value, we consider the gap
135 // from `len` to `start` to be part of the range, and have a single subrange to
136 // handle: we'll grow and set the `len` to `end` range.
137 //
138 // Note that we have to materialize, set blocks, and grow the mask. We could
139 // therefore slightly optimize things in situations where these writes overlap.
140 // However, as of writing this, growing the mask doesn't happen in practice yet, so
141 // we don't do this micro-optimization.
142143if end <= len {
144// Handle case 1.
145blocks.set_range_inbounds(start, end, new_state);
146 } else {
147if start < len {
148// Handle the first subrange of case 2.
149blocks.set_range_inbounds(start, len, new_state);
150 }
151152// Handle the second subrange of case 2, and case 3.
153blocks.grow(len, end - len, new_state); // `Size` operation
154self.len = end;
155 }
156 }
157 }
158 }
159160/// Materializes this mask's blocks when the mask is lazy.
161#[inline]
162fn materialize_blocks(&mut self) -> &mut InitMaskMaterialized {
163if let InitMaskBlocks::Lazy { state } = self.blocks {
164self.blocks = InitMaskBlocks::Materialized(InitMaskMaterialized::new(self.len, state));
165 }
166167let InitMaskBlocks::Materialized(ref mut blocks) = self.blocks else {
168crate::util::bug::bug_fmt(format_args!("initmask blocks must be materialized here"))bug!("initmask blocks must be materialized here")169 };
170blocks171 }
172173/// Returns the initialization state at the specified in-bounds index.
174#[inline]
175pub fn get(&self, idx: Size) -> bool {
176match self.blocks {
177 InitMaskBlocks::Lazy { state } => state,
178 InitMaskBlocks::Materialized(ref blocks) => blocks.get(idx),
179 }
180 }
181}
182183/// The actual materialized blocks of the bitmask, when we can't keep the `InitMask` lazy.
184// Note: for performance reasons when interning, some of the fields can be partially
185// hashed. (see the `Hash` impl below for more details), so the impl is not derived.
186#[derive(#[automatically_derived]
impl ::core::clone::Clone for InitMaskMaterialized {
#[inline]
fn clone(&self) -> InitMaskMaterialized {
InitMaskMaterialized {
blocks: ::core::clone::Clone::clone(&self.blocks),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InitMaskMaterialized {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InitMaskMaterialized", "blocks", &&self.blocks)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for InitMaskMaterialized {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Vec<Block>>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for InitMaskMaterialized {
#[inline]
fn eq(&self, other: &InitMaskMaterialized) -> bool {
self.blocks == other.blocks
}
}PartialEq, const _: () =
{
impl<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
for InitMaskMaterialized {
#[inline]
fn hash_stable(&self,
__hcx:
&mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self {
InitMaskMaterialized { blocks: ref __binding_0 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable)]
187struct InitMaskMaterialized {
188 blocks: Vec<Block>,
189}
190191// `Block` is a `u64`, but it is a bitmask not a numeric value. If we were to just derive
192// Encodable and Decodable we would apply varint encoding to the bitmasks, which is slower
193// and also produces more output when the high bits of each `u64` are occupied.
194// Note: There is probably a remaining optimization for masks that do not use an entire
195// `Block`.
196impl<E: Encoder> Encodable<E> for InitMaskMaterialized {
197fn encode(&self, encoder: &mut E) {
198encoder.emit_usize(self.blocks.len());
199for block in &self.blocks {
200 encoder.emit_raw_bytes(&block.to_le_bytes());
201 }
202 }
203}
204205// This implementation is deliberately not derived, see the matching `Encodable` impl.
206impl<D: Decoder> Decodable<D> for InitMaskMaterialized {
207fn decode(decoder: &mut D) -> Self {
208let num_blocks = decoder.read_usize();
209let mut blocks = Vec::with_capacity(num_blocks);
210for _ in 0..num_blocks {
211let bytes = decoder.read_raw_bytes(8);
212let block = u64::from_le_bytes(bytes.try_into().unwrap());
213 blocks.push(block);
214 }
215InitMaskMaterialized { blocks }
216 }
217}
218219// Const allocations are only hashed for interning. However, they can be large, making the hashing
220// expensive especially since it uses `FxHash`: it's better suited to short keys, not potentially
221// big buffers like the allocation's init mask. We can partially hash some fields when they're
222// large.
223impl hash::Hashfor InitMaskMaterialized {
224fn hash<H: hash::Hasher>(&self, state: &mut H) {
225const MAX_BLOCKS_TO_HASH: usize = super::MAX_BYTES_TO_HASH / size_of::<Block>();
226const MAX_BLOCKS_LEN: usize = super::MAX_HASHED_BUFFER_LEN / size_of::<Block>();
227228// Partially hash the `blocks` buffer when it is large. To limit collisions with common
229 // prefixes and suffixes, we hash the length and some slices of the buffer.
230let block_count = self.blocks.len();
231if block_count > MAX_BLOCKS_LEN {
232// Hash the buffer's length.
233block_count.hash(state);
234235// And its head and tail.
236self.blocks[..MAX_BLOCKS_TO_HASH].hash(state);
237self.blocks[block_count - MAX_BLOCKS_TO_HASH..].hash(state);
238 } else {
239self.blocks.hash(state);
240 }
241 }
242}
243244impl InitMaskMaterialized {
245const BLOCK_SIZE: u64 = 64;
246247fn new(size: Size, state: bool) -> Self {
248let mut m = InitMaskMaterialized { blocks: ::alloc::vec::Vec::new()vec![] };
249m.grow(Size::ZERO, size, state);
250m251 }
252253#[inline]
254fn bit_index(bits: Size) -> (usize, usize) {
255// BLOCK_SIZE is the number of bits that can fit in a `Block`.
256 // Each bit in a `Block` represents the initialization state of one byte of an allocation,
257 // so we use `.bytes()` here.
258let bits = bits.bytes();
259let a = bits / Self::BLOCK_SIZE;
260let b = bits % Self::BLOCK_SIZE;
261 (usize::try_from(a).unwrap(), usize::try_from(b).unwrap())
262 }
263264#[inline]
265fn size_from_bit_index(block: impl TryInto<u64>, bit: impl TryInto<u64>) -> Size {
266let block = block.try_into().ok().unwrap();
267let bit = bit.try_into().ok().unwrap();
268Size::from_bytes(block * Self::BLOCK_SIZE + bit)
269 }
270271/// Checks whether the `range` is entirely initialized.
272 ///
273 /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte
274 /// indexes for the first contiguous span of the uninitialized access.
275#[inline]
276fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), AllocRange> {
277let uninit_start = self.find_bit(start, end, false);
278279match uninit_start {
280Some(uninit_start) => {
281let uninit_end = self.find_bit(uninit_start, end, true).unwrap_or(end);
282Err(AllocRange::from(uninit_start..uninit_end))
283 }
284None => Ok(()),
285 }
286 }
287288fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
289let (block_a, bit_a) = Self::bit_index(start);
290let (block_b, bit_b) = Self::bit_index(end);
291if block_a == block_b {
292// First set all bits except the first `bit_a`,
293 // then unset the last `64 - bit_b` bits.
294let range = if bit_b == 0 {
295u64::MAX << bit_a296 } else {
297 (u64::MAX << bit_a) & (u64::MAX >> (64 - bit_b))
298 };
299if new_state {
300self.blocks[block_a] |= range;
301 } else {
302self.blocks[block_a] &= !range;
303 }
304return;
305 }
306// across block boundaries
307if new_state {
308// Set `bit_a..64` to `1`.
309self.blocks[block_a] |= u64::MAX << bit_a;
310// Set `0..bit_b` to `1`.
311if bit_b != 0 {
312self.blocks[block_b] |= u64::MAX >> (64 - bit_b);
313 }
314// Fill in all the other blocks (much faster than one bit at a time).
315for block in (block_a + 1)..block_b {
316self.blocks[block] = u64::MAX;
317 }
318 } else {
319// Set `bit_a..64` to `0`.
320self.blocks[block_a] &= !(u64::MAX << bit_a);
321// Set `0..bit_b` to `0`.
322if bit_b != 0 {
323self.blocks[block_b] &= !(u64::MAX >> (64 - bit_b));
324 }
325// Fill in all the other blocks (much faster than one bit at a time).
326for block in (block_a + 1)..block_b {
327self.blocks[block] = 0;
328 }
329 }
330 }
331332#[inline]
333fn get(&self, i: Size) -> bool {
334let (block, bit) = Self::bit_index(i);
335 (self.blocks[block] & (1 << bit)) != 0
336}
337338fn grow(&mut self, len: Size, amount: Size, new_state: bool) {
339if amount.bytes() == 0 {
340return;
341 }
342let unused_trailing_bits =
343u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - len.bytes();
344345// If there's not enough capacity in the currently allocated blocks, allocate some more.
346if amount.bytes() > unused_trailing_bits {
347let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
348349// We allocate the blocks to the correct value for the requested init state, so we won't
350 // have to manually set them with another write.
351let block = if new_state { u64::MAX } else { 0 };
352self.blocks
353 .extend(iter::repeat(block).take(usize::try_from(additional_blocks).unwrap()));
354 }
355356// New blocks have already been set here, so we only need to set the unused trailing bits,
357 // if any.
358if unused_trailing_bits > 0 {
359let in_bounds_tail = Size::from_bytes(unused_trailing_bits);
360self.set_range_inbounds(len, len + in_bounds_tail, new_state); // `Size` operation
361}
362 }
363364/// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init.
365fn find_bit(&self, start: Size, end: Size, is_init: bool) -> Option<Size> {
366/// A fast implementation of `find_bit`,
367 /// which skips over an entire block at a time if it's all 0s (resp. 1s),
368 /// and finds the first 1 (resp. 0) bit inside a block using `trailing_zeros` instead of a loop.
369 ///
370 /// Note that all examples below are written with 8 (instead of 64) bit blocks for simplicity,
371 /// and with the least significant bit (and lowest block) first:
372 /// ```text
373 /// 00000000|00000000
374 /// ^ ^ ^ ^
375 /// index: 0 7 8 15
376 /// ```
377 /// Also, if not stated, assume that `is_init = true`, that is, we are searching for the first 1 bit.
378fn find_bit_fast(
379 init_mask: &InitMaskMaterialized,
380 start: Size,
381 end: Size,
382 is_init: bool,
383 ) -> Option<Size> {
384/// Search one block, returning the index of the first bit equal to `is_init`.
385fn search_block(
386 bits: Block,
387 block: usize,
388 start_bit: usize,
389 is_init: bool,
390 ) -> Option<Size> {
391// For the following examples, assume this function was called with:
392 // bits = 0b00111011
393 // start_bit = 3
394 // is_init = false
395 // Note that, for the examples in this function, the most significant bit is written first,
396 // which is backwards compared to the comments in `find_bit`/`find_bit_fast`.
397398 // Invert bits so we're always looking for the first set bit.
399 // ! 0b00111011
400 // bits = 0b11000100
401let bits = if is_init { bits } else { !bits };
402// Mask off unused start bits.
403 // 0b11000100
404 // & 0b11111000
405 // bits = 0b11000000
406let bits = bits & (!0 << start_bit);
407// Find set bit, if any.
408 // bit = trailing_zeros(0b11000000)
409 // bit = 6
410if bits == 0 {
411None412 } else {
413let bit = bits.trailing_zeros();
414Some(InitMaskMaterialized::size_from_bit_index(block, bit))
415 }
416 }
417418if start >= end {
419return None;
420 }
421422// Convert `start` and `end` to block indexes and bit indexes within each block.
423 // We must convert `end` to an inclusive bound to handle block boundaries correctly.
424 //
425 // For example:
426 //
427 // (a) 00000000|00000000 (b) 00000000|
428 // ^~~~~~~~~~~^ ^~~~~~~~~^
429 // start end start end
430 //
431 // In both cases, the block index of `end` is 1.
432 // But we do want to search block 1 in (a), and we don't in (b).
433 //
434 // We subtract 1 from both end positions to make them inclusive:
435 //
436 // (a) 00000000|00000000 (b) 00000000|
437 // ^~~~~~~~~~^ ^~~~~~~^
438 // start end_inclusive start end_inclusive
439 //
440 // For (a), the block index of `end_inclusive` is 1, and for (b), it's 0.
441 // This provides the desired behavior of searching blocks 0 and 1 for (a),
442 // and searching only block 0 for (b).
443 // There is no concern of overflows since we checked for `start >= end` above.
444let (start_block, start_bit) = InitMaskMaterialized::bit_index(start);
445let end_inclusive = Size::from_bytes(end.bytes() - 1);
446let (end_block_inclusive, _) = InitMaskMaterialized::bit_index(end_inclusive);
447448// Handle first block: need to skip `start_bit` bits.
449 //
450 // We need to handle the first block separately,
451 // because there may be bits earlier in the block that should be ignored,
452 // such as the bit marked (1) in this example:
453 //
454 // (1)
455 // -|------
456 // (c) 01000000|00000000|00000001
457 // ^~~~~~~~~~~~~~~~~~^
458 // start end
459if let Some(i) =
460search_block(init_mask.blocks[start_block], start_block, start_bit, is_init)
461 {
462// If the range is less than a block, we may find a matching bit after `end`.
463 //
464 // For example, we shouldn't successfully find bit (2), because it's after `end`:
465 //
466 // (2)
467 // -------|
468 // (d) 00000001|00000000|00000001
469 // ^~~~~^
470 // start end
471 //
472 // An alternative would be to mask off end bits in the same way as we do for start bits,
473 // but performing this check afterwards is faster and simpler to implement.
474if i < end {
475return Some(i);
476 } else {
477return None;
478 }
479 }
480481// Handle remaining blocks.
482 //
483 // We can skip over an entire block at once if it's all 0s (resp. 1s).
484 // The block marked (3) in this example is the first block that will be handled by this loop,
485 // and it will be skipped for that reason:
486 //
487 // (3)
488 // --------
489 // (e) 01000000|00000000|00000001
490 // ^~~~~~~~~~~~~~~~~~^
491 // start end
492if start_block < end_block_inclusive {
493// This loop is written in a specific way for performance.
494 // Notably: `..end_block_inclusive + 1` is used for an inclusive range instead of `..=end_block_inclusive`,
495 // and `.zip(start_block + 1..)` is used to track the index instead of `.enumerate().skip().take()`,
496 // because both alternatives result in significantly worse codegen.
497 // `end_block_inclusive + 1` is guaranteed not to wrap, because `end_block_inclusive <= end / BLOCK_SIZE`,
498 // and `BLOCK_SIZE` (the number of bits per block) will always be at least 8 (1 byte).
499for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1]
500 .iter()
501 .zip(start_block + 1..)
502 {
503if let Some(i) = search_block(bits, block, 0, is_init) {
504// If this is the last block, we may find a matching bit after `end`.
505 //
506 // For example, we shouldn't successfully find bit (4), because it's after `end`:
507 //
508 // (4)
509 // -------|
510 // (f) 00000001|00000000|00000001
511 // ^~~~~~~~~~~~~~~~~~^
512 // start end
513 //
514 // As above with example (d), we could handle the end block separately and mask off end bits,
515 // but unconditionally searching an entire block at once and performing this check afterwards
516 // is faster and much simpler to implement.
517if i < end {
518return Some(i);
519 } else {
520return None;
521 }
522 }
523 }
524 }
525526None527 }
528529#[cfg_attr(not(debug_assertions), allow(dead_code))]
530fn find_bit_slow(
531 init_mask: &InitMaskMaterialized,
532 start: Size,
533 end: Size,
534 is_init: bool,
535 ) -> Option<Size> {
536 (start..end).find(|&i| init_mask.get(i) == is_init)
537 }
538539let result = find_bit_fast(self, start, end, is_init);
540541if true {
match (&result, &find_bit_slow(self, start, end, is_init)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("optimized implementation of find_bit is wrong for start={0:?} end={1:?} is_init={2} init_mask={3:#?}",
start, end, is_init, self)));
}
}
};
};debug_assert_eq!(
542 result,
543 find_bit_slow(self, start, end, is_init),
544"optimized implementation of find_bit is wrong for start={start:?} end={end:?} is_init={is_init} init_mask={self:#?}"
545);
546547result548 }
549}
550551/// A contiguous chunk of initialized or uninitialized memory.
552pub enum InitChunk {
553 Init(Range<Size>),
554 Uninit(Range<Size>),
555}
556557impl InitChunk {
558#[inline]
559pub fn is_init(&self) -> bool {
560match self {
561Self::Init(_) => true,
562Self::Uninit(_) => false,
563 }
564 }
565566#[inline]
567pub fn range(&self) -> Range<Size> {
568match self {
569Self::Init(r) => r.clone(),
570Self::Uninit(r) => r.clone(),
571 }
572 }
573}
574575impl InitMask {
576/// Returns an iterator, yielding a range of byte indexes for each contiguous region
577 /// of initialized or uninitialized bytes inside the range `start..end` (end-exclusive).
578 ///
579 /// The iterator guarantees the following:
580 /// - Chunks are nonempty.
581 /// - Chunks are adjacent (each range's start is equal to the previous range's end).
582 /// - Chunks span exactly `start..end` (the first starts at `start`, the last ends at `end`).
583 /// - Chunks alternate between [`InitChunk::Init`] and [`InitChunk::Uninit`].
584#[inline]
585pub fn range_as_init_chunks(&self, range: AllocRange) -> InitChunkIter<'_> {
586let start = range.start;
587let end = range.end();
588if !(end <= self.len) {
::core::panicking::panic("assertion failed: end <= self.len")
};assert!(end <= self.len);
589590let is_init = if start < end {
591self.get(start)
592 } else {
593// `start..end` is empty: there are no chunks, so use some arbitrary value
594false
595};
596597InitChunkIter { init_mask: self, is_init, start, end }
598 }
599}
600601/// Yields [`InitChunk`]s. See [`InitMask::range_as_init_chunks`].
602#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for InitChunkIter<'a> {
#[inline]
fn clone(&self) -> InitChunkIter<'a> {
InitChunkIter {
init_mask: ::core::clone::Clone::clone(&self.init_mask),
is_init: ::core::clone::Clone::clone(&self.is_init),
start: ::core::clone::Clone::clone(&self.start),
end: ::core::clone::Clone::clone(&self.end),
}
}
}Clone)]
603pub struct InitChunkIter<'a> {
604 init_mask: &'a InitMask,
605/// Whether the next chunk we will return is initialized.
606 /// If there are no more chunks, contains some arbitrary value.
607is_init: bool,
608/// The current byte index into `init_mask`.
609start: Size,
610/// The end byte index into `init_mask`.
611end: Size,
612}
613614impl<'a> Iteratorfor InitChunkIter<'a> {
615type Item = InitChunk;
616617#[inline]
618fn next(&mut self) -> Option<Self::Item> {
619if self.start >= self.end {
620return None;
621 }
622623let end_of_chunk = match self.init_mask.blocks {
624 InitMaskBlocks::Lazy { .. } => {
625// If we're iterating over the chunks of lazy blocks, we just emit a single
626 // full-size chunk.
627self.end
628 }
629 InitMaskBlocks::Materialized(ref blocks) => {
630let end_of_chunk =
631blocks.find_bit(self.start, self.end, !self.is_init).unwrap_or(self.end);
632end_of_chunk633 }
634 };
635let range = self.start..end_of_chunk;
636let ret =
637Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) });
638639self.is_init = !self.is_init;
640self.start = end_of_chunk;
641642ret643 }
644}
645646/// Run-length encoding of the uninit mask.
647/// Used to copy parts of a mask multiple times to another allocation.
648pub struct InitCopy {
649/// Whether the first range is initialized.
650initial: bool,
651/// The lengths of ranges that are run-length encoded.
652 /// The initialization state of the ranges alternate starting with `initial`.
653ranges: smallvec::SmallVec<[u64; 1]>,
654}
655656impl InitCopy {
657pub fn no_bytes_init(&self) -> bool {
658// The `ranges` are run-length encoded and of alternating initialization state.
659 // So if `ranges.len() > 1` then the second block is an initialized range.
660!self.initial && self.ranges.len() == 1
661}
662}
663664/// Transferring the initialization mask to other allocations.
665impl InitMask {
666/// Creates a run-length encoding of the initialization mask; panics if range is empty.
667 ///
668 /// This is essentially a more space-efficient version of
669 /// `InitMask::range_as_init_chunks(...).collect::<Vec<_>>()`.
670pub fn prepare_copy(&self, range: AllocRange) -> InitCopy {
671// Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
672 // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from
673 // the source and write it to the destination. Even if we optimized the memory accesses,
674 // we'd be doing all of this `repeat` times.
675 // Therefore we precompute a compressed version of the initialization mask of the source value and
676 // then write it back `repeat` times without computing any more information from the source.
677678 // A precomputed cache for ranges of initialized / uninitialized bits
679 // 0000010010001110 will become
680 // `[5, 1, 2, 1, 3, 3, 1]`,
681 // where each element toggles the state.
682683let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
684685let mut chunks = self.range_as_init_chunks(range).peekable();
686687let initial = chunks.peek().expect("range should be nonempty").is_init();
688689// Here we rely on `range_as_init_chunks` to yield alternating init/uninit chunks.
690for chunk in chunks {
691let len = chunk.range().end.bytes() - chunk.range().start.bytes();
692 ranges.push(len);
693 }
694695InitCopy { ranges, initial }
696 }
697698/// Applies multiple instances of the run-length encoding to the initialization mask.
699pub fn apply_copy(&mut self, defined: InitCopy, range: AllocRange, repeat: u64) {
700// An optimization where we can just overwrite an entire range of initialization bits if
701 // they are going to be uniformly `1` or `0`. If this happens to be a full-range overwrite,
702 // we won't need materialized blocks either.
703if defined.ranges.len() <= 1 {
704let start = range.start;
705let end = range.start + range.size * repeat; // `Size` operations
706self.set_range(AllocRange::from(start..end), defined.initial);
707return;
708 }
709710// We're about to do one or more partial writes, so we ensure the blocks are materialized.
711let blocks = self.materialize_blocks();
712713for mut j in 0..repeat {
714 j *= range.size.bytes();
715 j += range.start.bytes();
716let mut cur = defined.initial;
717for range in &defined.ranges {
718let old_j = j;
719 j += range;
720 blocks.set_range_inbounds(Size::from_bytes(old_j), Size::from_bytes(j), cur);
721 cur = !cur;
722 }
723 }
724 }
725}