Truly independent web browser
LibJS/JIT: Hoist checks out of loops from conditional blocks
Andreas Klingf242af295353
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 683d6cd0304..b85fe4d6c6f 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -317,7 +317,7 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i| Check elimination | A forward dataflow of facts removes checks that passed already, decides branches that a branch on the same values decided before, and reuses loads whose value is known; may turn shape checks into `AssumeValid` plus a stable shape dependency. || Simplification | Again, for what the branches that check elimination decided left foldable (like the double path of `Math.abs` of an int32). || Global value numbering | Again, for the nodes that check elimination and simplification made the same. |-| Loop invariant code motion | Gives loops entered from several blocks a merged preheader, then moves effect-free nodes with inputs from outside the loop to it; nodes that may exit only from blocks every iteration runs, exiting to the loop header, and not where that kind of exit was taken there before. |+| Loop invariant code motion | Gives loops entered from several blocks a merged preheader, then moves effect-free nodes with inputs from outside the loop to it; nodes that may exit too, exiting to the loop header, and not where that kind of exit was taken there before. Those from blocks that not every iteration runs, but for cold ones, move speculatively: they exit with `Hoisted`, and stay in the loop where such an exit was taken there before. || Bounds check elimination | Bounds checks against constant counts go away where the index is known to be in range: induction variables of loops whose back edge compares the grown counter with a constant bound, merges of values from outside a loop, and int32 arithmetic on them that cannot overflow. The counter an on-stack replacement entry brings is checked against the bound once where it enters, unless such a check exited there before. With the same ranges, `((x << k) + c) >> k` becomes `x + (c >> k)` where nothing overflows and `c` is a multiple of 2^k. Int32 additions, subtractions and multiplications become `Int32WrappingBinary` where the ranges of their operands keep the result an int32 (and not -0), with operands also bounded by the masks and shifts of any int32, and by the dominating bounds checks and in-bounds branches of indices. || Exit unboxing | Frame states take the unboxed value of an int32, float64 or bool boxing that only frame states use, so that exits box it instead of the fast path. || Dead code elimination | Removes nodes without uses and without effects; frame states count as uses. Branches whose edges lead to the same place doing the same thing become jumps. |diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex 2ae556a4f37..fda89b3a9b0 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -109,6 +109,12 @@ pub enum ExitKind {OutOfBounds,/// A value had another type than the instruction's feedback had seen.BadType,+ /// A node that may exit, which loop invariant code motion moved out of a+ /// block that not every iteration of its loop runs, exited before the+ /// loop. Exits of this kind are recorded at the loop header, and keep+ /// such nodes in that loop, but not the nodes from blocks every iteration+ /// runs.+ Hoisted,/// Something the code depended on stopped holding while it ran other/// code (see `Dependency`), so the code was invalidated.Invalidated,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex e2a0fcb2fd3..1b53f130999 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -80,6 +80,7 @@ use crate::bytecode::OperandRole;use crate::bytecode::SlowPathAbi;use crate::bytecode::decode_instruction;use crate::bytecode::slow_path_layout;+use crate::code::ExitKind;use crate::code::JitStatus;use crate::code::Site;use crate::code::SiteKind;@@ -972,7 +973,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// Registers an exit of `node` (with its frame state) and returns the/// label its checks branch to when they fail.fn exit_site(&mut self, node: NodeId) -> Label {- let kind = self.graph.node(node).op.exit_kind().expect("the node can exit");+ let kind = if self.graph.speculatively_hoisted.contains(&node) {+ ExitKind::Hoisted+ } else {+ self.graph.node(node).op.exit_kind().expect("the node can exit")+ };let index = u32::try_from(self.sites.len()).expect("site count fits in u32");self.sites.push((node, SiteKind::Exit(kind)));let label = self.masm.new_label();diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 913085853a5..c437b2dd220 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1929,6 +1929,10 @@ pub struct Graph {/// Where exits of each executable were taken before, as (executable,/// pc, kind), for passes that must not repeat a failed speculation.pub exit_sites: Vec<(u32, u32, ExitKind)>,+ /// The nodes that loop invariant code motion moved out of blocks that not+ /// every iteration of their loop runs, which exit with+ /// `ExitKind::Hoisted` instead of their own kind of exit.+ pub speculatively_hoisted: Vec<NodeId>,/// The argument slots of the compiled function that its legacy/// `arguments` shows. Empty for functions without legacy `arguments`.pub legacy_arguments: core::ops::Range<u32>,diff --git a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs b/Libraries/LibJS/JIT/Rust/src/passes/licm.rsindex f625a9beb0b..23add0135ce 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs@@ -12,17 +12,21 @@//! from several blocks (like the function entry and an on-stack replacement//! entry) first get a preheader that merges what those bring.//!-//! Checks and other nodes that may exit move only from blocks every-//! iteration of the loop runs (the header, and blocks on the way to every-//! back edge), so they exit early at most where the loop runs no iteration-//! to its end, and only in loops whose header has a frame state to exit-//! with: the interpreter then resumes at the loop header, with the values-//! the preheader brings into the loop. Hoisting a check whose kind of exit-//! was taken at the loop header before is never repeated.+//! Checks and other nodes that may exit move too, only in loops whose header+//! has a frame state to exit with: the interpreter then resumes at the loop+//! header, with the values the preheader brings into the loop. Those from+//! blocks that not every iteration runs (like the code after a `continue`),+//! but for cold ones, move speculatively: they may exit where the loop would+//! never have run them, and exit with `ExitKind::Hoisted` instead of their+//! own kind. Hoisting a check whose kind of exit was taken at the loop header+//! before is never repeated, nor are speculative hoists where one of them+//! exited there, so a speculation that fails costs one exit, and keeps the+//! other checks moving.use super::dominators::Dominators;use super::edit;use crate::bitset::BitSet;+use crate::code::ExitKind;use crate::ir::Block;use crate::ir::BlockId;use crate::ir::FrameStateId;@@ -204,6 +208,7 @@ pub fn run(graph: &mut Graph) {for block in loop_.blocks.iter() {let block_id = BlockId::from_index(block);let runs_every_iteration = dominators.runs_every_iteration(block_id, &loop_.back_edge_sources);+ let is_cold = graph.block(block_id).is_cold;for node in graph.block(block_id).body.clone() {let data = graph.node(node);let properties = data.op.properties();@@ -223,11 +228,14 @@ pub fn run(graph: &mut Graph) {continue;}if let Some(kind) = data.op.exit_kind() {- let gated = header_state.is_some_and(|state| {- let state = graph.frame_state(state);- graph.exit_sites.contains(&(state.executable, state.pc, kind))- });- if !runs_every_iteration || gated {+ let speculative = !runs_every_iteration || graph.speculatively_hoisted.contains(&node);+ let exited = |kind| {+ header_state.is_some_and(|state| {+ let state = graph.frame_state(state);+ graph.exit_sites.contains(&(state.executable, state.pc, kind))+ })+ };+ if (speculative && is_cold) || exited(kind) || (speculative && exited(ExitKind::Hoisted)) {continue;}let state = *exit_state.get_or_insert_with(|| {@@ -238,6 +246,9 @@ pub fn run(graph: &mut Graph) {continue;};graph.nodes[node.index()].frame_state = Some(state);+ if speculative && !graph.speculatively_hoisted.contains(&node) {+ graph.speculatively_hoisted.push(node);+ }}graph.blocks[block].body.retain(|other| *other != node);block_of[node.index()] = Some(loop_.preheader.index());diff --git a/Tests/LibJS/JIT/ir/check-elimination-refinements.js b/Tests/LibJS/JIT/ir/check-elimination-refinements.jsindex 9fa41b158de..954109f92c2 100644--- a/Tests/LibJS/JIT/ir/check-elimination-refinements.js+++ b/Tests/LibJS/JIT/ir/check-elimination-refinements.js@@ -1,5 +1,5 @@// A shape check that an earlier one in the loop makes redundant is removed, and the property load after it uses the-// earlier check's value, so it stays in the loop behind that check instead of moving out of the loop ahead of it.+// earlier check's value, so it moves out of the loop only behind that check.function total(object, count) {let sum = 0;@@ -17,8 +17,9 @@ jit.compile(total);// CHECK-FUNCTION: total// CHECK-PASS: loop invariant code motion-// CHECK: loop:// CHECK: [[CHECKED:v[0-9]+]] = CheckShape// CHECK: LoadNamed +0 ([[CHECKED]],// CHECK-NOT: CheckShape// CHECK: LoadNamed +1 ([[CHECKED]],+// CHECK-NOT: CheckShape+// CHECK: loop:diff --git a/Tests/LibJS/JIT/ir/licm-speculative-hoists.js b/Tests/LibJS/JIT/ir/licm-speculative-hoists.jsnew file mode 100644index 00000000000..311bde758d3--- /dev/null+++ b/Tests/LibJS/JIT/ir/licm-speculative-hoists.js@@ -0,0 +1,29 @@+// Checks in blocks that not every iteration runs move out of the loop too, speculatively. One that fails there exits+// with its own reason, Hoisted, so the code compiled next keeps such checks in the loop, and still moves those that+// every iteration runs.++function sum(object, other, n) {+ let total = 0;+ for (let i = 0; i < n; ++i) {+ total = (total + object.x) | 0;+ if (i === 7) total = (total + other.y) | 0;+ }+ return total;+}+jit.prepare(sum);+for (let i = 0; i < 10; ++i) sum({ x: i }, { y: 1 }, 10);+jit.compile(sum);+sum({ x: 1 }, { z: 0, y: 2 }, 3);+jit.discard(sum);+jit.compile(sum);++// CHECK-FUNCTION: sum+// CHECK-PASS: loop invariant code motion+// CHECK: CheckShape+// CHECK-NEXT: CellAddress+// CHECK-NEXT: LoadNamed +0+// CHECK-NOT: CheckShape+// CHECK: loop:+// CHECK: CheckShape++console.log(sum({ x: 2 }, { y: 3 }, 10));