Truly independent web browser
LibJS/JIT: Keep the dominators and the loops of a graph in tables
Andreas Kling71ba13e4a800
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 3279d3bbb53..eed7638d8a2 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -7,6 +7,7 @@use super::*;use crate::bytecode::test_support::*;use crate::ir::dump;+use crate::passes::dominators::Dominators;use crate::snapshot::ExecutableSnapshot;use crate::snapshot::List;@@ -47,14 +48,20 @@ pub(crate) fn build_with_layout(program: &Program, layout: FrameLayout, never_ra.map(|index| program.offsets[*index]).collect::<Vec<_>>();let mut graph = build_graph_with_feedback(&snapshot, &|pc| !never_ran_pcs.contains(&pc)).unwrap();- crate::passes::optimize(&mut graph, &layout, true);+ crate::passes::optimize(&mut graph, &layout, true, &mut Dominators::new()).unwrap();graph}/// Builds and optimizes the graph of `snapshot`, like compilation does.pub(crate) fn optimized_graph(snapshot: &Snapshot) -> Graph {let mut graph = build_graph(snapshot).unwrap();- crate::passes::optimize(&mut graph, &snapshot.executables[0].layout, true);+ crate::passes::optimize(+ &mut graph,+ &snapshot.executables[0].layout,+ true,+ &mut Dominators::new(),+ )+ .unwrap();graph}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 24b0a1e5cab..c0bec821ae5 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -430,6 +430,7 @@ pub fn generate<M: PortableMacroAssembler>(artifact,sites,regalloc,+ ..} = scratch;let allocation = ®alloc.allocation;let (_, pinned) = target_registers::<M>();diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 9b029ece52c..16336138409 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -119,16 +119,22 @@ fn compile_into<M: asm::PortableMacroAssembler>(&mut graph,&executable.layout,snapshot.options.verify_ir,- ))+ &mut scratch.dominators,+ )?)} else {- passes::optimize(&mut graph, &executable.layout, snapshot.options.verify_ir);+ passes::optimize(+ &mut graph,+ &executable.layout,+ snapshot.options.verify_ir,+ &mut scratch.dominators,+ )?;None};let (mut registers, _) = codegen::target_registers::<M>();if snapshot.options.stress.few_registers {registers.allocatable_gprs = registers.few_registers(STRESS_EXTRA_REGISTERS);}- regalloc::allocate(&graph, ®isters, &mut scratch.regalloc)?;+ regalloc::allocate(&graph, ®isters, &mut scratch.regalloc, &mut scratch.dominators)?;if snapshot.options.verify_ir&& let Err(errors) = regalloc::verify(&graph, ®isters, &scratch.regalloc.allocation){diff --git a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rsindex 9459449520e..905b65b8cb6 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs@@ -43,6 +43,8 @@//! accesses (and the branches on an index being in bounds) that dominate//! the operation: an index is below the elements' count there.+use ak::ColumnFull;+use super::dominators::Dominators;use super::edit::Constants;use super::edit::Replacements;@@ -512,7 +514,7 @@ fn entering_counters(entering}-pub fn run(graph: &mut Graph) {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {let mut phi_blocks = HashMap::default();let mut checks = Vec::new();let mut shifts = Vec::new();@@ -566,13 +568,14 @@ pub fn run(graph: &mut Graph) {checks.retain(|check| graph.int32_constant(graph.node(*check).inputs[1]).is_some());arithmetic.retain(|(node, ..)| graph.node(*node).inputs.iter().all(|input| may_have_range(*input)));if checks.is_empty() && shifts.is_empty() && arithmetic.is_empty() {- return;+ return Ok(());}- let dominators = Dominators::compute(graph);- let entering = entering_counters(graph, &dominators, &phi_blocks);+ dominators.compute(graph)?;+ let dominators = &*dominators;+ let entering = entering_counters(graph, dominators, &phi_blocks);let mut ranges = Ranges {graph,- dominators: &dominators,+ dominators,phi_blocks: &phi_blocks,assumed: &entering,known: HashMap::default(),@@ -643,7 +646,7 @@ pub fn run(graph: &mut Graph) {}).collect::<Vec<_>>();if passing.is_empty() && scaled.is_empty() && exact.is_empty() {- return;+ return Ok(());}// NB: Only the entering counters that the removed checks, the// rewritten shifts and the operations that stop checking for overflow@@ -731,4 +734,5 @@ pub fn run(graph: &mut Graph) {graph.nodes[guard.index()].inputs[0] = value;}super::edit::remove_nodes(graph, &removed);+ Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rsindex ee0ed84d8a2..0a6b78f0e07 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs@@ -12,6 +12,8 @@//! its own path rather than phis of both. A for-in loop's body then reads//! the key the cache holds, not a phi that also holds `undefined`.+use ak::ColumnFull;+use super::dominators::Dominators;use crate::bitset::BitSet;use crate::ir::BlockId;@@ -232,10 +234,11 @@ 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) -> bool {- let dominators = Dominators::compute(graph);+fn split_one(graph: &mut Graph, dominators: &mut Dominators) -> Result<bool, ColumnFull> {+ dominators.compute(graph)?;+ let dominators = &*dominators;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)) else {continue;};let mut phis = BitSet::new(graph.nodes.len());@@ -254,13 +257,13 @@ fn split_one(graph: &mut Graph) -> bool {}for phi in &block.phis {for (predecessor, input) in block.predecessors.iter().zip(&graph.node(*phi).inputs) {- if phis.contains(input.index()) && side_of(&dominators, &split, *predecessor).is_none() {+ if phis.contains(input.index()) && side_of(dominators, &split, *predecessor).is_none() {uses_ok = false;break 'blocks;}}}- let side = side_of(&dominators, &split, block_id);+ let side = side_of(dominators, &split, block_id);for node in block.body.iter().chain(block.control.iter()) {if graph.node(*node)@@ -277,7 +280,7 @@ fn split_one(graph: &mut Graph) -> bool {if !uses_ok {continue;}- let Some(frame_state_sides) = frame_state_sides(graph, &dominators, &split, &phis) else {+ let Some(frame_state_sides) = frame_state_sides(graph, dominators, &split, &phis) else {continue;};@@ -329,13 +332,13 @@ fn split_one(graph: &mut Graph) -> bool {let block = graph.block(block_id).clone();for phi in &block.phis {for (input_index, predecessor) in block.predecessors.iter().enumerate() {- if let Some(side) = side_of(&dominators, &split, *predecessor) {+ if let Some(side) = side_of(dominators, &split, *predecessor) {let input = graph.nodes[phi.index()].inputs[input_index];graph.nodes[phi.index()].inputs[input_index] = rename(side, input);}}}- if let Some(side) = side_of(&dominators, &split, block_id) {+ if let Some(side) = side_of(dominators, &split, block_id) {for node in block.body.iter().chain(block.control.iter()) {for input in &mut graph.nodes[node.index()].inputs {*input = rename(side, *input);@@ -360,15 +363,16 @@ fn split_one(graph: &mut Graph) -> bool {graph.nodes[phi.index()].inputs.clear();}super::edit::clean_up_control_flow(graph);- return true;+ return Ok(true);}- false+ Ok(false)}-pub fn run(graph: &mut Graph) {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {for _ in 0..graph.blocks.len() {- if !split_one(graph) {+ if !split_one(graph, dominators)? {break;}}+ Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rsindex cc07d06982d..05fb5023b9b 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs@@ -10,111 +10,189 @@//! immediate dominator, and neither has a block reached from several//! entries.+use ak::Column;+use ak::ColumnFull;+use crate::bitset::BitSet;use crate::ir::BlockId;use crate::ir::Graph;+use crate::tables::Lists;+use crate::tables::pop;+use crate::tables::release;+use crate::tables::reset;+/// The dominator tree of a graph, in tables that serve one graph after the other: `compute()` makes no block of the+/// heap.pub struct Dominators {/// The immediate dominator of each block, if it has one.- idom: Vec<Option<BlockId>>,+ idom: Column<Option<BlockId>>,/// Whether each block is reachable from an entry.- reachable: Vec<bool>,+ reachable: Column<bool>,/// When a depth first walk of the dominator tree enters and leaves each reachable block. A block dominates those/// it enters and leaves while it is entered.- tree_intervals: Vec<(u32, u32)>,+ tree_intervals: Column<(u32, u32)>,+ /// The children of each block in the dominator tree, in linear order.+ children: Lists<BlockId>,+ /// The reachable blocks in reverse postorder.+ order: Column<BlockId>,+ /// The place of each reachable block in `order`, plus one.+ ranks: Column<u32>,+ /// Whether each block has an immediate dominator or the virtual root above every entry as its dominator so far.+ processed: Column<bool>,+ /// The blocks that a walk still has to enter or leave, and whether it is to leave them.+ pending: Column<(BlockId, bool)>,}impl Dominators {- /// Computes the dominators with the iterative algorithm of Cooper,- /// Harvey and Kennedy, visiting blocks in reverse postorder.- pub fn compute(graph: &Graph) -> Self {+ // NB: The tables do not hold the dominators of a graph with more blocks.+ const MAX_BLOCKS: usize = 1 << 24;++ /// Tables that take no memory before a graph uses them.+ pub fn new() -> Self {+ fn by_block<T: Copy>() -> Column<T> {+ Column::new(Dominators::MAX_BLOCKS, c"JIT dominators")+ }+ Self {+ idom: by_block(),+ reachable: by_block(),+ tree_intervals: by_block(),+ children: Lists::new(Self::MAX_BLOCKS, Self::MAX_BLOCKS, c"JIT dominators"),+ order: by_block(),+ ranks: by_block(),+ processed: by_block(),+ // NB: A block waits to be left one time, and to be entered one time for each edge into it.+ pending: Column::new(Self::MAX_BLOCKS * 16, c"JIT dominators"),+ }+ }++ /// Drops the tables and gives their memory back to the system.+ pub fn release_memory(&mut self) {+ release(&mut self.idom);+ release(&mut self.reachable);+ release(&mut self.tree_intervals);+ self.children.release_memory();+ release(&mut self.order);+ release(&mut self.ranks);+ release(&mut self.processed);+ release(&mut self.pending);+ }++ /// Computes the dominators of `graph` with the iterative algorithm of Cooper,+ /// Harvey and Kennedy, visiting blocks in reverse postorder. The tables then hold the dominators of `graph` as+ /// it is now, and nothing of an earlier graph.+ pub fn compute(&mut self, graph: &Graph) -> Result<(), ColumnFull> {let count = graph.blocks.len();- let mut reachable = vec![false; count];- let mut postorder = Vec::with_capacity(count);- enum Step {- Enter(BlockId),- Leave(BlockId),+ reset(&mut self.reachable, count, false)?;+ self.order.clear();+ self.pending.clear();+ for entry in graph.entries() {+ self.pending.try_push((entry, false))?;}- let mut pending = graph.entries().map(Step::Enter).collect::<Vec<_>>();- while let Some(step) = pending.pop() {- let block = match step {- Step::Enter(block) => block,- Step::Leave(block) => {- postorder.push(block);- continue;- }- };- if reachable[block.index()] {+ while let Some((block, leaving)) = pop(&mut self.pending) {+ if leaving {+ self.order.try_push(block)?;+ continue;+ }+ if self.reachable[block.index()] {continue;}- reachable[block.index()] = true;- pending.push(Step::Leave(block));- pending.extend(graph.successors(block).iter().copied().map(Step::Enter));+ self.reachable[block.index()] = true;+ self.pending.try_push((block, true))?;+ let mut pushed = Ok(());+ graph.control(block).op.for_each_successor(|successor| {+ if pushed.is_ok() {+ pushed = self.pending.try_push((successor, false));+ }+ });+ pushed?;}- postorder.reverse();+ self.order.reverse();// NB: Rank zero is the virtual root. Walking to an immediate// dominator decreases the rank, avoiding ancestor-depth scans.- let mut ranks = vec![0; count];- for (index, block) in postorder.iter().enumerate() {- ranks[block.index()] = index + 1;+ reset(&mut self.ranks, count, 0)?;+ for (index, block) in self.order.iter().enumerate() {+ self.ranks[block.index()] = index as u32 + 1;}// NB: `None` with `processed` set means "dominated by the virtual root".- let mut idom: Vec<Option<BlockId>> = vec![None; count];- let mut processed = vec![false; count];+ reset(&mut self.idom, count, None)?;+ reset(&mut self.processed, count, false)?;let mut changed = true;while changed {changed = false;- for block in postorder.iter().map(|block| block.index()) {+ for block in self.order.iter().map(|block| block.index()) {let predecessors = &graph.blocks[block].predecessors;let new_idom = if predecessors.is_empty() {None} else {- let mut candidates = predecessors.iter().filter(|predecessor| processed[predecessor.index()]);+ let mut candidates = predecessors+ .iter()+ .filter(|predecessor| self.processed[predecessor.index()]);let Some(first) = candidates.next() else {continue;};let mut new_idom = Some(*first);for predecessor in candidates {- new_idom = intersect(&idom, &ranks, new_idom, Some(*predecessor));+ new_idom = intersect(&self.idom, &self.ranks, new_idom, Some(*predecessor));}new_idom};- if !processed[block] || idom[block] != new_idom {- processed[block] = true;- idom[block] = new_idom;+ if !self.processed[block] || self.idom[block] != new_idom {+ self.processed[block] = true;+ self.idom[block] = new_idom;changed = true;}}}- let mut dominators = Self {- idom,- reachable,- tree_intervals: Vec::new(),- };- dominators.tree_intervals = dominators.compute_tree_intervals();- dominators+ self.compute_children()?;+ self.compute_tree_intervals()}- fn compute_tree_intervals(&self) -> Vec<(u32, u32)> {- let children = self.children();- let mut intervals = vec![(0, 0); self.idom.len()];+ fn compute_children(&mut self) -> Result<(), ColumnFull> {+ let count = self.idom.len();+ self.children.begin_counts(count)?;+ for block in 0..count {+ if let Some(idom) = self.idom[block]+ && self.reachable[block]+ {+ self.children.count(idom.index());+ }+ }+ self.children.end_counts(BlockId(0))?;+ for block in 0..count {+ if let Some(idom) = self.idom[block]+ && self.reachable[block]+ {+ self.children.fill(idom.index(), BlockId::from_index(block));+ }+ }+ self.children.end_fill();+ Ok(())+ }++ fn compute_tree_intervals(&mut self) -> Result<(), ColumnFull> {+ let count = self.idom.len();+ reset(&mut self.tree_intervals, count, (0, 0))?;let mut time = 0;- let mut pending = (0..self.idom.len())- .filter(|block| self.reachable[*block] && self.idom[*block].is_none())- .map(|block| (block, false))- .collect::<Vec<_>>();- while let Some((block, leaving)) = pending.pop() {+ self.pending.clear();+ for block in 0..count {+ if self.reachable[block] && self.idom[block].is_none() {+ self.pending.try_push((BlockId::from_index(block), false))?;+ }+ }+ while let Some((block, leaving)) = pop(&mut self.pending) {time += 1;if leaving {- intervals[block].1 = time;+ self.tree_intervals[block.index()].1 = time;continue;}- intervals[block].0 = time;- pending.push((block, true));- pending.extend(children[block].iter().map(|child| (child.index(), false)));+ self.tree_intervals[block.index()].0 = time;+ self.pending.try_push((block, true))?;+ for child in self.children.get(block.index()) {+ self.pending.try_push((*child, false))?;+ }}- intervals+ Ok(())}pub fn idom(&self, block: BlockId) -> Option<BlockId> {@@ -180,43 +258,15 @@ impl Dominators {false}- /// The children of each block in the dominator tree, in linear order.- pub fn children(&self) -> Children {- let mut offsets = vec![0; self.idom.len() + 1];- for (block, idom) in self.idom.iter().enumerate() {- if let Some(idom) = idom- && self.reachable[block]- {- offsets[idom.index() + 1] += 1;- }- }- for index in 1..offsets.len() {- offsets[index] += offsets[index - 1];- }- let mut blocks = vec![BlockId(0); *offsets.last().unwrap()];- let mut next = offsets.clone();- for (block, idom) in self.idom.iter().enumerate() {- if let Some(idom) = idom- && self.reachable[block]- {- blocks[next[idom.index()]] = BlockId::from_index(block);- next[idom.index()] += 1;- }- }- Children { offsets, blocks }+ /// The children of `block` in the dominator tree, in linear order.+ pub fn children(&self, block: BlockId) -> &[BlockId] {+ self.children.get(block.index())}}-pub struct Children {- offsets: Vec<usize>,- blocks: Vec<BlockId>,-}--impl std::ops::Index<usize> for Children {- type Output = [BlockId];-- fn index(&self, block: usize) -> &Self::Output {- &self.blocks[self.offsets[block]..self.offsets[block + 1]]+impl Default for Dominators {+ fn default() -> Self {+ Self::new()}}@@ -224,7 +274,7 @@ impl std::ops::Index<usize> for Children {/// virtual root above every entry.fn intersect(idom: &[Option<BlockId>],- ranks: &[usize],+ ranks: &[u32],mut a: Option<BlockId>,mut b: Option<BlockId>,) -> Option<BlockId> {@@ -246,6 +296,7 @@ mod tests {#[test]fn cyclic_graphs_with_multiple_entries_match_dominator_sets() {+ let mut dominators = Dominators::new();for seed in 1..33u64 {let mut random = seed;let mut graph = Graph::default();@@ -277,7 +328,8 @@ mod tests {.push(BlockId::from_index(block));}}- let dominators = Dominators::compute(&graph);+ // NB: The tables of one graph serve the next one.+ dominators.compute(&graph).unwrap();// NB: Independently solve the defining set equations: each// block dominates itself and inherits the intersection of// its predecessors' dominators.@@ -310,7 +362,6 @@ mod tests {break;}}- let children = dominators.children();for (block, expected) in sets.iter().enumerate() {let block = BlockId::from_index(block);if !dominators.is_reachable(block) {@@ -324,11 +375,12 @@ mod tests {);}if let Some(parent) = dominators.idom(block) {- assert!(children[parent.index()].contains(&block));+ assert!(dominators.children(parent).contains(&block));}}for block in 0..count {- assert!(children[block].windows(2).all(|pair| pair[0].index() < pair[1].index()));+ let children = dominators.children(BlockId::from_index(block));+ assert!(children.windows(2).all(|pair| pair[0].index() < pair[1].index()));}}}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rsindex 4eb5840319d..ea569f39515 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs@@ -12,6 +12,8 @@//! Nodes that may exit qualify too: the dominating node made the same check//! on the same values, so this one cannot fail.+use ak::ColumnFull;+use super::dominators::Dominators;use super::edit;use super::edit::Replacements;@@ -38,8 +40,8 @@ fn is_numbered(op: &Op) -> bool {&& !op.is_control()}-pub fn run(graph: &mut Graph) {- run_with_hash(graph, |node, replacements| {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {+ run_with_hash(graph, dominators, |node, replacements| {let mut hash = FastHasher::default();discriminant(&node.op).hash(&mut hash);node.inputs.len().hash(&mut hash);@@ -47,10 +49,14 @@ pub fn run(graph: &mut Graph) {replacements.resolve(*input).hash(&mut hash);}hash.finish()- });+ })}-fn run_with_hash(graph: &mut Graph, hash: impl Fn(&Node, &Replacements) -> u64) {+fn run_with_hash(+ graph: &mut Graph,+ dominators: &mut Dominators,+ hash: impl Fn(&Node, &Replacements) -> u64,+) -> Result<(), ColumnFull> {if graph.blocks.iter()@@ -60,10 +66,9 @@ fn run_with_hash(graph: &mut Graph, hash: impl Fn(&Node, &Replacements) -> u64).count()< 2{- return;+ return Ok(());}- let dominators = Dominators::compute(graph);- let children = dominators.children();+ dominators.compute(graph)?;let mut replacements = Replacements::new(graph);let mut removed = BitSet::new(graph.nodes.len());// NB: Hash borrowed inputs instead of allocating keys. Candidates with@@ -135,12 +140,13 @@ fn run_with_hash(graph: &mut Graph, hash: impl Fn(&Node, &Replacements) -> u64)added.push((key, old));}steps.push(Step::Leave(checkpoint));- for child in children[block.index()].iter().rev() {+ for child in dominators.children(block).iter().rev() {steps.push(Step::Enter(*child));}}replacements.apply(graph);edit::remove_nodes(graph, &removed);+ Ok(())}#[cfg(test)]@@ -162,7 +168,7 @@ mod tests {let returned = graph.add_node(Node::new(Op::Return, vec![duplicate], None, 0));graph.blocks[0].body = vec![first, different_input, different_operation, duplicate];graph.blocks[0].control = Some(returned);- run_with_hash(&mut graph, |_, _| 0);+ run_with_hash(&mut graph, &mut Dominators::new(), |_, _| 0).unwrap();assert_eq!(graph.blocks[0].body, [first, different_input, different_operation]);assert_eq!(graph.node(returned).inputs, [first]);}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rsindex 067db9a415a..36995dc5b94 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs@@ -25,6 +25,8 @@//! exits on overflow: only the check's frame state keeps a counter alive that//! nothing else uses, without which the loop would not count anything.+use ak::ColumnFull;+use super::dominators::Dominators;use crate::bitset::BitSet;use crate::ir::BinaryOp;@@ -227,11 +229,12 @@ fn has_loop_around(graph: &Graph, loop_: &Loop) -> bool {false}-pub fn run(graph: &mut Graph) {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {if !graph.nodes.iter().any(|node| matches!(node.op, Op::CheckInterrupt)) {- return;+ return Ok(());}- let dominators = Dominators::compute(graph);+ dominators.compute(graph)?;+ let dominators = &*dominators;let mut loops = Vec::new();for index in 0..graph.blocks.len() {let header = BlockId::from_index(index);@@ -254,7 +257,7 @@ pub fn run(graph: &mut Graph) {.block(loop_.header).phis.iter()- .filter_map(|phi| trip_of(graph, &dominators, loop_, *phi))+ .filter_map(|phi| trip_of(graph, dominators, loop_, *phi)).max();let may_lose_check = match best_trip {Some(Trip::Short) => true,@@ -271,4 +274,5 @@ pub fn run(graph: &mut Graph) {.retain(|node| !matches!(nodes[node.index()].op, Op::CheckInterrupt));}}+ Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs b/Libraries/LibJS/JIT/Rust/src/passes/licm.rsindex 6e5ff1c3f20..6386150aab6 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs@@ -25,6 +25,8 @@//! exited there, so a speculation that fails costs one exit, and keeps the//! other checks moving.+use ak::ColumnFull;+use super::dominators::Dominators;use super::edit;use crate::bitset::BitSet;@@ -149,7 +151,7 @@ fn find_loops(graph: &Graph, dominators: &Dominators) -> Vec<Loop> {loops}-pub fn run(graph: &mut Graph) {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {// NB: Loops have a back edge from a later block or the block itself.let has_loops = graph.blocks.iter().enumerate().any(|(index, block)| {block@@ -158,19 +160,20 @@ pub fn run(graph: &mut Graph) {.any(|predecessor| predecessor.index() >= index)});if !has_loops {- return;+ return Ok(());}- let mut dominators = Dominators::compute(graph);- if add_preheaders(graph, &dominators) {+ dominators.compute(graph)?;+ if add_preheaders(graph, dominators) {// 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.edit::remove_trivial_phis(graph);- dominators = Dominators::compute(graph);+ dominators.compute(graph)?;}- let loops = find_loops(graph, &dominators);+ let dominators = &*dominators;+ let loops = find_loops(graph, dominators);if loops.is_empty() {- return;+ return Ok(());}let mut block_of = vec![None; graph.nodes.len()];for (index, block) in graph.blocks.iter().enumerate() {@@ -259,4 +262,5 @@ pub fn run(graph: &mut Graph) {}graph.blocks[loop_.preheader.index()].body.extend(hoisted);}+ Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rsindex 6a2bb74be1e..11bde10bb60 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs@@ -18,6 +18,8 @@//! test makes only reach the blocks it leads to through their phis, since it dominates none of them, so the copy's//! edges bring its values to those phis.+use ak::ColumnFull;+use super::dominators::Dominators;use super::edit;use crate::bitset::BitSet;@@ -32,15 +34,15 @@ use crate::ir::Op;/// How many nodes the blocks of a test that gets copied may have at most.const MAX_COPIED_NODES: usize = 64;-pub fn run(graph: &mut Graph) {+pub fn run(graph: &mut Graph, dominators: &mut Dominators) -> Result<(), ColumnFull> {if graph.osr_entries.is_empty() {- return;+ return Ok(());}let mut rotated = false;// NB: Each rotation makes one irreducible loop reducible; a graph has fewer such loops than blocks.for _ in 0..graph.blocks.len() {- let dominators = Dominators::compute(graph);- let Some((test, region, sources)) = find_rotatable_test(graph, &dominators) else {+ dominators.compute(graph)?;+ let Some((test, region, sources)) = find_rotatable_test(graph, dominators) else {break;};rotate(graph, test, ®ion, &sources);@@ -50,6 +52,7 @@ pub fn run(graph: &mut Graph) {lay_out_in_reverse_post_order(graph);edit::remove_trivial_phis(graph);}+ Ok(())}/// The blocks a depth-first walk from the entries reaches each block from over a retreating edge: an edge to a blockdiff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rsindex 28bb5be61ac..e909b2bfbec 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -38,144 +38,175 @@ pub mod verify;#[cfg(test)]mod tests;+use ak::ColumnFull;+use crate::bytecode::FrameLayout;use crate::ir::Graph;+use dominators::Dominators;/// One transformation of the graph.struct Pass {name: &'static str,- run: fn(&mut Graph),+ run: Run,+}++/// How a pass is run.+#[derive(Clone, Copy)]+enum Run {+ Plain(fn(&mut Graph)),+ /// The pass computes the dominators of the graph into the tables it gets. It fails if the graph is too large+ /// for them.+ WithDominators(fn(&mut Graph, &mut Dominators) -> Result<(), ColumnFull>),}/// The passes, in the order they run.const PASSES: &[Pass] = &[Pass {name: "loop rotation",- run: loop_rotation::run,+ run: Run::WithDominators(loop_rotation::run),},Pass {name: "trivial phi removal",- run: edit::remove_trivial_phis,+ run: Run::Plain(edit::remove_trivial_phis),},Pass {name: "truncation",- run: truncation::run,+ run: Run::Plain(truncation::run),},Pass {name: "simplification",- run: simplify::run,+ run: Run::Plain(simplify::run),},Pass {name: "representation selection",- run: representation::run,+ run: Run::Plain(representation::run),},Pass {name: "simplification",- run: simplify::run,+ run: Run::Plain(simplify::run),},Pass {name: "branch splitting",- run: branch_splitting::run,+ run: Run::WithDominators(branch_splitting::run),},Pass {name: "global value numbering",- run: gvn::run,+ run: Run::WithDominators(gvn::run),},Pass {name: "check elimination",- run: check_elimination::run,+ run: Run::Plain(check_elimination::run),},Pass {name: "simplification",- run: simplify::run_after_check_elimination,+ run: Run::Plain(simplify::run_after_check_elimination),},Pass {name: "global value numbering",- run: gvn::run,+ run: Run::WithDominators(gvn::run),},Pass {name: "loop invariant code motion",- run: licm::run,+ run: Run::WithDominators(licm::run),},Pass {name: "bounds check elimination",- run: bounds_check_elimination::run,+ run: Run::WithDominators(bounds_check_elimination::run),},Pass {name: "interrupt check elimination",- run: interrupt_check_elimination::run,+ run: Run::WithDominators(interrupt_check_elimination::run),},Pass {name: "exit unboxing",- run: exit_unboxing::run,+ run: Run::Plain(exit_unboxing::run),},Pass {name: "dead code elimination",- run: dce::run,+ run: Run::Plain(dce::run),},Pass {name: "escape analysis",- run: escape_analysis::run,+ run: Run::Plain(escape_analysis::run),},Pass {name: "dead code elimination",- run: dce::run,+ run: Run::Plain(dce::run),},Pass {name: "enumerated keys",- run: enumerated_keys::run,+ run: Run::Plain(enumerated_keys::run),},Pass {name: "branch fusion",- run: branch_fusion::run,+ run: Run::Plain(branch_fusion::run),},Pass {name: "key strings",- run: key_strings::run,+ run: Run::Plain(key_strings::run),},];/// Runs every pass over `graph`, whose compiled function has frame layout/// `layout` (for dumps of invalid graphs). Checks the graph's invariants/// before and after every pass in debug builds and tests, or if `verify`.-pub fn optimize(graph: &mut Graph, layout: &FrameLayout, verify: bool) {- run_passes(graph, layout, verify, &mut |_, _| {});+pub fn optimize(+ graph: &mut Graph,+ layout: &FrameLayout,+ verify: bool,+ dominators: &mut Dominators,+) -> Result<(), ColumnFull> {+ run_passes(graph, layout, verify, dominators, &mut |_, _| {})}/// `optimize()`, returning the graph as text after building it and after/// every pass, each headed by "=== after <pass>" (for tests of passes).-pub fn optimize_with_dumps(graph: &mut Graph, layout: &FrameLayout, verify: bool) -> String {+pub fn optimize_with_dumps(+ graph: &mut Graph,+ layout: &FrameLayout,+ verify: bool,+ dominators: &mut Dominators,+) -> Result<String, ColumnFull> {let mut text = String::new();- run_passes(graph, layout, verify, &mut |graph, after| {+ run_passes(graph, layout, verify, dominators, &mut |graph, after| {text.push_str(&format!("=== after {after}\n"));text.push_str(&crate::ir::dump(graph, layout));- });- text+ })?;+ Ok(text)}-fn run_passes(graph: &mut Graph, layout: &FrameLayout, verify: bool, observe: &mut dyn FnMut(&Graph, &str)) {+fn run_passes(+ graph: &mut Graph,+ layout: &FrameLayout,+ verify: bool,+ dominators: &mut Dominators,+ observe: &mut dyn FnMut(&Graph, &str),+) -> Result<(), ColumnFull> {let verify = verify || cfg!(debug_assertions) || cfg!(test);// NB: Graph building builds the loops around OSR entries even without// a forward entry, which no entry reaches when every path out of the// inner loop ends in an exit.edit::remove_unreachable_blocks(graph);- check(graph, layout, verify, "graph building");+ check(graph, layout, verify, dominators, "graph building");observe(graph, "graph building");for pass in PASSES {- (pass.run)(graph);- check(graph, layout, verify, pass.name);+ match pass.run {+ Run::Plain(run) => run(graph),+ Run::WithDominators(run) => run(graph, dominators)?,+ }+ check(graph, layout, verify, dominators, pass.name);observe(graph, pass.name);}// NB: Nodes that took different refinements of one value compute the// same once the refinements are gone, and nothing moves anymore.edit::remove_refinements(graph);- gvn::run(graph);+ gvn::run(graph, dominators)?;// NB: Checks that merged took their frame states along, which may have been the last uses of what those refer to.dce::run(graph);- check(graph, layout, verify, "refinement removal");+ check(graph, layout, verify, dominators, "refinement removal");observe(graph, "refinement removal");frame_initialization::run(graph, layout);- check(graph, layout, verify, "frame initialization");+ check(graph, layout, verify, dominators, "frame initialization");edit::remove_unused_frame_states(graph);// NB: Only the final block order puts the cold code last; passes see// every block after its predecessors (except over back edges).@@ -186,15 +217,16 @@ fn run_passes(graph: &mut Graph, layout: &FrameLayout, verify: bool, observe: &mgraph.blocks[block.index()].is_cold = true;}edit::move_cold_blocks_last(graph);- check(graph, layout, verify, "cold block layout");+ check(graph, layout, verify, dominators, "cold block layout");observe(graph, "frame initialization");+ Ok(())}-fn check(graph: &Graph, layout: &FrameLayout, verify: bool, after: &str) {+fn check(graph: &Graph, layout: &FrameLayout, verify: bool, dominators: &mut Dominators, after: &str) {if !verify {return;}- if let Err(errors) = verify::verify(graph).and(verify::verify_frame_writes(graph, layout)) {+ if let Err(errors) = verify::verify_with(graph, dominators).and(verify::verify_frame_writes(graph, layout)) {panic!("invalid graph after {after}:\n{errors}\n{}",crate::ir::dump(graph, layout)diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rsindex 7af3ba0d525..941873fe7b3 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs@@ -66,7 +66,8 @@ fn diamond() -> (Graph, NodeId) {#[test]fn dominators_of_a_diamond() {let (graph, _) = diamond();- let dominators = Dominators::compute(&graph);+ let mut dominators = Dominators::new();+ dominators.compute(&graph).unwrap();assert_eq!(dominators.idom(BlockId(0)), None);assert_eq!(dominators.idom(BlockId(1)), Some(BlockId(0)));assert_eq!(dominators.idom(BlockId(3)), Some(BlockId(0)));@@ -345,7 +346,7 @@ fn element_counts_move_out_of_loops_that_only_store_elements() {graph.blocks[2].control = Some(ret);verify(&graph).unwrap();- super::licm::run(&mut graph);+ super::licm::run(&mut graph, &mut Dominators::new()).unwrap();assert!(graph.blocks[0].body.contains(&length), "{:?}", graph.blocks);assert_eq!(graph.blocks[1].body, vec![store]);}@@ -404,7 +405,7 @@ fn loads_of_slots_that_nothing_writes_move_out_of_loops_that_call() {graph.blocks[2].control = Some(ret);verify(&graph).unwrap();- super::licm::run(&mut graph);+ super::licm::run(&mut graph, &mut Dominators::new()).unwrap();assert_eq!(graph.blocks[0].body, vec![unwritten], "{:?}", graph.blocks);assert_eq!(graph.blocks[1].body, vec![written, call]);verify(&graph).unwrap();@@ -544,7 +545,7 @@ fn typed_array_storage_metadata_moves_out_of_loops_that_only_store_elements() {let ret = node(&mut graph, Op::Return, vec![object], None);graph.blocks[2].control = Some(ret);verify(&graph).unwrap();- super::licm::run(&mut graph);+ super::licm::run(&mut graph, &mut Dominators::new()).unwrap();for metadata in [length, offset, data] {assert!(graph.blocks[0].body.contains(&metadata));}@@ -1006,7 +1007,7 @@ fn hoisted_checks_gate_exits_by_the_loop_headers_executable() {graph.blocks[2].control = Some(ret);graph.exit_sites.push((failed_executable, 77, ExitKind::NotObject));verify(&graph).unwrap();- super::licm::run(&mut graph);+ super::licm::run(&mut graph, &mut Dominators::new()).unwrap();verify(&graph).unwrap();assert_eq!(graph.blocks[0].body.contains(&check), failed_executable == 0);let recovery = graph.frame_state(graph.node(check).frame_state.unwrap());@@ -1167,7 +1168,7 @@ fn overflow_checks_removed_by_bounds_checks_check_the_counters_of_their_counts()graph.blocks[5].control = Some(ret);verify(&graph).unwrap();- super::bounds_check_elimination::run(&mut graph);+ super::bounds_check_elimination::run(&mut graph, &mut Dominators::new()).unwrap();verify(&graph).unwrap();let guarded = graph.blocks[1].body.iter().any(|node| {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rsindex f0c7d1637cf..2215085c2f3 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs@@ -118,9 +118,14 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), St/// 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 `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_edges(graph)?;- verify_nodes(graph, &places)?;+ verify_nodes(graph, &places, dominators)?;verify_frame_states(graph)}@@ -233,9 +238,12 @@ fn verify_edges(graph: &Graph) -> Result<(), String> {/// Checks that values are defined before their uses, and the rules of each/// kind of node.-fn verify_nodes(graph: &Graph, places: &[Option<Place>]) -> Result<(), String> {+fn verify_nodes(graph: &Graph, places: &[Option<Place>], dominators: &mut Dominators) -> Result<(), String> {let mut errors: Vec<String> = Vec::new();- let dominators = Dominators::compute(graph);+ if dominators.compute(graph).is_err() {+ return Err("the graph has more blocks than the tables of the dominators hold".to_string());+ }+ let dominators = &*dominators;let is_defined_before = |value: NodeId, block: BlockId, index: usize| -> bool {// NB: Virtual objects are in no block; their properties are listed// with the frame state values that need them.diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rsindex 43849c562d8..1c8f58dad33 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs@@ -11,142 +11,264 @@//! back edges), so loops are sets of blocks. Their cold blocks are left out://! those take values from where they are, and cost the loop nothing.+use ak::Column;+use ak::ColumnFull;+use super::liveness::ValueLiveness;-use crate::bitset::BitSet;use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::passes::dominators::Dominators;-use crate::sparse_bitset::SparseBitSet;+use crate::tables::Lists;+use crate::tables::pop;+use crate::tables::release;+use crate::tables::reset;+#[derive(Clone, Copy)]pub(super) struct Loop {pub header: BlockId,- /// The blocks of the loop but the cold ones.- blocks: BitSet,/// The first and last positions of its blocks.pub start: u32,end: u32,- /// The values live into the header that no node of the loop uses.- carried_through: SparseBitSet,+ /// Which loop of the graph it is, in the order of the headers.+ index: u32,+ /// How many blocks it has, without the cold ones.+ block_count: u32,}+/// In place of the loop around a block that is in no loop.+const NO_LOOP: u32 = u32::MAX;++/// The loops of a graph, in tables that serve one compile after the other.pub(super) struct Loops {- loops: Vec<Loop>,- /// The innermost loop around each block, as an index into `loops`.- innermost: Vec<Option<usize>>,+ loops: Column<Loop>,+ /// The blocks of each loop but the cold ones: for each loop, `words_for_each_loop` words with one bit for each+ /// block of the graph.+ blocks: Column<u64>,+ words_for_each_loop: usize,+ /// The innermost loop around each block, as an index into `loops`, or `NO_LOOP`.+ innermost: Column<u32>,/// The block of each position.- position_blocks: Vec<u32>,+ position_blocks: Column<u32>,+ /// For each loop, the values live into the header that no node of the loop uses, sorted.+ carried_through: Lists<NodeId>,+ /// The blocks that the back edges of a loop come from.+ back_edge_sources: Column<BlockId>,+ /// The blocks that the walk over a loop still has to visit.+ pending: Column<BlockId>,+ /// The loops, from the one with the most blocks to the one with the fewest.+ by_size: Column<u32>,}impl Loops {- pub fn compute(graph: &Graph, liveness: &ValueLiveness) -> Self {- let mut position_blocks = Vec::new();+ // NB: A compile whose graph needs more of these fails.+ const MAX_BLOCKS: usize = 1 << 24;+ const MAX_NODES: usize = 1 << 24;+ const MAX_ITEMS: usize = 1 << 26;++ /// Tables that take no memory before a compile uses them.+ pub fn new() -> Self {+ Self {+ loops: Column::new(Self::MAX_BLOCKS, c"JIT loops"),+ blocks: Column::new(Self::MAX_ITEMS, c"JIT loops"),+ words_for_each_loop: 0,+ innermost: Column::new(Self::MAX_BLOCKS, c"JIT loops"),+ position_blocks: Column::new(Self::MAX_NODES, c"JIT loops"),+ carried_through: Lists::new(Self::MAX_BLOCKS, Self::MAX_ITEMS, c"JIT loops"),+ back_edge_sources: Column::new(Self::MAX_ITEMS, c"JIT loops"),+ pending: Column::new(Self::MAX_ITEMS, c"JIT loops"),+ by_size: Column::new(Self::MAX_BLOCKS, c"JIT loops"),+ }+ }++ /// Drops the tables and gives their memory back to the system.+ pub fn release_memory(&mut self) {+ release(&mut self.loops);+ release(&mut self.blocks);+ release(&mut self.innermost);+ release(&mut self.position_blocks);+ self.carried_through.release_memory();+ release(&mut self.back_edge_sources);+ release(&mut self.pending);+ release(&mut self.by_size);+ }++ /// Finds the loops of `graph`. `dominators` are tables to compute its dominators in.+ pub fn compute(+ &mut self,+ graph: &Graph,+ liveness: &ValueLiveness,+ dominators: &mut Dominators,+ ) -> Result<(), ColumnFull> {+ let block_count = graph.blocks.len();+ self.position_blocks.clear();for (index, block) in graph.blocks.iter().enumerate() {- position_blocks.extend(std::iter::repeat_n(index as u32, block.nodes().count()));+ let end = self.position_blocks.len() + block.nodes().count();+ self.position_blocks.try_resize(end, index as u32)?;}- let mut loops = Vec::new();- let mut innermost = vec![None; graph.blocks.len()];+ self.loops.clear();+ self.blocks.clear();+ self.words_for_each_loop = block_count.div_ceil(64);+ self.carried_through.begin()?;+ reset(&mut self.innermost, block_count, NO_LOOP)?;// NB: Cold blocks are left out of loops, so only the edges from hot blocks make loops. Cold blocks come after// the hot ones, so their edges back into hot code would otherwise look like loops wherever they rejoin it.- let is_hot = |block: &BlockId| !graph.blocks[block.index()].is_cold;+ let is_hot = |block: BlockId| !graph.blocks[block.index()].is_cold;let has_back_edges = graph.blocks.iter().enumerate().any(|(index, block)| {block.predecessors.iter()- .any(|predecessor| predecessor.index() >= index && is_hot(predecessor))+ .any(|predecessor| predecessor.index() >= index && is_hot(*predecessor))});if !has_back_edges {- return Self {- loops,- innermost,- position_blocks,- };+ return Ok(());}- let dominators = Dominators::compute(graph);- for index in 0..graph.blocks.len() {+ dominators.compute(graph)?;+ for index in 0..block_count {let header = BlockId::from_index(index);- let mut back_edge_sources = dominators.back_edge_sources(graph, header);- back_edge_sources.retain(is_hot);- if back_edge_sources.is_empty() {+ // The sources of the back edges of the loop that the block heads, if it heads one: its predecessors that+ // it dominates.+ self.back_edge_sources.clear();+ for predecessor in &graph.block(header).predecessors {+ if dominators.dominates(header, *predecessor) && is_hot(*predecessor) {+ self.back_edge_sources.try_push(*predecessor)?;+ }+ }+ if self.back_edge_sources.is_empty() {continue;}- let mut blocks = dominators.loop_blocks(graph, header, &back_edge_sources);- for block in blocks.iter().collect::<Vec<_>>() {- if graph.blocks[block].is_cold {- blocks.remove(block);+ // The blocks of the loop: the header and every reachable block that reaches a source of a back edge+ // without going through the header.+ let row = self.blocks.len();+ self.blocks.try_resize(row + self.words_for_each_loop, 0)?;+ let blocks = &mut self.blocks[row..];+ let contains = |blocks: &[u64], block: usize| blocks[block / 64] & (1 << (block % 64)) != 0;+ blocks[index / 64] |= 1 << (index % 64);+ self.pending.clear();+ self.pending.try_extend_from_slice(&self.back_edge_sources)?;+ while let Some(block) = pop(&mut self.pending) {+ if contains(blocks, block.index()) || !dominators.is_reachable(block) {+ continue;}+ blocks[block.index() / 64] |= 1 << (block.index() % 64);+ self.pending.try_extend_from_slice(&graph.block(block).predecessors)?;}let position_of = |node: NodeId| liveness.positions[node.index()];let start = position_of(graph.block_nodes(header).next().expect("blocks have a control node"));- let end = blocks- .iter()- .map(|block| position_of(graph.control_id(BlockId::from_index(block))))- .max()- .unwrap_or(start);- let mut loop_ = Loop {+ let mut end = None;+ let mut count = 0;+ for (word_index, word) in blocks.iter_mut().enumerate() {+ let mut bits = *word;+ while bits != 0 {+ let bit = bits.trailing_zeros();+ bits &= bits - 1;+ let block = word_index * 64 + bit as usize;+ if graph.blocks[block].is_cold {+ *word &= !(1 << bit);+ continue;+ }+ count += 1;+ end = end.max(Some(position_of(graph.control_id(BlockId::from_index(block)))));+ }+ }+ let loop_ = Loop {header,- blocks,start,- end,- carried_through: SparseBitSet::new(graph.nodes.len()),+ end: end.unwrap_or(start),+ index: self.loops.len() as u32,+ block_count: count,};+ // NB: The values live into a block are in the order of their numbers, so this list is in that order too.for value in liveness.live_in.get(index) {let uses = liveness.use_positions(*value);- if loop_.first_use_in(uses, &position_blocks, 0..uses.len()).is_none() {- loop_.carried_through.insert(value.index());+ if loop_+ .first_use_in(blocks, uses, &self.position_blocks, 0..uses.len())+ .is_none()+ {+ self.carried_through.try_push(*value)?;}}- loops.push(loop_);+ self.carried_through.end_list()?;+ self.loops.try_push(loop_)?;}// NB: A loop inside another one has fewer blocks, so the smallest loop around a block is the innermost one.- let mut order = (0..loops.len()).collect::<Vec<_>>();- order.sort_by_key(|index| std::cmp::Reverse(loops[*index].blocks.count()));- for index in order {- for block in loops[index].blocks.iter() {- innermost[block] = Some(index);- }+ // Of two loops with as many blocks, the later one is taken.+ self.by_size.clear();+ for index in 0..self.loops.len() as u32 {+ self.by_size.try_push(index)?;}- Self {- loops,- innermost,- position_blocks,+ let loops = &self.loops;+ self.by_size+ .sort_unstable_by_key(|index| (std::cmp::Reverse(loops[*index as usize].block_count), *index));+ for index in self.by_size.iter() {+ let row = *index as usize * self.words_for_each_loop;+ let blocks = &self.blocks[row..row + self.words_for_each_loop];+ for (word_index, word) in blocks.iter().enumerate() {+ let mut word = *word;+ while word != 0 {+ let block = word_index * 64 + word.trailing_zeros() as usize;+ self.innermost[block] = *index;+ word &= word - 1;+ }+ }}+ Ok(())+ }++ /// The bits for the blocks of `loop_`.+ fn blocks_of(&self, loop_: &Loop) -> &[u64] {+ let start = loop_.index as usize * self.words_for_each_loop;+ &self.blocks[start..start + self.words_for_each_loop]+ }++ fn loop_around(&self, block: usize) -> Option<&Loop> {+ let index = self.innermost[block];+ (index != NO_LOOP).then(|| &self.loops[index as usize])}/// The innermost loop around the node at `position`.pub fn innermost_at(&self, position: u32) -> Option<&Loop> {let block = *self.position_blocks.get(position as usize)?;- self.innermost[block as usize].map(|index| &self.loops[index])+ self.loop_around(block as usize)}/// The loop that `header` heads, if it heads one.pub fn headed_by(&self, header: BlockId) -> Option<&Loop> {- self.innermost[header.index()]- .map(|index| &self.loops[index])- .filter(|loop_| loop_.header == header)+ self.loop_around(header.index()).filter(|loop_| loop_.header == header)}/// The first of the use positions `uses[range]` (in order) that is in `loop_`.pub fn first_use_in(&self, loop_: &Loop, uses: &[u32], range: std::ops::Range<usize>) -> Option<u32> {- loop_.first_use_in(uses, &self.position_blocks, range)+ loop_.first_use_in(self.blocks_of(loop_), uses, &self.position_blocks, range)}-}-impl Loop {- /// Whether no node of the loop uses `value`, which is live into its header.- pub fn carries_through(&self, value: usize) -> bool {- self.carried_through.contains(value)+ /// Whether no node of `loop_` uses `value`, which is live into its header.+ pub fn carries_through(&self, loop_: &Loop, value: NodeId) -> bool {+ self.carried_through+ .get(loop_.index as usize)+ .binary_search(&value)+ .is_ok()}+}- fn first_use_in(&self, uses: &[u32], position_blocks: &[u32], range: std::ops::Range<usize>) -> Option<u32> {+impl Loop {+ /// The first of the use positions `uses[range]` (in order) that is in the loop, which has the blocks with a bit+ /// in `blocks`.+ fn first_use_in(+ &self,+ blocks: &[u64],+ uses: &[u32],+ position_blocks: &[u32],+ range: std::ops::Range<usize>,+ ) -> Option<u32> {let uses = &uses[range];let from = uses.partition_point(|position| *position < self.start);let to = uses.partition_point(|position| *position <= self.end);- uses[from..to.max(from)]- .iter()- .copied()- .find(|position| self.blocks.contains(position_blocks[*position as usize] as usize))+ uses[from..to.max(from)].iter().copied().find(|position| {+ let block = position_blocks[*position as usize] as usize;+ blocks[block / 64] & (1 << (block % 64)) != 0+ })}}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rsindex 588e76c19e8..e29fdbe3b97 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs@@ -69,6 +69,7 @@ use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;+use crate::passes::dominators::Dominators;use crate::tables::Lists;use crate::tables::Run;use crate::tables::release;@@ -421,6 +422,7 @@ pub struct Regalloc {pub allocation: Allocation,liveness: ValueLiveness,coalescing: Coalescing,+ loops: Loops,/// The register each value is in, if any.value_registers: Column<Option<u8>>,/// The register contents at the end of each finished block: `REGISTER_COUNT` values for each block.@@ -440,6 +442,7 @@ impl Regalloc {allocation: Allocation::new(),liveness: ValueLiveness::new(),coalescing: Coalescing::new(),+ loops: Loops::new(),value_registers: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),end_contents: Column::new(Allocation::MAX_NODES * REGISTER_COUNT,@@ -456,6 +459,7 @@ impl Regalloc {self.allocation.release_memory();self.liveness.release_memory();self.coalescing.release_memory();+ self.loops.release_memory();release(&mut self.value_registers);release(&mut self.end_contents);release(&mut self.finished);@@ -486,14 +490,21 @@ pub fn frame_home(graph: &Graph, value: NodeId) -> Option<u32> {}/// Assigns locations to the values of `graph`, into `regalloc.allocation`. The verifier checks the-/// result where the IR is verified (see `verify()`).-pub fn allocate(graph: &Graph, registers: &RegisterSet, regalloc: &mut Regalloc) -> Result<(), CompileFailure> {+/// result where the IR is verified (see `verify()`). `dominators` are tables to compute the dominators of the graph+/// in.+pub fn allocate(+ graph: &Graph,+ registers: &RegisterSet,+ regalloc: &mut Regalloc,+ dominators: &mut Dominators,+) -> Result<(), CompileFailure> {assert!(registers.allocatable_gprs.0 >> FPR_BASE == 0);assert!(!registers.allocatable_gprs.contains(registers.scratch_gpr));let Regalloc {allocation,liveness,coalescing,+ loops,value_registers,end_contents,finished,@@ -502,7 +513,7 @@ pub fn allocate(graph: &Graph, registers: &RegisterSet, regalloc: &mut Regalloc)} = regalloc;liveness.compute(graph)?;coalescing.compute(graph, liveness)?;- let loops = Loops::compute(graph, liveness);+ loops.compute(graph, liveness, dominators)?;allocation.begin(graph.nodes.len(), graph.blocks.len())?;reset(value_registers, graph.nodes.len(), None)?;reset(end_contents, graph.blocks.len() * REGISTER_COUNT, None)?;@@ -545,7 +556,7 @@ struct Allocator<'a> {slot_classes: &'a [u32],class_slots: &'a mut Column<Option<u32>>,parallel_moves: &'a mut Column<Move>,- loops: Loops,+ loops: &'a Loops,}impl Allocator<'_> {@@ -696,7 +707,7 @@ impl Allocator<'_> {fn loop_leaves_in_stack(&self, block: BlockId, value: NodeId) -> bool {self.loops.headed_by(block)- .is_some_and(|loop_| loop_.carries_through(value.index()))+ .is_some_and(|loop_| self.loops.carries_through(loop_, value))&& self.liveness.needs_spill(value)}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex cf3e9f6b23b..b510f849ddf 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -18,6 +18,7 @@ use crate::code::SiteKind;use crate::code::ValueLocation;use crate::codegen::sites::SiteSource;use crate::ir::value;+use crate::passes::dominators::Dominators;/// The tables of a register allocation, which the tests read as the allocation.struct Allocated(Regalloc);@@ -38,7 +39,7 @@ impl std::ops::DerefMut for Allocated {fn allocate_with(graph: &Graph, registers: &RegisterSet) -> Allocated {let mut regalloc = Regalloc::new();- allocate(graph, registers, &mut regalloc).unwrap();+ allocate(graph, registers, &mut regalloc, &mut Dominators::new()).unwrap();Allocated(regalloc)}@@ -412,10 +413,7 @@ fn loop_phis_share_spill_slots_with_their_inputs() {let (mut shared, mut filled) = (0, 0);for phi in &graph.blocks[header].phis {let input = graph.node(*phi).inputs[back_edge];- let (phi_slot, input_slot) = (- allocation.node(*phi).spill_slot,- allocation.node(input).spill_slot,- );+ let (phi_slot, input_slot) = (allocation.node(*phi).spill_slot, allocation.node(input).spill_slot);if let (Some(phi_slot), Some(input_slot)) = (phi_slot, input_slot) {assert_eq!(phi_slot, input_slot, "{}", dump_allocation(&graph, &allocation));shared += 1;@@ -1251,7 +1249,13 @@ fn float64_values_get_floating_point_registers() {..Default::default()}]);let mut graph = crate::builder::build_graph_with_feedback(&snapshot, &|_| true).unwrap();- crate::passes::optimize(&mut graph, &snapshot.executables[0].layout, true);+ crate::passes::optimize(+ &mut graph,+ &snapshot.executables[0].layout,+ true,+ &mut Dominators::new(),+ )+ .unwrap();let allocation = allocate_and_verify(&graph);let mut floats = 0;for (index, node) in graph.nodes.iter().enumerate() {diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rsindex 9cc16c50dfb..d5ee4289cf0 100644--- a/Libraries/LibJS/JIT/Rust/src/scratch.rs+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs@@ -8,6 +8,7 @@use crate::artifact::ArtifactWriter;use crate::codegen::sites::SiteScratch;+use crate::passes::dominators::Dominators;use crate::regalloc::Regalloc;/// What a compile keeps its data in, apart from what the heap still holds of it. A thread that compiles has one, and@@ -18,6 +19,9 @@ pub struct Scratch {pub(crate) artifact: ArtifactWriter,pub(crate) sites: SiteScratch,pub(crate) regalloc: Regalloc,+ /// The dominators of the graph. The passes and the register allocator compute them when they need them, for the+ /// graph as it is then.+ pub(crate) dominators: Dominators,}impl Default for Scratch {@@ -33,6 +37,7 @@ impl Scratch {artifact: ArtifactWriter::new(),sites: SiteScratch::new(),regalloc: Regalloc::new(),+ dominators: Dominators::new(),}}@@ -41,5 +46,6 @@ impl Scratch {self.artifact.release_memory();self.sites.release_memory();self.regalloc.release_memory();+ self.dominators.release_memory();}}