Skip to content

Truly independent web browser

LibJS: Drop interrupt checks from small counting loops

Andreas Kling8a1b7149a159
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 39c365653ee..9f41993c0ca 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -412,6 +412,7 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i
| 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 (but calls in cold blocks); 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. |
+| Interrupt check elimination | Small innermost loops that count towards an end lose their `CheckInterrupt`, if they run under 5000 times or a loop around them keeps its check (section 9, "Interrupts"). |
| 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. |
| Escape analysis | Allocations that do not escape become their properties' SSA values; frame states refer to `VirtualObject`s. `AssumeLegacyArgumentsUnread` nodes after calls whose frame states have virtual objects among legacy arguments become `AssumeValid` nodes; the others go away. |
@@ -484,6 +485,18 @@ A `CheckInterrupt` also exits where the stack really got that deep, which only a
compiled code below the limit does; the interpreter then continues the frame, like after any exit.
The exit counts as nothing learned, and not towards discarding the code.
+The check is two instructions, which costs a loop of a few instructions up to 18% of them. So
+interrupt check elimination removes it from small innermost loops without calls that count: a
+branch on every iteration tests an int32 that changes by a constant on every back edge against a
+bound in that direction. A loop whose constant start and bound say it runs under 5000 times (V8's
+bound for the same thing) goes wherever it is. Any other counting loop ends within 2^32 iterations,
+like a builtin that goes through a huge array, and only goes where it has a loop around it: an edge
+path from its exits back to its header, whose back edge keeps a check. An interrupt can thus take as
+long as one such loop takes to finish, up to seconds for one of 2^31 iterations, but only in a loop
+around it. An on-stack replacement entry into an inner loop keeps the outer one from being a natural
+loop, which is why this follows edges. Loops with an edge to a block before them, like a `continue`
+of the loop around them, keep their check, as that may be the only one of the loop around them.
+
To be written: exit reasons, recompiles.
## 10. The snapshot and the caches
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs
new file mode 100644
index 00000000000..067db9a415a
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/passes/interrupt_check_elimination.rs
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Interrupt check elimination: small counting loops lose their
+//! `Op::CheckInterrupt`.
+//!
+//! The check is two instructions, which is a lot for a loop of a few. It is
+//! there so that no script runs forever and an interrupt arrives soon, and
+//! both still hold for two kinds of innermost loops. One that is known to
+//! run a few thousand times at most stops soon by itself. One that counts
+//! towards any other bound ends within 2^32 iterations, like a builtin that
+//! goes through a huge array, and script then stops at the check of a loop
+//! around it. A counting loop without a loop around it keeps its check, or it
+//! could run for seconds after an interrupt. The code around a loop must not
+//! be able to continue without passing a check.
+//!
+//! A loop counts if a header phi changes by a constant on every back edge,
+//! towards a bound that a branch tests on every iteration: an int32 only has
+//! so many values, and the addition exits on overflow. One that wraps around
+//! instead (`(i + 1) | 0`) only counts if it steps by one and the bound is one
+//! it never steps past. The branch is what matters even where the addition
+//! 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 super::dominators::Dominators;
+use crate::bitset::BitSet;
+use crate::ir::BinaryOp;
+use crate::ir::BlockId;
+use crate::ir::BranchCondition;
+use crate::ir::Comparison;
+use crate::ir::Graph;
+use crate::ir::NodeId;
+use crate::ir::Op;
+
+/// How many nodes a loop may have to lose its check. In larger ones the check
+/// costs next to nothing, and they take longer to count to their end.
+const MAX_LOOP_SIZE: usize = 64;
+
+/// How many iterations a loop may have to lose its check without a loop around
+/// it, the bound V8 uses for this.
+const MAX_ITERATIONS_WITHOUT_CHECK: i64 = 5000;
+
+struct Loop {
+ header: BlockId,
+ blocks: BitSet,
+ back_edge_sources: Vec<BlockId>,
+}
+
+/// By how much `next` changes the phi `phi`, if that is a constant, and
+/// whether the change exits on overflow.
+fn step_of(graph: &Graph, phi: NodeId, next: NodeId) -> Option<(i64, bool)> {
+ let node = graph.node(graph.unrefined(next));
+ let (op, exits_on_overflow) = match node.op {
+ Op::Int32Binary { op } => (op, true),
+ Op::Int32WrappingBinary { op } => (op, false),
+ _ => return None,
+ };
+ if graph.unrefined(node.inputs[0]) != phi {
+ return None;
+ }
+ let constant = i64::from(graph.int32_constant(graph.unrefined(node.inputs[1]))?);
+ let step = match op {
+ BinaryOp::Add => constant,
+ BinaryOp::Sub => -constant,
+ _ => return None,
+ };
+ (step != 0).then_some((step, exits_on_overflow))
+}
+
+/// The bound of a branch that every iteration of the loop passes, and that
+/// leaves it once `phi` or `next`, which changes it by `step`, gets there. An
+/// addition that wraps around must not get past the bound.
+fn tested_bound(
+ graph: &Graph,
+ dominators: &Dominators,
+ loop_: &Loop,
+ phi: NodeId,
+ next: NodeId,
+ step: i64,
+ exits_on_overflow: bool,
+) -> Option<NodeId> {
+ loop_.blocks.iter().map(BlockId::from_index).find_map(|block| {
+ let control = graph.control(block);
+ let Op::Branch {
+ condition: BranchCondition::Bool,
+ if_true,
+ if_false,
+ } = control.op
+ else {
+ return None;
+ };
+ if !loop_
+ .back_edge_sources
+ .iter()
+ .all(|source| dominators.dominates(block, *source))
+ {
+ return None;
+ }
+ let compare = graph.node(graph.unrefined(control.inputs[0]));
+ let Op::Int32Compare { comparison } = compare.op else {
+ return None;
+ };
+ let counter = graph.unrefined(compare.inputs[0]);
+ if counter != phi && counter != graph.unrefined(next) {
+ return None;
+ }
+ let stays_in_loop_if_true = match (
+ loop_.blocks.contains(if_true.index()),
+ loop_.blocks.contains(if_false.index()),
+ ) {
+ (true, false) => true,
+ (false, true) => false,
+ _ => return None,
+ };
+ let is_strict = match (step > 0, comparison, stays_in_loop_if_true) {
+ (true, Comparison::LessThan, true)
+ | (true, Comparison::GreaterThanEquals, false)
+ | (false, Comparison::GreaterThan, true)
+ | (false, Comparison::LessThanEquals, false) => true,
+ (true, Comparison::LessThanEquals, true)
+ | (true, Comparison::GreaterThan, false)
+ | (false, Comparison::GreaterThanEquals, true)
+ | (false, Comparison::LessThan, false) => false,
+ _ => return None,
+ };
+ (exits_on_overflow || (is_strict && step.abs() == 1)).then(|| graph.unrefined(compare.inputs[1]))
+ })
+}
+
+/// How much is known about how long a loop runs.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum Trip {
+ /// It counts towards a bound, so it ends.
+ Counted,
+ /// It ends within MAX_ITERATIONS_WITHOUT_CHECK iterations.
+ Short,
+}
+
+/// Whether the iterations from every way into the loop to `bound` are few.
+fn is_short(graph: &Graph, loop_: &Loop, phi: NodeId, bound: NodeId, step: i64) -> bool {
+ let Some(bound) = graph.int32_constant(bound).map(i64::from) else {
+ return false;
+ };
+ let predecessors = &graph.block(loop_.header).predecessors;
+ predecessors
+ .iter()
+ .zip(&graph.node(phi).inputs)
+ .filter(|(predecessor, _)| !loop_.back_edge_sources.contains(predecessor))
+ .all(|(_, start)| {
+ graph
+ .int32_constant(graph.unrefined(*start))
+ .is_some_and(|start| (bound - i64::from(start)) / step < MAX_ITERATIONS_WITHOUT_CHECK)
+ })
+}
+
+/// What the header phi `phi` tells about the end of the loop, if it counts
+/// towards one.
+fn trip_of(graph: &Graph, dominators: &Dominators, loop_: &Loop, phi: NodeId) -> Option<Trip> {
+ let predecessors = &graph.block(loop_.header).predecessors;
+ let inputs = &graph.node(phi).inputs;
+ let mut direction = 0;
+ let mut trip = Trip::Short;
+ for (_, next) in predecessors
+ .iter()
+ .zip(inputs)
+ .filter(|(predecessor, _)| loop_.back_edge_sources.contains(predecessor))
+ {
+ let (step, exits_on_overflow) = step_of(graph, phi, *next)?;
+ // NB: Back edges that step in opposite directions could go on forever.
+ if direction != 0 && direction != step.signum() {
+ return None;
+ }
+ direction = step.signum();
+ let bound = tested_bound(graph, dominators, loop_, phi, *next, step, exits_on_overflow)?;
+ if !is_short(graph, loop_, phi, bound, step) {
+ trip = Trip::Counted;
+ }
+ }
+ Some(trip)
+}
+
+/// Whether the loop has no loop inside it, nothing that makes its check not
+/// worth removing, and no edge back to a block around it, which would be a
+/// back edge of a loop around it without a check of its own (like a
+/// `continue` of an outer loop).
+fn is_small_and_innermost(graph: &Graph, loop_: &Loop) -> bool {
+ let mut size = 0;
+ for index in loop_.blocks.iter() {
+ let block = graph.block(BlockId::from_index(index));
+ if !block.is_cold {
+ size += block.body.len();
+ if block.body.iter().any(|node| graph.node(*node).op.properties().is_call) {
+ return false;
+ }
+ }
+ for successor in graph.successors(BlockId::from_index(index)) {
+ if successor != loop_.header && successor.index() <= index {
+ return false;
+ }
+ }
+ }
+ size <= MAX_LOOP_SIZE
+}
+
+/// Whether what follows the loop can get back to it. Whatever way that goes,
+/// it has a back edge of a loop that keeps its check, since only innermost
+/// ones lose theirs. This looks at the edges and not at natural loops: an
+/// on-stack replacement entry into a loop keeps the loop around it from being
+/// a natural loop.
+fn has_loop_around(graph: &Graph, loop_: &Loop) -> bool {
+ let mut visited = BitSet::new(graph.blocks.len());
+ let mut worklist: Vec<BlockId> = loop_.blocks.iter().map(BlockId::from_index).collect();
+ while let Some(block) = worklist.pop() {
+ for successor in graph.successors(block) {
+ if successor == loop_.header && !loop_.blocks.contains(block.index()) {
+ return true;
+ }
+ if !loop_.blocks.contains(successor.index()) && !visited.contains(successor.index()) {
+ visited.insert(successor.index());
+ worklist.push(successor);
+ }
+ }
+ }
+ false
+}
+
+pub fn run(graph: &mut Graph) {
+ if !graph.nodes.iter().any(|node| matches!(node.op, Op::CheckInterrupt)) {
+ return;
+ }
+ let dominators = Dominators::compute(graph);
+ let mut loops = Vec::new();
+ for index in 0..graph.blocks.len() {
+ let header = BlockId::from_index(index);
+ let back_edge_sources = dominators.back_edge_sources(graph, header);
+ if back_edge_sources.is_empty() {
+ continue;
+ }
+ let blocks = dominators.loop_blocks(graph, header, &back_edge_sources);
+ loops.push(Loop {
+ header,
+ blocks,
+ back_edge_sources,
+ });
+ }
+ for loop_ in &loops {
+ if !is_small_and_innermost(graph, loop_) {
+ continue;
+ }
+ let best_trip = graph
+ .block(loop_.header)
+ .phis
+ .iter()
+ .filter_map(|phi| trip_of(graph, &dominators, loop_, *phi))
+ .max();
+ let may_lose_check = match best_trip {
+ Some(Trip::Short) => true,
+ Some(Trip::Counted) => has_loop_around(graph, loop_),
+ None => false,
+ };
+ if !may_lose_check {
+ continue;
+ }
+ for block in loop_.blocks.iter() {
+ let nodes = &graph.nodes;
+ graph.blocks[block]
+ .body
+ .retain(|node| !matches!(nodes[node.index()].op, Op::CheckInterrupt));
+ }
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
index eb9039555a5..297bd620fef 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
@@ -24,6 +24,7 @@ mod exit_unboxing;
mod facts;
mod frame_initialization;
mod gvn;
+mod interrupt_check_elimination;
mod licm;
mod loop_rotation;
mod representation;
@@ -93,6 +94,10 @@ const PASSES: &[Pass] = &[
name: "bounds check elimination",
run: bounds_check_elimination::run,
},
+ Pass {
+ name: "interrupt check elimination",
+ run: interrupt_check_elimination::run,
+ },
Pass {
name: "exit unboxing",
run: exit_unboxing::run,
diff --git a/Tests/LibJS/JIT/ir/interrupt-checks.js b/Tests/LibJS/JIT/ir/interrupt-checks.js
new file mode 100644
index 00000000000..6a963fb107f
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/interrupt-checks.js
@@ -0,0 +1,85 @@
+// Every loop checks for interrupts where it jumps back, and keeps the check in the loop. Loops that count to an end lose
+// theirs if they have a loop around them to stop at, or end soon by themselves.
+
+function untilZero(object) {
+ while (object.value !== 0) object.value = object.next;
+}
+function counts(object, count) {
+ let sum = 0;
+ for (let i = 0; i < count; ++i) sum = (sum + object.value) | 0;
+ return sum;
+}
+function wraps(object) {
+ let i = 0;
+ while (object.value-- > 0) i = (i + 2) | 0;
+ return i;
+}
+function short(object) {
+ let sum = 0;
+ for (let i = 0; i < 4000; ++i) sum = (sum + object.value) | 0;
+ return sum;
+}
+function notShort(object) {
+ let sum = 0;
+ for (let i = 0; i < 6000; ++i) sum = (sum + object.value) | 0;
+ return sum;
+}
+function nested(count) {
+ let sum = 0;
+ for (let i = 0; i < count; ++i) {
+ for (let j = 0; j < 10; ++j) sum = (sum + j) | 0;
+ }
+ return sum;
+}
+
+jit.prepare(untilZero);
+jit.prepare(counts);
+jit.prepare(wraps);
+jit.prepare(short);
+jit.prepare(notShort);
+jit.prepare(nested);
+for (let i = 0; i < 10; ++i) {
+ untilZero({ value: 1, next: 0 });
+ counts({ value: i }, 10);
+ wraps({ value: 2 });
+ short({ value: i });
+ notShort({ value: i });
+ nested(2);
+}
+jit.compile(untilZero);
+jit.compile(counts);
+jit.compile(wraps);
+jit.compile(short);
+jit.compile(notShort);
+jit.compile(nested);
+
+// CHECK-FUNCTION: untilZero
+// CHECK-PASS: loop invariant code motion
+// CHECK: loop:
+// CHECK: CheckInterrupt
+// CHECK-PASS: interrupt check elimination
+// CHECK: CheckInterrupt
+
+// CHECK-FUNCTION: counts
+// CHECK-PASS: interrupt check elimination
+// CHECK: CheckInterrupt
+
+// CHECK-FUNCTION: short
+// CHECK-PASS: graph building
+// CHECK: CheckInterrupt
+// CHECK-PASS: interrupt check elimination
+// CHECK-COUNT-0: CheckInterrupt
+
+// CHECK-FUNCTION: notShort
+// CHECK-PASS: interrupt check elimination
+// CHECK: CheckInterrupt
+
+// CHECK-FUNCTION: wraps
+// CHECK-PASS: interrupt check elimination
+// CHECK: CheckInterrupt
+
+// CHECK-FUNCTION: nested
+// CHECK-PASS: graph building
+// CHECK-COUNT-2: CheckInterrupt
+// CHECK-PASS: interrupt check elimination
+// CHECK-COUNT-1: CheckInterrupt