Skip to content

Commit 6c9954e

Browse files
committed
Optimize TreeNodeIndex with wrapping operations (checked in godbolt.org)
1 parent 5f69161 commit 6c9954e

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

compiler/rustc_data_structures/src/tree_node_index.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,13 @@ impl TreeNodeIndex {
4040
fn try_bits_branch(self, branch_idx: u64, bits: u32) -> Result<Self, BranchingError> {
4141
let trailing_zeros = self.0.trailing_zeros();
4242
let allocated_shift = trailing_zeros.checked_sub(bits).ok_or(BranchingError(()))?;
43+
// Using wrapping operations for optimization, as edge cases are unreachable:
44+
// - `trailing_zeros < 64` as we are guaranteed at least one bit is set
45+
// - `allocated_shift == trailing_zeros - bits <= trailing_zeros < 64`
4346
Ok(TreeNodeIndex(
44-
self.0 & !(1 << trailing_zeros)
45-
| (1 << allocated_shift)
46-
| branch_idx.unbounded_shl(allocated_shift + 1),
47+
self.0 & !u64::wrapping_shl(1, trailing_zeros)
48+
| u64::wrapping_shl(1, allocated_shift)
49+
| branch_idx.unbounded_shl(allocated_shift.wrapping_add(1)),
4750
))
4851
}
4952

@@ -61,8 +64,9 @@ impl TreeNodeIndex {
6164

6265
#[inline]
6366
fn ceil_ilog2(branch_num: u64) -> u32 {
64-
// floor(log2(n - 1)) + 1 == ceil(log2(n))
65-
(branch_num - 1).checked_ilog2().map_or(0, |b| b + 1)
67+
// Using `wrapping_sub` for optimization, consider `log(0)` to be undefined
68+
// `floor(log2(n - 1)) + 1 == ceil(log2(n))`
69+
branch_num.wrapping_sub(1).checked_ilog2().map_or(0, |b| b.wrapping_add(1))
6670
}
6771

6872
/// Error for exhausting free bits

0 commit comments

Comments
 (0)