Skip to content

Truly independent web browser

LibJS/JIT: Keep the data of all passes and of the graph helpers in zones

Andreas Kling95a2a230bf29
diff --git a/Libraries/LibJS/JIT/Rust/clippy.toml b/Libraries/LibJS/JIT/Rust/clippy.toml
index 112251f6b15..76cc57aa7d3 100644
--- a/Libraries/LibJS/JIT/Rust/clippy.toml
+++ b/Libraries/LibJS/JIT/Rust/clippy.toml
@@ -52,6 +52,10 @@ disallowed-methods = [
{ path = "f64::asinh", reason = "the C library of each platform computes this differently: use ak::math::asinh" },
{ path = "f64::acosh", reason = "the C library of each platform computes this differently: use ak::math::acosh" },
{ path = "f64::atanh", reason = "the C library of each platform computes this differently: use ak::math::atanh" },
+ { path = "slice::sort", reason = "a stable sort makes a block in the heap: use sort_unstable, with a key that has no ties" },
+ { path = "slice::sort_by", reason = "a stable sort makes a block in the heap: use sort_unstable_by, with a key that has no ties" },
+ { path = "slice::sort_by_key", reason = "a stable sort makes a block in the heap: use sort_unstable_by_key, with a key that has no ties" },
+ { path = "slice::sort_by_cached_key", reason = "this sort makes a block in the heap: use sort_unstable_by_key, with a key that has no ties" },
]
# The compiler keeps its data in zones (see ak::Zone), so that all the memory of a compile can go back to the system.
@@ -68,8 +72,6 @@ disallowed-types = [
{ path = "std::boxed::Box", reason = "the compiler makes no block in the heap: use Zone::alloc" },
{ path = "std::rc::Rc", reason = "the compiler makes no block in the heap: share a reference into a zone" },
{ path = "std::sync::Arc", reason = "the compiler makes no block in the heap: share a reference into a zone" },
- { path = "libjs_jit::bitset::BitSet", reason = "the compiler makes no block in the heap: use crate::bitset::ZoneBitSet" },
- { path = "libjs_jit::sparse_bitset::SparseBitSet", reason = "the compiler makes no block in the heap: use crate::bitset::ZoneBitSet" },
{ path = "libjs_jit::inline_vec::InlineVec", reason = "the compiler makes no block in the heap: use ak::ZoneVec" },
{ path = "libjs_jit::fast_hash::HashMap", reason = "the compiler makes no block in the heap: use crate::zone_map::ZoneMap" },
{ path = "libjs_jit::fast_hash::HashSet", reason = "the compiler makes no block in the heap: use crate::zone_map::ZoneSet" },
diff --git a/Libraries/LibJS/JIT/Rust/src/bitset.rs b/Libraries/LibJS/JIT/Rust/src/bitset.rs
index 20ec55ee4bf..87e144ceb9a 100644
--- a/Libraries/LibJS/JIT/Rust/src/bitset.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bitset.rs
@@ -9,167 +9,6 @@
use ak::Zone;
use ak::ZoneVec;
-#[derive(PartialEq, Eq, Default)]
-pub struct BitSet {
- // NB: Most bytecode liveness sets fit in one word and need no allocation.
- first_word: u64,
- extra_words: Vec<u64>,
- len: usize,
-}
-
-impl Clone for BitSet {
- fn clone(&self) -> Self {
- Self {
- first_word: self.first_word,
- extra_words: self.extra_words.clone(),
- len: self.len,
- }
- }
-
- fn clone_from(&mut self, other: &Self) {
- self.first_word = other.first_word;
- self.extra_words.clone_from(&other.extra_words);
- self.len = other.len;
- }
-}
-
-impl BitSet {
- /// An empty set that can hold the integers `0..len`.
- pub fn new(len: usize) -> Self {
- Self {
- first_word: 0,
- extra_words: vec![0; len.div_ceil(64).saturating_sub(1)],
- len,
- }
- }
-
- /// The exclusive upper bound of the integers this set can hold.
- pub fn capacity(&self) -> usize {
- self.len
- }
-
- pub fn contains(&self, index: usize) -> bool {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- let word = if index < 64 {
- self.first_word
- } else {
- self.extra_words[index / 64 - 1]
- };
- word & (1 << (index % 64)) != 0
- }
-
- pub fn insert(&mut self, index: usize) {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- if index < 64 {
- self.first_word |= 1 << index;
- } else {
- self.extra_words[index / 64 - 1] |= 1 << (index % 64);
- }
- }
-
- pub fn remove(&mut self, index: usize) {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- if index < 64 {
- self.first_word &= !(1 << index);
- } else {
- self.extra_words[index / 64 - 1] &= !(1 << (index % 64));
- }
- }
-
- pub fn insert_range(&mut self, range: std::ops::Range<usize>) {
- for index in range {
- self.insert(index);
- }
- }
-
- /// Adds every element of `other`. Returns whether this set changed.
- pub fn union_with(&mut self, other: &BitSet) -> bool {
- assert_eq!(self.len, other.len, "union of differently sized sets");
- let first_word = self.first_word | other.first_word;
- let mut changed = first_word != self.first_word;
- self.first_word = first_word;
- for (word, other_word) in self.extra_words.iter_mut().zip(&other.extra_words) {
- let new_word = *word | other_word;
- changed |= new_word != *word;
- *word = new_word;
- }
- changed
- }
-
- /// Removes every element of `other`.
- pub fn subtract(&mut self, other: &BitSet) {
- assert_eq!(self.len, other.len, "difference of differently sized sets");
- self.first_word &= !other.first_word;
- for (word, other_word) in self.extra_words.iter_mut().zip(&other.extra_words) {
- *word &= !other_word;
- }
- }
-
- pub fn is_empty(&self) -> bool {
- self.first_word == 0 && self.extra_words.iter().all(|word| *word == 0)
- }
-
- pub fn count(&self) -> usize {
- self.first_word.count_ones() as usize
- + self
- .extra_words
- .iter()
- .map(|word| word.count_ones() as usize)
- .sum::<usize>()
- }
-
- /// The elements in increasing order.
- pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
- std::iter::once(&self.first_word)
- .chain(&self.extra_words)
- .enumerate()
- .flat_map(|(word_index, word)| {
- let mut bits = *word;
- std::iter::from_fn(move || {
- if bits == 0 {
- return None;
- }
- let bit = bits.trailing_zeros() as usize;
- bits &= bits - 1;
- Some(word_index * 64 + bit)
- })
- })
- }
-}
-
-/// A set of small integers that is fixed in size: a `BitSet` or a `ZoneBitSet`.
-pub trait IndexSet {
- /// The exclusive upper bound of the integers this set can hold.
- fn capacity(&self) -> usize;
- fn contains(&self, index: usize) -> bool;
-}
-
-impl IndexSet for BitSet {
- fn capacity(&self) -> usize {
- BitSet::capacity(self)
- }
-
- fn contains(&self, index: usize) -> bool {
- BitSet::contains(self, index)
- }
-}
-
-impl IndexSet for ZoneBitSet<'_> {
- fn capacity(&self) -> usize {
- ZoneBitSet::capacity(self)
- }
-
- fn contains(&self, index: usize) -> bool {
- ZoneBitSet::contains(self, index)
- }
-}
-
-impl std::fmt::Debug for BitSet {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- formatter.debug_set().entries(self.iter()).finish()
- }
-}
-
/// A fixed-size set of small integers, whose words are in a zone (see `ak::Zone`).
#[derive(PartialEq, Eq)]
pub struct ZoneBitSet<'z> {
@@ -316,38 +155,17 @@ impl std::fmt::Debug for ZoneBitSet<'_> {
mod tests {
use super::*;
- #[test]
- fn inserts_removes_and_iterates_across_words() {
- let mut set = BitSet::new(130);
- assert!(set.is_empty());
- for index in [0, 63, 64, 129] {
- set.insert(index);
- }
- assert!(set.contains(63) && set.contains(64) && !set.contains(65));
- assert_eq!(set.iter().collect::<Vec<_>>(), [0, 63, 64, 129]);
- set.remove(63);
- assert_eq!(set.count(), 3);
-
- let mut other = BitSet::new(130);
- other.insert(1);
- assert!(set.union_with(&other));
- assert!(!set.union_with(&other));
- assert_eq!(set.iter().collect::<Vec<_>>(), [0, 1, 64, 129]);
- other.insert(129);
- set.subtract(&other);
- assert_eq!(set.iter().collect::<Vec<_>>(), [0, 64]);
- }
-
#[test]
fn empty_and_single_word_sets_clone_without_losing_bits() {
+ let zone = Zone::new(1 << 20, c"test");
for len in [0, 1, 63, 64, 65, 128, 129] {
- let mut set = BitSet::new(len);
+ let mut set = ZoneBitSet::new_in(len, &zone);
assert_eq!(set.capacity(), len);
assert!(set.iter().next().is_none());
if len > 0 {
set.insert(len - 1);
}
- let mut cloned = BitSet::new(130);
+ let mut cloned = ZoneBitSet::new_in(130, &zone);
cloned.clone_from(&set);
assert_eq!(cloned, set);
assert_eq!(cloned.count(), usize::from(len > 0));
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 01275050a92..9b318c6eb01 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -789,7 +789,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
}
}
assert_eq!(graph.blocks.len(), self.order.len(), "every created block was started");
- graph.reorder_blocks(&self.order);
+ graph.reorder_blocks(&self.order, self.work);
for block in &graph.blocks {
assert!(block.control.is_some(), "every block was finished");
for phi in &block.phis {
@@ -1225,7 +1225,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// every iteration, also where on-stack replacement entries reach the header over back edges.
let reloaded = self.graph.block(header).body.contains(&header_value.node)
&& matches!(self.graph.node(header_value.node).op, Op::LoadSlot { .. });
- if !reloaded && !self.graph.has_value_of(current.node, header_value.node) {
+ if !reloaded && !self.graph.has_value_of(current.node, header_value.node, self.work) {
return Err(CompileFailure::InvalidBytecode {
pc: self.function.pc,
reason: "loop back edge changes a value the loop does not assign",
@@ -1616,7 +1616,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// never empty needs no check for it.
let layout = self.function.layout;
let arguments = layout.arguments_base()..layout.arguments_base() + layout.number_of_arguments;
- let value = if self.graph.is_known_non_empty(value, arguments) {
+ let value = if self.graph.is_known_non_empty(value, arguments, self.work) {
value
} else {
self.emit(Op::EmptyToUndefined, &[value], Some(Repr::Tagged))
@@ -1988,7 +1988,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// `undefined`.
let layout = self.function.layout;
let arguments = layout.arguments_base()..layout.arguments_base() + layout.number_of_arguments;
- let value = if self.graph.is_known_non_empty(value, arguments) {
+ let value = if self.graph.is_known_non_empty(value, arguments, self.work) {
value
} else {
self.emit(Op::EmptyToUndefined, &[value], Some(Repr::Tagged))
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
index c8748fef7d4..774f56a7b7a 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
@@ -307,7 +307,8 @@ impl<'w> Cfg<'w> {
mut back_edges: ZoneVec<'w, (BlockIndex, BlockIndex)>,
) {
let zone = self.blocks.zone();
- back_edges.sort_by_key(|(source, header)| (self.blocks[*header].rpo_number, *source));
+ // NB: Edges with the same key are the same edge, so the order of equal keys does not matter.
+ back_edges.sort_unstable_by_key(|(source, header)| (self.blocks[*header].rpo_number, *source));
let mut loops: ZoneVec<'w, Loop<'w>> = ZoneVec::new_in(zone);
for &(source, header) in &back_edges {
if let Some(existing) = loops.last_mut().filter(|existing| existing.header == header) {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index c10f1b06903..634d6448550 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -872,6 +872,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {
kind,
stack_slot_offset: &|slot| self.frame_pointer_offset(slot),
saves: &saves,
+ work: self.work,
})
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
index b6f2a3142db..3e312bb508b 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
@@ -8,6 +8,7 @@
//! state, from the register allocation.
use ak::Column;
+use ak::Zone;
use crate::CompileFailure;
use crate::artifact::ArtifactWriter;
@@ -179,6 +180,8 @@ pub(crate) struct SiteSource<'a> {
/// Registers that are in the saves area at the site and not where they were allocated, with the frame pointer
/// offsets of their words there.
pub saves: &'a [(Gpr, i32)],
+ /// Where the site keeps the lists it makes while it is written.
+ pub work: &'a Zone,
}
impl SiteSource<'_> {
@@ -187,7 +190,7 @@ impl SiteSource<'_> {
let graph = self.graph;
let frame_state = graph.node(self.node).frame_state.expect("the node has a frame state");
let frame = scratch.frame_record(graph, frame_state, artifact)?;
- let objects = graph.virtual_objects(frame_state);
+ let objects = graph.virtual_objects(frame_state, self.work);
if !objects.is_empty() && !artifact.frame_has_objects(frame) {
let objects = objects.iter().map(|object| {
let Op::VirtualObject { kind, allocation } = graph.node(*object).op else {
@@ -248,7 +251,7 @@ impl SiteSource<'_> {
.node(self.node)
.frame_state
.expect("the node has a frame state");
- let objects = self.graph.virtual_objects(frame_state);
+ let objects = self.graph.virtual_objects(frame_state, self.work);
let mut locations = self.locations(&objects);
let mut values = Vec::new();
let mut next = Some(frame_state);
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index ce10df6e8c1..aed167c37fa 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -32,6 +32,15 @@ pub fn slot_name(layout: &FrameLayout, slot: u32) -> String {
}
}
+/// `text` with `item` after it, and a comma between the two if `text` is not empty.
+fn join(mut text: String, item: String) -> String {
+ if !text.is_empty() {
+ text.push_str(", ");
+ }
+ text.push_str(&item);
+ text
+}
+
fn value_name(graph: &Graph, id: NodeId) -> String {
match (graph.constant_value(id), graph.node(id).repr) {
(Some(bits), Some(Repr::Int32)) => format!("#i32:{}", (bits as u32).cast_signed()),
@@ -62,8 +71,7 @@ fn shapes_text<'a>(shapes: impl Iterator<Item = &'a ShapeCheck>) -> String {
Some(generation) => format!("{:#x}@{generation}", shape.shape.0),
None => format!("{:#x}", shape.shape.0),
})
- .collect::<Vec<_>>()
- .join(", ")
+ .fold(String::new(), join)
}
fn condition_text(condition: BranchCondition) -> String {
@@ -285,8 +293,8 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
.iter()
.zip(*targets)
.map(|(shape, block)| format!("{} -> {}", shapes_text(std::iter::once(shape)), block_name(*block)))
- .collect::<Vec<_>>();
- format!("{} [{}]", with_inputs("ShapeSwitch"), cases.join(", "))
+ .fold(String::new(), join);
+ format!("{} [{}]", with_inputs("ShapeSwitch"), cases)
}
Op::CallSlowPath {
opcode, executable, pc, ..
@@ -429,8 +437,8 @@ pub fn node_text(graph: &Graph, layout: &FrameLayout, node_id: NodeId) -> String
.inputs
.iter()
.map(|input| value_name(graph, *input))
- .collect::<Vec<_>>();
- format!("({})", inputs.join(", "))
+ .fold(String::new(), join);
+ format!("({inputs})")
};
out.push_str(&op_text(layout, &node.op, &inputs));
if let Some(frame_state) = node.frame_state {
@@ -453,8 +461,8 @@ pub fn dump(graph: &Graph, layout: &FrameLayout) -> String {
.predecessors
.iter()
.map(|block| block_name(*block))
- .collect::<Vec<_>>();
- write!(out, " <- {}", predecessors.join(", ")).unwrap();
+ .fold(String::new(), join);
+ write!(out, " <- {predecessors}").unwrap();
}
if block.is_loop_header {
out.push_str(" loop");
@@ -490,15 +498,15 @@ pub fn dump(graph: &Graph, layout: &FrameLayout) -> String {
.values
.iter()
.map(|(slot, value)| format!("{}={}", slot_name(layout, *slot), value_name(graph, *value)))
- .collect::<Vec<_>>();
- write!(out, " {{{}}}", values.join(", ")).unwrap();
+ .fold(String::new(), join);
+ write!(out, " {{{values}}}").unwrap();
if !frame_state.in_frame.is_empty() {
let in_frame = frame_state
.in_frame
.iter()
.map(|slot| slot_name(layout, *slot))
- .collect::<Vec<_>>();
- write!(out, " frame [{}]", in_frame.join(", ")).unwrap();
+ .fold(String::new(), join);
+ write!(out, " frame [{in_frame}]").unwrap();
}
if let Some(parent) = frame_state.parent {
write!(out, " in fs{}", parent.0).unwrap();
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/info.rs b/Libraries/LibJS/JIT/Rust/src/ir/info.rs
index 779b742cf44..693ee6c06e0 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/info.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/info.rs
@@ -127,38 +127,49 @@ impl Inputs {
/// The representations of `count` inputs, if they are of this signature, or `None` if `count` is wrong. A
/// `HelperCall` of an intrinsic without one, and `Unchecked`, accept anything.
- pub fn reprs(self, count: usize) -> Result<Option<Vec<Repr>>, usize> {
- match self {
- Inputs::Exactly(reprs) if reprs.len() == count => Ok(Some(reprs.to_vec())),
- Inputs::Exactly(reprs) => Err(reprs.len()),
- Inputs::AtLeast(first, rest) if count >= first.len() => Ok(Some(
- first
- .iter()
- .copied()
- .chain(std::iter::repeat_n(rest, count - first.len()))
- .collect(),
- )),
- Inputs::AtLeast(first, _) => Err(first.len()),
- Inputs::WithOptional(first, _) if count == first.len() => Ok(Some(first.to_vec())),
- Inputs::WithOptional(first, optional) if count == first.len() + optional.len() => {
- Ok(Some(first.iter().chain(optional).copied().collect()))
+ pub fn reprs(self, count: usize) -> Result<Option<impl Iterator<Item = Repr>>, usize> {
+ let takes = match self {
+ Inputs::Exactly(reprs) if reprs.len() == count => true,
+ Inputs::Exactly(reprs) => return Err(reprs.len()),
+ Inputs::AtLeast(first, _) if count >= first.len() => true,
+ Inputs::AtLeast(first, _) => return Err(first.len()),
+ Inputs::WithOptional(first, optional) => {
+ if count != first.len() && count != first.len() + optional.len() {
+ return Err(first.len());
+ }
+ true
}
- Inputs::WithOptional(first, _) => Err(first.len()),
Inputs::HelperCall(intrinsic) => {
let Some(call) = intrinsic.helper_call() else {
return Ok(None);
};
- let reprs = std::iter::once(call.receiver)
- .chain(call.arguments.iter().copied())
- .map(|operand| operand.repr())
- .collect::<Vec<_>>();
- if reprs.len() == count {
- Ok(Some(reprs))
- } else {
- Err(reprs.len())
+ if call.arguments.len() + 1 != count {
+ return Err(call.arguments.len() + 1);
+ }
+ true
+ }
+ Inputs::Unchecked => false,
+ };
+ Ok(takes.then(|| (0..count).map(move |index| self.repr(index))))
+ }
+
+ /// The representation of input `index`, of a count of inputs that `reprs()` accepts.
+ fn repr(self, index: usize) -> Repr {
+ match self {
+ Inputs::Exactly(reprs) => reprs[index],
+ Inputs::AtLeast(first, rest) => first.get(index).copied().unwrap_or(rest),
+ Inputs::WithOptional(first, optional) => first
+ .get(index)
+ .copied()
+ .unwrap_or_else(|| optional[index - first.len()]),
+ Inputs::HelperCall(intrinsic) => {
+ let call = intrinsic.helper_call().expect("the intrinsic has a helper call");
+ match index {
+ 0 => call.receiver.repr(),
+ _ => call.arguments[index - 1].repr(),
}
}
- Inputs::Unchecked => Ok(None),
+ Inputs::Unchecked => unreachable!("unchecked inputs have no representations"),
}
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 995a2893891..e208d899587 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -1847,14 +1847,15 @@ impl<'z> Graph<'z> {
/// Whether `node` never is the empty value. `arguments` are the slots
/// of the compiled function's arguments, which always hold values.
- pub fn is_known_non_empty(&self, node: NodeId, arguments: core::ops::Range<u32>) -> bool {
- let mut pending = vec![node];
- let mut seen = Vec::new();
- while let Some(node) = pending.pop() {
+ pub fn is_known_non_empty(&self, node: NodeId, arguments: core::ops::Range<u32>, work: &Zone) -> bool {
+ // NB: Only phis lead to other nodes, so only they are kept in `seen`.
+ let mut pending = ZoneVec::new_in(work);
+ let mut seen = ZoneVec::new_in(work);
+ let mut next = Some(node);
+ while let Some(node) = next.take().or_else(|| pending.pop()) {
if seen.contains(&node) {
continue;
}
- seen.push(node);
let data = self.node(node);
if data.repr.is_some_and(|repr| repr != Repr::Tagged) {
continue;
@@ -1862,7 +1863,10 @@ impl<'z> Graph<'z> {
match &data.op {
Op::Constant(bits) if *bits != value::EMPTY => {}
Op::LoadSlot { slot } if arguments.contains(&crate::bytecode::Operand::from_raw(*slot).raw()) => {}
- Op::Phi => pending.extend(data.inputs.iter().copied()),
+ Op::Phi => {
+ seen.push(node);
+ pending.extend(data.inputs.iter().copied());
+ }
op if op.info().never_empty => {}
_ => return false,
}
@@ -1885,12 +1889,12 @@ impl<'z> Graph<'z> {
/// The values `node` uses: its inputs, then the values of its frame
/// state.
- pub fn used_values(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
+ pub fn used_values<'a>(&'a self, node: NodeId, work: &'a Zone) -> impl Iterator<Item = NodeId> + 'a {
let data = self.node(node);
data.inputs.iter().copied().chain(
data.frame_state
.into_iter()
- .flat_map(|id| self.frame_state_values(id).map(|(_, value)| value)),
+ .flat_map(move |id| self.frame_state_values(id, work).map(|(_, value)| value)),
)
}
@@ -1932,9 +1936,15 @@ impl<'z> Graph<'z> {
/// They are followed by the properties of the virtual objects among them
/// (see `virtual_objects()`), in order, with the slot
/// `VIRTUAL_OBJECT_PROPERTY`: exits need those values too.
- pub fn frame_state_values(&self, id: FrameStateId) -> impl Iterator<Item = (u32, NodeId)> + '_ {
+ ///
+ /// The list of the virtual objects goes in `work`, if the chain has any.
+ pub fn frame_state_values<'a>(
+ &'a self,
+ id: FrameStateId,
+ work: &'a Zone,
+ ) -> impl Iterator<Item = (u32, NodeId)> + 'a {
self.chain_values(id).chain(
- std::iter::once_with(move || self.virtual_objects(id))
+ std::iter::once_with(move || self.virtual_objects(id, work))
.flatten()
.flat_map(|object| {
self.node(object)
@@ -1948,21 +1958,23 @@ impl<'z> Graph<'z> {
/// The virtual objects the values of a frame state chain refer to,
/// directly or through other virtual objects, each once, in the order
/// they are first referred to.
- pub fn virtual_objects(&self, id: FrameStateId) -> Vec<NodeId> {
+ pub fn virtual_objects<'w>(&self, id: FrameStateId, work: &'w Zone) -> ZoneVec<'w, NodeId> {
let is_virtual_object = |value: NodeId| matches!(self.node(value).op, Op::VirtualObject { .. });
+ let mut objects = ZoneVec::new_in(work);
// NB: Most frame states refer to no virtual object.
if !self.chain_values(id).any(|(_, value)| is_virtual_object(value)) {
- return Vec::new();
+ return objects;
}
- let mut objects = Vec::new();
- let mut pending = self.chain_values(id).map(|(_, value)| value).collect::<Vec<_>>();
- pending.reverse();
- while let Some(value) = pending.pop() {
- if !is_virtual_object(value) || objects.contains(&value) {
- continue;
+ let mut pending = ZoneVec::new_in(work);
+ for (_, value) in self.chain_values(id) {
+ pending.push(value);
+ while let Some(value) = pending.pop() {
+ if !is_virtual_object(value) || objects.contains(&value) {
+ continue;
+ }
+ objects.push(value);
+ pending.extend(self.node(value).inputs.iter().rev().copied());
}
- objects.push(value);
- pending.extend(self.node(value).inputs.iter().rev().copied());
}
objects
}
@@ -2027,11 +2039,11 @@ impl<'z> Graph<'z> {
/// Reorders the blocks so that `order[i]` becomes block `i`. Blocks not
/// in `order` are dropped; nothing may refer to them.
- pub fn reorder_blocks(&mut self, order: &[BlockId]) {
+ pub fn reorder_blocks(&mut self, order: &[BlockId], work: &Zone) {
if order.len() == self.blocks.len() && order.iter().enumerate().all(|(index, block)| block.index() == index) {
return;
}
- let mut new_index = vec![None; self.blocks.len()];
+ let mut new_index = ZoneVec::from_elem_in(None, self.blocks.len(), work);
for (index, block) in order.iter().enumerate() {
assert!(new_index[block.index()].is_none(), "blocks appear once in the order");
new_index[block.index()] = Some(BlockId::from_index(index));
@@ -2109,10 +2121,11 @@ impl<'z> Graph<'z> {
/// Whether `id` always has the value of `value`, because it refines
/// `value` or a phi whose inputs all have that value.
- pub fn has_value_of(&self, id: NodeId, value: NodeId) -> bool {
- let mut pending = vec![id];
- let mut seen = Vec::new();
- while let Some(mut node) = pending.pop() {
+ pub fn has_value_of(&self, id: NodeId, value: NodeId, work: &Zone) -> bool {
+ let mut pending = ZoneVec::new_in(work);
+ let mut seen = ZoneVec::new_in(work);
+ let mut next = Some(id);
+ while let Some(mut node) = next.take().or_else(|| pending.pop()) {
while node != value
&& let Some(index) = self.node(node).op.refined_input()
{
@@ -2121,10 +2134,10 @@ impl<'z> Graph<'z> {
if node == value || seen.contains(&node) {
continue;
}
- seen.push(node);
if !matches!(self.node(node).op, Op::Phi) {
return false;
}
+ seen.push(node);
pending.extend(self.node(node).inputs.iter().copied());
}
true
@@ -2180,7 +2193,7 @@ mod tests {
graph.osr_entries.push((10, BlockId(3)));
let storage = graph.blocks.as_ptr();
let order = order.map(BlockId);
- graph.reorder_blocks(&order);
+ graph.reorder_blocks(&order, crate::test_zone());
assert_eq!(graph.blocks.as_ptr(), storage);
assert_eq!(graph.blocks.len(), 3);
for (index, old) in order.iter().enumerate() {
@@ -2217,9 +2230,11 @@ mod tests {
);
let parent = state(&mut graph, vec![(0, value), (1, inner)], None);
let current = state(&mut graph, vec![(0, outer), (1, inner)], Some(parent));
- assert_eq!(graph.virtual_objects(current), [outer, inner]);
+ assert_eq!(graph.virtual_objects(current, crate::test_zone()), [outer, inner]);
assert_eq!(
- graph.frame_state_values(current).collect::<Vec<_>>(),
+ graph
+ .frame_state_values(current, crate::test_zone())
+ .collect::<Vec<_>>(),
[
(0, outer),
(1, inner),
@@ -2231,12 +2246,12 @@ mod tests {
]
);
graph.nodes[inner.index()].inputs.push(outer);
- assert_eq!(graph.virtual_objects(current), [outer, inner]);
+ assert_eq!(graph.virtual_objects(current, crate::test_zone()), [outer, inner]);
assert_eq!(
- graph.frame_state_values(current).last(),
+ graph.frame_state_values(current, crate::test_zone()).last(),
Some((VIRTUAL_OBJECT_PROPERTY, outer))
);
let empty = state(&mut graph, vec![], None);
- assert_eq!(graph.frame_state_values(empty).count(), 0);
+ assert_eq!(graph.frame_state_values(empty, crate::test_zone()).count(), 0);
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index a184403351c..b5841f7e6a2 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -20,7 +20,6 @@
pub mod artifact;
#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod asm;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod bitset;
pub mod builder;
pub mod bytecode;
@@ -36,7 +35,6 @@ pub mod coverage;
pub mod fast_hash;
#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod inline_vec;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod ir;
#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod options;
@@ -46,8 +44,6 @@ pub mod regalloc;
pub mod scratch;
#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod snapshot;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
-pub mod sparse_bitset;
pub mod tables;
pub mod zone_map;
@@ -212,9 +208,9 @@ fn run_stages<M: asm::PortableMacroAssembler>(
if snapshot.options.stress.few_registers {
registers.allocatable_gprs = registers.few_registers(STRESS_EXTRA_REGISTERS);
}
- regalloc::allocate(&graph, &registers, &mut tables.regalloc, &mut tables.dominators)?;
+ work.scope(|work| regalloc::allocate(&graph, &registers, &mut tables.regalloc, &mut tables.dominators, work))?;
if snapshot.options.verify_ir
- && let Err(errors) = regalloc::verify(&graph, &registers, &tables.regalloc.allocation)
+ && let Err(errors) = work.scope(|work| regalloc::verify(&graph, &registers, &tables.regalloc.allocation, work))
{
panic!(
"invalid register allocation:\n{errors}\n{}",
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs
index 39105abb184..acffe932549 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs
@@ -45,14 +45,14 @@
use ak::ColumnFull;
use ak::Zone;
+use ak::ZoneVec;
use super::dominators::Dominators;
use super::edit::Constants;
use super::edit::Replacements;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::code::ExitKind;
use crate::code::Repr;
-use crate::fast_hash::HashMap;
use crate::ir::BinaryOp;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
@@ -61,6 +61,7 @@ use crate::ir::Graph;
use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
+use crate::zone_map::ZoneMap;
/// The inclusive range of an int32 value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -117,11 +118,11 @@ struct Ranges<'a> {
graph: &'a Graph<'a>,
dominators: &'a Dominators,
/// The block of each phi.
- phi_blocks: &'a HashMap<NodeId, BlockId>,
+ phi_blocks: &'a ZoneMap<'a, NodeId, BlockId>,
/// The ranges of entering counters that checks added where they enter
/// would give them.
- assumed: &'a HashMap<NodeId, Range>,
- known: HashMap<NodeId, Option<Range>>,
+ assumed: &'a ZoneMap<'a, NodeId, Range>,
+ known: ZoneMap<'a, NodeId, Option<Range>>,
}
impl Ranges<'_> {
@@ -163,9 +164,8 @@ impl Ranges<'_> {
}
match node.op {
Op::Phi if self.is_merge(value) => {
- let inputs = node.inputs.to_vec();
let mut range: Option<Range> = None;
- for input in inputs {
+ for input in node.inputs.iter().copied() {
let input = self.of(input)?;
range = Some(match range {
None => input,
@@ -391,9 +391,16 @@ impl Ranges<'_> {
}
/// The entering counters of `assumed` that the range of `value` relies
- /// on, added to `used`.
- fn assumptions_of(&self, value: NodeId, used: &mut BitSet, visited: &mut BitSet) {
- let mut pending = vec![value];
+ /// on, added to `used`. `pending` is for its own use.
+ fn assumptions_of(
+ &self,
+ value: NodeId,
+ used: &mut ZoneBitSet,
+ visited: &mut ZoneBitSet,
+ pending: &mut ZoneVec<NodeId>,
+ ) {
+ pending.clear();
+ pending.push(value);
while let Some(value) = pending.pop() {
if visited.contains(value.index()) {
continue;
@@ -422,10 +429,10 @@ fn bounds_index(op: &Op) -> bool {
}
/// The blocks that only on-stack replacement entries reach.
-fn osr_only_blocks(graph: &Graph) -> BitSet {
- let reach = |starts: Vec<BlockId>| {
- let mut reached = BitSet::new(graph.blocks.len());
- let mut pending = starts;
+fn osr_only_blocks<'w>(graph: &Graph, work: &'w Zone) -> ZoneBitSet<'w> {
+ let reach = |starts: &mut dyn Iterator<Item = BlockId>| {
+ let mut reached = ZoneBitSet::new_in(graph.blocks.len(), work);
+ let mut pending = ZoneVec::from_iter_in(starts, work);
while let Some(block) = pending.pop() {
if reached.contains(block.index()) {
continue;
@@ -435,38 +442,41 @@ fn osr_only_blocks(graph: &Graph) -> BitSet {
}
reached
};
- let mut osr = reach(graph.osr_entries.iter().map(|(_, block)| *block).collect());
- osr.subtract(&reach(vec![BlockId::from_index(0)]));
+ let mut osr = reach(&mut graph.osr_entries.iter().map(|(_, block)| *block));
+ osr.subtract(&reach(&mut core::iter::once(BlockId::from_index(0))));
osr
}
/// The counters that on-stack replacement entries bring to induction
/// variables and check to be int32 values, with the bound each could be
/// checked against: the tightest of the loops it starts.
-fn entering_counters(
+fn entering_counters<'w>(
graph: &Graph,
dominators: &Dominators,
- phi_blocks: &HashMap<NodeId, BlockId>,
-) -> HashMap<NodeId, Range> {
- let mut entering = HashMap::default();
+ phi_blocks: &ZoneMap<NodeId, BlockId>,
+ work: &'w Zone,
+) -> ZoneMap<'w, NodeId, Range> {
+ let mut entering = ZoneMap::new_in(work);
if graph.osr_entries.is_empty() {
return entering;
}
- let osr_only = osr_only_blocks(graph);
- let mut block_of = HashMap::default();
+ let osr_only = osr_only_blocks(graph, work);
+ let mut block_of = ZoneMap::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
for node in &block.body {
block_of.insert(*node, index);
}
}
- let none = HashMap::default();
+ let none = ZoneMap::new_in(work);
let ranges = Ranges {
graph,
dominators,
phi_blocks,
assumed: &none,
- known: HashMap::default(),
+ known: ZoneMap::new_in(work),
};
+ let mut pending = ZoneVec::new_in(work);
+ let mut seen = ZoneBitSet::new_in(graph.nodes.len(), work);
for phi in phi_blocks.keys() {
let Some((_, comparison, bound)) = ranges.induction_step(*phi) else {
continue;
@@ -480,8 +490,9 @@ fn entering_counters(
continue;
}
// NB: Look through merges of the values the entries bring.
- let mut pending = vec![graph.node(*phi).inputs[0]];
- let mut seen = BitSet::new(graph.nodes.len());
+ pending.clear();
+ pending.push(graph.node(*phi).inputs[0]);
+ seen.clear();
while let Some(value) = pending.pop() {
let value = graph.unrefined(value);
if seen.contains(value.index()) {
@@ -505,10 +516,12 @@ fn entering_counters(
&& block_of.get(&value).is_some_and(|block| osr_only.contains(*block))
{
let range = Range::new(0, bound - 1).expect("the bound is a positive int32");
- entering
- .entry(value)
- .and_modify(|assumed: &mut Range| assumed.max = assumed.max.min(range.max))
- .or_insert(range);
+ match entering.get_mut(&value) {
+ Some(assumed) => assumed.max = assumed.max.min(range.max),
+ None => {
+ entering.insert(value, range);
+ }
+ }
}
}
}
@@ -516,13 +529,13 @@ fn entering_counters(
}
pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {
- let mut phi_blocks = HashMap::default();
- let mut checks = Vec::new();
- let mut shifts = Vec::new();
- let mut arithmetic = Vec::new();
+ let mut phi_blocks = ZoneMap::new_in(work);
+ let mut checks = ZoneVec::new_in(work);
+ let mut shifts = ZoneVec::new_in(work);
+ let mut arithmetic = ZoneVec::new_in(work);
// NB: For every index that bounds checks and branches check, where
// those checks are and the counts.
- let mut bounded: HashMap<NodeId, Vec<(BlockId, usize, NodeId)>> = HashMap::default();
+ let mut bounded: ZoneMap<NodeId, ZoneVec<(BlockId, usize, NodeId)>> = ZoneMap::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
for phi in &block.phis {
phi_blocks.insert(*phi, BlockId::from_index(index));
@@ -530,11 +543,10 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
for (position, node) in block.body.iter().enumerate() {
let check = graph.node(*node);
if bounds_index(&check.op) {
- bounded.entry(graph.unrefined(check.inputs[0])).or_default().push((
- BlockId::from_index(index),
- position,
- check.inputs[1],
- ));
+ bounded
+ .entry(graph.unrefined(check.inputs[0]))
+ .or_insert_with(|| ZoneVec::new_in(work))
+ .push((BlockId::from_index(index), position, check.inputs[1]));
}
match check.op {
Op::CheckBounds => checks.push(*node),
@@ -573,114 +585,119 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
}
dominators.compute(graph)?;
let dominators = &*dominators;
- let entering = entering_counters(graph, dominators, &phi_blocks);
+ let entering = entering_counters(graph, dominators, &phi_blocks, work);
let mut ranges = Ranges {
graph,
dominators,
phi_blocks: &phi_blocks,
assumed: &entering,
- known: HashMap::default(),
+ known: ZoneMap::new_in(work),
};
- let passing = checks
- .into_iter()
- .filter(|check| {
+ let passing = ZoneVec::from_iter_in(
+ checks.iter().copied().filter(|check| {
let node = graph.node(*check);
match (ranges.constant(node.inputs[1]), ranges.of(node.inputs[0])) {
(Some(count), Some(index)) => index.min >= 0 && index.max < count,
_ => false,
}
- })
- .collect::<Vec<_>>();
- let scaled = shifts
- .into_iter()
- .filter_map(|(shift, block)| {
+ }),
+ work,
+ );
+ let scaled = ZoneVec::from_iter_in(
+ shifts.iter().copied().filter_map(|(shift, block)| {
ranges
.unscaled(shift)
.map(|(value, offset)| (shift, block, value, offset))
- })
- .collect::<Vec<_>>();
+ }),
+ work,
+ );
// NB: With the counts of the bounds checks that their operands' ranges
- // rely on.
- let exact = arithmetic
- .into_iter()
- .filter_map(|(node, block, position)| {
- let node_data = graph.node(node);
- let Op::Int32Binary { op } = node_data.op else {
- unreachable!("only int32 arithmetic is collected");
- };
- let mut counts = Vec::new();
- // NB: Every dominating bounds check narrows the range of an
- // operand further.
- let mut operand = |input: NodeId| {
- let mut range = ranges.of(input);
- let dominating = bounded.get(&graph.unrefined(input)).into_iter().flatten().filter(
- |(check_block, check_position, _)| {
- if *check_block == block {
- *check_position < position
- } else {
- dominators.dominates(*check_block, block)
- }
- },
- );
- for (_, _, count) in dominating {
- let narrowed = ranges.below_count(range, *count);
- if narrowed.is_some() && narrowed != range {
- counts.push(*count);
- range = narrowed;
+ // rely on: those of `exact[i]` are `exact_counts[exact[i].1..exact[i].2]`.
+ let mut exact = ZoneVec::new_in(work);
+ let mut exact_counts = ZoneVec::new_in(work);
+ for (node, block, position) in arithmetic.iter().copied() {
+ let node_data = graph.node(node);
+ let Op::Int32Binary { op } = node_data.op else {
+ unreachable!("only int32 arithmetic is collected");
+ };
+ let start = exact_counts.len();
+ // NB: Every dominating bounds check narrows the range of an
+ // operand further.
+ let mut operand = |input: NodeId| {
+ let mut range = ranges.of(input);
+ let dominating = bounded.get(&graph.unrefined(input)).into_iter().flatten().filter(
+ |(check_block, check_position, _)| {
+ if *check_block == block {
+ *check_position < position
+ } else {
+ dominators.dominates(*check_block, block)
}
+ },
+ );
+ for (_, _, count) in dominating {
+ let narrowed = ranges.below_count(range, *count);
+ if narrowed.is_some() && narrowed != range {
+ exact_counts.push(*count);
+ range = narrowed;
}
- range
- };
- let (lhs, rhs) = (operand(node_data.inputs[0])?, operand(node_data.inputs[1])?);
- let exact = match op {
- BinaryOp::Add => lhs.sum(rhs).is_some(),
- BinaryOp::Sub => lhs.difference(rhs).is_some(),
- // NB: A zero product is -0 where an operand is negative.
- BinaryOp::Mul => {
- lhs.product(rhs).is_some()
- && ((lhs.min >= 0 && rhs.min >= 0) || (!lhs.contains(0) && !rhs.contains(0)))
- }
- _ => unreachable!("only additions, subtractions and multiplications are collected"),
- };
- exact.then_some((node, counts))
- })
- .collect::<Vec<_>>();
+ }
+ range
+ };
+ let operands = operand(node_data.inputs[0]).and_then(|lhs| Some((lhs, operand(node_data.inputs[1])?)));
+ let is_exact = operands.is_some_and(|(lhs, rhs)| match op {
+ BinaryOp::Add => lhs.sum(rhs).is_some(),
+ BinaryOp::Sub => lhs.difference(rhs).is_some(),
+ // NB: A zero product is -0 where an operand is negative.
+ BinaryOp::Mul => {
+ lhs.product(rhs).is_some() && ((lhs.min >= 0 && rhs.min >= 0) || (!lhs.contains(0) && !rhs.contains(0)))
+ }
+ _ => unreachable!("only additions, subtractions and multiplications are collected"),
+ });
+ if is_exact {
+ exact.push((node, start, exact_counts.len()));
+ } else {
+ exact_counts.truncate(start);
+ }
+ }
if passing.is_empty() && scaled.is_empty() && exact.is_empty() {
return Ok(());
}
// NB: Only the entering counters that the removed checks, the
// rewritten shifts and the operations that stop checking for overflow
// relied on get checked where they enter.
- let mut used = BitSet::new(graph.nodes.len());
- let mut visited = BitSet::new(graph.nodes.len());
+ let mut used = ZoneBitSet::new_in(graph.nodes.len(), work);
+ let mut visited = ZoneBitSet::new_in(graph.nodes.len(), work);
+ let mut pending = ZoneVec::new_in(work);
for check in &passing {
- ranges.assumptions_of(graph.node(*check).inputs[0], &mut used, &mut visited);
+ ranges.assumptions_of(graph.node(*check).inputs[0], &mut used, &mut visited, &mut pending);
}
for (shift, ..) in &scaled {
- ranges.assumptions_of(*shift, &mut used, &mut visited);
+ ranges.assumptions_of(*shift, &mut used, &mut visited, &mut pending);
}
- for (node, counts) in &exact {
- ranges.assumptions_of(*node, &mut used, &mut visited);
- for count in counts {
- ranges.assumptions_of(*count, &mut used, &mut visited);
+ for (node, start, end) in &exact {
+ ranges.assumptions_of(*node, &mut used, &mut visited, &mut pending);
+ for count in &exact_counts[*start..*end] {
+ ranges.assumptions_of(*count, &mut used, &mut visited, &mut pending);
}
}
- let guards = entering
- .iter()
- .filter(|(value, _)| used.contains(value.index()))
- .map(|(value, range)| (*value, range.max + 1))
- .collect::<Vec<_>>();
+ let guards = ZoneVec::from_iter_in(
+ entering
+ .iter()
+ .filter(|(value, _)| used.contains(value.index()))
+ .map(|(value, range)| (*value, range.max + 1)),
+ work,
+ );
let mut replacements = Replacements::new(graph, work);
- let mut removed = BitSet::new(graph.nodes.len());
- for check in passing {
+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
+ for check in passing.iter().copied() {
replacements.replace(check, graph.node(check).inputs[0]);
removed.insert(check.index());
}
let mut constants = Constants::new(graph, work);
- let mut guard_nodes = Vec::new();
- for (value, bound) in guards {
+ let mut guard_nodes = ZoneVec::new_in(work);
+ for (value, bound) in guards.iter().copied() {
let count = constants.get_typed(graph, u64::from((bound as i32).cast_unsigned()), Repr::Int32);
let (frame_state, pc) = (graph.node(value).frame_state, graph.node(value).pc);
let guard = graph.add_node(Node {
@@ -704,7 +721,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
replacements.replace(value, guard);
guard_nodes.push((guard, value));
}
- for (shift, block, value, offset) in scaled {
+ for (shift, block, value, offset) in scaled.iter().copied() {
let replacement = if offset == 0 {
value
} else {
@@ -726,12 +743,12 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
replacements.replace(shift, replacement);
removed.insert(shift.index());
}
- for (node, _) in exact {
+ for (node, ..) in exact.iter().copied() {
super::edit::make_wrapping(graph, node);
}
replacements.apply(graph);
// NB: The guards check the values they replace.
- for (guard, value) in guard_nodes {
+ for (guard, value) in guard_nodes.iter().copied() {
graph.nodes[guard.index()].inputs[0] = value;
}
super::edit::remove_nodes(graph, &removed);
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/branch_fusion.rs b/Libraries/LibJS/JIT/Rust/src/passes/branch_fusion.rs
index 700d2ee313b..2aec50ef602 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/branch_fusion.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_fusion.rs
@@ -15,7 +15,7 @@
//! is a constant, so that its comparison fuses with the branch there.
use super::edit;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::code::Repr;
use crate::ir::Block;
use crate::ir::BlockId;
@@ -25,6 +25,7 @@ use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
use ak::Zone;
+use ak::ZoneVec;
/// The comparison of swapped operands that has the same result.
fn mirrored(comparison: Comparison) -> Comparison {
@@ -45,11 +46,11 @@ fn mirrored(comparison: Comparison) -> Comparison {
}
/// How many nodes and frame states use each node.
-fn count_uses(graph: &Graph) -> Vec<u32> {
- let mut uses = vec![0u32; graph.nodes.len()];
+fn count_uses<'w>(graph: &Graph, work: &'w Zone) -> ZoneVec<'w, u32> {
+ let mut uses = ZoneVec::from_elem_in(0u32, graph.nodes.len(), work);
for block in &graph.blocks {
for node in block.nodes() {
- for value in graph.used_values(node) {
+ for value in graph.used_values(node, work) {
uses[value.index()] += 1;
}
}
@@ -61,10 +62,14 @@ fn count_uses(graph: &Graph) -> Vec<u32> {
/// booleans, which nothing else uses, branch on their input of the phi
/// themselves (through a new block on each edge, which jumps on), or jump
/// to the target of a constant one.
-fn thread_boolean_phis(graph: &mut Graph, uses: &[u32]) {
+fn thread_boolean_phis(graph: &mut Graph, uses: &[u32], work: &Zone) {
let block_count = graph.blocks.len();
- let mut new_blocks: Vec<Vec<BlockId>> = vec![Vec::new(); block_count];
- let mut threaded = BitSet::new(block_count);
+ // NB: A block whose jump becomes a branch gets the two blocks of its edges. It then jumps nowhere, so it gets
+ // no more.
+ let mut new_blocks: ZoneVec<Option<[BlockId; 2]>> = ZoneVec::from_elem_in(None, block_count, work);
+ let mut threaded = ZoneBitSet::new_in(block_count, work);
+ let mut predecessors = ZoneVec::new_in(work);
+ let mut inputs = ZoneVec::new_in(work);
for block in 0..block_count {
let data = &graph.blocks[block];
let (Some(control), [phi]) = (data.control, data.phis.as_slice()) else {
@@ -80,7 +85,6 @@ fn thread_boolean_phis(graph: &mut Graph, uses: &[u32]) {
continue;
};
let block_id = BlockId::from_index(block);
- let predecessors = data.predecessors.to_vec();
let jumps_here = |predecessor: &BlockId| {
graph.control(*predecessor).op == Op::Jump { target: block_id } && predecessor.index() < block
};
@@ -90,13 +94,14 @@ fn thread_boolean_phis(graph: &mut Graph, uses: &[u32]) {
|| uses[phi.index()] != 1
|| if_true.index() <= block
|| if_false.index() <= block
- || !predecessors.iter().all(jumps_here)
+ || !data.predecessors.iter().all(jumps_here)
{
continue;
}
let pc = graph.node(control).pc;
- let inputs = graph.node(phi).inputs.to_vec();
- for (predecessor, input) in predecessors.into_iter().zip(inputs) {
+ predecessors.assign(&data.predecessors);
+ inputs.assign(&graph.node(phi).inputs);
+ for (predecessor, input) in predecessors.iter().copied().zip(inputs.iter().copied()) {
let truth = (graph.node(input).repr == Some(Repr::Bool))
.then(|| graph.constant_value(input))
.flatten();
@@ -126,7 +131,11 @@ fn thread_boolean_phis(graph: &mut Graph, uses: &[u32]) {
if_false: edges[1],
};
data.inputs.assign(&[input]);
- new_blocks[predecessor.index()].extend(edges);
+ assert!(
+ new_blocks[predecessor.index()].is_none(),
+ "a block gets the blocks of one branch"
+ );
+ new_blocks[predecessor.index()] = Some(edges);
}
// NB: Nothing reaches the block anymore.
for target in [if_true, if_false] {
@@ -138,11 +147,15 @@ fn thread_boolean_phis(graph: &mut Graph, uses: &[u32]) {
return;
}
// NB: The new blocks follow their predecessor, before their targets.
- let order = (0..block_count)
- .filter(|block| !threaded.contains(*block))
- .flat_map(|block| std::iter::once(BlockId::from_index(block)).chain(new_blocks[block].iter().copied()))
- .collect::<Vec<_>>();
- graph.reorder_blocks(&order);
+ let order = ZoneVec::from_iter_in(
+ (0..block_count)
+ .filter(|block| !threaded.contains(*block))
+ .flat_map(|block| {
+ std::iter::once(BlockId::from_index(block)).chain(new_blocks[block].into_iter().flatten())
+ }),
+ work,
+ );
+ graph.reorder_blocks(&order, work);
}
/// Removes `predecessor` from the predecessors of `target`, and its inputs
@@ -176,12 +189,13 @@ fn add_predecessor(graph: &mut Graph, target: BlockId, predecessor: BlockId, lik
}
}
-pub fn run(graph: &mut Graph, _work: &Zone) {
+pub fn run(graph: &mut Graph, work: &Zone) {
// NB: Threading moves the uses of each phi's inputs to the branches.
- let uses = count_uses(graph);
- thread_boolean_phis(graph, &uses);
+ let uses = count_uses(graph, work);
+ thread_boolean_phis(graph, &uses, work);
let count = graph.nodes.len();
- let mut removed = BitSet::new(count);
+ let mut removed = ZoneBitSet::new_in(count, work);
+ let mut inputs = ZoneVec::new_in(work);
for block in 0..graph.blocks.len() {
let control = graph.control_id(BlockId::from_index(block));
let Op::Branch {
@@ -204,7 +218,7 @@ pub fn run(graph: &mut Graph, _work: &Zone) {
Op::TaggedEquals { equal } => BranchCondition::TaggedEquals { equal },
_ => continue,
};
- let mut inputs = graph.node(comparison).inputs.clone();
+ inputs.assign(&graph.node(comparison).inputs);
// NB: Code generation takes a constant on the right as an immediate.
let constant = |input| graph.constant_value(input).is_some();
let condition = if constant(inputs[0]) && !constant(inputs[1]) {
@@ -223,7 +237,7 @@ pub fn run(graph: &mut Graph, _work: &Zone) {
if_true,
if_false,
};
- data.inputs = inputs;
+ data.inputs.assign(&inputs);
removed.insert(comparison.index());
}
edit::remove_nodes(graph, &removed);
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs
index d2849e79677..d5c7ae7990a 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs
@@ -14,9 +14,10 @@
use ak::ColumnFull;
use ak::Zone;
+use ak::ZoneVec;
use super::dominators::Dominators;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
use crate::ir::FrameStateId;
@@ -25,16 +26,29 @@ use crate::ir::NodeId;
use crate::ir::Op;
/// A block to split: its phis, the block that branches (itself, or the one
-/// it jumps to), the nodes before that branch (which each side gets a copy
-/// of), and for each side of the branch, the predecessor that takes it and
-/// its target.
+/// it jumps to), and for each side of the branch, the predecessor that takes
+/// it and its target. The nodes before that branch, which each side gets a
+/// copy of, are in `Lists::moved`.
struct Split {
block: BlockId,
branch_block: BlockId,
- moved: Vec<NodeId>,
sides: [(BlockId, BlockId); 2],
}
+/// The lists that the splits use, which each split clears.
+struct Lists<'w> {
+ zone: &'w Zone,
+ /// The nodes that each side gets a copy of.
+ moved: ZoneVec<'w, NodeId>,
+ /// The phis of the block, and the nodes in `moved`.
+ phis: ZoneBitSet<'w>,
+ frame_state_sides: ZoneVec<'w, (FrameStateId, usize)>,
+ block_phis: ZoneVec<'w, NodeId>,
+ predecessors: ZoneVec<'w, BlockId>,
+ renames: [ZoneVec<'w, (NodeId, NodeId)>; 2],
+ copies: ZoneVec<'w, NodeId>,
+}
+
/// Whether a copy of `node` can run at the start of each side instead: an
/// `AssumeValid`, or a node without effects that cannot exit.
fn is_movable(graph: &Graph, node: NodeId) -> bool {
@@ -60,7 +74,8 @@ fn side_of(dominators: &Dominators, split: &Split, block: BlockId) -> Option<usi
}
/// Whether `block` has the shape of `Split`, and its split if so.
-fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId) -> Option<Split> {
+/// It puts the nodes that each side gets a copy of in `moved`.
+fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId, moved: &mut ZoneVec<NodeId>) -> Option<Split> {
let data = graph.block(block);
if data.phis.is_empty() || data.is_loop_header || data.predecessors.len() != 2 || !dominators.is_reachable(block) {
return None;
@@ -132,11 +147,10 @@ fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId) -> Option<
return None;
}
}
- let moved: Vec<NodeId> = if branch_block == block {
- data.body.to_vec()
- } else {
- data.body.iter().chain(&branch_data.body).copied().collect()
- };
+ moved.assign(&data.body);
+ if branch_block != block {
+ moved.extend_from_slice(&branch_data.body);
+ }
// NB: Refines must stay at the head of their block, so the copies of the moved nodes cannot go before one.
let starts_with_refine = |target: BlockId| {
graph
@@ -151,7 +165,6 @@ fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId) -> Option<
Some(Split {
block,
branch_block,
- moved,
sides: [(sides[0]?, targets[0]), (sides[1]?, targets[1])],
})
}
@@ -159,14 +172,16 @@ fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId) -> Option<
/// The side of each frame state that a node or block of one side uses and
/// that holds one of the phis, or `None` if one of them cannot be renamed: a
/// node or block of another place uses it, or the phi is in a frame of its
-/// chain other than its own, or in a virtual object.
+/// chain other than its own, or in a virtual object. The sides go in `sides`.
fn frame_state_sides(
graph: &Graph,
dominators: &Dominators,
split: &Split,
- phis: &BitSet,
-) -> Option<Vec<(FrameStateId, usize)>> {
- let mut sides: Vec<(FrameStateId, usize)> = Vec::new();
+ phis: &ZoneBitSet,
+ sides: &mut ZoneVec<(FrameStateId, usize)>,
+ work: &Zone,
+) -> Option<()> {
+ sides.clear();
for (index, block) in graph.blocks.iter().enumerate() {
let block_id = BlockId::from_index(index);
if !dominators.is_reachable(block_id) || block_id == split.block || block_id == split.branch_block {
@@ -181,7 +196,7 @@ fn frame_state_sides(
for frame_state in frame_states {
let holds_phi = |id| {
graph
- .frame_state_values(id)
+ .frame_state_values(id, work)
.any(|(_, value)| phis.contains(value.index()))
};
if !holds_phi(frame_state) {
@@ -199,7 +214,7 @@ fn frame_state_sides(
.iter()
.any(|(_, value)| phis.contains(value.index()))
});
- let all_count = graph.frame_state_values(frame_state).count();
+ let all_count = graph.frame_state_values(frame_state, work).count();
let chain_count: usize = graph
.frame_state_chain(frame_state)
.map(|id| graph.frame_state(id).values.len())
@@ -207,7 +222,7 @@ fn frame_state_sides(
// NB: Virtual objects add values past those of the chain's frames.
let virtual_holds = all_count != chain_count
&& graph
- .frame_state_values(frame_state)
+ .frame_state_values(frame_state, work)
.skip(chain_count)
.any(|(_, value)| phis.contains(value.index()));
if !own_holds || chain_holds || virtual_holds {
@@ -221,7 +236,7 @@ fn frame_state_sides(
}
}
}
- Some(sides)
+ Some(())
}
/// `value`, or what `renames` renames it to.
@@ -233,21 +248,33 @@ fn renamed(renames: &[(NodeId, NodeId)], value: NodeId) -> NodeId {
}
/// Splits one block, if any has the shape of `Split` and all uses of its
-/// phis are on one side of its branch. Returns whether it split one.
-fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Result<bool, ColumnFull> {
+/// phis are on one side of its branch. Returns whether it split one. The
+/// data of the split that `lists` does not keep goes in `step`.
+fn split_one(
+ graph: &mut Graph,
+ dominators: &mut Dominators,
+ lists: &mut Lists,
+ step: &Zone,
+) -> Result<bool, ColumnFull> {
dominators.compute(graph)?;
let dominators = &*dominators;
+ // NB: Splits add nodes, so the set grows ahead of them.
+ if lists.phis.capacity() < graph.nodes.len() {
+ lists.phis = ZoneBitSet::new_in(graph.nodes.len().max(lists.phis.capacity() * 2), lists.zone);
+ }
for index in 0..graph.blocks.len() {
- let Some(split) = find_split(graph, dominators, BlockId::from_index(index)) else {
+ let Some(split) = find_split(graph, dominators, BlockId::from_index(index), &mut lists.moved) else {
continue;
};
- let mut phis = BitSet::new(graph.nodes.len());
+ let phis = &mut lists.phis;
+ phis.clear();
for phi in &graph.block(split.block).phis {
phis.insert(phi.index());
}
- for node in &split.moved {
+ for node in &lists.moved {
phis.insert(node.index());
}
+ let phis = &lists.phis;
// Every use of a phi must be on one side. A phi's input is used at the end of its predecessor.
let mut uses_ok = true;
'blocks: for (block_index, block) in graph.blocks.iter().enumerate() {
@@ -280,28 +307,35 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Res
if !uses_ok {
continue;
}
- let Some(frame_state_sides) = frame_state_sides(graph, dominators, &split, &phis) else {
+ if frame_state_sides(graph, dominators, &split, phis, &mut lists.frame_state_sides, step).is_none() {
continue;
- };
+ }
- let block_phis = graph.block(split.block).phis.to_vec();
- let predecessors = graph.block(split.block).predecessors.to_vec();
- let mut renames: [Vec<(NodeId, NodeId)>; 2] = std::array::from_fn(|side| {
+ let Lists {
+ moved: moved_nodes,
+ frame_state_sides,
+ block_phis,
+ predecessors,
+ renames,
+ copies,
+ ..
+ } = lists;
+ block_phis.assign(&graph.block(split.block).phis);
+ predecessors.assign(&graph.block(split.block).predecessors);
+ for (side, side_renames) in renames.iter_mut().enumerate() {
let predecessor = split.sides[side].0;
let index = predecessors
.iter()
.position(|block| *block == predecessor)
.expect("the side's predecessor enters the block");
- block_phis
- .iter()
- .map(|phi| (*phi, graph.node(*phi).inputs[index]))
- .collect()
- });
+ side_renames.clear();
+ side_renames.extend(block_phis.iter().map(|phi| (*phi, graph.node(*phi).inputs[index])));
+ }
// Each side starts with copies of the moved nodes, with its values.
for (side, side_renames) in renames.iter_mut().enumerate() {
let target = split.sides[side].1;
- let mut copies = Vec::new();
- for moved in &split.moved {
+ copies.clear();
+ for moved in moved_nodes.iter() {
let mut node = graph.node(*moved).clone();
for input in &mut node.inputs {
*input = renamed(side_renames, *input);
@@ -319,7 +353,7 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Res
}
let body = &mut graph.blocks[target.index()].body;
copies.extend_from_slice(body);
- body.assign(&copies);
+ body.assign(copies);
}
let rename = |side: usize, value: NodeId| renamed(&renames[side], value);
@@ -347,7 +381,7 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Res
}
}
}
- for (frame_state, side) in frame_state_sides {
+ for (frame_state, side) in frame_state_sides.iter().copied() {
for (_, value) in &mut graph.frame_states[frame_state.0 as usize].values {
*value = rename(side, *value);
}
@@ -360,7 +394,7 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Res
graph.blocks[target.index()].predecessors.assign(&[predecessor]);
}
graph.blocks[split.block.index()].predecessors.clear();
- for phi in block_phis {
+ for phi in block_phis.iter() {
graph.nodes[phi.index()].inputs.clear();
}
super::edit::clean_up_control_flow(graph, step);
@@ -372,13 +406,23 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Res
pub fn run(
graph: &mut Graph,
dominators: &mut Dominators,
- _work: &Zone,
+ work: &Zone,
steps: &mut [Zone; 2],
) -> Result<(), ColumnFull> {
let [step, _] = steps;
+ let mut lists = Lists {
+ zone: work,
+ moved: ZoneVec::new_in(work),
+ phis: ZoneBitSet::new_in(0, work),
+ frame_state_sides: ZoneVec::new_in(work),
+ block_phis: ZoneVec::new_in(work),
+ predecessors: ZoneVec::new_in(work),
+ renames: [ZoneVec::new_in(work), ZoneVec::new_in(work)],
+ copies: ZoneVec::new_in(work),
+ };
for _ in 0..graph.blocks.len() {
// NB: Each split cleans up the control flow, with data as large as the graph, which goes when the split ends.
- if !step.scope(|step| split_one(graph, dominators, step))? {
+ if !step.scope(|step| split_one(graph, dominators, &mut lists, step))? {
break;
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs b/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
index 684b4b010e2..974448eb4bf 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
@@ -11,10 +11,11 @@
//! of whose edges lead to the same place, doing nothing, become jumps.
use super::edit;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::Graph;
use crate::ir::Op;
use ak::Zone;
+use ak::ZoneVec;
/// Whether a node can be dropped when its value is unused.
fn is_removable(op: &Op) -> bool {
@@ -31,19 +32,19 @@ fn is_removable(op: &Op) -> bool {
}
pub fn run(graph: &mut Graph, work: &Zone) {
- remove_dead_nodes(graph);
+ remove_dead_nodes(graph, work);
// NB: Branches whose edges did the same are left jumping where they go,
// which leaves what only they used dead.
if edit::fold_branches_to_one_target(graph, work) {
- remove_dead_nodes(graph);
+ remove_dead_nodes(graph, work);
}
}
-fn remove_dead_nodes(graph: &mut Graph) {
+fn remove_dead_nodes(graph: &mut Graph, work: &Zone) {
let count = graph.nodes.len();
- let mut live = BitSet::new(count);
- let mut live_frames = BitSet::new(graph.frame_states.len());
- let mut pending = Vec::new();
+ let mut live = ZoneBitSet::new_in(count, work);
+ let mut live_frames = ZoneBitSet::new_in(graph.frame_states.len(), work);
+ let mut pending = ZoneVec::new_in(work);
for block in &graph.blocks {
pending.extend(block.nodes().filter(|node| {
let data = graph.node(*node);
@@ -68,7 +69,7 @@ fn remove_dead_nodes(graph: &mut Graph) {
frame = state.parent;
}
}
- let mut removed = BitSet::new(count);
+ let mut removed = ZoneBitSet::new_in(count, work);
for block in &graph.blocks {
for node in block.nodes() {
if !live.contains(node.index()) {
@@ -105,7 +106,7 @@ mod tests {
graph.blocks[0].body.push(add);
let returned = graph.add(Op::Return, &[constant], None, 0);
graph.blocks[0].control = Some(returned);
- remove_dead_nodes(&mut graph);
+ remove_dead_nodes(&mut graph, crate::test_zone());
assert!(graph.blocks[0].phis.is_empty());
assert!(graph.blocks[0].body.is_empty());
assert_eq!(graph.blocks[0].control, Some(returned));
@@ -144,7 +145,7 @@ mod tests {
}
let returned = graph.add(Op::Return, &[constant], None, 0);
graph.blocks[0].control = Some(returned);
- remove_dead_nodes(&mut graph);
+ remove_dead_nodes(&mut graph, crate::test_zone());
assert!(graph.blocks[0].body.contains(&boxed));
assert_eq!(graph.blocks[0].body.len(), 3);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
index d2baaeb5392..50ffb305691 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
@@ -12,8 +12,10 @@
use ak::Column;
use ak::ColumnFull;
+use ak::Zone;
+use ak::ZoneVec;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::tables::Lists;
@@ -205,23 +207,31 @@ impl Dominators {
/// The predecessors of `header` that it dominates: the sources of the
/// back edges of the loop it heads, if it heads one.
- pub fn back_edge_sources(&self, graph: &Graph, header: BlockId) -> Vec<BlockId> {
- graph
- .block(header)
- .predecessors
- .iter()
- .copied()
- .filter(|predecessor| self.dominates(header, *predecessor))
- .collect()
+ pub fn back_edge_sources<'w>(&self, graph: &Graph, header: BlockId, work: &'w Zone) -> ZoneVec<'w, BlockId> {
+ ZoneVec::from_iter_in(
+ graph
+ .block(header)
+ .predecessors
+ .iter()
+ .copied()
+ .filter(|predecessor| self.dominates(header, *predecessor)),
+ work,
+ )
}
/// The blocks of the loop that `header` heads, with back edges from
/// `back_edge_sources`: the header and every reachable block that reaches
/// one of them without going through it.
- pub fn loop_blocks(&self, graph: &Graph, header: BlockId, back_edge_sources: &[BlockId]) -> BitSet {
- let mut blocks = BitSet::new(graph.blocks.len());
+ pub fn loop_blocks<'w>(
+ &self,
+ graph: &Graph,
+ header: BlockId,
+ back_edge_sources: &[BlockId],
+ work: &'w Zone,
+ ) -> ZoneBitSet<'w> {
+ let mut blocks = ZoneBitSet::new_in(graph.blocks.len(), work);
blocks.insert(header.index());
- let mut pending = back_edge_sources.to_vec();
+ let mut pending = ZoneVec::from_slice_in(back_edge_sources, work);
while let Some(block) = pending.pop() {
if blocks.contains(block.index()) || !self.is_reachable(block) {
continue;
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/edit.rs b/Libraries/LibJS/JIT/Rust/src/passes/edit.rs
index 4a1e1a17984..ff65f03de23 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/edit.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/edit.rs
@@ -7,7 +7,6 @@
//! Graph edits shared by the passes: replacing values, removing nodes, and
//! cleaning up the control flow graph after control nodes lost successors.
-use crate::bitset::IndexSet;
use crate::bitset::ZoneBitSet;
use crate::code::Repr;
use crate::ir::BlockId;
@@ -111,7 +110,7 @@ pub fn remove_refinements(graph: &mut Graph, work: &Zone) {
/// Removes the nodes in `removed` from the blocks they are in. Nodes added
/// after `removed` was made are kept.
-pub fn remove_nodes(graph: &mut Graph, removed: &impl IndexSet) {
+pub fn remove_nodes(graph: &mut Graph, removed: &ZoneBitSet) {
let is_removed = |node: &NodeId| node.index() < removed.capacity() && removed.contains(node.index());
for block in &mut graph.blocks {
block.body.retain(|node| !is_removed(node));
@@ -254,7 +253,7 @@ pub fn clean_up_control_flow(graph: &mut Graph, work: &Zone) {
work,
);
if order.len() != block_count {
- graph.reorder_blocks(&order);
+ graph.reorder_blocks(&order, work);
}
remove_trivial_phis(graph, work);
}
@@ -402,7 +401,7 @@ pub fn move_cold_blocks_last(graph: &mut Graph, work: &Zone) {
let hot = blocks().filter(|block| !graph.block(*block).is_cold);
let cold = blocks().filter(|block| graph.block(*block).is_cold);
let order = ZoneVec::from_iter_in(hot.chain(cold), work);
- graph.reorder_blocks(&order);
+ graph.reorder_blocks(&order, work);
}
/// Replaces phis whose inputs are all one value (or the phi itself) by
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/exit_unboxing.rs b/Libraries/LibJS/JIT/Rust/src/passes/exit_unboxing.rs
index 1594e927cdc..38598793ed2 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/exit_unboxing.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/exit_unboxing.rs
@@ -13,7 +13,7 @@
//! which dominates its boxing and thus the exit, and dead code elimination
//! removes the boxing.
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::Graph;
use crate::ir::Op;
use ak::Zone;
@@ -22,10 +22,10 @@ fn is_boxing(op: &Op) -> bool {
matches!(op, Op::BoxInt32 | Op::BoxFloat64 | Op::BoxBool)
}
-pub fn run(graph: &mut Graph, _work: &Zone) {
+pub fn run(graph: &mut Graph, work: &Zone) {
// NB: Boxings that other nodes use stay in frame states, where they
// cost nothing more than the unboxed value would.
- let mut used = BitSet::new(graph.nodes.len());
+ let mut used = ZoneBitSet::new_in(graph.nodes.len(), work);
for block in &graph.blocks {
for node in block.nodes() {
for input in &graph.node(node).inputs {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
index 8e1e1d4ef12..48a7cf95401 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
@@ -34,6 +34,9 @@
//! run, so after them it may be. Before nodes that only need the frame
//! published, where it may not be, it puts a `PublishFrame`.
+use ak::Zone;
+use ak::ZoneVec;
+
use crate::bytecode::FrameLayout;
use crate::bytecode::RESERVED_REGISTER_COUNT;
use crate::ir::BlockId;
@@ -147,7 +150,7 @@ fn need(node: &Node, layout: &FrameLayout) -> Need {
}
}
-pub fn run(graph: &mut Graph, layout: &FrameLayout) {
+pub fn run(graph: &mut Graph, layout: &FrameLayout, work: &Zone) {
// Only functions entered through `Enter` initialize their frame.
let Some((entry_block, entry_node)) = graph.blocks.iter().enumerate().find_map(|(index, block)| {
block
@@ -162,14 +165,14 @@ pub fn run(graph: &mut Graph, layout: &FrameLayout) {
let entry_pc = graph.node(entry_node).pc;
let block_count = graph.blocks.len();
- let osr_blocks = graph.osr_entries.iter().map(|(_, block)| *block).collect::<Vec<_>>();
- let mut end_states: Vec<Option<State>> = vec![None; block_count];
+ let osr_blocks = ZoneVec::from_iter_in(graph.osr_entries.iter().map(|(_, block)| *block), work);
+ let mut end_states: ZoneVec<Option<State>> = ZoneVec::from_elem_in(None, block_count, work);
// Where to put which initialization, as (block, index in its body).
- let mut insertions: Vec<(usize, usize, Op)>;
- let mut slow_paths: Vec<NodeId>;
+ let mut insertions: ZoneVec<(usize, usize, Op)> = ZoneVec::new_in(work);
+ let mut slow_paths: ZoneVec<NodeId> = ZoneVec::new_in(work);
loop {
- insertions = Vec::new();
- slow_paths = Vec::new();
+ insertions.clear();
+ slow_paths.clear();
let mut changed = false;
for block in 0..block_count {
let block_id = BlockId::from_index(block);
@@ -231,8 +234,9 @@ pub fn run(graph: &mut Graph, layout: &FrameLayout) {
}
}
- // Insert from the back so earlier indices stay valid.
- insertions.sort_by_key(|(block, index, _)| (*block, *index));
+ // Insert from the back so earlier indices stay valid. A place gets one
+ // initialization at most.
+ insertions.sort_unstable_by_key(|(block, index, _)| (*block, *index));
for (block, index, op) in insertions.into_iter().rev() {
let node = graph.add(op, &[], None, entry_pc);
graph.blocks[block].body.insert(index, node);
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs
index fed6a7cb73e..d733dc7ac4c 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs
@@ -14,18 +14,19 @@
use ak::ColumnFull;
use ak::Zone;
+use ak::ZoneVec;
use super::dominators::Dominators;
use super::edit;
use super::edit::Replacements;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::fast_hash::FastHasher;
-use crate::fast_hash::HashMap;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
+use crate::zone_map::ZoneMap;
use std::hash::Hash;
use std::hash::Hasher;
use std::mem::discriminant;
@@ -72,25 +73,28 @@ fn run_with_hash(
}
dominators.compute(graph)?;
let mut replacements = Replacements::new(graph, work);
- let mut removed = BitSet::new(graph.nodes.len());
+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
// NB: Hash borrowed inputs instead of allocating keys. Candidates with
// the same hash form a chain through `previous`; equality is checked
// before reusing one, including when hashes collide.
- let mut available: HashMap<u64, NodeId> = HashMap::default();
- let mut previous = vec![None; graph.nodes.len()];
- let mut added = Vec::new();
+ let mut available: ZoneMap<u64, NodeId> = ZoneMap::new_in(work);
+ let mut previous = ZoneVec::from_elem_in(None, graph.nodes.len(), work);
+ let mut added = ZoneVec::new_in(work);
// Iterative preorder walk of the dominator tree; leaving a block drops
// what its nodes made available.
- let roots = (0..graph.blocks.len())
- .map(BlockId::from_index)
- .filter(|block| dominators.is_reachable(*block) && dominators.idom(*block).is_none())
- .collect::<Vec<_>>();
enum Step {
Enter(BlockId),
Leave(usize),
}
- let mut steps = roots.into_iter().rev().map(Step::Enter).collect::<Vec<_>>();
+ let mut steps = ZoneVec::from_iter_in(
+ (0..graph.blocks.len())
+ .rev()
+ .map(BlockId::from_index)
+ .filter(|block| dominators.is_reachable(*block) && dominators.idom(*block).is_none())
+ .map(Step::Enter),
+ work,
+ );
while let Some(step) = steps.pop() {
let block = match step {
Step::Enter(block) => block,
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs
index 7f091a0489c..879f1cd0751 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs
@@ -27,9 +27,10 @@
use ak::ColumnFull;
use ak::Zone;
+use ak::ZoneVec;
use super::dominators::Dominators;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::BinaryOp;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
@@ -46,10 +47,10 @@ const MAX_LOOP_SIZE: usize = 64;
/// it, the bound V8 uses for this.
const MAX_ITERATIONS_WITHOUT_CHECK: i64 = 5000;
-struct Loop {
+struct Loop<'w> {
header: BlockId,
- blocks: BitSet,
- back_edge_sources: Vec<BlockId>,
+ blocks: ZoneBitSet<'w>,
+ back_edge_sources: ZoneVec<'w, BlockId>,
}
/// By how much `next` changes the phi `phi`, if that is a constant, and
@@ -212,10 +213,11 @@ fn is_small_and_innermost(graph: &Graph, loop_: &Loop) -> bool {
/// it has a back edge of a loop that keeps its check, since only innermost
/// ones lose theirs. This looks at the edges and not at natural loops: an
/// on-stack replacement entry into a loop keeps the loop around it from being
-/// a natural loop.
-fn has_loop_around(graph: &Graph, loop_: &Loop) -> bool {
- let mut visited = BitSet::new(graph.blocks.len());
- let mut worklist: Vec<BlockId> = loop_.blocks.iter().map(BlockId::from_index).collect();
+/// a natural loop. `visited` and `worklist` are for its own use.
+fn has_loop_around(graph: &Graph, loop_: &Loop, visited: &mut ZoneBitSet, worklist: &mut ZoneVec<BlockId>) -> bool {
+ visited.clear();
+ worklist.clear();
+ worklist.extend(loop_.blocks.iter().map(BlockId::from_index));
while let Some(block) = worklist.pop() {
for successor in graph.successors(block) {
if successor == loop_.header && !loop_.blocks.contains(block.index()) {
@@ -230,26 +232,28 @@ fn has_loop_around(graph: &Graph, loop_: &Loop) -> bool {
false
}
-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {
+pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {
if !graph.nodes.iter().any(|node| matches!(node.op, Op::CheckInterrupt)) {
return Ok(());
}
dominators.compute(graph)?;
let dominators = &*dominators;
- let mut loops = Vec::new();
+ let mut loops = ZoneVec::new_in(work);
for index in 0..graph.blocks.len() {
let header = BlockId::from_index(index);
- let back_edge_sources = dominators.back_edge_sources(graph, header);
+ let back_edge_sources = dominators.back_edge_sources(graph, header, work);
if back_edge_sources.is_empty() {
continue;
}
- let blocks = dominators.loop_blocks(graph, header, &back_edge_sources);
+ let blocks = dominators.loop_blocks(graph, header, &back_edge_sources, work);
loops.push(Loop {
header,
blocks,
back_edge_sources,
});
}
+ let mut visited = ZoneBitSet::new_in(graph.blocks.len(), work);
+ let mut worklist = ZoneVec::new_in(work);
for loop_ in &loops {
if !is_small_and_innermost(graph, loop_) {
continue;
@@ -262,7 +266,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resu
.max();
let may_lose_check = match best_trip {
Some(Trip::Short) => true,
- Some(Trip::Counted) => has_loop_around(graph, loop_),
+ Some(Trip::Counted) => has_loop_around(graph, loop_, &mut visited, &mut worklist),
None => false,
};
if !may_lose_check {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs b/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs
index 8352e916108..fce49f1e284 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs
@@ -28,14 +28,15 @@
//! concatenation with other uses than keys is marked all the same: its
//! string has the same characters either way.
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
use ak::Zone;
+use ak::ZoneVec;
-pub fn run(graph: &mut Graph, _work: &Zone) {
- let mut pending = Vec::new();
+pub fn run(graph: &mut Graph, work: &Zone) {
+ let mut pending = ZoneVec::new_in(work);
for block in &graph.blocks {
for node in block.nodes() {
let node = graph.node(node);
@@ -47,14 +48,14 @@ pub fn run(graph: &mut Graph, _work: &Zone) {
}
}
}
- let mut loop_phis = BitSet::new(graph.nodes.len());
+ let mut loop_phis = ZoneBitSet::new_in(graph.nodes.len(), work);
for block in graph.blocks.iter().filter(|block| block.is_loop_header) {
for phi in &block.phis {
loop_phis.insert(phi.index());
}
}
- let mut seen = BitSet::new(graph.nodes.len());
- let mut concatenations: Vec<NodeId> = Vec::new();
+ let mut seen = ZoneBitSet::new_in(graph.nodes.len(), work);
+ let mut concatenations: ZoneVec<NodeId> = ZoneVec::new_in(work);
while let Some(value) = pending.pop() {
let value = graph.unrefined(value);
if seen.contains(value.index()) {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
index 807c9f2b4f9..aa565582c49 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
@@ -27,10 +27,11 @@
use ak::ColumnFull;
use ak::Zone;
+use ak::ZoneVec;
use super::dominators::Dominators;
use super::edit;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::code::ExitKind;
use crate::ir::Block;
use crate::ir::BlockId;
@@ -39,12 +40,12 @@ use crate::ir::Graph;
use crate::ir::Locations;
use crate::ir::Op;
-struct Loop {
+struct Loop<'w> {
header: BlockId,
preheader: BlockId,
- blocks: BitSet,
+ blocks: ZoneBitSet<'w>,
/// The blocks in the loop that jump back to its header.
- back_edge_sources: Vec<BlockId>,
+ back_edge_sources: ZoneVec<'w, BlockId>,
}
/// Gives each loop header that several earlier blocks outside the loop
@@ -52,14 +53,26 @@ struct Loop {
/// before the header that they jump to instead, with phis of what they
/// bring.
/// Returns whether it added any.
-fn add_preheaders(graph: &mut Graph, dominators: &Dominators) -> bool {
+fn add_preheaders(graph: &mut Graph, dominators: &Dominators, work: &Zone) -> bool {
let count = graph.blocks.len();
- let mut order = Vec::new();
+ let mut order = ZoneVec::new_in(work);
+ let mut predecessors = ZoneVec::new_in(work);
+ let mut back_edge_sources = ZoneVec::new_in(work);
+ let mut entries = ZoneVec::new_in(work);
+ let mut phis = ZoneVec::new_in(work);
+ let mut back_inputs = ZoneVec::new_in(work);
+ let mut entry_inputs = ZoneVec::new_in(work);
for header in (0..count).map(BlockId::from_index) {
- let predecessors = graph.block(header).predecessors.to_vec();
- let (back_edge_sources, entries): (Vec<BlockId>, Vec<BlockId>) = predecessors
- .iter()
- .partition(|predecessor| dominators.dominates(header, **predecessor));
+ predecessors.assign(&graph.block(header).predecessors);
+ back_edge_sources.clear();
+ entries.clear();
+ for predecessor in predecessors.iter().copied() {
+ if dominators.dominates(header, predecessor) {
+ back_edge_sources.push(predecessor);
+ } else {
+ entries.push(predecessor);
+ }
+ }
// NB: Edges from later blocks the header does not dominate are
// back edges of cycles around the header, which an on-stack
// replacement entry inside them reaches without the header.
@@ -78,14 +91,17 @@ fn add_preheaders(graph: &mut Graph, dominators: &Dominators) -> bool {
for entry in &entries {
graph.replace_successor(*entry, header, preheader);
}
- let phis = graph.block(header).phis.to_vec();
- for phi in phis {
- let (back_inputs, entry_inputs): (Vec<_>, Vec<_>) = predecessors
- .iter()
- .copied()
- .zip(graph.node(phi).inputs.iter().copied())
- .partition(|(predecessor, _)| back_edge_sources.contains(predecessor));
- let entry_inputs = entry_inputs.into_iter().map(|(_, input)| input).collect::<Vec<_>>();
+ phis.assign(&graph.block(header).phis);
+ for phi in phis.iter().copied() {
+ back_inputs.clear();
+ entry_inputs.clear();
+ for (predecessor, input) in predecessors.iter().zip(graph.node(phi).inputs.iter().copied()) {
+ if back_edge_sources.contains(predecessor) {
+ back_inputs.push(input);
+ } else {
+ entry_inputs.push(input);
+ }
+ }
let entering = if entry_inputs.iter().all(|input| *input == entry_inputs[0]) {
entry_inputs[0]
} else {
@@ -96,40 +112,38 @@ fn add_preheaders(graph: &mut Graph, dominators: &Dominators) -> bool {
let inputs = &mut graph.nodes[phi.index()].inputs;
inputs.clear();
inputs.push(entering);
- inputs.extend(back_inputs.into_iter().map(|(_, input)| input));
+ inputs.extend_from_slice(&back_inputs);
}
let jump = graph.add(Op::Jump { target: header }, &[], None, graph.control(header).pc);
graph.blocks[preheader.index()].control = Some(jump);
let header_predecessors = &mut graph.blocks[header.index()].predecessors;
header_predecessors.clear();
header_predecessors.push(preheader);
- header_predecessors.extend(back_edge_sources);
+ header_predecessors.extend_from_slice(&back_edge_sources);
order.push(preheader);
order.push(header);
}
if graph.blocks.len() == count {
return false;
}
- graph.reorder_blocks(&order);
+ graph.reorder_blocks(&order, work);
true
}
-fn find_loops(graph: &Graph, dominators: &Dominators) -> Vec<Loop> {
- let mut loops = Vec::new();
+fn find_loops<'w>(graph: &Graph, dominators: &Dominators, work: &'w Zone) -> ZoneVec<'w, Loop<'w>> {
+ let mut loops = ZoneVec::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
let header = BlockId::from_index(index);
- let back_edge_sources = dominators.back_edge_sources(graph, header);
+ let back_edge_sources = dominators.back_edge_sources(graph, header, work);
if back_edge_sources.is_empty() {
continue;
}
- let blocks = dominators.loop_blocks(graph, header, &back_edge_sources);
- let entries = block
+ let blocks = dominators.loop_blocks(graph, header, &back_edge_sources, work);
+ let mut entries = block
.predecessors
.iter()
- .copied()
- .filter(|predecessor| !blocks.contains(predecessor.index()))
- .collect::<Vec<_>>();
- let [preheader] = entries.as_slice() else {
+ .filter(|predecessor| !blocks.contains(predecessor.index()));
+ let (Some(preheader), None) = (entries.next(), entries.next()) else {
continue;
};
if *graph.successors(*preheader) != [header] {
@@ -157,7 +171,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
return Ok(());
}
dominators.compute(graph)?;
- if add_preheaders(graph, dominators) {
+ if add_preheaders(graph, dominators, work) {
// NB: The phis of headers that merged their entries in a preheader
// only take the value the preheader brings where the loop leaves
// it as it is, which is then invariant in the loop.
@@ -165,11 +179,13 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
dominators.compute(graph)?;
}
let dominators = &*dominators;
- let loops = find_loops(graph, dominators);
+ let loops = find_loops(graph, dominators, work);
if loops.is_empty() {
return Ok(());
}
- let mut block_of = vec![None; graph.nodes.len()];
+ let mut block_of = ZoneVec::from_elem_in(None, graph.nodes.len(), work);
+ let mut hoisted = ZoneVec::new_in(work);
+ let mut body = ZoneVec::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
for node in block.nodes() {
block_of[node.index()] = Some(index);
@@ -194,13 +210,13 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
}
let header_state = graph.block(loop_.header).start_frame_state;
let mut exit_state: Option<Option<FrameStateId>> = None;
- let mut hoisted = Vec::new();
+ hoisted.clear();
for block in loop_.blocks.iter() {
let block_id = BlockId::from_index(block);
let runs_every_iteration = dominators.runs_every_iteration(block_id, &loop_.back_edge_sources);
let is_cold = graph.block(block_id).is_cold;
- let body = graph.block(block_id).body.to_vec();
- for node in body {
+ body.assign(&graph.block(block_id).body);
+ for node in body.iter().copied() {
let data = graph.node(node);
let mut properties = data.op.properties();
// OPTIMIZATION: Nothing writes these slots, so their loads leave even loops that call, like the
@@ -255,7 +271,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul
hoisted.push(node);
}
}
- graph.blocks[loop_.preheader.index()].body.extend(hoisted);
+ graph.blocks[loop_.preheader.index()].body.extend_from_slice(&hoisted);
}
Ok(())
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs
index 660747bcd40..6cd22aaaaee 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs
@@ -465,7 +465,7 @@ fn lay_out_in_reverse_post_order(graph: &mut Graph, work: &Zone) {
}
}
post_order.reverse();
- graph.reorder_blocks(&post_order);
+ graph.reorder_blocks(&post_order, work);
for index in 0..graph.blocks.len() {
let is_cold = graph.blocks[index].is_cold;
let reached_from_later = graph.blocks[index]
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
index ac287cf74a2..67a24ae8465 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
@@ -13,42 +13,26 @@
//! tests check the graph's invariants (see `verify`) after building and after
//! every pass.
-// NB: A pass with `allow(clippy::disallowed_types)` still uses containers of the heap (see clippy.toml in the
-// directory of the crate). It loses the `allow` when its data is in zones.
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod bounds_check_elimination;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod branch_fusion;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod branch_splitting;
mod check_elimination;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod dce;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod dominators;
pub mod edit;
mod enumerated_keys;
mod escape_analysis;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod exit_unboxing;
mod facts;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod frame_initialization;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod gvn;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod interrupt_check_elimination;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod key_strings;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod licm;
mod loop_rotation;
mod representation;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod simplify;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
mod truncation;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod verify;
#[cfg(test)]
@@ -255,11 +239,11 @@ fn run_passes(
// a forward entry, which no entry reaches when every path out of the
// inner loop ends in an exit.
work.scope(|work| edit::remove_unreachable_blocks(graph, work));
- check(graph, layout, verify, dominators, "graph building");
+ check(graph, layout, verify, dominators, work, "graph building");
observe(graph, "graph building");
for pass in PASSES {
pass.run.run(graph, dominators, work, steps)?;
- check(graph, layout, verify, dominators, pass.name);
+ check(graph, layout, verify, dominators, work, pass.name);
observe(graph, pass.name);
}
// NB: Nodes that took different refinements of one value compute the
@@ -268,31 +252,34 @@ fn run_passes(
Run::WithDominators(gvn::run).run(graph, dominators, work, steps)?;
// NB: Checks that merged took their frame states along, which may have been the last uses of what those refer to.
Run::Plain(dce::run).run(graph, dominators, work, steps)?;
- check(graph, layout, verify, dominators, "refinement removal");
+ check(graph, layout, verify, dominators, work, "refinement removal");
observe(graph, "refinement removal");
- frame_initialization::run(graph, layout);
- check(graph, layout, verify, dominators, "frame initialization");
+ work.scope(|work| frame_initialization::run(graph, layout, work));
+ check(graph, layout, verify, dominators, work, "frame initialization");
work.scope(|work| edit::remove_unused_frame_states(graph, work));
// NB: Only the final block order puts the cold code last; passes see
// every block after its predecessors (except over back edges).
// On-stack replacement entries run once per entry, so they are cold
// code too, which keeps the blocks they lead to from starting with
// their register state.
- let osr_entries = graph.osr_entries.to_vec();
- for (_, block) in osr_entries {
+ for index in 0..graph.osr_entries.len() {
+ let (_, block) = graph.osr_entries[index];
graph.blocks[block.index()].is_cold = true;
}
work.scope(|work| edit::move_cold_blocks_last(graph, work));
- check(graph, layout, verify, dominators, "cold block layout");
+ check(graph, layout, verify, dominators, work, "cold block layout");
observe(graph, "frame initialization");
Ok(())
}
-fn check(graph: &Graph, layout: &FrameLayout, verify: bool, dominators: &mut Dominators, after: &str) {
+fn check(graph: &Graph, layout: &FrameLayout, verify: bool, dominators: &mut Dominators, work: &mut Zone, after: &str) {
if !verify {
return;
}
- if let Err(errors) = verify::verify_with(graph, dominators).and(verify::verify_frame_writes(graph, layout)) {
+ let result = work.scope(|work| {
+ verify::verify_with(graph, dominators, work).and(verify::verify_frame_writes(graph, layout, work))
+ });
+ if let Err(errors) = result {
panic!(
"invalid graph after {after}:\n{errors}\n{}",
crate::ir::dump(graph, layout)
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
index 2d2b10be20c..b50111c8355 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
@@ -18,9 +18,8 @@
use super::edit;
use super::edit::Constants;
use super::edit::Replacements;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::code::Repr;
-use crate::inline_vec::InlineVec;
use crate::ir::BinaryOp;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
@@ -30,6 +29,7 @@ use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::value;
use ak::Zone;
+use ak::ZoneVec;
/// The truthiness of a constant, where it does not depend on the heap.
fn constant_truthiness(bits: u64, repr: Repr) -> Option<bool> {
@@ -116,10 +116,10 @@ fn is_int32_identity(op: BinaryOp, rhs: i32, wrapping: bool) -> bool {
/// Double arithmetic of int32 values, which ToInt32 of its result can do
/// as wrapping int32 arithmetic instead.
-enum Int32Term {
+enum Int32Term<'w> {
Value(NodeId),
Constant(i32),
- Binary(BinaryOp, Box<Int32Term>, Box<Int32Term>),
+ Binary(BinaryOp, &'w Int32Term<'w>, &'w Int32Term<'w>),
}
/// How many levels of additions and subtractions `int32_term()` looks
@@ -130,8 +130,8 @@ const MAX_INT32_TERM_DEPTH: u32 = 8;
/// `value`, a `Repr::Float64`, as double arithmetic of int32 values, if it
/// is that: conversions of int32 values, int32 constants, and additions and
-/// subtractions of such.
-fn int32_term(graph: &Graph, value: NodeId, depth: u32) -> Option<Int32Term> {
+/// subtractions of such. The terms it is made of are in `work`.
+fn int32_term<'w>(graph: &Graph, value: NodeId, depth: u32, work: &'w Zone) -> Option<Int32Term<'w>> {
let node = graph.node(graph.unrefined(value));
match node.op {
Op::Int32ToFloat64 => Some(Int32Term::Value(node.inputs[0])),
@@ -145,8 +145,8 @@ fn int32_term(graph: &Graph, value: NodeId, depth: u32) -> Option<Int32Term> {
op: op @ (BinaryOp::Add | BinaryOp::Sub),
} if depth < MAX_INT32_TERM_DEPTH => Some(Int32Term::Binary(
op,
- Box::new(int32_term(graph, node.inputs[0], depth + 1)?),
- Box::new(int32_term(graph, node.inputs[1], depth + 1)?),
+ work.alloc(int32_term(graph, node.inputs[0], depth + 1, work)?),
+ work.alloc(int32_term(graph, node.inputs[1], depth + 1, work)?),
)),
_ => None,
}
@@ -210,9 +210,9 @@ fn may_stand_for_result(graph: &Graph, value: NodeId) -> bool {
/// doubles, boxings and frame states. The values of doubles are numbers,
/// so the checks guard no conversion with effects, and they go before check
/// elimination could rely on what they established.
-fn dissolvable_checks(graph: &Graph) -> BitSet {
- let mut checks = BitSet::new(graph.nodes.len());
- let mut blocked = BitSet::new(graph.nodes.len());
+fn dissolvable_checks<'w>(graph: &Graph, work: &'w Zone) -> ZoneBitSet<'w> {
+ let mut checks = ZoneBitSet::new_in(graph.nodes.len(), work);
+ let mut blocked = ZoneBitSet::new_in(graph.nodes.len(), work);
for block in &graph.blocks {
for node in block.nodes() {
let data = graph.node(node);
@@ -332,9 +332,9 @@ pub fn run_after_check_elimination(graph: &mut Graph, work: &Zone) {
fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
let dissolvable = if dissolve_checks {
- dissolvable_checks(graph)
+ dissolvable_checks(graph, work)
} else {
- BitSet::new(0)
+ ZoneBitSet::new_in(0, work)
};
let dissolved_double = |graph: &Graph, value: NodeId| {
// NB: Nodes the pass adds are no checks.
@@ -344,7 +344,9 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
};
let mut constants = Constants::new(graph, work);
let mut replacements = Replacements::new(graph, work);
- let mut removed = BitSet::new(graph.nodes.len());
+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
+ let mut inputs = ZoneVec::new_in(work);
+ let mut control_inputs = ZoneVec::new_in(work);
let mut changed_control_flow = false;
for block in 0..graph.blocks.len() {
let block = BlockId::from_index(block);
@@ -375,12 +377,8 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
) {
continue;
}
- let inputs = graph
- .node(node)
- .inputs
- .iter()
- .map(|input| replacements.resolve(*input))
- .collect::<InlineVec<NodeId, 4>>();
+ inputs.clear();
+ inputs.extend(graph.node(node).inputs.iter().map(|input| replacements.resolve(*input)));
// NB: A number check of a boxed int32 value converts the value.
let converted = (graph.node(node).op == Op::CheckNumber)
.then(|| graph.node(graph.unrefined(inputs[0])))
@@ -389,7 +387,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
// NB: ToInt32 of double arithmetic of int32 values is wrapping
// int32 arithmetic.
let wrapping = (graph.node(node).op == Op::Float64ToInt32)
- .then(|| int32_term(graph, inputs[0], 0))
+ .then(|| int32_term(graph, inputs[0], 0, work))
.flatten()
.filter(|term| matches!(term, Int32Term::Binary(..)));
// NB: An int32 comparison of a double checked to be an int32
@@ -422,7 +420,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
Op::UnboxInt32 => boxed(Op::BoxInt32, inputs[0]),
// NB: Inlined callees return values that representation
// selection may have found to be boxes, never empty.
- Op::EmptyToUndefined => graph.is_known_non_empty(inputs[0], 0..0).then_some(inputs[0]),
+ Op::EmptyToUndefined => graph.is_known_non_empty(inputs[0], 0..0, work).then_some(inputs[0]),
Op::CheckNonNegativeInt32 => int32_of(graph, inputs[0])
.filter(|value| *value >= 0)
.map(|_| inputs[0]),
@@ -519,14 +517,15 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
let folded = folded.or_else(|| {
let (comparison, doubles) = double_compare?;
let pc = graph.node(node).pc;
- let mut operands = Vec::new();
- for (input, double) in inputs.iter().zip(doubles) {
- operands.push(double.unwrap_or_else(|| {
- let conversion = graph.add(Op::Int32ToFloat64, &[*input], Some(Repr::Float64), pc);
+ let mut operands = [inputs[0], inputs[1]];
+ for (operand, double) in operands.iter_mut().zip(doubles) {
+ let input = *operand;
+ *operand = double.unwrap_or_else(|| {
+ let conversion = graph.add(Op::Int32ToFloat64, &[input], Some(Repr::Float64), pc);
graph.blocks[block.index()].body.insert(index - 1, conversion);
index += 1;
conversion
- }));
+ });
}
let compare = graph.add(Op::Float64Compare { comparison }, &operands, Some(Repr::Bool), pc);
graph.blocks[block.index()].body.insert(index - 1, compare);
@@ -588,6 +587,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
.inputs
.first()
.map(|input| replacements.resolve(*input));
+ control_inputs.clear();
let new_op = match (graph.node(control).op.clone(), input) {
(
Op::BranchTruthy { if_true, if_false, .. }
@@ -599,13 +599,8 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
Some(input),
) if graph.constant_value(input).is_some() => {
let repr = graph.node(input).repr.unwrap_or(Repr::Tagged);
- constant_truthiness(graph.constant_value(input).expect("a constant"), repr).map(|truthy| {
- (
- Op::Jump {
- target: if truthy { if_true } else { if_false },
- },
- Vec::new(),
- )
+ constant_truthiness(graph.constant_value(input).expect("a constant"), repr).map(|truthy| Op::Jump {
+ target: if truthy { if_true } else { if_false },
})
}
(
@@ -625,38 +620,32 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
.get(1)
.map(|input| replacements.resolve(*input)),
)
- .map(|holds| {
- (
- Op::Jump {
- target: if holds { if_true } else { if_false },
- },
- Vec::new(),
- )
+ .map(|holds| Op::Jump {
+ target: if holds { if_true } else { if_false },
}),
- (Op::BranchTruthy { if_true, if_false, .. }, Some(input)) if graph.node(input).op == Op::BoxBool => Some((
- Op::Branch {
+ (Op::BranchTruthy { if_true, if_false, .. }, Some(input)) if graph.node(input).op == Op::BoxBool => {
+ control_inputs.push(graph.node(input).inputs[0]);
+ Some(Op::Branch {
condition: BranchCondition::Bool,
if_true,
if_false,
- },
- vec![graph.node(input).inputs[0]],
- )),
+ })
+ }
(Op::BranchTruthy { if_true, if_false, .. }, Some(input)) if graph.node(input).op == Op::BoxInt32 => {
- Some((
- Op::Branch {
- condition: BranchCondition::Int32(Comparison::StrictlyInequals),
- if_true,
- if_false,
- },
- vec![graph.node(input).inputs[0], constants.get_typed(graph, 0, Repr::Int32)],
- ))
+ control_inputs.push(graph.node(input).inputs[0]);
+ control_inputs.push(constants.get_typed(graph, 0, Repr::Int32));
+ Some(Op::Branch {
+ condition: BranchCondition::Int32(Comparison::StrictlyInequals),
+ if_true,
+ if_false,
+ })
}
_ => None,
};
- if let Some((op, inputs)) = new_op {
+ if let Some(op) = new_op {
let data = &mut graph.nodes[control.index()];
data.op = op;
- data.inputs.assign(&inputs);
+ data.inputs.assign(&control_inputs);
changed_control_flow = true;
}
}
@@ -684,7 +673,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {
}
}
let mut replacements = Replacements::new(graph, work);
- let mut removed = BitSet::new(graph.nodes.len());
+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
for check in dissolvable.iter() {
let check = NodeId::from_index(check);
let double = checked_double(graph, check).expect("dissolvable checks check doubles");
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
index 872e3d07371..308611baa64 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
@@ -995,7 +995,7 @@ fn frame_writes_after_slow_paths_that_may_initialize_the_frame_check_first() {
graph.blocks[0].body.assign(&[initialize, call, store]);
graph.blocks[0].control = Some(ret);
- super::frame_initialization::run(&mut graph, &layout);
+ super::frame_initialization::run(&mut graph, &layout, crate::test_zone());
assert_eq!(graph.slow_paths_initializing_frame, vec![call]);
let ops: Vec<&Op> = graph.blocks[0].body.iter().map(|node| &graph.node(*node).op).collect();
assert!(matches!(
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs b/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs
index b8168bf2e93..a6205338045 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs
@@ -30,7 +30,7 @@
//! shifts unused.
use super::edit::Constants;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::code::Repr;
use crate::ir::BinaryOp;
use crate::ir::ElementsKind;
@@ -40,6 +40,7 @@ use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::TypedArrayElement;
use ak::Zone;
+use ak::ZoneVec;
/// The operations that wrap where their users only read the low 32 bits.
fn can_wrap(op: &Op) -> bool {
@@ -53,7 +54,7 @@ fn can_wrap(op: &Op) -> bool {
/// Whether input `index` of `user` only reads its low 32 bits, given the
/// nodes that are to wrap.
-fn reads_low_bits(graph: &Graph, user: NodeId, index: usize, wrapping: &BitSet) -> bool {
+fn reads_low_bits(graph: &Graph, user: NodeId, index: usize, wrapping: &ZoneBitSet) -> bool {
match graph.node(user).op {
Op::Int32Binary { op } | Op::Int32WrappingBinary { op } if op.is_bitwise() => true,
Op::Int32Binary {
@@ -171,11 +172,25 @@ fn compare_uint32_bits(graph: &mut Graph, work: &Zone) {
pub fn run(graph: &mut Graph, work: &Zone) {
compare_uint32_bits(graph, work);
let count = graph.nodes.len();
- let mut wrapping = BitSet::new(count);
- let mut users: Vec<Vec<(NodeId, usize)>> = vec![Vec::new(); count];
+ let mut wrapping = ZoneBitSet::new_in(count, work);
+ // The users of each node, with the index of the input that it is: those of node `n` are
+ // `user_list[user_starts[n]..user_starts[n + 1]]`.
+ let mut user_starts = ZoneVec::from_elem_in(0, count + 1, work);
+ for block in &graph.blocks {
+ for node in block.nodes() {
+ for input in &graph.node(node).inputs {
+ user_starts[input.index() + 1] += 1;
+ }
+ }
+ }
+ for index in 1..user_starts.len() {
+ user_starts[index] += user_starts[index - 1];
+ }
+ let mut user_list = ZoneVec::from_elem_in((NodeId(0), 0), user_starts[count], work);
+ let mut user_ends = ZoneVec::from_slice_in(&user_starts[..count], work);
// The node each frame state belongs to alone, if any: those of nodes
// that wrap go away with their exits.
- let mut owners = vec![Owner::None; graph.frame_states.len()];
+ let mut owners = ZoneVec::from_elem_in(Owner::None, graph.frame_states.len(), work);
for block in &graph.blocks {
if let Some(frame_state) = block.start_frame_state {
share(&mut owners, frame_state, Owner::Shared);
@@ -189,13 +204,15 @@ pub fn run(graph: &mut Graph, work: &Zone) {
share(&mut owners, frame_state, Owner::Node(node));
}
for (index, input) in data.inputs.iter().enumerate() {
- users[input.index()].push((node, index));
+ user_list[user_ends[input.index()]] = (node, index);
+ user_ends[input.index()] += 1;
}
}
}
if wrapping.is_empty() {
return;
}
+ let users = |node: usize| &user_list[user_starts[node]..user_starts[node + 1]];
for frame_state in &graph.frame_states {
if let Some(parent) = frame_state.parent {
share(&mut owners, parent, Owner::Shared);
@@ -205,8 +222,10 @@ pub fn run(graph: &mut Graph, work: &Zone) {
// Start from every candidate wrapping, and drop those with users that
// need more than the low 32 bits until none is left. Values of frame
// states that stay need all their bits too.
+ let mut in_frame_state = ZoneBitSet::new_in(count, work);
+ let mut candidates = ZoneVec::new_in(work);
loop {
- let mut in_frame_state = BitSet::new(count);
+ in_frame_state.clear();
for (frame_state, owner) in graph.frame_states.iter().zip(&owners) {
if matches!(owner, Owner::Node(node) if wrapping.contains(node.index())) {
continue;
@@ -219,13 +238,15 @@ pub fn run(graph: &mut Graph, work: &Zone) {
// builder boxes every result it writes to a slot.
let is_unused_boxing = |node: NodeId| {
graph.node(node).op == Op::BoxInt32
- && users[node.index()].is_empty()
+ && users(node.index()).is_empty()
&& !in_frame_state.contains(node.index())
};
let mut changed = false;
- for node in wrapping.iter().collect::<Vec<_>>() {
+ candidates.clear();
+ candidates.extend(wrapping.iter());
+ for node in candidates.iter().copied() {
let keeps_checking = in_frame_state.contains(node)
- || users[node]
+ || users(node)
.iter()
.any(|(user, index)| !is_unused_boxing(*user) && !reads_low_bits(graph, *user, *index, &wrapping));
if keeps_checking {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 2215085c2f3..6f47250acea 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -34,6 +34,9 @@
//! from the frame) or `Suspend` reads (see `verify_frame_writes()`), and
//! never one of `Graph::unwritten_slots`.
+use ak::Zone;
+use ak::ZoneVec;
+
use super::dominators::Dominators;
use crate::bytecode::FrameLayout;
use crate::bytecode::Operand;
@@ -46,6 +49,23 @@ use crate::ir::Locations;
use crate::ir::NodeId;
use crate::ir::Op;
+/// The descriptions of the violated invariants, one on each line.
+#[derive(Default)]
+struct Errors(String);
+
+impl Errors {
+ fn push(&mut self, message: String) {
+ if !self.0.is_empty() {
+ self.0.push('\n');
+ }
+ self.0.push_str(&message);
+ }
+
+ fn finish(self) -> Result<(), String> {
+ if self.0.is_empty() { Ok(()) } else { Err(self.0) }
+ }
+}
+
/// Where a node is: its block and its position there (phis come first, then
/// the body, then the control node).
#[derive(Debug, Clone, Copy)]
@@ -57,15 +77,12 @@ struct Place {
/// Checks that `StoreSlot` writes frame memory only where something reads it: written constants, which live there,
/// the arguments the compiled function's legacy `arguments` shows, and the slots a node that reads the frame reads,
/// right before it. Merges and back edges never write frame memory: slots that differ get phis.
-pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), String> {
- let mut errors = Vec::new();
+pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout, work: &Zone) -> Result<(), String> {
+ let mut errors = Errors::default();
+ let mut nodes = ZoneVec::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
- let nodes = block
- .body
- .iter()
- .chain(block.control.iter())
- .copied()
- .collect::<Vec<_>>();
+ nodes.assign(&block.body);
+ nodes.extend(block.control);
for (position, node) in nodes.iter().enumerate() {
let Op::StoreSlot { slot } = graph.node(*node).op else {
continue;
@@ -109,30 +126,26 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), St
}
}
}
- if errors.is_empty() {
- Ok(())
- } else {
- Err(errors.join("\n"))
- }
+ errors.finish()
}
/// Returns a description of every violated invariant, or `Ok` if there is none.
pub fn verify(graph: &Graph) -> Result<(), String> {
- verify_with(graph, &mut Dominators::new())
+ verify_with(graph, &mut Dominators::new(), &Zone::new(1 << 30, c"JIT verifier"))
}
-/// `verify()`, with `dominators` as the tables to compute the dominators of the graph in.
-pub fn verify_with(graph: &Graph, dominators: &mut Dominators) -> Result<(), String> {
- let places = verify_blocks(graph)?;
+/// `verify()`, with `dominators` as the tables to compute the dominators of the graph in, and `work` for its lists.
+pub fn verify_with(graph: &Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), String> {
+ let places = verify_blocks(graph, work)?;
verify_edges(graph)?;
- verify_nodes(graph, &places, dominators)?;
- verify_frame_states(graph)
+ verify_nodes(graph, &places, dominators, work)?;
+ verify_frame_states(graph, work)
}
/// Checks what each block holds, and returns where each node is.
-fn verify_blocks(graph: &Graph) -> Result<Vec<Option<Place>>, String> {
- let mut errors: Vec<String> = Vec::new();
- let mut places: Vec<Option<Place>> = vec![None; graph.nodes.len()];
+fn verify_blocks<'w>(graph: &Graph, work: &'w Zone) -> Result<ZoneVec<'w, Option<Place>>, String> {
+ let mut errors = Errors::default();
+ let mut places: ZoneVec<Option<Place>> = ZoneVec::from_elem_in(None, graph.nodes.len(), work);
for (index, block) in graph.blocks.iter().enumerate() {
let block_id = BlockId::from_index(index);
let Some(control) = block.control else {
@@ -173,16 +186,12 @@ fn verify_blocks(graph: &Graph) -> Result<Vec<Option<Place>>, String> {
}
}
}
- if errors.is_empty() {
- Ok(places)
- } else {
- Err(errors.join("\n"))
- }
+ errors.finish().map(|()| places)
}
/// Checks the edges between blocks and their order.
fn verify_edges(graph: &Graph) -> Result<(), String> {
- let mut errors: Vec<String> = Vec::new();
+ let mut errors = Errors::default();
for (index, block) in graph.blocks.iter().enumerate() {
let block_id = BlockId::from_index(index);
for successor in graph.successors(block_id) {
@@ -229,17 +238,18 @@ fn verify_edges(graph: &Graph) -> Result<(), String> {
}
}
}
- if errors.is_empty() {
- Ok(())
- } else {
- Err(errors.join("\n"))
- }
+ errors.finish()
}
/// Checks that values are defined before their uses, and the rules of each
/// kind of node.
-fn verify_nodes(graph: &Graph, places: &[Option<Place>], dominators: &mut Dominators) -> Result<(), String> {
- let mut errors: Vec<String> = Vec::new();
+fn verify_nodes(
+ graph: &Graph,
+ places: &[Option<Place>],
+ dominators: &mut Dominators,
+ work: &Zone,
+) -> Result<(), String> {
+ let mut errors = Errors::default();
if dominators.compute(graph).is_err() {
return Err("the graph has more blocks than the tables of the dominators hold".to_string());
}
@@ -317,7 +327,7 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], dominators: &mut Domina
// NB: Lazy exits of calls find their values after the call, but
// those are defined before it all the same.
if let Some(frame_state) = node.frame_state {
- for (slot, value) in graph.frame_state_values(frame_state) {
+ for (slot, value) in graph.frame_state_values(frame_state, work) {
if graph.node(value).repr.is_none() && !matches!(graph.node(value).op, Op::VirtualObject { .. }) {
errors.push(format!(
"the frame state of v{} has v{} for slot {slot}, which has no value",
@@ -431,12 +441,12 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], dominators: &mut Domina
// until anything else runs.
if let Op::SlowPathOutput { .. } = node.op {
let call = node.inputs[0];
- let before = graph.block_nodes(block_id).take(position).collect::<Vec<_>>();
+ let before = || graph.block_nodes(block_id).take(position);
let follows_call = matches!(graph.node(call).op, Op::CallSlowPath { .. })
- && before.iter().position(|other| *other == call).is_some_and(|start| {
- before[start + 1..]
- .iter()
- .all(|other| matches!(graph.node(*other).op, Op::SlowPathOutput { .. }))
+ && before().position(|other| other == call).is_some_and(|start| {
+ before()
+ .skip(start + 1)
+ .all(|other| matches!(graph.node(other).op, Op::SlowPathOutput { .. }))
});
if !follows_call {
errors.push(format!(
@@ -447,33 +457,23 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], dominators: &mut Domina
}
}
}
- if errors.is_empty() {
- Ok(())
- } else {
- Err(errors.join("\n"))
- }
+ errors.finish()
}
/// Checks that frame states list each slot once.
-fn verify_frame_states(graph: &Graph) -> Result<(), String> {
- let mut errors: Vec<String> = Vec::new();
+fn verify_frame_states(graph: &Graph, work: &Zone) -> Result<(), String> {
+ let mut errors = Errors::default();
+ let mut slots = ZoneVec::new_in(work);
for (index, frame_state) in graph.frame_states.iter().enumerate() {
- let mut slots: Vec<u32> = frame_state
- .values
- .iter()
- .map(|(slot, _)| *slot)
- .chain(frame_state.in_frame.iter().copied())
- .collect();
+ slots.clear();
+ slots.extend(frame_state.values.iter().map(|(slot, _)| *slot));
+ slots.extend_from_slice(&frame_state.in_frame);
slots.sort_unstable();
if slots.windows(2).any(|pair| pair[0] == pair[1]) {
errors.push(format!("fs{index} lists a slot more than once"));
}
}
- if errors.is_empty() {
- Ok(())
- } else {
- Err(errors.join("\n"))
- }
+ errors.finish()
}
fn check_input_reprs(graph: &Graph, node_id: NodeId) -> Option<String> {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
index 768093ac3b1..630d4a6afdc 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
@@ -18,6 +18,7 @@
use ak::Column;
use ak::ColumnFull;
+use ak::Zone;
use super::liveness::ValueLiveness;
use super::liveness::is_allocated_value;
@@ -59,6 +60,7 @@ struct Interference<'a> {
liveness: &'a ValueLiveness,
definitions: &'a [Definition],
deaths: &'a Lists<(usize, u32)>,
+ work: &'a Zone,
}
impl Interference<'_> {
@@ -87,7 +89,7 @@ impl Interference<'_> {
node.op.properties().is_call
&& node.frame_state.is_some_and(|frame_state| {
self.graph
- .frame_state_values(frame_state)
+ .frame_state_values(frame_state, self.work)
.any(|(_, frame_value)| frame_value == value)
})
};
@@ -141,7 +143,7 @@ impl Coalescing {
}
/// Finds the class of each value of `graph`.
- pub fn compute(&mut self, graph: &Graph, liveness: &ValueLiveness) -> Result<(), ColumnFull> {
+ pub fn compute(&mut self, graph: &Graph, liveness: &ValueLiveness, work: &Zone) -> Result<(), ColumnFull> {
let count = graph.nodes.len();
self.classes.clear();
for value in 0..count as u32 {
@@ -203,6 +205,7 @@ impl Coalescing {
liveness,
definitions,
deaths,
+ work,
};
for block in &graph.blocks {
for phi in &block.phis {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
index 3ff0032bccd..fca41c975bc 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
@@ -12,6 +12,7 @@
use ak::Column;
use ak::ColumnFull;
+use ak::Zone;
use crate::codegen::lowering_info::Clobbers as LoweringClobbers;
use crate::codegen::lowering_info::lowering_info;
@@ -263,12 +264,12 @@ impl ValueLiveness {
}
/// Lists the allocated values of the frame state `frame`, if they are not listed yet.
- fn list_frame_uses(&mut self, graph: &Graph, frame: FrameStateId) -> Result<(), ColumnFull> {
+ fn list_frame_uses(&mut self, graph: &Graph, frame: FrameStateId, work: &Zone) -> Result<(), ColumnFull> {
if self.frame_runs[frame.index()] != NOT_LISTED {
return Ok(());
}
let start = self.frame_uses.len();
- for (_, value) in graph.frame_state_values(frame) {
+ for (_, value) in graph.frame_state_values(frame, work) {
if is_allocated_value(graph, value) {
self.frame_uses.try_push(value)?;
}
@@ -288,7 +289,7 @@ impl ValueLiveness {
.try_push(pair(value.0, (block as u32) << 1 | u32::from(flows_out)))
}
- pub fn compute(&mut self, graph: &Graph) -> Result<(), ColumnFull> {
+ pub fn compute(&mut self, graph: &Graph, work: &Zone) -> Result<(), ColumnFull> {
let value_count = graph.nodes.len();
let block_count = graph.blocks.len();
@@ -331,7 +332,7 @@ impl ValueLiveness {
}
}
if let Some(frame) = node.frame_state {
- self.list_frame_uses(graph, frame)?;
+ self.list_frame_uses(graph, frame, work)?;
for use_index in self.frame_runs[frame.index()].range() {
self.add_seed(self.frame_uses[use_index], index, false)?;
}
@@ -591,7 +592,7 @@ mod tests {
let returned = graph.add(Op::Return, &[constant], None, 0);
graph.blocks[0].control = Some(returned);
let mut liveness = ValueLiveness::new();
- liveness.compute(&graph).unwrap();
+ liveness.compute(&graph, crate::test_zone()).unwrap();
assert!(liveness.dies_at(checks[0]).is_empty());
assert_eq!(liveness.dies_at(checks[1]), [value]);
assert!(!liveness.is_dead_output(value));
@@ -630,7 +631,7 @@ mod tests {
let mut liveness = ValueLiveness::new();
// NB: The second time, the tables hold what the first time left in them.
for _ in 0..2 {
- liveness.compute(&graph).unwrap();
+ liveness.compute(&graph, crate::test_zone()).unwrap();
assert!(liveness.live_in.get(0).is_empty());
assert!(liveness.live_out.get(block_count - 1).is_empty());
for index in 1..block_count {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index ef72c46f7c0..0bb4bd385b1 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -77,6 +77,7 @@ use crate::tables::release;
use crate::tables::reset;
use ak::Column;
use ak::ColumnFull;
+use ak::Zone;
use coalescing::Coalescing;
use liveness::ValueLiveness;
use liveness::is_allocated_value;
@@ -501,6 +502,7 @@ pub fn allocate(
registers: &RegisterSet,
regalloc: &mut Regalloc,
dominators: &mut Dominators,
+ work: &Zone,
) -> Result<(), CompileFailure> {
assert!(registers.allocatable_gprs.0 >> FPR_BASE == 0);
assert!(!registers.allocatable_gprs.contains(registers.scratch_gpr));
@@ -515,8 +517,8 @@ pub fn allocate(
class_slots,
parallel_moves,
} = regalloc;
- liveness.compute(graph)?;
- coalescing.compute(graph, liveness)?;
+ liveness.compute(graph, work)?;
+ coalescing.compute(graph, liveness, work)?;
loops.compute(graph, liveness, dominators)?;
allocation.begin(graph.nodes.len(), graph.blocks.len())?;
reset(value_registers, graph.nodes.len(), None)?;
@@ -537,6 +539,7 @@ pub fn allocate(
class_slots,
parallel_moves,
loops,
+ work,
};
allocator.run()?;
// NB: The code generator reads which values are live into a block.
@@ -561,6 +564,7 @@ struct Allocator<'a> {
class_slots: &'a mut Column<Option<u32>>,
parallel_moves: &'a mut Column<Move>,
loops: &'a Loops,
+ work: &'a Zone,
}
impl Allocator<'_> {
@@ -1012,7 +1016,7 @@ impl Allocator<'_> {
// their values after the clobber.
let exit_values_start = self.allocation.exit_values.len();
if let Some(frame_state) = node.frame_state {
- for (slot, value) in self.graph.frame_state_values(frame_state) {
+ for (slot, value) in self.graph.frame_state_values(frame_state, self.work) {
let location = self.current_location(value);
self.allocation.exit_values.try_push((slot, location))?;
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index 5fd7e44124d..9bb851d5d6a 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -39,7 +39,14 @@ impl std::ops::DerefMut for Allocated {
fn allocate_with(graph: &Graph, registers: &RegisterSet) -> Allocated {
let mut regalloc = Regalloc::new();
- allocate(graph, registers, &mut regalloc, &mut Dominators::new()).unwrap();
+ allocate(
+ graph,
+ registers,
+ &mut regalloc,
+ &mut Dominators::new(),
+ crate::test_zone(),
+ )
+ .unwrap();
Allocated(regalloc)
}
@@ -47,7 +54,7 @@ fn allocate_with(graph: &Graph, registers: &RegisterSet) -> Allocated {
fn allocate_and_verify(graph: &Graph) -> Allocated {
let registers = RegisterSet::test_configuration();
let allocation = allocate_with(graph, &registers);
- if let Err(errors) = verify(graph, &registers, &allocation) {
+ if let Err(errors) = verify(graph, &registers, &allocation, crate::test_zone()) {
panic!("{errors}\n{}", dump_allocation(graph, &allocation));
}
allocation
@@ -619,7 +626,7 @@ fn shift_amounts_are_in_the_targets_shift_register_or_immediates() {
..RegisterSet::test_configuration()
};
let allocation = allocate_with(&graph, &registers);
- if let Err(errors) = verify(&graph, &registers, &allocation) {
+ if let Err(errors) = verify(&graph, &registers, &allocation, crate::test_zone()) {
panic!("{errors}\n{}", dump_allocation(&graph, &allocation));
}
let dump = dump_allocation(&graph, &allocation);
@@ -719,6 +726,7 @@ fn exits_find_constants_registers_and_spilled_values() {
kind: SiteKind::Exit(ExitKind::NoFeedback),
stack_slot_offset: &|slot| -8 * (i32::try_from(slot).unwrap() + 1),
saves: &[],
+ work: crate::test_zone(),
}
.write(&mut scratch.tables.sites, &mut scratch.tables.artifact)
.unwrap();
@@ -771,13 +779,13 @@ fn the_verifier_finds_values_in_the_wrong_place() {
let graph = build(&program);
let registers = RegisterSet::test_configuration();
let allocation = allocate_with(&graph, &registers);
- verify(&graph, &registers, &allocation).unwrap();
+ verify(&graph, &registers, &allocation, crate::test_zone()).unwrap();
// Forgetting to spill a value that is live across a call loses it.
let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });
let mut broken = allocate_with(&graph, &registers);
broken.set_spill_slot(argument, None);
- assert!(verify(&graph, &registers, &broken).is_err());
+ assert!(verify(&graph, &registers, &broken, crate::test_zone()).is_err());
// Reading an input from a register that holds something else.
let call = find_node(&graph, |node| matches!(node.op, Op::CallSlowPath { .. }));
@@ -786,7 +794,7 @@ fn the_verifier_finds_values_in_the_wrong_place() {
panic!("the argument is in a register");
};
broken.set_input(call, 2, Location::Register((register + 1) % 6));
- assert!(verify(&graph, &registers, &broken).is_err());
+ assert!(verify(&graph, &registers, &broken, crate::test_zone()).is_err());
}
#[test]
@@ -808,7 +816,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
let graph = build(&program);
let registers = RegisterSet::test_configuration();
let allocation = allocate_with(&graph, &registers);
- verify(&graph, &registers, &allocation).unwrap();
+ verify(&graph, &registers, &allocation, crate::test_zone()).unwrap();
let returned = find_node(&graph, |node| matches!(node.op, Op::Return));
assert_eq!(
allocation.node(returned).moves_before,
@@ -821,7 +829,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
// A frame slot that the code may write is no home.
let mut written = graph.clone_in(crate::test_zone());
written.unwritten_slots = crate::bitset::ZoneBitSet::new_in(0, written.zone);
- assert!(verify(&written, &registers, &allocation).is_err());
+ assert!(verify(&written, &registers, &allocation, crate::test_zone()).is_err());
// Another frame slot holds another value.
let mut broken = allocate_with(&graph, &registers);
@@ -830,7 +838,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
..broken.node(returned).moves_before[0]
};
broken.set_move_before(returned, 0, wrong_move);
- assert!(verify(&graph, &registers, &broken).is_err());
+ assert!(verify(&graph, &registers, &broken, crate::test_zone()).is_err());
// A store to the slot, which nothing may do, makes it hold another value.
let mut stored = graph.clone_in(crate::test_zone());
@@ -845,7 +853,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
let mut allocation = allocation;
allocation.push_node(&[], None);
allocation.push_node(&[Location::Constant(value::UNDEFINED)], None);
- let errors = verify(&stored, &registers, &allocation).unwrap_err();
+ let errors = verify(&stored, &registers, &allocation, crate::test_zone()).unwrap_err();
assert!(errors.contains("nothing writes"), "{errors}");
}
@@ -1179,7 +1187,7 @@ fn random_structured_programs_with_cold_blocks_allocate_correctly() {
}
let registers = RegisterSet::test_configuration();
let allocation = allocate_with(&graph, &registers);
- if let Err(errors) = verify(&graph, &registers, &allocation) {
+ if let Err(errors) = verify(&graph, &registers, &allocation, crate::test_zone()) {
panic!(
"seed {seed}: {errors}\n{}\n{}",
crate::ir::dump(&graph, &layout),
@@ -1206,7 +1214,7 @@ fn random_structured_programs_allocate_correctly() {
let graph = build_with_layout(&program, layout, &never_ran);
let registers = RegisterSet::test_configuration();
let allocation = allocate_with(&graph, &registers);
- if let Err(errors) = verify(&graph, &registers, &allocation) {
+ if let Err(errors) = verify(&graph, &registers, &allocation, crate::test_zone()) {
panic!(
"seed {seed}: {errors}\n{}\n{}",
crate::ir::dump(&graph, &layout),
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
index 079255b3362..2d28d5f7a56 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
@@ -16,6 +16,8 @@
//! nothing on any path may store to it. Every load of such a slot loads that
//! value, so the state names it by the slot rather than by a load.
+use ak::Zone;
+
use super::Allocation;
use super::Location;
use super::Move;
@@ -49,17 +51,19 @@ struct Verifier<'a> {
/// being computed.
checking: bool,
errors: Vec<String>,
+ work: &'a Zone,
}
/// Checks `allocation` against `graph`, returning a description of every
/// problem found.
-pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation) -> Result<(), String> {
+pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation, work: &Zone) -> Result<(), String> {
let mut verifier = Verifier {
graph,
registers,
allocation,
checking: false,
errors: Vec::new(),
+ work,
};
let block_count = graph.blocks.len();
let block_ids = (0..block_count).map(BlockId::from_index).collect::<Vec<_>>();
@@ -256,7 +260,7 @@ impl Verifier<'_> {
let Some(frame_state) = self.graph.node(node).frame_state else {
return;
};
- let expected_count = self.graph.frame_state_values(frame_state).count();
+ let expected_count = self.graph.frame_state_values(frame_state, self.work).count();
let exit_values = self.allocation.node(node).exit_values;
if expected_count != exit_values.len() {
self.error(format!(
@@ -266,7 +270,9 @@ impl Verifier<'_> {
));
return;
}
- for ((slot, value), (exit_slot, location)) in self.graph.frame_state_values(frame_state).zip(exit_values) {
+ for ((slot, value), (exit_slot, location)) in
+ self.graph.frame_state_values(frame_state, self.work).zip(exit_values)
+ {
if slot != *exit_slot {
self.error(format!(
"{context}: exit value for slot {exit_slot}, frame state slot {slot}"
diff --git a/Libraries/LibJS/JIT/Rust/src/sparse_bitset.rs b/Libraries/LibJS/JIT/Rust/src/sparse_bitset.rs
deleted file mode 100644
index 70b16aaf469..00000000000
--- a/Libraries/LibJS/JIT/Rust/src/sparse_bitset.rs
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-//! A fixed-size set of integers that stores only its nonempty words. Block liveness sets cover the whole graph's
-//! node space but usually contain few values, so allocating that space for every block would be quadratic.
-
-#[derive(Clone, Copy, Default, PartialEq, Eq)]
-struct Word {
- index: usize,
- bits: u64,
-}
-
-#[derive(Default, PartialEq, Eq)]
-pub struct SparseBitSet {
- // Sorted by index, with no empty words.
- words: Vec<Word>,
- len: usize,
-}
-
-impl Clone for SparseBitSet {
- fn clone(&self) -> Self {
- Self {
- words: self.words.clone(),
- len: self.len,
- }
- }
-
- fn clone_from(&mut self, other: &Self) {
- self.words.clone_from(&other.words);
- self.len = other.len;
- }
-}
-
-impl SparseBitSet {
- /// An empty set that can hold the integers `0..len`, without allocating storage for them.
- pub fn new(len: usize) -> Self {
- Self { words: Vec::new(), len }
- }
-
- pub fn contains(&self, index: usize) -> bool {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- self.words
- .binary_search_by_key(&(index / 64), |word| word.index)
- .is_ok_and(|position| self.words[position].bits & (1 << (index % 64)) != 0)
- }
-
- pub fn insert(&mut self, index: usize) {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- let word_index = index / 64;
- let bits = 1 << (index % 64);
- match self.words.binary_search_by_key(&word_index, |word| word.index) {
- Ok(position) => self.words[position].bits |= bits,
- Err(position) => self.words.insert(
- position,
- Word {
- index: word_index,
- bits,
- },
- ),
- }
- }
-
- pub fn remove(&mut self, index: usize) {
- assert!(index < self.len, "bit {index} out of range {}", self.len);
- if let Ok(position) = self.words.binary_search_by_key(&(index / 64), |word| word.index) {
- self.words[position].bits &= !(1 << (index % 64));
- if self.words[position].bits == 0 {
- self.words.remove(position);
- }
- }
- }
-
- /// Adds every element of `other`. Returns whether this set changed.
- pub fn union_with(&mut self, other: &Self) -> bool {
- assert_eq!(self.len, other.len, "union of differently sized sets");
- // Update the words already present and count the missing ones before growing. Most unions add no words;
- // the rest merge backwards into the same allocation, without shifting the suffix for each insertion.
- let mut position = 0;
- let mut missing = 0;
- let mut changed = false;
- for other_word in &other.words {
- while position < self.words.len() && self.words[position].index < other_word.index {
- position += 1;
- }
- if position < self.words.len() && self.words[position].index == other_word.index {
- let word = &mut self.words[position];
- let bits = word.bits | other_word.bits;
- changed |= bits != word.bits;
- word.bits = bits;
- position += 1;
- } else {
- missing += 1;
- }
- }
- if missing == 0 {
- return changed;
- }
- let mut left = self.words.len();
- let mut right = other.words.len();
- self.words.resize(left + missing, Word::default());
- let mut output = self.words.len();
- while right > 0 {
- let other_word = other.words[right - 1];
- let word = if left > 0 && self.words[left - 1].index > other_word.index {
- left -= 1;
- self.words[left]
- } else if left > 0 && self.words[left - 1].index == other_word.index {
- left -= 1;
- right -= 1;
- Word {
- index: other_word.index,
- bits: self.words[left].bits | other_word.bits,
- }
- } else {
- right -= 1;
- other_word
- };
- output -= 1;
- self.words[output] = word;
- }
- true
- }
-
- /// Removes every element of `other`.
- pub fn subtract(&mut self, other: &Self) {
- assert_eq!(self.len, other.len, "difference of differently sized sets");
- let mut position = 0;
- self.words.retain_mut(|word| {
- while position < other.words.len() && other.words[position].index < word.index {
- position += 1;
- }
- if position < other.words.len() && other.words[position].index == word.index {
- word.bits &= !other.words[position].bits;
- }
- word.bits != 0
- });
- }
-
- pub fn is_empty(&self) -> bool {
- self.words.is_empty()
- }
-
- /// The elements in increasing order.
- pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
- self.words.iter().flat_map(|word| {
- let mut bits = word.bits;
- std::iter::from_fn(move || {
- if bits == 0 {
- return None;
- }
- let bit = bits.trailing_zeros() as usize;
- bits &= bits - 1;
- Some(word.index * 64 + bit)
- })
- })
- }
-}
-
-impl std::fmt::Debug for SparseBitSet {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- formatter.debug_set().entries(self.iter()).finish()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::bitset::BitSet;
-
- #[test]
- fn storage_depends_on_nonempty_words_not_the_universe() {
- let mut set = SparseBitSet::new(1_000_000);
- assert_eq!(set.words.capacity(), 0);
- for index in [999_999, 64, 63, 65] {
- set.insert(index);
- }
- assert_eq!(set.words.len(), 3);
- assert_eq!(set.iter().collect::<Vec<_>>(), [63, 64, 65, 999_999]);
- set.remove(64);
- assert_eq!(set.words.len(), 3);
- set.remove(65);
- assert_eq!(set.words.len(), 2);
- let copy = set.clone();
- set.subtract(&copy);
- assert!(set.is_empty());
- }
-
- #[test]
- fn operations_match_dense_sets() {
- let mut random = 42u64;
- let mut next = || {
- random ^= random << 13;
- random ^= random >> 7;
- random ^= random << 17;
- random as usize
- };
- let mut sparse = SparseBitSet::default();
- let mut dense = BitSet::default();
- for len in [0, 1, 63, 64, 65, 130, 4097] {
- sparse.clone_from(&SparseBitSet::new(len));
- dense.clone_from(&BitSet::new(len));
- for _ in 0..500 {
- let mut other_sparse = SparseBitSet::new(len);
- let mut other_dense = BitSet::new(len);
- for _ in 0..next() % 32 {
- if len > 0 {
- let index = next() % len;
- other_sparse.insert(index);
- other_dense.insert(index);
- }
- }
- match next() % 5 {
- 0 if len > 0 => {
- let index = next() % len;
- sparse.insert(index);
- dense.insert(index);
- }
- 1 if len > 0 => {
- let index = next() % len;
- sparse.remove(index);
- dense.remove(index);
- }
- 2 => assert_eq!(sparse.union_with(&other_sparse), dense.union_with(&other_dense)),
- 3 => {
- sparse.subtract(&other_sparse);
- dense.subtract(&other_dense);
- }
- _ => {
- sparse.clone_from(&other_sparse);
- dense.clone_from(&other_dense);
- }
- }
- assert_eq!(sparse.iter().collect::<Vec<_>>(), dense.iter().collect::<Vec<_>>());
- assert_eq!(sparse.is_empty(), dense.is_empty());
- assert!(sparse.words.windows(2).all(|words| words[0].index < words[1].index));
- assert!(sparse.words.iter().all(|word| word.bits != 0));
- for index in 0..len {
- assert_eq!(sparse.contains(index), dense.contains(index));
- }
- assert_eq!(sparse, sparse.clone());
- }
- }
- }
-}