Truly independent web browser
LibJS/JIT: Keep the tables of the register allocator in the work zone
Andreas Klingc1c2abac38ee
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex efe36c21f65..097006daf0b 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -7,7 +7,6 @@use super::*;use crate::bytecode::test_support::*;use crate::ir::dump;-use crate::passes::dominators::Dominators;use crate::snapshot::ExecutableSnapshot;use crate::snapshot::List;@@ -53,7 +52,6 @@ pub(crate) fn build_with_layout(program: &Program, layout: FrameLayout, never_ra&mut graph,&layout,true,- &mut Dominators::new(),&mut crate::test_work(),&mut crate::test_steps(),)@@ -68,7 +66,6 @@ pub(crate) fn optimized_graph(snapshot: &Snapshot) -> Graph<'static> {&mut graph,&snapshot.executables[0].layout,true,- &mut Dominators::new(),&mut crate::test_work(),&mut crate::test_steps(),)diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 9640d09c669..524e300e7d4 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -104,7 +104,7 @@ fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bo// NB: A stub has no graph to build: the graph stays empty, so its zone gives out nothing and takes no memory.let zone = ak::Zone::new(0, c"JIT stub graph");let graph = Graph::new_in(&zone);- let allocation = Allocation::default();+ let allocation = Allocation::new_in(&zone);// NB: A stub is code for no executable. It reads no list of the runtime info.let snapshot = Snapshot::new();let (_, pinned) = target_registers::<M>();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 634d6448550..644e29eef67 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -272,7 +272,7 @@ struct Locals {struct Codegen<'a, M: PortableMacroAssembler> {masm: M,graph: &'a Graph<'a>,- allocation: &'a Allocation,+ allocation: &'a Allocation<'a>,/// What the graph was built from. Executable 0 is the compiled function.snapshot: &'a Snapshot,/// Where the instructions that code generation decodes again keep their arrays.@@ -419,7 +419,7 @@ struct LeaveStub {leave_arguments: Vec<(u32, bool)>,}-/// Generates code for `graph` with the register allocation in `tables`, whose registers came from+/// Generates code for `graph` with the register allocation `allocation`, whose registers came from/// `target_registers::<M>()`, and writes the sites of the code into/// `tables`. With `verify` (and in debug builds), checks that/// every lowering matches its `lowering_info()`.@@ -428,15 +428,10 @@ pub fn generate<M: PortableMacroAssembler>(snapshot: &Snapshot,verify: bool,tables: &mut Tables,+ allocation: &Allocation,work: &Zone,) -> Result<GeneratedCode, CompileFailure> {- let Tables {- artifact,- sites,- regalloc,- ..- } = tables;- let allocation = ®alloc.allocation;+ let Tables { artifact, sites } = tables;let (_, pinned) = target_registers::<M>();let (gpr_dump_count, fpr_dump_count) = register_dump_counts::<M>();let mut masm = M::new();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rsindex 3e312bb508b..5842a580a27 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs@@ -112,7 +112,7 @@ impl SiteScratch {/// `Graph::frame_state_values()`.struct Locations<'a> {graph: &'a Graph<'a>,- allocation: &'a Allocation,+ allocation: &'a Allocation<'a>,kind: SiteKind,/// See `Graph::virtual_objects()`.objects: &'a [NodeId],@@ -171,7 +171,7 @@ impl Locations<'_> {/// What a site is written from.pub(crate) struct SiteSource<'a> {pub graph: &'a Graph<'a>,- pub allocation: &'a Allocation,+ pub allocation: &'a Allocation<'a>,/// The node whose frame state the site has.pub node: NodeId,pub kind: SiteKind,diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex b5841f7e6a2..2a4a1c19b1c 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -39,7 +39,6 @@ pub mod ir;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod options;pub mod passes;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod regalloc;pub mod scratch;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]@@ -51,6 +50,7 @@ pub mod zone_map;#[cfg(all(test, windows, not(target_arch = "x86_64")))]compile_error!("the tests of the JIT run on Windows on x86-64 only");+use ak::Zone;use artifact::Artifact;use artifact::Tail;use bytecode::OpCode;@@ -189,35 +189,31 @@ fn run_stages<M: asm::PortableMacroAssembler>(&mut graph,&executable.layout,snapshot.options.verify_ir,- &mut tables.dominators,work,steps,)?)} else {- passes::optimize(- &mut graph,- &executable.layout,- snapshot.options.verify_ir,- &mut tables.dominators,- work,- steps,- )?;+ passes::optimize(&mut graph, &executable.layout, snapshot.options.verify_ir, work, steps)?;None};let (mut registers, _) = codegen::target_registers::<M>();if snapshot.options.stress.few_registers {registers.allocatable_gprs = registers.few_registers(STRESS_EXTRA_REGISTERS);}- work.scope(|work| regalloc::allocate(&graph, ®isters, &mut tables.regalloc, &mut tables.dominators, work))?;+ // NB: The allocation is in the work zone, and the code generator reads it, so the work data of the register+ // allocator, and of the stages after it, stays until the compile ends.+ let work: &Zone = work;+ let allocation = regalloc::allocate(&graph, ®isters, work)?;if snapshot.options.verify_ir- && let Err(errors) = work.scope(|work| regalloc::verify(&graph, ®isters, &tables.regalloc.allocation, work))+ && let Err(errors) = regalloc::verify(&graph, ®isters, &allocation, work){panic!("invalid register allocation:\n{errors}\n{}",- regalloc::dump_allocation(&graph, &tables.regalloc.allocation)+ regalloc::dump_allocation(&graph, &allocation));}- let mut generated = codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, tables, work)?;+ let mut generated =+ codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, tables, &allocation, work)?;generated.osr_entries.sort_unstable();let layout = tables.artifact.finish(&Tail {@@ -238,7 +234,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(let mut text = pass_dumps.unwrap_or_default();if snapshot.options.dump_ir {text.push_str(&ir::dump(&graph, &executable.layout));- text.push_str(®alloc::dump_allocation(&graph, &tables.regalloc.allocation));+ text.push_str(®alloc::dump_allocation(&graph, &allocation));}if snapshot.options.dump_asm {text.push_str(&codegen::dump_code(diff --git a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rsindex acffe932549..6acf8c215ec 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs@@ -43,7 +43,6 @@//! 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 ak::Zone;use ak::ZoneVec;@@ -116,7 +115,7 @@ impl Range {struct Ranges<'a> {graph: &'a Graph<'a>,- dominators: &'a Dominators,+ dominators: &'a Dominators<'a>,/// The block of each phi.phi_blocks: &'a ZoneMap<'a, NodeId, BlockId>,/// The ranges of entering counters that checks added where they enter@@ -528,7 +527,7 @@ fn entering_counters<'w>(entering}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, work: &Zone) {let mut phi_blocks = ZoneMap::new_in(work);let mut checks = ZoneVec::new_in(work);let mut shifts = ZoneVec::new_in(work);@@ -581,10 +580,9 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resulchecks.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 Ok(());+ return;}- dominators.compute(graph)?;- let dominators = &*dominators;+ let dominators = &Dominators::of(graph, work);let entering = entering_counters(graph, dominators, &phi_blocks, work);let mut ranges = Ranges {graph,@@ -661,7 +659,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul}}if passing.is_empty() && scaled.is_empty() && exact.is_empty() {- return Ok(());+ return;}// NB: Only the entering counters that the removed checks, the// rewritten shifts and the operations that stop checking for overflow@@ -752,5 +750,4 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resulgraph.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 d5c7ae7990a..34451b6b5ab 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs@@ -12,7 +12,6 @@//! 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 ak::Zone;use ak::ZoneVec;@@ -250,13 +249,8 @@ 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. 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)?;+fn split_one(graph: &mut Graph, dominators: &mut Dominators, lists: &mut Lists, step: &Zone) -> bool {+ dominators.compute(graph);let dominators = &*dominators;// NB: Splits add nodes, so the set grows ahead of them.if lists.phis.capacity() < graph.nodes.len() {@@ -398,17 +392,12 @@ fn split_one(graph.nodes[phi.index()].inputs.clear();}super::edit::clean_up_control_flow(graph, step);- return Ok(true);+ return true;}- Ok(false)+ false}-pub fn run(- graph: &mut Graph,- dominators: &mut Dominators,- work: &Zone,- steps: &mut [Zone; 2],-) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {let [step, _] = steps;let mut lists = Lists {zone: work,@@ -420,11 +409,11 @@ pub fn run(renames: [ZoneVec::new_in(work), ZoneVec::new_in(work)],copies: ZoneVec::new_in(work),};+ let mut dominators = Dominators::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, &mut lists, step))? {+ if !step.scope(|step| split_one(graph, &mut dominators, &mut lists, step)) {break;}}- Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rsindex 50ffb305691..30769088eac 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs@@ -10,8 +10,6 @@//! immediate dominator, and neither has a block reached from several//! entries.-use ak::Column;-use ak::ColumnFull;use ak::Zone;use ak::ZoneVec;@@ -19,106 +17,100 @@ use crate::bitset::ZoneBitSet;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 dominator tree of a graph, in lists of a work zone. `compute()` makes them anew for the graph as it is then,+/// in the memory they have where it is enough.+pub struct Dominators<'w> {/// The immediate dominator of each block, if it has one.- idom: Column<Option<BlockId>>,+ idom: ZoneVec<'w, Option<BlockId>>,/// Whether each block is reachable from an entry.- reachable: Column<bool>,+ reachable: ZoneVec<'w, 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: Column<(u32, u32)>,+ tree_intervals: ZoneVec<'w, (u32, u32)>,/// The children of each block in the dominator tree, in linear order.- children: Lists<BlockId>,+ children: Lists<'w, BlockId>,/// The reachable blocks in reverse postorder.- order: Column<BlockId>,+ order: ZoneVec<'w, BlockId>,/// The place of each reachable block in `order`, plus one.- ranks: Column<u32>,+ ranks: ZoneVec<'w, u32>,/// Whether each block has an immediate dominator or the virtual root above every entry as its dominator so far.- processed: Column<bool>,+ processed: ZoneVec<'w, bool>,/// The blocks that a walk still has to enter or leave, and whether it is to leave them.- pending: Column<(BlockId, bool)>,+ pending: ZoneVec<'w, (BlockId, bool)>,}-impl Dominators {- // NB: The tables do not hold the dominators of a graph with more blocks.- const MAX_BLOCKS: usize = 1 << 24;+impl<'w> Dominators<'w> {+ /// The most blocks a graph has whose dominators a compile computes. A compile whose graph has more fails (see+ /// `passes::optimize()`).+ pub 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")- }+ /// Lists for the dominators of a graph, which take no memory before `compute()` uses them.+ pub fn new_in(work: &'w Zone) -> Self {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"),+ idom: ZoneVec::new_in(work),+ reachable: ZoneVec::new_in(work),+ tree_intervals: ZoneVec::new_in(work),+ children: Lists::new_in(work),+ order: ZoneVec::new_in(work),+ ranks: ZoneVec::new_in(work),+ processed: ZoneVec::new_in(work),+ pending: ZoneVec::new_in(work),}}- /// 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);+ /// The dominators of `graph` as it is now, in `work`.+ pub fn of(graph: &Graph, work: &'w Zone) -> Self {+ let mut dominators = Self::new_in(work);+ dominators.compute(graph);+ dominators}/// 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+ /// Harvey and Kennedy, visiting blocks in reverse postorder. The lists 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> {+ pub fn compute(&mut self, graph: &Graph) {let count = graph.blocks.len();- reset(&mut self.reachable, count, false)?;+ self.reachable.clear();+ self.reachable.resize(count, false);self.order.clear();+ self.order.reserve(count);self.pending.clear();+ // NB: A block waits to be left one time, and to be entered one time for each edge into it and for each entry+ // it is.+ let edges = graph.blocks.iter().map(|block| block.predecessors.len()).sum::<usize>();+ self.pending.reserve(count + edges + graph.entries().count());for entry in graph.entries() {- self.pending.try_push((entry, false))?;+ self.pending.push((entry, false));}- while let Some((block, leaving)) = pop(&mut self.pending) {+ while let Some((block, leaving)) = self.pending.pop() {if leaving {- self.order.try_push(block)?;+ self.order.push(block);continue;}if self.reachable[block.index()] {continue;}self.reachable[block.index()] = true;- self.pending.try_push((block, true))?;- let mut pushed = Ok(());+ self.pending.push((block, true));graph.control(block).op.for_each_successor(|successor| {- if pushed.is_ok() {- pushed = self.pending.try_push((successor, false));- }+ self.pending.push((successor, false));});- pushed?;}self.order.reverse();// NB: Rank zero is the virtual root. Walking to an immediate// dominator decreases the rank, avoiding ancestor-depth scans.- reset(&mut self.ranks, count, 0)?;+ self.ranks.clear();+ self.ranks.resize(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".- reset(&mut self.idom, count, None)?;- reset(&mut self.processed, count, false)?;+ self.idom.clear();+ self.idom.resize(count, None);+ self.processed.clear();+ self.processed.resize(count, false);let mut changed = true;while changed {changed = false;@@ -146,13 +138,13 @@ impl Dominators {}}}- self.compute_children()?;- self.compute_tree_intervals()+ self.compute_children();+ self.compute_tree_intervals();}- fn compute_children(&mut self) -> Result<(), ColumnFull> {+ fn compute_children(&mut self) {let count = self.idom.len();- self.children.begin_counts(count)?;+ self.children.begin_counts(count);for block in 0..count {if let Some(idom) = self.idom[block]&& self.reachable[block]@@ -160,7 +152,7 @@ impl Dominators {self.children.count(idom.index());}}- self.children.end_counts(BlockId(0))?;+ self.children.end_counts(BlockId(0));for block in 0..count {if let Some(idom) = self.idom[block]&& self.reachable[block]@@ -169,32 +161,31 @@ impl Dominators {}}self.children.end_fill();- Ok(())}- fn compute_tree_intervals(&mut self) -> Result<(), ColumnFull> {+ fn compute_tree_intervals(&mut self) {let count = self.idom.len();- reset(&mut self.tree_intervals, count, (0, 0))?;+ self.tree_intervals.clear();+ self.tree_intervals.resize(count, (0, 0));let mut time = 0;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))?;+ self.pending.push((BlockId::from_index(block), false));}}- while let Some((block, leaving)) = pop(&mut self.pending) {+ while let Some((block, leaving)) = self.pending.pop() {time += 1;if leaving {self.tree_intervals[block.index()].1 = time;continue;}self.tree_intervals[block.index()].0 = time;- self.pending.try_push((block, true))?;+ self.pending.push((block, true));for child in self.children.get(block.index()) {- self.pending.try_push((*child, false))?;+ self.pending.push((*child, false));}}- Ok(())}pub fn idom(&self, block: BlockId) -> Option<BlockId> {@@ -207,7 +198,7 @@ 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<'w>(&self, graph: &Graph, header: BlockId, work: &'w Zone) -> ZoneVec<'w, BlockId> {+ pub fn back_edge_sources<'v>(&self, graph: &Graph, header: BlockId, work: &'v Zone) -> ZoneVec<'v, BlockId> {ZoneVec::from_iter_in(graph.block(header)@@ -222,13 +213,13 @@ impl Dominators {/// 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<'w>(+ pub fn loop_blocks<'v>(&self,graph: &Graph,header: BlockId,back_edge_sources: &[BlockId],- work: &'w Zone,- ) -> ZoneBitSet<'w> {+ work: &'v Zone,+ ) -> ZoneBitSet<'v> {let mut blocks = ZoneBitSet::new_in(graph.blocks.len(), work);blocks.insert(header.index());let mut pending = ZoneVec::from_slice_in(back_edge_sources, work);@@ -274,12 +265,6 @@ impl Dominators {}}-impl Default for Dominators {- fn default() -> Self {- Self::new()- }-}-/// The nearest common dominator of two blocks, `None` standing for the/// virtual root above every entry.fn intersect(@@ -306,7 +291,8 @@ mod tests {#[test]fn cyclic_graphs_with_multiple_entries_match_dominator_sets() {- let mut dominators = Dominators::new();+ let work = crate::test_work();+ let mut dominators = Dominators::new_in(&work);for seed in 1..33u64 {let mut random = seed;let mut graph = Graph::default();@@ -339,7 +325,7 @@ mod tests {}}// NB: The tables of one graph serve the next one.- dominators.compute(&graph).unwrap();+ dominators.compute(&graph);// NB: Independently solve the defining set equations: each// block dominates itself and inherits the intersection of// its predecessors' dominators.diff --git a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rsindex d733dc7ac4c..515293b4a1a 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs@@ -12,7 +12,6 @@//! 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 ak::Zone;use ak::ZoneVec;@@ -42,8 +41,8 @@ fn is_numbered(op: &Op) -> bool {&& !op.is_control()}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {- run_with_hash(graph, dominators, work, |node, replacements| {+pub fn run(graph: &mut Graph, work: &Zone) {+ run_with_hash(graph, work, |node, replacements| {let mut hash = FastHasher::default();discriminant(&node.op).hash(&mut hash);node.inputs.len().hash(&mut hash);@@ -51,15 +50,10 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resulreplacements.resolve(*input).hash(&mut hash);}hash.finish()- })+ });}-fn run_with_hash(- graph: &mut Graph,- dominators: &mut Dominators,- work: &Zone,- hash: impl Fn(&Node, &Replacements) -> u64,-) -> Result<(), ColumnFull> {+fn run_with_hash(graph: &mut Graph, work: &Zone, hash: impl Fn(&Node, &Replacements) -> u64) {if graph.blocks.iter()@@ -69,9 +63,9 @@ fn run_with_hash(.count()< 2{- return Ok(());+ return;}- dominators.compute(graph)?;+ let dominators = Dominators::of(graph, work);let mut replacements = Replacements::new(graph, work);let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);// NB: Hash borrowed inputs instead of allocating keys. Candidates with@@ -152,7 +146,6 @@ fn run_with_hash(}replacements.apply(graph);edit::remove_nodes(graph, &removed);- Ok(())}#[cfg(test)]@@ -176,7 +169,7 @@ mod tests {.body.assign(&[first, different_input, different_operation, duplicate]);graph.blocks[0].control = Some(returned);- run_with_hash(&mut graph, &mut Dominators::new(), crate::test_zone(), |_, _| 0).unwrap();+ run_with_hash(&mut graph, crate::test_zone(), |_, _| 0);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 879f1cd0751..1418582ba56 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs@@ -25,7 +25,6 @@//! 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 ak::Zone;use ak::ZoneVec;@@ -232,12 +231,11 @@ fn has_loop_around(graph: &Graph, loop_: &Loop, visited: &mut ZoneBitSet, worklifalse}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, work: &Zone) {if !graph.nodes.iter().any(|node| matches!(node.op, Op::CheckInterrupt)) {- return Ok(());+ return;}- dominators.compute(graph)?;- let dominators = &*dominators;+ let dominators = &Dominators::of(graph, work);let mut loops = ZoneVec::new_in(work);for index in 0..graph.blocks.len() {let header = BlockId::from_index(index);@@ -279,5 +277,4 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul.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 aa565582c49..ca1592b1e09 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs@@ -25,7 +25,6 @@//! exited there, so a speculation that fails costs one exit, and keeps the//! other checks moving.-use ak::ColumnFull;use ak::Zone;use ak::ZoneVec;@@ -159,7 +158,7 @@ fn find_loops<'w>(graph: &Graph, dominators: &Dominators, work: &'w Zone) -> Zonloops}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, work: &Zone) {// 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@@ -168,20 +167,20 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul.any(|predecessor| predecessor.index() >= index)});if !has_loops {- return Ok(());+ return;}- dominators.compute(graph)?;- if add_preheaders(graph, dominators, work) {+ let mut dominators = Dominators::of(graph, work);+ 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.edit::remove_trivial_phis(graph, work);- dominators.compute(graph)?;+ dominators.compute(graph);}- let dominators = &*dominators;+ let dominators = &dominators;let loops = find_loops(graph, dominators, work);if loops.is_empty() {- return Ok(());+ return;}let mut block_of = ZoneVec::from_elem_in(None, graph.nodes.len(), work);let mut hoisted = ZoneVec::new_in(work);@@ -273,5 +272,4 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Resul}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.rsindex 6cd22aaaaee..1ba8383f9a7 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs@@ -18,7 +18,6 @@//! 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 ak::Zone;use ak::ZoneVec;@@ -35,23 +34,19 @@ 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,- dominators: &mut Dominators,- work: &Zone,- steps: &mut [Zone; 2],-) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {let [step, _] = steps;if graph.osr_entries.is_empty() {- return Ok(());+ return;}let mut rotated = false;+ let mut dominators = Dominators::new_in(work);// NB: Each rotation makes one irreducible loop reducible; a graph has fewer such loops than blocks.for _ in 0..graph.blocks.len() {- dominators.compute(graph)?;// NB: Each rotation makes tables as large as the graph, which go when it ends.let rotated_one = step.scope(|step| {- let Some((test, region, sources)) = find_rotatable_test(graph, dominators, step) else {+ dominators.compute(graph);+ let Some((test, region, sources)) = find_rotatable_test(graph, &dominators, step) else {return false;};rotate(graph, test, ®ion, &sources, step);@@ -66,7 +61,6 @@ pub fn run(lay_out_in_reverse_post_order(graph, work);edit::remove_trivial_phis(graph, work);}- 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 67a24ae8465..beca81a8c2f 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -38,9 +38,9 @@ pub mod verify;#[cfg(test)]mod tests;-use ak::ColumnFull;use ak::Zone;+use crate::CompileFailure;use crate::bytecode::FrameLayout;use crate::ir::Graph;use dominators::Dominators;@@ -57,42 +57,24 @@ struct Pass {/// one step zone to the other (see `check_elimination`).#[derive(Clone, Copy)]enum Run {- Plain(fn(&mut Graph, &Zone)),- /// 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, &Zone) -> Result<(), ColumnFull>),+ /// A pass that keeps its data in the work zone.+ Once(fn(&mut Graph, &Zone)),/// A pass that keeps what lasts for the whole pass in the work zone, and the data of its steps in the step zones/// (see `Scratch::steps`).Steps(fn(&mut Graph, &Zone, &mut [Zone; 2])),- StepsWithDominators(fn(&mut Graph, &mut Dominators, &Zone, &mut [Zone; 2]) -> Result<(), ColumnFull>),}/// How many bytes of memory each step zone keeps after a pass, so that the steps of most functions take no memory from/// the system again.const STEP_MEMORY_KEPT: usize = 4 << 20;-impl Run {- /// Runs the pass. It keeps its own data in `work` and `steps`, which hold none of it when this returns.- fn run(- self,- graph: &mut Graph,- dominators: &mut Dominators,- work: &mut Zone,- steps: &mut [Zone; 2],- ) -> Result<(), ColumnFull> {- let result = work.scope(|work| match self {- Run::Plain(run) => {- run(graph, work);- Ok(())- }- Run::WithDominators(run) => run(graph, dominators, work),- Run::Steps(run) => {- run(graph, work, steps);- Ok(())- }- Run::StepsWithDominators(run) => run(graph, dominators, work, steps),- });- if let Run::Steps(_) | Run::StepsWithDominators(_) = self {+/// Runs the pass `run`. It keeps its own data in `work` and `steps`, which hold none of it when this returns.+fn run_pass(run: Run, graph: &mut Graph, work: &mut Zone, steps: &mut [Zone; 2]) -> Result<(), CompileFailure> {+ fits(graph)?;+ match run {+ Run::Once(run) => work.scope(|work| run(graph, work)),+ Run::Steps(run) => {+ work.scope(|work| run(graph, work, steps));// NB: A pass that moves its data between the step zones leaves data in both. The memory of large steps// goes back to the system, so that it does not stay on top of what the stages after this one take// in the work zone.@@ -101,43 +83,52 @@ impl Run {zone.trim(STEP_MEMORY_KEPT);}}- result}+ Ok(())+}++/// Fails the compile if the passes cannot compute the dominators of `graph`, which has too many blocks.+// NB: The passes add blocks, so the count is checked again before each of them.+fn fits(graph: &Graph) -> Result<(), CompileFailure> {+ if graph.blocks.len() > Dominators::MAX_BLOCKS {+ return Err(CompileFailure::TooLarge);+ }+ Ok(())}/// The passes, in the order they run.const PASSES: &[Pass] = &[Pass {name: "loop rotation",- run: Run::StepsWithDominators(loop_rotation::run),+ run: Run::Steps(loop_rotation::run),},Pass {name: "trivial phi removal",- run: Run::Plain(edit::remove_trivial_phis),+ run: Run::Once(edit::remove_trivial_phis),},Pass {name: "truncation",- run: Run::Plain(truncation::run),+ run: Run::Once(truncation::run),},Pass {name: "simplification",- run: Run::Plain(simplify::run),+ run: Run::Once(simplify::run),},Pass {name: "representation selection",- run: Run::Plain(representation::run),+ run: Run::Once(representation::run),},Pass {name: "simplification",- run: Run::Plain(simplify::run),+ run: Run::Once(simplify::run),},Pass {name: "branch splitting",- run: Run::StepsWithDominators(branch_splitting::run),+ run: Run::Steps(branch_splitting::run),},Pass {name: "global value numbering",- run: Run::WithDominators(gvn::run),+ run: Run::Once(gvn::run),},Pass {name: "check elimination",@@ -145,31 +136,31 @@ const PASSES: &[Pass] = &[},Pass {name: "simplification",- run: Run::Plain(simplify::run_after_check_elimination),+ run: Run::Once(simplify::run_after_check_elimination),},Pass {name: "global value numbering",- run: Run::WithDominators(gvn::run),+ run: Run::Once(gvn::run),},Pass {name: "loop invariant code motion",- run: Run::WithDominators(licm::run),+ run: Run::Once(licm::run),},Pass {name: "bounds check elimination",- run: Run::WithDominators(bounds_check_elimination::run),+ run: Run::Once(bounds_check_elimination::run),},Pass {name: "interrupt check elimination",- run: Run::WithDominators(interrupt_check_elimination::run),+ run: Run::Once(interrupt_check_elimination::run),},Pass {name: "exit unboxing",- run: Run::Plain(exit_unboxing::run),+ run: Run::Once(exit_unboxing::run),},Pass {name: "dead code elimination",- run: Run::Plain(dce::run),+ run: Run::Once(dce::run),},Pass {name: "escape analysis",@@ -177,19 +168,19 @@ const PASSES: &[Pass] = &[},Pass {name: "dead code elimination",- run: Run::Plain(dce::run),+ run: Run::Once(dce::run),},Pass {name: "enumerated keys",- run: Run::Plain(enumerated_keys::run),+ run: Run::Once(enumerated_keys::run),},Pass {name: "branch fusion",- run: Run::Plain(branch_fusion::run),+ run: Run::Once(branch_fusion::run),},Pass {name: "key strings",- run: Run::Plain(key_strings::run),+ run: Run::Once(key_strings::run),},];@@ -200,11 +191,10 @@ pub fn optimize(graph: &mut Graph,layout: &FrameLayout,verify: bool,- dominators: &mut Dominators,work: &mut Zone,steps: &mut [Zone; 2],-) -> Result<(), ColumnFull> {- run_passes(graph, layout, verify, dominators, work, steps, &mut |_, _| {})+) -> Result<(), CompileFailure> {+ run_passes(graph, layout, verify, work, steps, &mut |_, _| {})}/// `optimize()`, returning the graph as text after building it and after@@ -213,12 +203,11 @@ pub fn optimize_with_dumps(graph: &mut Graph,layout: &FrameLayout,verify: bool,- dominators: &mut Dominators,work: &mut Zone,steps: &mut [Zone; 2],-) -> Result<String, ColumnFull> {+) -> Result<String, CompileFailure> {let mut text = String::new();- run_passes(graph, layout, verify, dominators, work, steps, &mut |graph, after| {+ run_passes(graph, layout, verify, work, steps, &mut |graph, after| {text.push_str(&format!("=== after {after}\n"));text.push_str(&crate::ir::dump(graph, layout));})?;@@ -229,33 +218,32 @@ fn run_passes(graph: &mut Graph,layout: &FrameLayout,verify: bool,- dominators: &mut Dominators,work: &mut Zone,steps: &mut [Zone; 2],observe: &mut dyn FnMut(&Graph, &str),-) -> Result<(), ColumnFull> {+) -> Result<(), CompileFailure> {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.work.scope(|work| edit::remove_unreachable_blocks(graph, work));- check(graph, layout, verify, dominators, work, "graph building");+ check(graph, layout, verify, work, "graph building");observe(graph, "graph building");for pass in PASSES {- pass.run.run(graph, dominators, work, steps)?;- check(graph, layout, verify, dominators, work, pass.name);+ run_pass(pass.run, graph, work, steps)?;+ check(graph, layout, verify, work, 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.work.scope(|work| edit::remove_refinements(graph, work));- Run::WithDominators(gvn::run).run(graph, dominators, work, steps)?;+ run_pass(Run::Once(gvn::run), graph, 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, work, "refinement removal");+ run_pass(Run::Once(dce::run), graph, work, steps)?;+ check(graph, layout, verify, work, "refinement removal");observe(graph, "refinement removal");work.scope(|work| frame_initialization::run(graph, layout, work));- check(graph, layout, verify, dominators, work, "frame initialization");+ check(graph, layout, verify, 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).@@ -267,18 +255,17 @@ fn run_passes(graph.blocks[block.index()].is_cold = true;}work.scope(|work| edit::move_cold_blocks_last(graph, work));- check(graph, layout, verify, dominators, work, "cold block layout");+ check(graph, layout, verify, work, "cold block layout");observe(graph, "frame initialization");Ok(())}-fn check(graph: &Graph, layout: &FrameLayout, verify: bool, dominators: &mut Dominators, work: &mut Zone, after: &str) {+fn check(graph: &Graph, layout: &FrameLayout, verify: bool, work: &mut Zone, after: &str) {if !verify {return;}- let result = work.scope(|work| {- verify::verify_with(graph, dominators, work).and(verify::verify_frame_writes(graph, layout, work))- });+ let result =+ work.scope(|work| verify::verify_with(graph, work).and(verify::verify_frame_writes(graph, layout, work)));if let Err(errors) = result {panic!("invalid graph after {after}:\n{errors}\n{}",diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rsindex 308611baa64..40a0716de02 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs@@ -66,8 +66,7 @@ fn diamond() -> (Graph<'static>, NodeId) {#[test]fn dominators_of_a_diamond() {let (graph, _) = diamond();- let mut dominators = Dominators::new();- dominators.compute(&graph).unwrap();+ let dominators = Dominators::of(&graph, crate::test_zone());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)));@@ -346,7 +345,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, &mut Dominators::new(), crate::test_zone()).unwrap();+ super::licm::run(&mut graph, crate::test_zone());assert!(graph.blocks[0].body.contains(&length), "{:?}", graph.blocks);assert_eq!(graph.blocks[1].body, vec![store]);}@@ -405,7 +404,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, &mut Dominators::new(), crate::test_zone()).unwrap();+ super::licm::run(&mut graph, crate::test_zone());assert_eq!(graph.blocks[0].body, vec![unwritten], "{:?}", graph.blocks);assert_eq!(graph.blocks[1].body, vec![written, call]);verify(&graph).unwrap();@@ -545,7 +544,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, &mut Dominators::new(), crate::test_zone()).unwrap();+ super::licm::run(&mut graph, crate::test_zone());for metadata in [length, offset, data] {assert!(graph.blocks[0].body.contains(&metadata));}@@ -1066,7 +1065,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, &mut Dominators::new(), crate::test_zone()).unwrap();+ super::licm::run(&mut graph, crate::test_zone());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());@@ -1227,7 +1226,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, &mut Dominators::new(), crate::test_zone()).unwrap();+ super::bounds_check_elimination::run(&mut graph, crate::test_zone());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 6f47250acea..b4ccad2f843 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs@@ -131,14 +131,14 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout, work: &Zone) ->/// 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(), &Zone::new(1 << 30, c"JIT verifier"))+ verify_with(graph, &Zone::new(1 << 30, c"JIT verifier"))}-/// `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> {+/// `verify()`, with `work` for its lists.+pub fn verify_with(graph: &Graph, work: &Zone) -> Result<(), String> {let places = verify_blocks(graph, work)?;verify_edges(graph)?;- verify_nodes(graph, &places, dominators, work)?;+ verify_nodes(graph, &places, work)?;verify_frame_states(graph, work)}@@ -243,17 +243,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>],- dominators: &mut Dominators,- work: &Zone,-) -> Result<(), String> {+fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<(), String> {let mut errors = Errors::default();- if dominators.compute(graph).is_err() {+ if graph.blocks.len() > Dominators::MAX_BLOCKS {return Err("the graph has more blocks than the tables of the dominators hold".to_string());}- let dominators = &*dominators;+ let dominators = &Dominators::of(graph, work);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/coalescing.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rsindex 630d4a6afdc..f4f31dcf014 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs@@ -16,9 +16,8 @@//! is defined. Values join a class of values sharing one slot only if they//! overlap with no value already in it.-use ak::Column;-use ak::ColumnFull;use ak::Zone;+use ak::ZoneVec;use super::liveness::ValueLiveness;use super::liveness::is_allocated_value;@@ -26,8 +25,6 @@ use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::tables::Lists;-use crate::tables::release;-use crate::tables::reset;/// The most values one class holds, which keeps the pairwise checks cheap.const MAX_CLASS_SIZE: u32 = 32;@@ -40,26 +37,26 @@ struct Definition {position: Option<u32>,}-/// The spill slot classes of the values of a graph, in tables that serve one compile after the other.-pub(super) struct Coalescing {+/// The spill slot classes of the values of a graph, in tables in the work zone of a compile.+pub(super) struct Coalescing<'w> {/// The class of each value: values of one class share their spill slot./// Classes are named by one of their values.- pub classes: Column<u32>,+ pub classes: ZoneVec<'w, u32>,/// For each value, the next value of its class. The values of a class are a ring, so that two classes join with/// no list to copy.- next: Column<u32>,+ next: ZoneVec<'w, u32>,/// For each value that names a class, how many values the class has.- sizes: Column<u32>,- definitions: Column<Definition>,+ sizes: ZoneVec<'w, u32>,+ definitions: ZoneVec<'w, Definition>,/// For each value, the blocks where it dies and the positions there.- deaths: Lists<(usize, u32)>,+ deaths: Lists<'w, (usize, u32)>,}struct Interference<'a> {graph: &'a Graph<'a>,- liveness: &'a ValueLiveness,+ liveness: &'a ValueLiveness<'a>,definitions: &'a [Definition],- deaths: &'a Lists<(usize, u32)>,+ deaths: &'a Lists<'a, (usize, u32)>,work: &'a Zone,}@@ -115,53 +112,36 @@ fn members(next: &[u32], value: u32) -> impl Iterator<Item = NodeId> + '_ {})}-impl Coalescing {- // NB: A compile whose graph has more nodes, or more deaths of values, fails.- const MAX_NODES: usize = 1 << 24;- const MAX_DEATHS: usize = 1 << 26;-- pub fn new() -> Self {- fn by_node<T: Copy>() -> Column<T> {- Column::new(Coalescing::MAX_NODES, c"JIT spill slot classes")- }- Self {- classes: by_node(),- next: by_node(),- sizes: by_node(),- definitions: by_node(),- deaths: Lists::new(Self::MAX_NODES, Self::MAX_DEATHS, c"JIT spill slot classes"),- }- }-- /// Drops the tables and gives their memory back to the system.- pub fn release_memory(&mut self) {- release(&mut self.classes);- release(&mut self.next);- release(&mut self.sizes);- release(&mut self.definitions);- self.deaths.release_memory();- }-+impl<'w> Coalescing<'w> {/// Finds the class of each value of `graph`.- pub fn compute(&mut self, graph: &Graph, liveness: &ValueLiveness, work: &Zone) -> Result<(), ColumnFull> {+ pub fn compute(graph: &Graph, liveness: &ValueLiveness, work: &'w Zone) -> Self {let count = graph.nodes.len();- self.classes.clear();- for value in 0..count as u32 {- self.classes.try_push(value)?;- }+ let mut coalescing = Self {+ classes: ZoneVec::from_iter_in(0..count as u32, work),+ next: ZoneVec::new_in(work),+ sizes: ZoneVec::new_in(work),+ definitions: ZoneVec::new_in(work),+ deaths: Lists::new_in(work),+ };// NB: Without phis, each value is a class of its own.if graph.blocks.iter().all(|block| block.phis.is_empty()) {- return Ok(());+ return coalescing;}- reset(- &mut self.definitions,+ coalescing.join_classes(graph, liveness, work);+ coalescing+ }++ /// Puts phis and their inputs in one class where they do not overlap.+ fn join_classes(&mut self, graph: &Graph, liveness: &ValueLiveness, work: &Zone) {+ let count = graph.nodes.len();+ self.definitions.resize(count,Definition {block: 0,position: None,},- )?;- self.deaths.begin_counts(count)?;+ );+ self.deaths.begin_counts(count);for (index, block) in graph.blocks.iter().enumerate() {for phi in &block.phis {self.definitions[phi.index()] = Definition {@@ -179,7 +159,7 @@ impl Coalescing {}}}- self.deaths.end_counts((0, 0))?;+ self.deaths.end_counts((0, 0));for (index, block) in graph.blocks.iter().enumerate() {for node in block.body.iter().chain(&block.control) {let position = liveness.positions[node.index()];@@ -189,9 +169,8 @@ impl Coalescing {}}self.deaths.end_fill();- self.next.clear();- self.next.try_extend_from_slice(&self.classes)?;- reset(&mut self.sizes, count, 1)?;+ self.next.extend_from_slice(&self.classes);+ self.sizes.resize(count, 1);let Self {classes,@@ -237,6 +216,5 @@ impl Coalescing {}}}- Ok(())}}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rsindex fca41c975bc..7492706963c 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs@@ -10,10 +10,12 @@//! used by a frame state is live at the node carrying it; for calls, frame//! state uses happen after the call returns.-use ak::Column;-use ak::ColumnFull;use ak::Zone;+use ak::ZoneVec;+use super::Size;+use super::check_items;+use crate::CompileFailure;use crate::codegen::lowering_info::Clobbers as LoweringClobbers;use crate::codegen::lowering_info::lowering_info;use crate::ir::BlockId;@@ -23,9 +25,6 @@ use crate::ir::NodeId;use crate::ir::Op;use crate::tables::Lists;use crate::tables::Run;-use crate::tables::pop;-use crate::tables::release;-use crate::tables::reset;/// A value that nobody uses.const DEAD_OUTPUT: u8 = 1 << 0;@@ -35,58 +34,58 @@ const NEEDS_SPILL: u8 = 1 << 1;/// In place of the frame state uses of a frame state: they are not listed yet.const NOT_LISTED: Run = Run::NOT_WRITTEN;-/// The liveness of the values of a graph, in tables that serve one compile after the other.+/// The liveness of the values of a graph, in tables in the work zone of a compile.////// No table here is a set that grows. A graph in SSA form makes that possible: a value is live into exactly the blocks/// that a walk up from its uses passes before it reaches the block of its definition, so one walk for each value/// gives all the blocks at one time. The values are walked in the order of their indices, so the list of the values/// that are live into a block is sorted as it is written.-pub(super) struct ValueLiveness {+pub(super) struct ValueLiveness<'w> {/// The values live into each block and out of each block, sorted.- pub live_in: Lists<NodeId>,- live_out: Lists<NodeId>,+ pub live_in: Lists<'w, NodeId>,+ live_out: Lists<'w, NodeId>,/// For each node, the values whose last use (on this path) it is, as a part of `dying`.- deaths: Column<Run>,- dying: Column<NodeId>,+ deaths: ZoneVec<'w, Run>,+ dying: ZoneVec<'w, NodeId>,/// For each value, `DEAD_OUTPUT` and `NEEDS_SPILL`.- flags: Column<u8>,+ flags: ZoneVec<'w, u8>,/// The position of each node in linear order.- pub positions: Column<u32>,+ pub positions: ZoneVec<'w, u32>,/// For each value, the positions of the nodes that use it as an input, in order, as a part of `uses`. A phi input/// is used at the control node of its predecessor, where the moves into the phis are.- use_runs: Column<Run>,- uses: Column<u32>,+ use_runs: ZoneVec<'w, Run>,+ uses: ZoneVec<'w, u32>,/// The blocks each block continues at.- pub successors: Lists<BlockId>,+ pub successors: Lists<'w, BlockId>,- // NB: Only compute() reads what is below.+ // NB: Only fill() reads what is below./// The block of each node.- blocks: Column<u32>,+ blocks: ZoneVec<'w, u32>,/// The uses of values as inputs, as the value in the high half and the position in the low half.- use_pairs: Column<u64>,+ use_pairs: ZoneVec<'w, u64>,/// Where the walks up start: the value in the high half, then the block, then whether the value is only known to/// flow out of the block (to a phi) in the lowest bit.- seeds: Column<u64>,+ seeds: ZoneVec<'w, u64>,/// For each block, the value (plus one) that was last found live into it and out of it.- in_marks: Column<u32>,- out_marks: Column<u32>,+ in_marks: ZoneVec<'w, u32>,+ out_marks: ZoneVec<'w, u32>,/// The blocks a walk up has still to pass.- pending: Column<u32>,+ pending: ZoneVec<'w, u32>,/// What the walks found: the block in the high half and the value in the low half, in the order of the values.- in_pairs: Column<u64>,- out_pairs: Column<u64>,+ in_pairs: ZoneVec<'w, u64>,+ out_pairs: ZoneVec<'w, u64>,/// For each frame state, the allocated values that a node uses through it, as a part of `frame_uses`.- frame_runs: Column<Run>,- frame_uses: Column<NodeId>,+ frame_runs: ZoneVec<'w, Run>,+ frame_uses: ZoneVec<'w, NodeId>,/// For each value, the block (plus one) whose backwards walk has it live at the place it is at.- live: Column<u32>,+ live: ZoneVec<'w, u32>,/// The values that were live at some place of the block that is walked.- touched: Column<NodeId>,+ touched: ZoneVec<'w, NodeId>,/// The values the node that is walked uses.- used: Column<NodeId>,+ used: ZoneVec<'w, NodeId>,/// For each value, the node (plus one) that was last noted as its death.- last_death: Column<u32>,- live_since: Column<Option<(BlockId, Clobbers)>>,+ last_death: ZoneVec<'w, u32>,+ live_since: ZoneVec<'w, Option<(BlockId, Clobbers)>>,}/// Whether a node is a value the register allocator tracks.@@ -160,78 +159,40 @@ fn low(pair: u64) -> u32 {pair as u32}-impl ValueLiveness {- // NB: A compile whose graph has more nodes or blocks, or more of what the columns hold, fails.- const MAX_NODES: usize = 1 << 24;- const MAX_BLOCKS: usize = 1 << 24;- const MAX_ITEMS: usize = 1 << 26;-- /// A table for the values live into each block, with no values.- pub fn new_live_in() -> Lists<NodeId> {- Lists::new(Self::MAX_BLOCKS, Self::MAX_ITEMS, c"JIT live values")- }-- pub fn new() -> Self {- fn by_node<T: Copy>() -> Column<T> {- Column::new(ValueLiveness::MAX_NODES, c"JIT liveness of nodes")- }- fn by_block<T: Copy>() -> Column<T> {- Column::new(ValueLiveness::MAX_BLOCKS, c"JIT liveness of blocks")- }- Self {- live_in: Self::new_live_in(),- live_out: Self::new_live_in(),- deaths: by_node(),- dying: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),- flags: by_node(),- positions: by_node(),- use_runs: by_node(),- uses: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),- successors: Lists::new(Self::MAX_BLOCKS, Self::MAX_ITEMS, c"JIT block successors"),- blocks: by_node(),- use_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- seeds: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- in_marks: by_block(),- out_marks: by_block(),- pending: by_block(),- in_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- out_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- frame_runs: Column::new(Self::MAX_NODES, c"JIT liveness lists"),- frame_uses: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),- live: by_node(),- touched: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- used: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),- last_death: by_node(),- live_since: by_node(),- }- }-- /// Drops the tables and gives their memory back to the system.- pub fn release_memory(&mut self) {- self.live_in.release_memory();- self.live_out.release_memory();- release(&mut self.deaths);- release(&mut self.dying);- release(&mut self.flags);- release(&mut self.positions);- release(&mut self.use_runs);- release(&mut self.uses);- self.successors.release_memory();- release(&mut self.blocks);- release(&mut self.use_pairs);- release(&mut self.seeds);- release(&mut self.in_marks);- release(&mut self.out_marks);- release(&mut self.pending);- release(&mut self.in_pairs);- release(&mut self.out_pairs);- release(&mut self.frame_runs);- release(&mut self.frame_uses);- release(&mut self.live);- release(&mut self.touched);- release(&mut self.used);- release(&mut self.last_death);- release(&mut self.live_since);+impl<'w> ValueLiveness<'w> {+ /// The liveness of the values of `graph`, which has `size`. A compile fails if the lists of the liveness grow+ /// past their limit (see `check_items()`).+ pub fn compute(graph: &Graph, size: &Size, work: &'w Zone) -> Result<Self, CompileFailure> {+ let mut liveness = Self {+ live_in: Lists::new_in(work),+ live_out: Lists::new_in(work),+ deaths: ZoneVec::from_elem_in(Run::default(), size.nodes, work),+ // NB: Most values die once for each use.+ dying: ZoneVec::with_capacity_in(size.inputs, work),+ flags: ZoneVec::from_elem_in(0, size.nodes, work),+ positions: ZoneVec::from_elem_in(0, size.nodes, work),+ use_runs: ZoneVec::from_elem_in(Run::default(), size.nodes, work),+ uses: ZoneVec::with_capacity_in(size.inputs, work),+ successors: Lists::with_capacity_in(size.blocks, size.edges, work),+ blocks: ZoneVec::from_elem_in(0, size.nodes, work),+ use_pairs: ZoneVec::with_capacity_in(size.inputs, work),+ seeds: ZoneVec::with_capacity_in(size.inputs, work),+ in_marks: ZoneVec::from_elem_in(0, size.blocks, work),+ out_marks: ZoneVec::from_elem_in(0, size.blocks, work),+ // NB: A walk up passes each block one time.+ pending: ZoneVec::with_capacity_in(size.blocks, work),+ in_pairs: ZoneVec::new_in(work),+ out_pairs: ZoneVec::new_in(work),+ frame_runs: ZoneVec::from_elem_in(NOT_LISTED, size.frame_states, work),+ frame_uses: ZoneVec::new_in(work),+ live: ZoneVec::from_elem_in(0, size.nodes, work),+ touched: ZoneVec::new_in(work),+ used: ZoneVec::new_in(work),+ last_death: ZoneVec::from_elem_in(0, size.nodes, work),+ live_since: ZoneVec::from_elem_in(None, size.nodes, work),+ };+ liveness.fill(graph, work)?;+ Ok(liveness)}pub fn is_live_in(&self, block: BlockId, value: NodeId) -> bool {@@ -264,40 +225,41 @@ 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, work: &Zone) -> Result<(), ColumnFull> {+ fn list_frame_uses(&mut self, graph: &Graph, frame: FrameStateId, work: &Zone) -> Result<(), CompileFailure> {if self.frame_runs[frame.index()] != NOT_LISTED {return Ok(());}let start = self.frame_uses.len();for (_, value) in graph.frame_state_values(frame, work) {if is_allocated_value(graph, value) {- self.frame_uses.try_push(value)?;+ self.frame_uses.push(value);}}self.frame_runs[frame.index()] = Run::new(start, self.frame_uses.len());- Ok(())+ // NB: How many values the frame states of a graph have in all is known only when they are listed.+ check_items(self.frame_uses.len())}/// Notes that `value` is used in `block`, at a node or (`flows_out`) by a phi of a block that `block` continues- /// at.- fn add_seed(&mut self, value: NodeId, block: usize, flows_out: bool) -> Result<(), ColumnFull> {+ /// at. Fails the compile if the seeds would be past their limit (see `check_items()`).+ fn add_seed(&mut self, value: NodeId, block: usize, flows_out: bool) -> Result<(), CompileFailure> {// NB: A use in the block of the definition makes the value live into no block.if !flows_out && self.blocks[value.index()] as usize == block {return Ok(());}+ // NB: The frame states of the nodes give a block seeds that its inputs do not tell, so the seeds of one+ // block alone can be past the limit.+ check_items(self.seeds.len() + 1)?;self.seeds- .try_push(pair(value.0, (block as u32) << 1 | u32::from(flows_out)))+ .push(pair(value.0, (block as u32) << 1 | u32::from(flows_out)));+ Ok(())}- pub fn compute(&mut self, graph: &Graph, work: &Zone) -> Result<(), ColumnFull> {- let value_count = graph.nodes.len();+ /// Fills the tables, which `compute()` made for `graph`.+ fn fill(&mut self, graph: &Graph, work: &Zone) -> Result<(), CompileFailure> {let block_count = graph.blocks.len();- reset(&mut self.positions, value_count, 0)?;- reset(&mut self.blocks, value_count, 0)?;- reset(&mut self.frame_runs, graph.frame_states.len(), NOT_LISTED)?;- self.frame_uses.clear();- self.successors.begin()?;+ self.successors.begin();let mut position = 0;for (index, block) in graph.blocks.iter().enumerate() {for node in block.nodes() {@@ -305,29 +267,21 @@ impl ValueLiveness {self.blocks[node.index()] = index as u32;position += 1;}- let mut result = Ok(());graph.control(BlockId::from_index(index)).op- .for_each_successor(|successor| {- if result.is_ok() {- result = self.successors.try_push(successor);- }- });- result?;- self.successors.end_list()?;+ .for_each_successor(|successor| self.successors.push(successor));+ self.successors.end_list();}// The uses of each value: where it is an input, and the blocks it is used in that are not its own.- self.use_pairs.clear();- self.seeds.clear();for (index, block) in graph.blocks.iter().enumerate() {for node_id in block.body.iter().chain(&block.control) {let node = graph.node(*node_id);let position = self.positions[node_id.index()];for input in &node.inputs {if is_allocated_value(graph, *input) {- self.use_pairs.try_push(pair(input.0, position))?;+ self.use_pairs.push(pair(input.0, position));self.add_seed(*input, index, false)?;}}@@ -344,32 +298,26 @@ impl ValueLiveness {let successor = self.successors.get(index)[successor_index];for (_, input) in phi_inputs_from(graph, block_id, successor) {if is_allocated_value(graph, input) {- self.use_pairs.try_push(pair(input.0, end))?;+ self.use_pairs.push(pair(input.0, end));self.add_seed(input, index, true)?;}}}}- reset(&mut self.use_runs, value_count, Run::default())?;- self.uses.clear();self.use_pairs.sort_unstable();let mut index = 0;while index < self.use_pairs.len() {let value = high(self.use_pairs[index]);let start = index;while index < self.use_pairs.len() && high(self.use_pairs[index]) == value {- self.uses.try_push(low(self.use_pairs[index]))?;+ self.uses.push(low(self.use_pairs[index]));index += 1;}self.use_runs[value as usize] = Run::new(start, index);}// Walk up from the uses of each value, as far as the block of its definition.- reset(&mut self.in_marks, block_count, 0)?;- reset(&mut self.out_marks, block_count, 0)?;- self.in_pairs.clear();- self.out_pairs.clear();self.seeds.sort_unstable();let mut index = 0;while index < self.seeds.len() {@@ -384,7 +332,7 @@ impl ValueLiveness {if flows_out {if self.out_marks[block as usize] != mark {self.out_marks[block as usize] = mark;- self.out_pairs.try_push(pair(block, value))?;+ self.out_pairs.push(pair(block, value));}if block == definition {continue;@@ -392,47 +340,43 @@ impl ValueLiveness {}if self.in_marks[block as usize] != mark {self.in_marks[block as usize] = mark;- self.in_pairs.try_push(pair(block, value))?;- self.pending.try_push(block)?;+ self.in_pairs.push(pair(block, value));+ self.pending.push(block);}}- while let Some(block) = pop(&mut self.pending) {+ while let Some(block) = self.pending.pop() {for predecessor in &graph.blocks[block as usize].predecessors {let predecessor = predecessor.0;if self.out_marks[predecessor as usize] != mark {self.out_marks[predecessor as usize] = mark;- self.out_pairs.try_push(pair(predecessor, value))?;+ self.out_pairs.push(pair(predecessor, value));}if predecessor != definition && self.in_marks[predecessor as usize] != mark {self.in_marks[predecessor as usize] = mark;- self.in_pairs.try_push(pair(predecessor, value))?;- self.pending.try_push(predecessor)?;+ self.in_pairs.push(pair(predecessor, value));+ self.pending.push(predecessor);}}}+ // NB: How many blocks a value is live into is known only when its walk is done.+ check_items(self.in_pairs.len())?;+ check_items(self.out_pairs.len())?;}// NB: The pairs are in the order of the values, so the list of each block comes out sorted.- fn lists_of_blocks(lists: &mut Lists<NodeId>, pairs: &[u64], block_count: usize) -> Result<(), ColumnFull> {- lists.begin_counts(block_count)?;+ fn lists_of_blocks(lists: &mut Lists<NodeId>, pairs: &[u64], block_count: usize) {+ lists.begin_counts(block_count);for pair in pairs {lists.count(high(*pair) as usize);}- lists.end_counts(NodeId(0))?;+ lists.end_counts(NodeId(0));for pair in pairs {lists.fill(high(*pair) as usize, NodeId(low(*pair)));}lists.end_fill();- Ok(())}- lists_of_blocks(&mut self.live_in, &self.in_pairs, block_count)?;- lists_of_blocks(&mut self.live_out, &self.out_pairs, block_count)?;-- reset(&mut self.deaths, value_count, Run::default())?;- self.dying.clear();- reset(&mut self.flags, value_count, 0)?;- reset(&mut self.last_death, value_count, 0)?;- reset(&mut self.live_since, value_count, None)?;- reset(&mut self.live, value_count, 0)?;+ lists_of_blocks(&mut self.live_in, &self.in_pairs, block_count);+ lists_of_blocks(&mut self.live_out, &self.out_pairs, block_count);+// OPTIMIZATION: Rather than marking every value live across each call or float clobbering slow path there,// which takes time quadratic in the size of code that keeps many values live past many of them// (like a large array literal of arrays), the walk counts those nodes, notes the counts where@@ -457,21 +401,21 @@ impl ValueLiveness {self.touched.clear();for value in self.live_out.get(index) {self.live[value.index()] = mark;- self.touched.try_push(*value)?;+ self.touched.push(*value);}for node_id in block.body.iter().chain(&block.control).rev() {let node = graph.node(*node_id);self.used.clear();for input in &node.inputs {if is_allocated_value(graph, *input) {- self.used.try_push(*input)?;+ self.used.push(*input);}}let frame_uses = match node.frame_state {Some(frame) => self.frame_runs[frame.index()].range(),None => 0..0,};- self.used.try_extend_from_slice(&self.frame_uses[frame_uses.clone()])?;+ self.used.extend_from_slice(&self.frame_uses[frame_uses.clone()]);if self.live[node_id.index()] == mark {check_spill(@@ -500,20 +444,20 @@ impl ValueLiveness {}}let deaths = self.dying.len();- for value in self.used.iter() {+ for value in &self.used {if self.live[value.index()] != mark && self.last_death[value.index()] != node_id.0 + 1 {self.last_death[value.index()] = node_id.0 + 1;- self.dying.try_push(*value)?;+ self.dying.push(*value);self.live_since[value.index()] = Some((block_id, clobbers));}}self.deaths[node_id.index()] = Run::new(deaths, self.dying.len());self.live[node_id.index()] = 0;- for value in self.used.iter() {+ for value in &self.used {if self.live[value.index()] != mark {self.live[value.index()] = mark;- self.touched.try_push(*value)?;+ self.touched.push(*value);}}}@@ -521,7 +465,7 @@ impl ValueLiveness {self.live[phi.index()] = 0;}// NB: `touched` may have a value more than one time, which does no harm here.- for value in self.touched.iter() {+ for value in &self.touched {if self.live[value.index()] == mark {check_spill(&mut self.flags,@@ -554,6 +498,8 @@ impl ValueLiveness {self.flags[value.index()] |= NEEDS_SPILL;}}+ // NB: The frame states of the nodes give a block deaths that its inputs do not tell.+ check_items(self.dying.len())?;}Ok(())}@@ -591,8 +537,8 @@ mod tests {let constant = graph.add(Op::Constant(0), &[], Some(Repr::Tagged), 0);let returned = graph.add(Op::Return, &[constant], None, 0);graph.blocks[0].control = Some(returned);- let mut liveness = ValueLiveness::new();- liveness.compute(&graph, crate::test_zone()).unwrap();+ let size = Size::of(&graph).unwrap();+ let liveness = ValueLiveness::compute(&graph, &size, 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));@@ -628,10 +574,10 @@ mod tests {});graph.add_block(block);}- let mut liveness = ValueLiveness::new();- // NB: The second time, the tables hold what the first time left in them.+ let size = Size::of(&graph).unwrap();+ // NB: The second time, the zone holds what the first time left in it.for _ in 0..2 {- liveness.compute(&graph, crate::test_zone()).unwrap();+ let liveness = ValueLiveness::compute(&graph, &size, 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/loops.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rsindex 1c8f58dad33..f51fd5c65e8 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs@@ -11,18 +11,17 @@//! 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 ak::Zone;+use ak::ZoneVec;+use super::check_items;use super::liveness::ValueLiveness;+use crate::CompileFailure;use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::passes::dominators::Dominators;use crate::tables::Lists;-use crate::tables::pop;-use crate::tables::release;-use crate::tables::reset;#[derive(Clone, Copy)]pub(super) struct Loop {@@ -39,78 +38,46 @@ pub(super) struct Loop {/// 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: Column<Loop>,+/// The loops of a graph, in tables in the work zone of a compile.+pub(super) struct Loops<'w> {+ loops: ZoneVec<'w, 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>,+ blocks: ZoneVec<'w, u64>,words_for_each_loop: usize,/// The innermost loop around each block, as an index into `loops`, or `NO_LOOP`.- innermost: Column<u32>,+ innermost: ZoneVec<'w, u32>,/// The block of each position.- position_blocks: Column<u32>,+ position_blocks: ZoneVec<'w, u32>,/// For each loop, the values live into the header that no node of the loop uses, sorted.- carried_through: Lists<NodeId>,+ carried_through: Lists<'w, NodeId>,/// The blocks that the back edges of a loop come from.- back_edge_sources: Column<BlockId>,+ back_edge_sources: ZoneVec<'w, BlockId>,/// The blocks that the walk over a loop still has to visit.- pending: Column<BlockId>,+ pending: ZoneVec<'w, BlockId>,/// The loops, from the one with the most blocks to the one with the fewest.- by_size: Column<u32>,+ by_size: ZoneVec<'w, u32>,}-impl Loops {- // 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> {+impl<'w> Loops<'w> {+ /// Finds the loops of `graph`.+ pub fn compute(graph: &Graph, liveness: &ValueLiveness, work: &'w Zone) -> Result<Self, CompileFailure> {let block_count = graph.blocks.len();- self.position_blocks.clear();+ let mut loops = Self {+ loops: ZoneVec::new_in(work),+ blocks: ZoneVec::new_in(work),+ words_for_each_loop: block_count.div_ceil(64),+ innermost: ZoneVec::from_elem_in(NO_LOOP, block_count, work),+ position_blocks: ZoneVec::with_capacity_in(graph.nodes.len(), work),+ carried_through: Lists::new_in(work),+ back_edge_sources: ZoneVec::new_in(work),+ pending: ZoneVec::new_in(work),+ by_size: ZoneVec::new_in(work),+ };for (index, block) in graph.blocks.iter().enumerate() {- let end = self.position_blocks.len() + block.nodes().count();- self.position_blocks.try_resize(end, index as u32)?;+ let end = loops.position_blocks.len() + block.nodes().count();+ loops.position_blocks.resize(end, index as u32);}- 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;@@ -121,18 +88,55 @@ impl Loops {.any(|predecessor| predecessor.index() >= index && is_hot(*predecessor))});if !has_back_edges {- return Ok(());+ return Ok(loops);}+ let dominators = Dominators::of(graph, work);+ loops.find(graph, liveness, &dominators, work)?;+ Ok(loops)+ }- dominators.compute(graph)?;+ /// Finds the loops of `graph`, which has back edges.+ fn find(+ &mut self,+ graph: &Graph,+ liveness: &ValueLiveness,+ dominators: &Dominators,+ work: &'w Zone,+ ) -> Result<(), CompileFailure> {+ let block_count = graph.blocks.len();+ let is_hot = |block: BlockId| !graph.blocks[block.index()].is_cold;+ // The sources of the back edges of the loop that a block heads, if it heads one: its predecessors that it+ // dominates.+ let is_back_edge =+ |header: BlockId, predecessor: BlockId| dominators.dominates(header, predecessor) && is_hot(predecessor);+ let mut loop_count = 0;+ let mut header_live_values = 0;+ let mut edges = 0;+ for (index, block) in graph.blocks.iter().enumerate() {+ let header = BlockId::from_index(index);+ edges += block.predecessors.len();+ if block+ .predecessors+ .iter()+ .any(|predecessor| is_back_edge(header, *predecessor))+ {+ loop_count += 1;+ header_live_values += liveness.live_in.get(index).len();+ }+ }+ check_items(loop_count * self.words_for_each_loop)?;+ self.loops = ZoneVec::with_capacity_in(loop_count, work);+ self.blocks = ZoneVec::with_capacity_in(loop_count * self.words_for_each_loop, work);+ self.carried_through = Lists::with_capacity_in(loop_count, header_live_values, work);+ self.carried_through.begin();+ self.pending = ZoneVec::with_capacity_in(edges, work);+ self.by_size = ZoneVec::with_capacity_in(loop_count, work);for index in 0..block_count {let header = BlockId::from_index(index);- // 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 is_back_edge(header, *predecessor) {+ self.back_edge_sources.push(*predecessor);}}if self.back_edge_sources.is_empty() {@@ -141,18 +145,18 @@ impl Loops {// 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)?;+ self.blocks.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) {+ self.pending.extend_from_slice(&self.back_edge_sources);+ while let Some(block) = self.pending.pop() {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)?;+ self.pending.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"));@@ -186,23 +190,22 @@ impl Loops {.first_use_in(blocks, uses, &self.position_blocks, 0..uses.len()).is_none(){- self.carried_through.try_push(*value)?;+ self.carried_through.push(*value);}}- self.carried_through.end_list()?;- self.loops.try_push(loop_)?;+ self.carried_through.end_list();+ self.loops.push(loop_);}// NB: A loop inside another one has fewer blocks, so the smallest loop around a block is the innermost one.// 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.by_size.push(index);}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() {+ for index in &self.by_size {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() {diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rsindex 0bb4bd385b1..468095be711 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs@@ -70,14 +70,10 @@ 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;-use crate::tables::reset;-use ak::Column;-use ak::ColumnFull;use ak::Zone;+use ak::ZoneVec;use coalescing::Coalescing;use liveness::ValueLiveness;use liveness::is_allocated_value;@@ -294,61 +290,102 @@ struct NodeRow {temp_count: u8,}-/// Where the allocator placed the values of a graph, in tables that serve one compile after the other.-pub struct Allocation {+/// How large a graph is, in what the tables of the allocator have rows and elements for.+struct Size {+ nodes: usize,+ blocks: usize,+ frame_states: usize,+ /// The inputs of all the nodes.+ inputs: usize,+ /// The edges from the blocks to the blocks they continue at.+ edges: usize,+}++impl Size {+ /// The size of `graph`. A compile whose graph is larger than the allocator takes fails.+ fn of(graph: &Graph) -> Result<Self, CompileFailure> {+ let mut edges = 0;+ for index in 0..graph.blocks.len() {+ graph+ .control(BlockId::from_index(index))+ .op+ .for_each_successor(|_| edges += 1);+ }+ let size = Self {+ nodes: graph.nodes.len(),+ blocks: graph.blocks.len(),+ frame_states: graph.frame_states.len(),+ inputs: graph.nodes.iter().map(|node| node.inputs.len()).sum(),+ edges,+ };+ if size.nodes > Allocation::MAX_NODES+ || size.blocks > Allocation::MAX_BLOCKS+ || size.frame_states > Allocation::MAX_NODES+ || size.inputs > Allocation::MAX_ITEMS+ || size.edges > Allocation::MAX_ITEMS+ {+ return Err(CompileFailure::TooLarge);+ }+ Ok(size)+ }+}++/// Fails the compile if a list of the allocator that grows while it runs, to a length that the size of the graph+/// does not tell, has more than `Allocation::MAX_ITEMS` elements.+fn check_items(len: usize) -> Result<(), CompileFailure> {+ if len > Allocation::MAX_ITEMS {+ return Err(CompileFailure::TooLarge);+ }+ Ok(())+}++/// Where the allocator placed the values of a graph, in tables in the work zone of a compile.+pub struct Allocation<'w> {/// Indexed by `NodeId`.- nodes: Column<NodeRow>,+ nodes: ZoneVec<'w, NodeRow>,/// The moves before the nodes and at the ends of the blocks.- moves: Column<Move>,+ moves: ZoneVec<'w, Move>,/// The locations of the inputs of the nodes.- locations: Column<Location>,- exit_values: Column<(u32, Location)>,+ locations: ZoneVec<'w, Location>,+ exit_values: ZoneVec<'w, (u32, Location)>,/// The moves at the end of each block, as a part of `moves`.- block_end_moves: Column<Run>,+ block_end_moves: ZoneVec<'w, Run>,pub spill_slot_count: u32,/// The values live into each block, sorted.- live_in: Lists<NodeId>,+ live_in: Lists<'w, NodeId>,}-impl Allocation {- // NB: A compile whose graph needs more of these fails.+impl<'w> Allocation<'w> {+ // NB: A compile whose graph has more of these fails (see `Size::of()` and `check_items()`).const MAX_NODES: usize = 1 << 24;+ const MAX_BLOCKS: usize = 1 << 24;const MAX_ITEMS: usize = 1 << 26;- pub fn new() -> Self {+ /// An allocation of no node, which takes no memory before it has some.+ pub fn new_in(work: &'w Zone) -> Self {Self {- nodes: Column::new(Self::MAX_NODES, c"JIT allocation of nodes"),- moves: Column::new(Self::MAX_ITEMS, c"JIT allocation moves"),- locations: Column::new(Self::MAX_ITEMS, c"JIT allocation locations"),- exit_values: Column::new(Self::MAX_ITEMS, c"JIT allocation exit values"),- block_end_moves: Column::new(Self::MAX_NODES, c"JIT allocation of blocks"),+ nodes: ZoneVec::new_in(work),+ moves: ZoneVec::new_in(work),+ locations: ZoneVec::new_in(work),+ exit_values: ZoneVec::new_in(work),+ block_end_moves: ZoneVec::new_in(work),spill_slot_count: 0,- live_in: ValueLiveness::new_live_in(),+ live_in: Lists::new_in(work),}}- /// Drops the tables and gives their memory back to the system.- fn release_memory(&mut self) {- release(&mut self.nodes);- release(&mut self.moves);- release(&mut self.locations);- release(&mut self.exit_values);- release(&mut self.block_end_moves);- self.live_in.release_memory();- }-- /// Starts the allocation of a graph with `node_count` nodes and `block_count` blocks, in tables that hold- /// nothing.- fn begin(&mut self, node_count: usize, block_count: usize) -> Result<(), ColumnFull> {- self.nodes.clear();- self.nodes.try_resize(node_count, NodeRow::default())?;- self.moves.clear();- self.locations.clear();- self.exit_values.clear();- self.block_end_moves.clear();- self.block_end_moves.try_resize(block_count, Run::default())?;- self.spill_slot_count = 0;- Ok(())+ /// Tables for the allocation of a graph of `size`.+ fn for_graph(size: &Size, work: &'w Zone) -> Self {+ Self {+ nodes: ZoneVec::from_elem_in(NodeRow::default(), size.nodes, work),+ // NB: Most nodes need fewer moves than they have inputs.+ moves: ZoneVec::with_capacity_in(size.inputs, work),+ locations: ZoneVec::with_capacity_in(size.inputs, work),+ exit_values: ZoneVec::new_in(work),+ block_end_moves: ZoneVec::from_elem_in(Run::default(), size.blocks, work),+ spill_slot_count: 0,+ live_in: Lists::new_in(work),+ }}/// How many nodes have an allocation.@@ -381,15 +418,9 @@ impl Allocation {}}-impl Default for Allocation {- fn default() -> Self {- Self::new()- }-}-// NB: The tests of the verifier make wrong allocations with these.#[cfg(test)]-impl Allocation {+impl Allocation<'_> {/// All the moves of the allocation.pub(crate) fn moves(&self) -> &[Move] {&self.moves@@ -421,64 +452,6 @@ impl Allocation {}}-/// What the register allocator works with and its result, in tables that serve one compile after the other. The-/// allocator makes no block of the heap: all its data is here.-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.- end_contents: Column<Option<NodeId>>,- /// Whether each block is finished.- finished: Column<bool>,- /// The slot of each spill slot class that has one.- class_slots: Column<Option<u32>>,- /// Moves that happen in parallel, before they are put in an order.- parallel_moves: Column<Move>,-}--impl Regalloc {- /// Tables that take no memory before a compile uses them.- pub fn new() -> Self {- Self {- 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,- c"JIT allocator register contents",- ),- finished: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),- class_slots: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),- parallel_moves: Column::new(Allocation::MAX_ITEMS, c"JIT allocator work"),- }- }-- /// Drops the tables and gives their memory back to the system.- pub fn release_memory(&mut self) {- 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);- release(&mut self.class_slots);- release(&mut self.parallel_moves);- }-}--impl Default for Regalloc {- fn default() -> Self {- Self::new()- }-}-/// The value each register holds.type Contents = [Option<NodeId>; REGISTER_COUNT];@@ -494,81 +467,63 @@ 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()`). `dominators` are tables to compute the dominators of the graph-/// in.-pub fn allocate(- graph: &Graph,- registers: &RegisterSet,- regalloc: &mut Regalloc,- dominators: &mut Dominators,- work: &Zone,-) -> Result<(), CompileFailure> {+/// Assigns locations to the values of `graph`, in tables in `work`. The verifier checks the result where the IR is+/// verified (see `verify()`).+pub fn allocate<'w>(graph: &Graph, registers: &RegisterSet, work: &'w Zone) -> Result<Allocation<'w>, 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,- class_slots,- parallel_moves,- } = regalloc;- 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)?;- reset(end_contents, graph.blocks.len() * REGISTER_COUNT, None)?;- reset(finished, graph.blocks.len(), false)?;- reset(class_slots, graph.nodes.len(), None)?;+ let size = Size::of(graph)?;+ let liveness = ValueLiveness::compute(graph, &size, work)?;+ let coalescing = Coalescing::compute(graph, &liveness, work);+ let loops = Loops::compute(graph, &liveness, work)?;let allocator = Allocator {graph,registers,- liveness,- allocation,+ liveness: &liveness,+ allocation: Allocation::for_graph(&size, work),contents: [None; REGISTER_COUNT],- value_registers,- end_contents,- finished,+ value_registers: ZoneVec::from_elem_in(None, size.nodes, work),+ end_contents: ZoneVec::from_elem_in(None, size.blocks * REGISTER_COUNT, work),+ finished: ZoneVec::from_elem_in(false, size.blocks, work),position: 0,slot_classes: &coalescing.classes,- class_slots,- parallel_moves,- loops,+ class_slots: ZoneVec::from_elem_in(None, size.nodes, work),+ parallel_moves: ZoneVec::new_in(work),+ loops: &loops,work,};- allocator.run()?;+ let mut allocation = allocator.run()?;// NB: The code generator reads which values are live into a block.- core::mem::swap(&mut allocation.live_in, &mut liveness.live_in);- Ok(())+ allocation.live_in = liveness.live_in;+ Ok(allocation)}-struct Allocator<'a> {+struct Allocator<'a, 'w> {graph: &'a Graph<'a>,registers: &'a RegisterSet,- liveness: &'a ValueLiveness,- allocation: &'a mut Allocation,+ liveness: &'a ValueLiveness<'w>,+ allocation: Allocation<'w>,contents: Contents,- value_registers: &'a mut Column<Option<u8>>,- end_contents: &'a mut Column<Option<NodeId>>,- finished: &'a mut Column<bool>,+ /// The register each value is in, if any.+ value_registers: ZoneVec<'w, Option<u8>>,+ /// The register contents at the end of each finished block: `REGISTER_COUNT` values for each block.+ end_contents: ZoneVec<'w, Option<NodeId>>,+ /// Whether each block is finished.+ finished: ZoneVec<'w, bool>,/// The position of the node being allocated.position: u32,/// The spill slot class of each value (see `coalescing`), and the/// slot of each class that has one.slot_classes: &'a [u32],- class_slots: &'a mut Column<Option<u32>>,- parallel_moves: &'a mut Column<Move>,- loops: &'a Loops,- work: &'a Zone,+ class_slots: ZoneVec<'w, Option<u32>>,+ /// Moves that happen in parallel, before they are put in an order.+ parallel_moves: ZoneVec<'w, Move>,+ loops: &'a Loops<'w>,+ work: &'w Zone,}-impl Allocator<'_> {- fn run(mut self) -> Result<(), ColumnFull> {+impl<'w> Allocator<'_, 'w> {+ fn run(mut self) -> Result<Allocation<'w>, CompileFailure> {// Give the phis of blocks without a state predecessor their locations// up front, since their predecessors may be allocated after them.// Phis of loop headers live in registers, which the header starts@@ -619,15 +574,18 @@ impl Allocator<'_> {self.start_block(block);let block_data = self.graph.block(block);for node in &block_data.body {- self.allocate_node(*node)?;+ self.allocate_node(*node);}- self.allocation.block_end_moves[block.index()] = self.phi_moves(block, &mut cycle_temp)?;- self.allocate_node(self.graph.control_id(block))?;+ self.allocation.block_end_moves[block.index()] = self.phi_moves(block, &mut cycle_temp);+ self.allocate_node(self.graph.control_id(block));let start = block.index() * REGISTER_COUNT;self.end_contents[start..start + REGISTER_COUNT].copy_from_slice(&self.contents);self.finished[block.index()] = true;+ // NB: How many moves and exit values a node gets is known only when it is allocated.+ check_items(self.allocation.moves.len())?;+ check_items(self.allocation.exit_values.len())?;}- Ok(())+ Ok(self.allocation)}/// Gives `phi` its location: `register` if it has one, and its spill@@ -863,11 +821,11 @@ impl Allocator<'_> {}/// Adds a move before the node that is being allocated.- fn add_move(&mut self, from: Location, to: Location) -> Result<(), ColumnFull> {- self.allocation.moves.try_push(Move { from, to })+ fn add_move(&mut self, from: Location, to: Location) {+ self.allocation.moves.push(Move { from, to });}- fn allocate_node(&mut self, node_id: NodeId) -> Result<(), ColumnFull> {+ fn allocate_node(&mut self, node_id: NodeId) {let node = self.graph.node(node_id);self.position = self.liveness.positions[node_id.index()];let constraints = lowering_info(node);@@ -877,7 +835,7 @@ impl Allocator<'_> {let inputs_start = self.allocation.locations.len();self.allocation.locations- .try_resize(inputs_start + node.inputs.len(), Location::Register(0))?;+ .resize(inputs_start + node.inputs.len(), Location::Register(0));let constrained_inputs = node.inputs.len().min(constraints.inputs.len());let constraint_of = |allocator: &Self, index: usize| {allocator.registers.resolve(@@ -900,7 +858,7 @@ impl Allocator<'_> {debug_assert!(!blocked.contains(register), "two inputs need the same register");self.evict(register);let from = self.current_location(input);- self.add_move(from, Location::Register(register))?;+ self.add_move(from, Location::Register(register));match from {// The value moves, unless an earlier input of this node// needs it where it is; then this is a copy for the node.@@ -936,7 +894,7 @@ impl Allocator<'_> {_ => {let register = self.pick_register(blocked, RegisterClass::of(self.graph.node(input).repr));let from = self.current_location(input);- self.add_move(from, Location::Register(register))?;+ self.add_move(from, Location::Register(register));if is_allocated_value(self.graph, input) {self.assign_register(register, input);}@@ -1018,7 +976,7 @@ impl Allocator<'_> {if let Some(frame_state) = node.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))?;+ self.allocation.exit_values.push((slot, location));}}@@ -1050,7 +1008,6 @@ impl Allocator<'_> {allocation.temp_count = constraints.temps;allocation.output = output.map(Location::Register);allocation.exit_values = exit_values;- Ok(())}/// Gives the phis of the merge `join` their locations, at the end of its@@ -1088,20 +1045,19 @@ impl Allocator<'_> {}/// Adds the moves into the phis of `successor` at the end of `block`, as moves that happen in parallel.- fn add_phi_moves(&mut self, block: BlockId, successor: BlockId) -> Result<(), ColumnFull> {+ fn add_phi_moves(&mut self, block: BlockId, successor: BlockId) {for (phi, input) in liveness::phi_inputs_from(self.graph, block, successor) {let parallel_move = Move {from: self.current_location(input),to: self.allocation.nodes[phi.index()].output.expect("phis have locations"),};- self.parallel_moves.try_push(parallel_move)?;+ self.parallel_moves.push(parallel_move);}- Ok(())}/// Adds the moves at the end of `block` that put the values live into the/// merge `join` (and its phis' inputs) where the merge expects them, as moves that happen in parallel.- fn add_merge_moves(&mut self, block: BlockId, join: BlockId) -> Result<(), ColumnFull> {+ fn add_merge_moves(&mut self, block: BlockId, join: BlockId) {let contents = self.merge_contents(join).expect("the merge has a state predecessor");let phis = &self.graph.block(join).phis;for (register, value) in contents.iter().enumerate() {@@ -1114,35 +1070,35 @@ impl Allocator<'_> {let to = Location::Register(u8::try_from(register).expect("register numbers fit in u8"));let from = self.current_location(value);if from != to {- self.parallel_moves.try_push(Move { from, to })?;+ self.parallel_moves.push(Move { from, to });}}- self.add_phi_moves(block, join)+ self.add_phi_moves(block, join);}/// The moves at the end of `block` that put the inputs of the phis of its/// successor in place, as a part of the moves of the allocation.- fn phi_moves(&mut self, block: BlockId, cycle_temp: &mut Option<u32>) -> Result<Run, ColumnFull> {+ fn phi_moves(&mut self, block: BlockId, cycle_temp: &mut Option<u32>) -> Run {let liveness = self.liveness;let successors = liveness.successors.get(block.index());let [successor] = successors else {for successor in successors {debug_assert!(self.graph.block(*successor).phis.is_empty(), "critical edge into a phi");}- return Ok(Run::default());+ return Run::default();};self.parallel_moves.clear();match state_predecessor(self.graph, *successor) {- Some(predecessor) if predecessor != block => self.add_merge_moves(block, *successor)?,+ Some(predecessor) if predecessor != block => self.add_merge_moves(block, *successor),merge => {if merge.is_some() {self.place_merge_phis(block, *successor);}- self.add_phi_moves(block, *successor)?;+ self.add_phi_moves(block, *successor);}}if self.parallel_moves.is_empty() {- return Ok(Run::default());+ return Run::default();}let temp = *cycle_temp.get_or_insert_with(|| {let slot = self.allocation.spill_slot_count;@@ -1150,8 +1106,12 @@ impl Allocator<'_> {slot});let start = self.allocation.moves.len();- resolve_parallel_moves(self.parallel_moves, Location::Stack(temp), &mut self.allocation.moves)?;- Ok(Run::new(start, self.allocation.moves.len()))+ resolve_parallel_moves(+ &mut self.parallel_moves,+ Location::Stack(temp),+ &mut self.allocation.moves,+ );+ Run::new(start, self.allocation.moves.len())}}@@ -1183,13 +1143,16 @@ pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {Location::Constant(bits) => format!("#{}", crate::ir::value::describe(*bits)),Location::Frame(slot) => format!("frame{slot}"),};- let moves_text = |moves: &[Move]| {- moves- .iter()- .map(|m| format!("{} -> {}", location_name(&m.from), location_name(&m.to)))- .collect::<Vec<_>>()- .join(", ")- };+ /// Writes the text of each item to `out`, with ", " between them.+ fn write_list<T>(out: &mut String, items: &[T], text: impl Fn(&T) -> String) {+ for (index, item) in items.iter().enumerate() {+ if index != 0 {+ out.push_str(", ");+ }+ out.push_str(&text(item));+ }+ }+ let move_name = |m: &Move| format!("{} -> {}", location_name(&m.from), location_name(&m.to));let mut out = String::new();for index in 0..graph.blocks.len() {let block = BlockId::from_index(index);@@ -1197,26 +1160,27 @@ pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {for node_id in graph.block_nodes(block) {let node = allocation.node(node_id);if Some(node_id) == graph.block(block).control && !allocation.block_end_moves(block).is_empty() {- writeln!(out, " moves {}", moves_text(allocation.block_end_moves(block))).unwrap();+ out.push_str(" moves ");+ write_list(&mut out, allocation.block_end_moves(block), move_name);+ out.push('\n');}if !node.moves_before.is_empty() {- writeln!(out, " moves {}", moves_text(node.moves_before)).unwrap();+ out.push_str(" moves ");+ write_list(&mut out, node.moves_before, move_name);+ out.push('\n');}write!(out, " v{} {}", node_id.0, graph.node(node_id).op.name()).unwrap();if !node.inputs.is_empty() {- let inputs = node.inputs.iter().map(location_name).collect::<Vec<_>>();- write!(out, " ({})", inputs.join(", ")).unwrap();+ out.push_str(" (");+ write_list(&mut out, node.inputs, location_name);+ out.push(')');}if let Some(output) = &node.output {write!(out, " -> {}", location_name(output)).unwrap();}if !node.temps.is_empty() {- let temps = node- .temps- .iter()- .map(|register| format!("r{register}"))- .collect::<Vec<_>>();- write!(out, " temps {}", temps.join(", ")).unwrap();+ out.push_str(" temps ");+ write_list(&mut out, node.temps, |register| format!("r{register}"));}if let Some(slot) = node.spill_slot&& graph.node(node_id).op != Op::Phi@@ -1224,12 +1188,11 @@ pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {write!(out, " spill s{slot}").unwrap();}if !node.exit_values.is_empty() {- let values = node- .exit_values- .iter()- .map(|(slot, location)| format!("{slot}={}", location_name(location)))- .collect::<Vec<_>>();- write!(out, " exit {{{}}}", values.join(", ")).unwrap();+ out.push_str(" exit {");+ write_list(&mut out, node.exit_values, |(slot, location)| {+ format!("{slot}={}", location_name(location))+ });+ out.push('}');}out.push('\n');}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rsindex b939d8ea01b..fe1ef2ecff6 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs@@ -6,8 +6,7 @@//! Sequentializing parallel moves.-use ak::Column;-use ak::ColumnFull;+use ak::ZoneVec;use super::Location;use super::Move;@@ -16,11 +15,7 @@ use super::Move;/// before any destination is written), into a sequence with the same effect, which it adds to `result`./// Destinations must be distinct and must not be constants. Cycles are broken/// through `temp`, which must not appear in the moves. No move is left in `pending`.-pub fn resolve_parallel_moves(- pending: &mut Column<Move>,- temp: Location,- result: &mut Column<Move>,-) -> Result<(), ColumnFull> {+pub fn resolve_parallel_moves(pending: &mut ZoneVec<'_, Move>, temp: Location, result: &mut ZoneVec<'_, Move>) {let mut kept = 0;for index in 0..pending.len() {let pending_move = pending[index];@@ -37,7 +32,7 @@ pub fn resolve_parallel_moves(.iter().position(|candidate| pending.iter().all(|other| other.from != candidate.to));if let Some(index) = ready {- result.try_push(pending[index])?;+ result.push(pending[index]);// NB: The moves that are left stay in their order.pending.copy_within(index + 1.., index);pending.truncate(pending.len() - 1);@@ -46,14 +41,13 @@ pub fn resolve_parallel_moves(// Every destination is still needed as a source, so the moves form// cycles. Save one destination's value and read it from the temp.let saved = pending[0].to;- result.try_push(Move { from: saved, to: temp })?;+ result.push(Move { from: saved, to: temp });for pending_move in pending.iter_mut() {if pending_move.from == saved {pending_move.from = temp;}}}- Ok(())}#[cfg(test)]@@ -75,10 +69,9 @@ mod tests {/// The sequence that `moves`, which happen in parallel, are put in.fn resolve(moves: &[Move], temp: Location) -> Vec<Move> {- let mut pending = Column::new(64, c"test");- let mut result = Column::new(64, c"test");- pending.try_extend_from_slice(moves).unwrap();- resolve_parallel_moves(&mut pending, temp, &mut result).unwrap();+ let mut pending = ZoneVec::from_slice_in(moves, crate::test_zone());+ let mut result = ZoneVec::new_in(crate::test_zone());+ resolve_parallel_moves(&mut pending, temp, &mut result);assert!(pending.is_empty());result.to_vec()}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 9bb851d5d6a..f85a51b680b 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -18,36 +18,12 @@ 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);--impl std::ops::Deref for Allocated {- type Target = Allocation;-- fn deref(&self) -> &Allocation {- &self.0.allocation- }-}--impl std::ops::DerefMut for Allocated {- fn deref_mut(&mut self) -> &mut Allocation {- &mut self.0.allocation- }-}+/// A register allocation, in the zone of the thread of the test.+type Allocated = Allocation<'static>;fn allocate_with(graph: &Graph, registers: &RegisterSet) -> Allocated {- let mut regalloc = Regalloc::new();- allocate(- graph,- registers,- &mut regalloc,- &mut Dominators::new(),- crate::test_zone(),- )- .unwrap();- Allocated(regalloc)+ allocate(graph, registers, crate::test_zone()).unwrap()}#[track_caller]@@ -1186,8 +1162,9 @@ fn random_structured_programs_with_cold_blocks_allocate_correctly() {panic!("seed {seed}: {errors}\n{}", crate::ir::dump(&graph, &layout));}let registers = RegisterSet::test_configuration();- let allocation = allocate_with(&graph, ®isters);- if let Err(errors) = verify(&graph, ®isters, &allocation, crate::test_zone()) {+ let work = crate::test_work();+ let allocation = allocate(&graph, ®isters, &work).unwrap();+ if let Err(errors) = verify(&graph, ®isters, &allocation, &work) {panic!("seed {seed}: {errors}\n{}\n{}",crate::ir::dump(&graph, &layout),@@ -1213,8 +1190,9 @@ fn random_structured_programs_allocate_correctly() {.collect::<Vec<_>>();let graph = build_with_layout(&program, layout, &never_ran);let registers = RegisterSet::test_configuration();- let allocation = allocate_with(&graph, ®isters);- if let Err(errors) = verify(&graph, ®isters, &allocation, crate::test_zone()) {+ let work = crate::test_work();+ let allocation = allocate(&graph, ®isters, &work).unwrap();+ if let Err(errors) = verify(&graph, ®isters, &allocation, &work) {panic!("seed {seed}: {errors}\n{}\n{}",crate::ir::dump(&graph, &layout),@@ -1251,7 +1229,6 @@ fn float64_values_get_floating_point_registers() {&mut graph,&snapshot.executables[0].layout,true,- &mut Dominators::new(),&mut crate::test_work(),&mut crate::test_steps(),)diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rsindex 2d28d5f7a56..6b3cf4e0f7b 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs@@ -17,6 +17,7 @@//! value, so the state names it by the slot rather than by a load.use ak::Zone;+use ak::ZoneVec;use super::Allocation;use super::Location;@@ -30,7 +31,7 @@ use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;-use std::collections::BTreeMap;+use crate::tables::Run;/// What a location holds.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -41,16 +42,172 @@ enum Content {UnwrittenSlot(u32),}-type State = BTreeMap<Location, Content>;+/// How many places a state has for registers, which come before the places for stack slots: one for each number a+/// register can have.+const REGISTER_PLACES: usize = 256;++/// The place of `location` in a state, if a state has one for it: registers and stack slots, in the order of+/// `Location`. Moves never write the other locations.+fn place(location: Location) -> Option<usize> {+ match location {+ Location::Register(register) => Some(usize::from(register)),+ Location::Stack(slot) => Some(REGISTER_PLACES + slot as usize),+ Location::Constant(_) | Location::Frame(_) => None,+ }+}++/// The location that has the place `place` in a state.+fn location_at(place: usize) -> Location {+ match u8::try_from(place) {+ Ok(register) => Location::Register(register),+ Err(_) => Location::Stack((place - REGISTER_PLACES) as u32),+ }+}++/// What the locations hold at one point of the program.+trait Holds {+ fn holds(&self, location: Location) -> Option<Content>;+}++/// What each location holds at the point that the walk is at, with a place for each register and stack slot.+struct State<'w> {+ contents: ZoneVec<'w, Option<Content>>,+ /// The places that were given contents since the state was last cleared, maybe more than one time.+ filled: ZoneVec<'w, u32>,+}++impl<'w> State<'w> {+ /// A state in which nothing holds anything, with places for `stack_slots` stack slots.+ fn new_in(stack_slots: usize, work: &'w Zone) -> Self {+ Self {+ contents: ZoneVec::from_elem_in(None, REGISTER_PLACES + stack_slots, work),+ filled: ZoneVec::new_in(work),+ }+ }++ fn insert(&mut self, location: Location, content: Content) {+ let Some(place) = place(location) else {+ return;+ };+ if self.contents[place].is_none() {+ self.filled.push(place as u32);+ }+ self.contents[place] = Some(content);+ }++ fn remove(&mut self, location: Location) -> Option<Content> {+ self.contents[place(location)?].take()+ }++ /// Makes the state what `stored` (see `store()`) says.+ fn load(&mut self, stored: &[(Location, Content)]) {+ for place in self.filled.drain_all() {+ self.contents[place as usize] = None;+ }+ for (location, content) in stored {+ self.insert(*location, *content);+ }+ }++ /// Writes what each location holds to `out`, in the order of the locations.+ fn store(&mut self, out: &mut ZoneVec<'_, (Location, Content)>) {+ self.filled.sort_unstable();+ self.filled.dedup();+ out.clear();+ for place in &self.filled {+ if let Some(content) = self.contents[*place as usize] {+ out.push((location_at(*place as usize), content));+ }+ }+ }+}++impl Holds for State<'_> {+ fn holds(&self, location: Location) -> Option<Content> {+ self.contents[place(location)?]+ }+}++/// What each location holds, in the order of the locations (see `State::store()`).+impl Holds for [(Location, Content)] {+ fn holds(&self, location: Location) -> Option<Content> {+ let index = self.binary_search_by_key(&location, |(location, _)| *location).ok()?;+ Some(self[index].1)+ }+}++/// A state for each block, if it has one yet, as what `State::store()` writes. The states of all the blocks are in+/// one list.+struct States<'w> {+ runs: ZoneVec<'w, Option<Run>>,+ /// How many elements the part of `items` of each block has room for.+ rooms: ZoneVec<'w, u32>,+ items: ZoneVec<'w, (Location, Content)>,+}++impl<'w> States<'w> {+ fn new_in(block_count: usize, work: &'w Zone) -> Self {+ Self {+ runs: ZoneVec::from_elem_in(None, block_count, work),+ rooms: ZoneVec::from_elem_in(0, block_count, work),+ items: ZoneVec::new_in(work),+ }+ }++ fn get(&self, block: BlockId) -> Option<&[(Location, Content)]> {+ Some(&self.items[self.runs[block.index()]?.range()])+ }++ fn set(&mut self, block: BlockId, state: &[(Location, Content)]) {+ let index = block.index();+ match self.runs[index] {+ // NB: A new state of a block takes the place of the one it had where it fits, which it mostly does: the+ // states of a block mostly hold less each time they are computed again.+ Some(run) if state.len() <= self.rooms[index] as usize => {+ let start = run.range().start;+ self.items[start..start + state.len()].copy_from_slice(state);+ self.runs[index] = Some(Run::new(start, start + state.len()));+ }+ _ => {+ let start = self.items.len();+ self.items.extend_from_slice(state);+ self.rooms[index] = state.len() as u32;+ self.runs[index] = Some(Run::new(start, self.items.len()));+ }+ }+ }+}++/// How many stack slots the locations of `allocation` name.+fn stack_slot_count(allocation: &Allocation) -> usize {+ let mut count = allocation.spill_slot_count as usize;+ let mut note = |location: Location| {+ if let Location::Stack(slot) = location {+ count = count.max(slot as usize + 1);+ }+ };+ for row in &allocation.nodes {+ row.output.into_iter().for_each(&mut note);+ row.spill_slot.map(Location::Stack).into_iter().for_each(&mut note);+ }+ for move_ in &allocation.moves {+ note(move_.from);+ note(move_.to);+ }+ allocation.locations.iter().copied().for_each(&mut note);+ allocation.exit_values.iter().for_each(|(_, location)| note(*location));+ count+}struct Verifier<'a> {graph: &'a Graph<'a>,registers: &'a RegisterSet,- allocation: &'a Allocation,+ allocation: &'a Allocation<'a>,/// Whether to report errors; off while the block states are still/// being computed.checking: bool,- errors: Vec<String>,+ /// The errors, one on each line.+ errors: String,work: &'a Zone,}@@ -62,55 +219,61 @@ pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation, wregisters,allocation,checking: false,- errors: Vec::new(),+ errors: String::new(),work,};let block_count = graph.blocks.len();- let block_ids = (0..block_count).map(BlockId::from_index).collect::<Vec<_>>();+ let block_ids = (0..block_count).map(BlockId::from_index);+ let mut state = State::new_in(stack_slot_count(allocation), work);+ let mut entry = ZoneVec::new_in(work);+ let mut exit = ZoneVec::new_in(work);// Compute the state at the start of every block: what holds on all// paths, starting optimistically from the predecessors seen so far.- let mut entry_states: Vec<Option<State>> = vec![None; block_count];- let mut exit_states: Vec<Option<State>> = vec![None; block_count];+ let mut entry_states = States::new_in(block_count, work);+ let mut exit_states = States::new_in(block_count, work);let mut changed = true;while changed {changed = false;- for block in &block_ids {- let Some(entry) = verifier.entry_state(*block, &exit_states) else {+ for block in block_ids.clone() {+ if !verifier.entry_state(block, &exit_states, &mut state, &mut entry) {continue;- };- if entry_states[block.index()].as_ref() == Some(&entry) && exit_states[block.index()].is_some() {+ }+ if entry_states.get(block) == Some(&entry[..]) && exit_states.get(block).is_some() {continue;}- let exit = verifier.simulate_block(*block, entry.clone());- entry_states[block.index()] = Some(entry);- exit_states[block.index()] = Some(exit);+ verifier.simulate_block(block, &entry, &mut state, &mut exit);+ entry_states.set(block, &entry);+ exit_states.set(block, &exit);changed = true;}}verifier.checking = true;- for block in &block_ids {- match &entry_states[block.index()] {+ for block in block_ids {+ match entry_states.get(block) {Some(entry) => {- verifier.check_phi_inputs(*block, &exit_states);- verifier.simulate_block(*block, entry.clone());+ verifier.check_phi_inputs(block, &exit_states);+ verifier.simulate_block(block, entry, &mut state, &mut exit);}- None => verifier.errors.push(format!("b{} is unreachable", block.0)),+ None => verifier.error(format!("b{} is unreachable", block.0)),}}if verifier.errors.is_empty() {Ok(())} else {- Err(verifier.errors.join("\n"))+ Err(verifier.errors)}}impl Verifier<'_> {fn error(&mut self, message: String) {if self.checking {- self.errors.push(message);+ if !self.errors.is_empty() {+ self.errors.push('\n');+ }+ self.errors.push_str(&message);}}@@ -129,55 +292,60 @@ impl Verifier<'_> {}}- fn read(&self, state: &State, location: Location) -> Option<Content> {+ fn read(&self, state: &(impl Holds + ?Sized), location: Location) -> Option<Content> {match location {Location::Constant(bits) => Some(Content::Constant(bits)),Location::Frame(slot) if self.graph.is_unwritten_slot(slot) => Some(Content::UnwrittenSlot(slot)),- _ => state.get(&location).copied(),+ _ => state.holds(location),}}- /// The state at the start of `block`: what holds at the end of all its- /// predecessors seen so far, with the phis in place. `None` if no- /// predecessor was seen yet.- fn entry_state(&self, block: BlockId, exit_states: &[Option<State>]) -> Option<State> {+ /// Writes to `out` the state at the start of `block`: what holds at the end of all its predecessors seen so far,+ /// with the phis in place. Returns false if no predecessor was seen yet. `state` is for the work.+ fn entry_state(+ &self,+ block: BlockId,+ exit_states: &States,+ state: &mut State,+ out: &mut ZoneVec<'_, (Location, Content)>,+ ) -> bool {+ out.clear();// NB: The entry and the on-stack replacement entries start with// every value in the frame.let block_data = self.graph.block(block);if block.0 == 0 || block_data.predecessors.is_empty() {- return Some(State::new());+ return true;}- let mut result: Option<State> = None;+ let mut seen = false;for predecessor in &block_data.predecessors {- let Some(exit) = &exit_states[predecessor.index()] else {+ let Some(exit) = exit_states.get(*predecessor) else {continue;};- let mut state = exit.clone();+ state.load(exit);for (phi, input) in phi_inputs_from(self.graph, *predecessor, block) {let output = self.allocation.node(phi).output.expect("phis have a location");for location in std::iter::once(output).chain(self.filled_slot(phi)) {- if self.read(&state, location) == Some(self.content_of_value(input)) {+ if self.read(&*state, location) == Some(self.content_of_value(input)) {state.insert(location, Content::Value(phi));} else {- state.remove(&location);+ state.remove(location);}}}- result = Some(match result {- None => state,- Some(previous) => previous- .into_iter()- .filter(|(location, content)| state.get(location) == Some(content))- .collect(),- });- }- result+ if seen {+ out.retain(|(location, content)| state.holds(*location) == Some(*content));+ } else {+ state.store(out);+ seen = true;+ }+ }+ seen}- fn check_phi_inputs(&mut self, block: BlockId, exit_states: &[Option<State>]) {- let predecessors = self.graph.block(block).predecessors.to_vec();- for predecessor in predecessors {- let Some(exit) = &exit_states[predecessor.index()] else {+ fn check_phi_inputs(&mut self, block: BlockId, exit_states: &States) {+ let graph = self.graph;+ for predecessor in graph.block(block).predecessors.iter().copied() {+ let Some(exit) = exit_states.get(predecessor) else {continue;};for (phi, input) in phi_inputs_from(self.graph, predecessor, block) {@@ -225,7 +393,7 @@ impl Verifier<'_> {}None => {self.error(format!("{context}: move reads {:?}, which holds nothing", m.from));- state.remove(&m.to);+ state.remove(m.to);}}}@@ -287,7 +455,15 @@ impl Verifier<'_> {}}- fn simulate_block(&mut self, block: BlockId, mut state: State) -> State {+ /// Writes to `out` what holds at the end of `block`, which starts with `entry`. `state` is for the work.+ fn simulate_block(+ &mut self,+ block: BlockId,+ entry: &[(Location, Content)],+ state: &mut State,+ out: &mut ZoneVec<'_, (Location, Content)>,+ ) {+ state.load(entry);let block_data = self.graph.block(block);// Phis in registers are stored to their spill slots first, unless// their inputs filled them already (see `filled_slot()`).@@ -297,12 +473,12 @@ impl Verifier<'_> {}}for node in &block_data.body {- self.simulate_node(&mut state, *node);+ self.simulate_node(state, *node);}let end_moves = self.allocation.block_end_moves(block);- self.apply_moves(&mut state, end_moves, &format!("end of b{}", block.0));- self.simulate_node(&mut state, self.graph.control_id(block));- state+ self.apply_moves(state, end_moves, &format!("end of b{}", block.0));+ self.simulate_node(state, self.graph.control_id(block));+ state.store(out);}fn simulate_node(&mut self, state: &mut State, node_id: NodeId) {@@ -358,7 +534,7 @@ impl Verifier<'_> {if allocation.inputs.contains(&Location::Register(*temp)) {self.error(format!("{context}: temp r{temp} is also an input"));}- state.remove(&Location::Register(*temp));+ state.remove(Location::Register(*temp));}let clobbered = match lowering.clobbers {Clobbers::CallerSaved => self.registers.caller_saved(),@@ -366,12 +542,12 @@ impl Verifier<'_> {Clobbers::Nothing => super::RegisterMask::default(),};for register in clobbered.iter() {- state.remove(&Location::Register(register));+ state.remove(Location::Register(register));}if let Some(output @ Location::Register(_)) = allocation.output {// NB: Cloning the state instead would take time quadratic in the size of code that keeps many values in// their stack slots past many nodes.- let previous = state.remove(&output);+ let previous = state.remove(output);self.check_exit_values(state, node_id, &context);if let Some(previous) = previous {state.insert(output, previous);@@ -396,3 +572,51 @@ impl Verifier<'_> {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn states_keep_the_order_of_the_locations_and_their_places() {+ let work = crate::test_work();+ let mut state = State::new_in(4, &work);+ let mut stored = ZoneVec::new_in(&work);+ state.insert(Location::Stack(3), Content::Constant(1));+ state.insert(Location::Register(200), Content::Value(NodeId(2)));+ state.insert(Location::Register(1), Content::Value(NodeId(3)));+ state.insert(Location::Stack(0), Content::UnwrittenSlot(4));+ assert_eq!(state.remove(Location::Stack(3)), Some(Content::Constant(1)));+ state.insert(Location::Stack(3), Content::Constant(5));+ state.insert(Location::Frame(7), Content::Constant(6));+ state.store(&mut stored);+ let expected = [+ (Location::Register(1), Content::Value(NodeId(3))),+ (Location::Register(200), Content::Value(NodeId(2))),+ (Location::Stack(0), Content::UnwrittenSlot(4)),+ (Location::Stack(3), Content::Constant(5)),+ ];+ assert_eq!(stored, expected);+ assert_eq!(stored.holds(Location::Stack(0)), Some(Content::UnwrittenSlot(4)));+ assert_eq!(stored.holds(Location::Stack(1)), None);+ assert_eq!(state.holds(Location::Frame(7)), None);++ state.load(&expected[1..]);+ assert_eq!(state.holds(Location::Register(1)), None);+ assert_eq!(state.holds(Location::Register(200)), Some(Content::Value(NodeId(2))));++ let mut states = States::new_in(2, &work);+ assert_eq!(states.get(BlockId(1)), None);+ states.set(BlockId(1), &expected);+ states.set(BlockId(0), &expected[..1]);+ assert_eq!(states.get(BlockId(1)), Some(&expected[..]));+ // NB: A smaller state takes the place of the one before it, and a larger one goes to new room.+ states.set(BlockId(1), &expected[2..]);+ assert_eq!(states.items.len(), 5);+ assert_eq!(states.get(BlockId(1)), Some(&expected[2..]));+ states.set(BlockId(0), &expected[..2]);+ assert_eq!(states.items.len(), 7);+ assert_eq!(states.get(BlockId(0)), Some(&expected[..2]));+ assert_eq!(states.get(BlockId(1)), Some(&expected[2..]));+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rsindex b1479cd096e..727685fc788 100644--- a/Libraries/LibJS/JIT/Rust/src/scratch.rs+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs@@ -10,8 +10,6 @@ use ak::Zone;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/// every compile of the thread uses it: a compile leaves nothing in it that the next one reads, only the memory.@@ -21,8 +19,9 @@ pub struct Scratch {/// Where the graph of a compile is, with all the lists of its nodes, blocks and frame states. A compile starts/// with a zone that holds nothing.pub(crate) zone: Zone,- /// Where the stages of a compile keep the data that only they use. The stage that is done leaves nothing in it- /// for the next one: the driver drops the data of the builder, and of each pass, when it ends.+ /// Where the stages of a compile keep the data that only they use. The driver drops the data of the builder,+ /// and of each pass, when it ends. The register allocator keeps the allocation here, with its own work data,+ /// for the code generator, so those stay until the compile ends.pub(crate) work: Zone,/// Where a stage that repeats a step keeps the data of one step, which the step drops when it ends. A stage/// keeps what lasts from one step to the next in `work`. So a stage whose steps each make data as large as the@@ -34,14 +33,11 @@ pub struct Scratch {pub(crate) tables: Tables,}-/// The tables of a compile that are not part of its graph.+/// The tables of the code generator and of the artifact writer, which are not in the zones. Each is its own range of+/// address space.pub struct Tables {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 {@@ -64,8 +60,6 @@ impl Scratch {tables: Tables {artifact: ArtifactWriter::new(),sites: SiteScratch::new(),- regalloc: Regalloc::new(),- dominators: Dominators::new(),},}}@@ -89,7 +83,5 @@ impl Scratch {}self.tables.artifact.release_memory();self.tables.sites.release_memory();- self.tables.regalloc.release_memory();- self.tables.dominators.release_memory();}}diff --git a/Libraries/LibJS/JIT/Rust/src/tables.rs b/Libraries/LibJS/JIT/Rust/src/tables.rsindex 0185fdb0665..d44d2d7e20b 100644--- a/Libraries/LibJS/JIT/Rust/src/tables.rs+++ b/Libraries/LibJS/JIT/Rust/src/tables.rs@@ -6,15 +6,15 @@//! Lists in the tables of a compile.//!-//! The data of a compile is rows in columns (see `ak::Column`). Where a row has a list of something, the elements of-//! the list are next to each other in a column that holds the lists of all the rows, and the row says which part of-//! that column is its own. So a compile makes no block of the heap for a list, however many lists it has.+//! The data of a compile is rows in columns: lists in a zone, with one element for each row. Where a row has a list+//! of something, the elements of the list are next to each other in a column that holds the lists of all the rows,+//! and the row says which part of that column is its own. So a compile makes one list in its zone for all the lists+//! of a kind, however many lists it has.-use core::ffi::CStr;use core::ops::Range;-use ak::Column;-use ak::ColumnFull;+use ak::Zone;+use ak::ZoneVec;/// The elements of one list: a part of a column that holds many lists.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]@@ -32,7 +32,7 @@ impl Run {/// The elements from index `start` to index `end` of a column, without the one at `end`.pub fn new(start: usize, end: usize) -> Self {- // NB: The columns of a compile hold fewer elements than this (see their limits).+ // NB: A list of a zone holds fewer than 2^32 elements.let start = u32::try_from(start).expect("the columns of a compile have 32-bit indices");let end = u32::try_from(end).expect("the columns of a compile have 32-bit indices");Self {@@ -55,50 +55,32 @@ impl Run {}}-/// Drops the elements of `column` and gives its memory back to the system.-pub fn release<T: Copy>(column: &mut Column<T>) {- column.clear();- column.trim(0);-}--/// Makes `column` hold `len` copies of `value` and nothing else.-pub fn reset<T: Copy>(column: &mut Column<T>, len: usize, value: T) -> Result<(), ColumnFull> {- column.clear();- column.try_resize(len, value)-}--/// Takes the last element out of `column`, if it has one.-pub fn pop<T: Copy>(column: &mut Column<T>) -> Option<T> {- let last = column.last().copied()?;- column.truncate(column.len() - 1);- Some(last)-}-/// A list of `T` for each index from 0 on, all in one column, in the order of the indices.///-/// The lists are written in one of two ways. In the order of their indices: `begin()`, then for each index-/// `try_push()` for its elements and `end_list()`. Or in any order, when it is known first how long each list is:+/// The lists are written in one of two ways. In the order of their indices: `begin()`, then for each index `push()`+/// for its elements and `end_list()`. Or in any order, when it is known first how long each list is:/// `begin_counts()`, `count()` for each element, `end_counts()`, `fill()` for each element, `end_fill()`.-pub struct Lists<T: Copy> {+pub struct Lists<'w, T: Copy> {/// Where the list of each index starts in `items`, and one more: where the last list ends.- starts: Column<u32>,- items: Column<T>,+ starts: ZoneVec<'w, u32>,+ items: ZoneVec<'w, T>,}-impl<T: Copy> Lists<T> {- /// Lists for up to `max_lists` indices, with up to `max_items` elements in all. They take no memory before they- /// have elements. `name` shows up for their memory in /proc/<pid>/smaps on Linux.- pub fn new(max_lists: usize, max_items: usize, name: &'static CStr) -> Self {+impl<'w, T: Copy> Lists<'w, T> {+ /// Lists for no index, which take no memory before they have some.+ pub fn new_in(zone: &'w Zone) -> Self {Self {- starts: Column::new(max_lists + 2, name),- items: Column::new(max_items.min(u32::MAX as usize), name),+ starts: ZoneVec::new_in(zone),+ items: ZoneVec::new_in(zone),}}- /// Drops the lists and gives their memory back to the system.- pub fn release_memory(&mut self) {- release(&mut self.starts);- release(&mut self.items);+ /// Lists for no index, with room for the lists of `lists` indices with `items` elements in all.+ pub fn with_capacity_in(lists: usize, items: usize, zone: &'w Zone) -> Self {+ Self {+ starts: ZoneVec::with_capacity_in(lists + 2, zone),+ items: ZoneVec::with_capacity_in(items, zone),+ }}/// How many indices have a list.@@ -116,30 +98,30 @@ impl<T: Copy> Lists<T> {}/// Drops the lists, to write new ones in the order of their indices.- pub fn begin(&mut self) -> Result<(), ColumnFull> {+ pub fn begin(&mut self) {self.starts.clear();self.items.clear();- self.starts.try_push(0)+ self.starts.push(0);}/// Adds an element to the list that is being written: the list of the first index that has none.- pub fn try_push(&mut self, item: T) -> Result<(), ColumnFull> {- self.items.try_push(item)+ pub fn push(&mut self, item: T) {+ self.items.push(item);}/// Ends the list that is being written.- pub fn end_list(&mut self) -> Result<(), ColumnFull> {- // NB: new() keeps the count of elements in 32 bits.- self.starts.try_push(self.items.len() as u32)+ pub fn end_list(&mut self) {+ // NB: A list of a zone holds fewer than 2^32 elements.+ self.starts.push(self.items.len() as u32);}/// Drops the lists, to write the lists of the indices below `count` in any order.- pub fn begin_counts(&mut self, count: usize) -> Result<(), ColumnFull> {+ pub fn begin_counts(&mut self, count: usize) {self.starts.clear();self.items.clear();// NB: While the lists are counted and filled, the entry of an index is one place further on, so that the// entries are where get() reads them when all the lists are full (see fill()).- self.starts.try_resize(count + 2, 0)+ self.starts.resize(count + 2, 0);}/// Notes that the list of `index` gets one more element.@@ -148,13 +130,15 @@ impl<T: Copy> Lists<T> {}/// Makes room for the elements that were counted, as copies of `filler`.- pub fn end_counts(&mut self, filler: T) -> Result<(), ColumnFull> {- let mut total = 0_u64;+ pub fn end_counts(&mut self, filler: T) {+ let mut total = 0_u32;for start in self.starts.iter_mut().skip(2) {- total += u64::from(*start);- *start = u32::try_from(total).map_err(|_| ColumnFull)?;+ total = total+ .checked_add(*start)+ .expect("a list of a zone holds fewer than 2^32 elements");+ *start = total;}- self.items.try_resize(total as usize, filler)+ self.items.resize(total as usize, filler);}/// Puts `item` in the next place of the list of `index`, which has a place left.@@ -178,33 +162,33 @@ mod tests {#[test]fn lists_written_in_the_order_of_their_indices() {- let mut lists = Lists::new(8, 64, c"test");+ let mut lists = Lists::new_in(crate::test_zone());assert!(lists.is_empty());- lists.begin().unwrap();- lists.try_push(5_u32).unwrap();- lists.try_push(6).unwrap();- lists.end_list().unwrap();- lists.end_list().unwrap();- lists.try_push(7).unwrap();- lists.end_list().unwrap();+ lists.begin();+ lists.push(5_u32);+ lists.push(6);+ lists.end_list();+ lists.end_list();+ lists.push(7);+ lists.end_list();assert_eq!(lists.len(), 3);assert_eq!(lists.get(0), [5, 6]);assert_eq!(lists.get(1), []);assert_eq!(lists.get(2), [7]);- lists.begin().unwrap();+ lists.begin();assert!(lists.is_empty());}#[test]fn lists_written_in_any_order() {- let mut lists = Lists::new(8, 64, c"test");+ let mut lists = Lists::new_in(crate::test_zone());let items = [(2, 'a'), (0, 'b'), (2, 'c'), (3, 'd'), (0, 'e'), (2, 'f')];for _ in 0..2 {- lists.begin_counts(5).unwrap();+ lists.begin_counts(5);for (index, _) in items {lists.count(index);}- lists.end_counts(' ').unwrap();+ lists.end_counts(' ');for (index, item) in items {lists.fill(index, item);}@@ -219,36 +203,27 @@ mod tests {}#[test]- fn lists_with_no_room_fail() {- let mut lists = Lists::new(2, 3, c"test");- lists.begin_counts(2).unwrap();+ fn lists_grow_past_the_room_they_were_made_with() {+ let mut lists = Lists::with_capacity_in(2, 3, crate::test_zone());+ lists.begin_counts(2);for _ in 0..4 {lists.count(1);}- assert_eq!(lists.end_counts(0_u8), Err(ColumnFull));- assert_eq!(lists.begin_counts(3), Err(ColumnFull));- lists.begin().unwrap();- for item in 0..3 {- lists.try_push(item).unwrap();+ lists.end_counts(0_u8);+ for item in 0..4 {+ lists.fill(1, item);}- assert_eq!(lists.try_push(3), Err(ColumnFull));- }-- #[test]- fn columns_are_reset_and_popped() {- let mut column = Column::new(8, c"test");- reset(&mut column, 3, 7_u8).unwrap();- assert_eq!(*column, [7, 7, 7]);- column[2] = 9;- assert_eq!(pop(&mut column), Some(9));- reset(&mut column, 1, 1).unwrap();- assert_eq!(pop(&mut column), Some(1));- assert_eq!(pop(&mut column), None);- assert_eq!(reset(&mut column, 9, 0), Err(ColumnFull));- column.push(5);- release(&mut column);- assert!(column.is_empty());- assert_eq!(column.memory(), 0);+ lists.end_fill();+ assert_eq!(lists.get(1), [0, 1, 2, 3]);+ lists.begin();+ for item in 0..4 {+ lists.push(item);+ }+ lists.end_list();+ lists.end_list();+ lists.end_list();+ assert_eq!(lists.len(), 3);+ assert_eq!(lists.get(0), [0, 1, 2, 3]);}#[test]