Skip to content

Truly independent web browser

LibWasm: Drop interrupt checks from small counting loops

Andreas Kling13706443c2d1
diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.md
index 9349a8b96f9..e96bd0cb364 100644
--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md
+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md
@@ -20,6 +20,7 @@ reused from one compile to the next:
|---|---|---|
| Decode and build | `decode.rs`, `builder/` | One forward pass over the validated, quickened body. Produces typed SSA with phis, folding and value numbering as it goes. |
| Cleanup | `passes/cleanup.rs` | Removes trivial phis to a fixed point, dead pure nodes, and fuses branches with the comparisons only they use. |
+| Interrupt check elimination | `passes/interrupt_checks.rs` | Small innermost loops that count towards an end lose their `CheckInterrupt`. |
| Loop invariant code motion | `passes/licm.rs` | Finds the nodes of call-free loops that compute the same value in every iteration. |
| Scheduling | `passes/schedule.rs` | Rebuilds the node arena in linear order without the dead nodes, with the invariant nodes at the end of their loop's preheader. |
| Liveness | `regalloc/liveness.rs` | One interval per value in linear order, extended over loops. |
@@ -253,6 +254,12 @@ a compare and a branch to the shared trap stub, which take no allocatable regist
it through the frame's instance. The embedder turns the trap into whatever stopped the store;
nothing else can observe it.
+Small innermost loops without calls lose their check (`passes/interrupt_checks.rs`) if an i32 counts
+by one towards a bound a step cannot go past: `<`, `>` or `!=` of an invariant bound. Everything wraps
+around here, so loops that step by more keep it. One known to run under 5000 times goes anywhere.
+Any other ends within 2^32 iterations, and goes only where a loop around it keeps its check, so that
+an interrupt takes as long as the rest of that loop at most.
+
**Calls.** Every call goes through `FunctionHeader::native_entry`. A direct call of a function of
the same instance passes the caller's instance and memory base; any other call (imports,
`call_indirect`, `call_ref`) passes the callee's, from its header (`CalleeInstance`). `call_indirect`
diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rs
index a4a9e2807ac..ae0951c0596 100644
--- a/Libraries/LibWasm/JIT/src/lib.rs
+++ b/Libraries/LibWasm/JIT/src/lib.rs
@@ -209,6 +209,7 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
);
}
passes::cleanup::cleanup(&mut context.func, &mut context.liveliness);
+ passes::interrupt_checks::run(&context.func, &mut context.liveliness);
// NB: The loop an OSR compile enters has two ways in, so it has no preheader to hoist into.
let no_licm = request.options.no_licm || request.osr.is_some();
if no_licm {
diff --git a/Libraries/LibWasm/JIT/src/passes/interrupt_checks.rs b/Libraries/LibWasm/JIT/src/passes/interrupt_checks.rs
new file mode 100644
index 00000000000..f7476567555
--- /dev/null
+++ b/Libraries/LibWasm/JIT/src/passes/interrupt_checks.rs
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Interrupt check elimination: small counting loops lose their `Op::CheckInterrupt`, as in LibJS's JIT.
+//!
+//! A check costs a loop of a few instructions a lot of them. It is there so that no code 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, and the code then
+//! stops at the check of the loop around it. A counting loop without a loop around it keeps its check, or it could run
+//! for seconds after an interrupt.
+//!
+//! An i32 phi of the loop's header counts if every back edge steps it by one in the same direction, and a branch that
+//! every iteration passes leaves the loop once it gets to a bound. Everything wraps around in WebAssembly, so the test
+//! must be one that a step by one cannot go past: `<` going up, `>` going down, or `!=` of a bound that stays the same
+//! and so eventually comes up. A step of any other size can go past all of those.
+
+use crate::ir::{BlockId, Func, IntCondition, NONE, Op, Type, Value};
+use crate::passes::cleanup::Liveliness;
+use crate::passes::dominators::Dominators;
+
+/// How many nodes a loop may have to lose its check. In larger ones the check costs next to nothing.
+const MAX_LOOP_SIZE: u32 = 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<'a> {
+ header: BlockId,
+ /// The blocks that get back to the header. The block after a loop can have the loop's `loop_index`.
+ blocks: &'a [BlockId],
+}
+
+impl Loop<'_> {
+ fn contains(&self, block: BlockId) -> bool {
+ self.blocks.contains(&block)
+ }
+
+ /// Whether a value is the same in every iteration.
+ fn is_invariant(&self, func: &Func, value: Value) -> bool {
+ func.node(value).constant().is_some()
+ || self.blocks.iter().all(|&block| {
+ let data = &func.blocks[block as usize];
+ !(data.start..data.end).contains(&value) && !func.phis(block).any(|phi| phi == value)
+ })
+ }
+}
+
+/// What a branch at the end of a block of the loop knows of `counter`: the bound, and the comparison of the counter with
+/// it that keeps the loop going.
+fn test_of(func: &Func, loop_: &Loop, block: BlockId, counters: [Value; 2]) -> Option<(Value, IntCondition)> {
+ let [first, second] = *func.successors(block) else {
+ return None;
+ };
+ let stays_if_true = match (loop_.contains(first), loop_.contains(second)) {
+ (true, false) => true,
+ (false, true) => false,
+ _ => return None,
+ };
+ let node = func.node(func.terminator(block));
+ let (left, right, condition) = match node.op {
+ Op::BranchCompare => (node.args[0], node.args[1], IntCondition::from_flags(node.flags)),
+ Op::Branch => {
+ let tested = func.resolve(node.args[0]);
+ let tested_node = func.node(tested);
+ match tested_node.op {
+ Op::Compare => (
+ tested_node.args[0],
+ tested_node.args[1],
+ IntCondition::from_flags(tested_node.flags),
+ ),
+ Op::Eqz => (tested_node.args[0], NONE, IntCondition::Eq),
+ _ => (tested, NONE, IntCondition::Ne),
+ }
+ }
+ _ => return None,
+ };
+ let left = func.resolve(left);
+ // NB: The zero of a plain branch is a bound that no node holds.
+ let right = if right == NONE { NONE } else { func.resolve(right) };
+ let (bound, condition) = if counters.contains(&left) {
+ (right, condition)
+ } else if right != NONE && counters.contains(&right) {
+ (left, condition.swap())
+ } else {
+ return None;
+ };
+ Some((bound, if stays_if_true { condition } else { condition.invert() }))
+}
+
+/// By how much `next` changes `phi`, if that is one up or down.
+fn step_of(func: &Func, phi: Value, next: Value) -> Option<i32> {
+ let node = func.node(next);
+ if node.ty != Type::I32 {
+ return None;
+ }
+ let (left, right) = (func.resolve(node.args[0]), func.resolve(node.args[1]));
+ let step = match node.op {
+ Op::Add if left == phi => func.node(right).constant()? as u32 as i32,
+ Op::Add if right == phi => func.node(left).constant()? as u32 as i32,
+ Op::Sub if left == phi => (func.node(right).constant()? as u32 as i32).wrapping_neg(),
+ _ => return None,
+ };
+ (step == 1 || step == -1).then_some(step)
+}
+
+/// How far `start` is from `bound` in steps, if the comparison of the two as it says tells that.
+fn distance(start: u32, bound: u32, step: i32, condition: IntCondition) -> Option<i64> {
+ let (start, bound) = match condition {
+ IntCondition::LtU | IntCondition::GtU => (i64::from(start), i64::from(bound)),
+ _ => (i64::from(start as i32), i64::from(bound as i32)),
+ };
+ let distance = (bound - start) * i64::from(step);
+ // NB: A test of `!=` that starts past its bound goes all the way around.
+ (condition != IntCondition::Ne || distance >= 0).then_some(distance)
+}
+
+/// How long a loop that counts with `phi` takes.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum Trip {
+ /// It ends by itself.
+ Counted,
+ /// It ends within MAX_ITERATIONS_WITHOUT_CHECK iterations.
+ Short,
+}
+
+fn trip_of(func: &Func, dominators: &Dominators, loop_: &Loop, back_edges: &[usize], phi: Value) -> Option<Trip> {
+ let inputs = func.inputs(phi);
+ let predecessors = func.predecessors(loop_.header);
+ let mut direction = 0;
+ let mut next = NONE;
+ for &edge in back_edges {
+ let input = func.resolve(inputs[edge]);
+ let step = step_of(func, phi, input)?;
+ if (direction != 0 && step != direction) || (next != NONE && next != input) {
+ return None;
+ }
+ direction = step;
+ next = input;
+ }
+ let test = loop_.blocks.iter().find_map(|&block| {
+ if !back_edges
+ .iter()
+ .all(|&edge| dominators.dominates(block, predecessors[edge]))
+ {
+ return None;
+ }
+ let (bound, condition) = test_of(func, loop_, block, [phi, next])?;
+ let can_go_past = match (direction, condition) {
+ (1, IntCondition::LtS | IntCondition::LtU) | (-1, IntCondition::GtS | IntCondition::GtU) => false,
+ (_, IntCondition::Ne) => bound != NONE && !loop_.is_invariant(func, bound),
+ _ => true,
+ };
+ (!can_go_past).then_some((bound, condition))
+ });
+ let (bound, condition) = test?;
+ let bound = if bound == NONE {
+ Some(0)
+ } else {
+ func.node(bound).constant()
+ };
+ let is_short = bound.is_some_and(|bound| {
+ inputs
+ .iter()
+ .enumerate()
+ .filter(|(edge, _)| !back_edges.contains(edge))
+ .all(|(_, start)| {
+ func.node(func.resolve(*start)).constant().is_some_and(|start| {
+ distance(start as u32, bound as u32, direction, condition)
+ .is_some_and(|distance| distance < MAX_ITERATIONS_WITHOUT_CHECK)
+ })
+ })
+ });
+ Some(if is_short { Trip::Short } else { Trip::Counted })
+}
+
+/// Marks the checks that go as dead, which keeps `schedule` from placing them.
+pub fn run(func: &Func, liveliness: &mut Liveliness) {
+ if func.loops.is_empty() {
+ return;
+ }
+ let mut dominators = Dominators::default();
+ dominators.compute(func);
+ let mut has_loop_inside = vec![false; func.loops.len()];
+ for loop_ in &func.loops {
+ if loop_.parent != NONE {
+ has_loop_inside[loop_.parent as usize] = true;
+ }
+ }
+ let mut blocks = Vec::new();
+ let mut back_edges = Vec::new();
+ for (index, loop_) in func.loops.iter().enumerate() {
+ if has_loop_inside[index] {
+ continue;
+ }
+ back_edges.clear();
+ back_edges.extend(
+ func.predecessors(loop_.header)
+ .iter()
+ .enumerate()
+ .filter(|(_, predecessor)| **predecessor >= loop_.header)
+ .map(|(edge, _)| edge),
+ );
+ blocks.clear();
+ blocks.push(loop_.header);
+ for &edge in &back_edges {
+ let source = func.predecessors(loop_.header)[edge];
+ if !blocks.contains(&source) {
+ blocks.push(source);
+ }
+ }
+ let mut next = 1;
+ while next < blocks.len() {
+ for &predecessor in func.predecessors(blocks[next]) {
+ if !blocks.contains(&predecessor) {
+ blocks.push(predecessor);
+ }
+ }
+ next += 1;
+ }
+ let mut size = 0;
+ let mut calls = false;
+ for &block in &blocks {
+ let data = &func.blocks[block as usize];
+ size += data.end - data.start;
+ calls |= (data.start..data.end)
+ .any(|value| !liveliness.is_dead(value) && matches!(func.node(value).op, Op::Call | Op::Helper));
+ }
+ if calls || size > MAX_LOOP_SIZE {
+ continue;
+ }
+ let current = Loop {
+ header: loop_.header,
+ blocks: &blocks,
+ };
+ let best_trip = func
+ .phis(loop_.header)
+ .filter(|phi| !liveliness.is_dead(*phi) && func.node(*phi).op == Op::Phi && func.node(*phi).ty == Type::I32)
+ .filter_map(|phi| trip_of(func, &dominators, &current, &back_edges, phi))
+ .max();
+ let may_lose_check = match best_trip {
+ Some(Trip::Short) => true,
+ Some(Trip::Counted) => loop_.parent != NONE,
+ None => false,
+ };
+ if !may_lose_check {
+ continue;
+ }
+ let header = &func.blocks[loop_.header as usize];
+ for value in header.start..header.end {
+ if func.node(value).op == Op::CheckInterrupt {
+ liveliness.dead[value as usize] = true;
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/passes/mod.rs b/Libraries/LibWasm/JIT/src/passes/mod.rs
index f29cbba1e1b..e4f6cc7f1b0 100644
--- a/Libraries/LibWasm/JIT/src/passes/mod.rs
+++ b/Libraries/LibWasm/JIT/src/passes/mod.rs
@@ -8,5 +8,6 @@
pub mod cleanup;
pub mod dominators;
+pub mod interrupt_checks;
pub mod licm;
pub mod schedule;
diff --git a/Libraries/LibWasm/JIT/tests/interrupt_checks.rs b/Libraries/LibWasm/JIT/tests/interrupt_checks.rs
new file mode 100644
index 00000000000..2d4e7a8e7b5
--- /dev/null
+++ b/Libraries/LibWasm/JIT/tests/interrupt_checks.rs
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Which loops keep their interrupt check: only a loop that ends soon or that a loop around it stops may lose it.
+
+#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]
+
+use libwasm_jit::{CompileContext, CompileRequest, Options, RuntimeInfo};
+use std::sync::Arc;
+
+const LOOP: [u8; 2] = [0x03, 0x40];
+const END: u8 = 0x0b;
+const BR_IF_0: [u8; 2] = [0x0d, 0x00];
+const I32_ADD: u8 = 0x6a;
+const I32_SUB: u8 = 0x6b;
+const I32_NE: u8 = 0x47;
+const I32_LT_S: u8 = 0x48;
+const I32_LE_S: u8 = 0x4c;
+const I32_GT_U: u8 = 0x4b;
+const CALL_0: [u8; 2] = [0x10, 0x00];
+const DROP: u8 = 0x1a;
+
+/// The bound parameter, and the two locals the loops count with.
+const BOUND: u8 = 0;
+const I: u8 = 1;
+const J: u8 = 2;
+
+fn constant(mut value: i32) -> Vec<u8> {
+ let mut bytes = vec![0x41];
+ loop {
+ let byte = (value & 0x7f) as u8;
+ value >>= 7;
+ if (value == 0 && byte & 0x40 == 0) || (value == -1 && byte & 0x40 != 0) {
+ bytes.push(byte);
+ return bytes;
+ }
+ bytes.push(byte | 0x80);
+ }
+}
+
+fn get(local: u8) -> Vec<u8> {
+ vec![0x20, local]
+}
+
+fn set(local: u8) -> Vec<u8> {
+ vec![0x21, local]
+}
+
+fn tee(local: u8) -> Vec<u8> {
+ vec![0x22, local]
+}
+
+/// `local += step`, leaving the new value on the stack.
+fn step(local: u8, step: i32) -> Vec<u8> {
+ [get(local), constant(step), vec![I32_ADD], tee(local)].concat()
+}
+
+/// A loop that steps `local` and goes on while `test` holds of its new value and `bound`.
+fn counting_loop(local: u8, amount: i32, bound: Vec<u8>, test: u8, around: &[u8]) -> Vec<u8> {
+ [
+ LOOP.to_vec(),
+ around.to_vec(),
+ step(local, amount),
+ bound,
+ vec![test],
+ BR_IF_0.to_vec(),
+ vec![END],
+ ]
+ .concat()
+}
+
+/// `inner` as the body of a loop that counts I up to the bound parameter.
+fn in_a_loop(inner: Vec<u8>) -> Vec<u8> {
+ counting_loop(I, 1, get(BOUND), I32_NE, &inner)
+}
+
+/// How many interrupt checks the code of `(func (param i32) (local i32 i32) body)` keeps.
+fn check_count(body: &[u8]) -> usize {
+ let function = [&[1, 2, 0x7f], body, &[END]].concat();
+ let mut bytes = b"\0asm\x01\0\0\0".to_vec();
+ bytes.extend([0x01, 0x05, 0x01, 0x60, 0x01, 0x7f, 0x00]);
+ bytes.extend([0x03, 0x02, 0x01, 0x00]);
+ let size = u8::try_from(function.len()).expect("a small function");
+ bytes.extend([0x0a, size + 2, 0x01, size]);
+ bytes.extend(function);
+ let module = Arc::new(libwasm_engine::compile(&bytes).expect("a valid module"));
+ let request = CompileRequest {
+ stack_limit: 0,
+ module,
+ function: 0,
+ runtime: RuntimeInfo::default(),
+ options: Options {
+ verify_ir: true,
+ dump_ir: true,
+ ..Options::default()
+ },
+ osr: None,
+ };
+ let compiled = libwasm_jit::compile(&mut CompileContext::default(), &request).expect("the function compiles");
+ let dump = compiled.dump.expect("the dump was asked for");
+ dump.lines().filter(|line| line.trim() == "check_interrupt").count()
+}
+
+#[test]
+fn a_counting_loop_without_a_loop_around_it_keeps_its_check() {
+ assert_eq!(check_count(&counting_loop(I, 1, get(BOUND), I32_NE, &[])), 1);
+ assert_eq!(check_count(&counting_loop(I, 1, get(BOUND), I32_LT_S, &[])), 1);
+ assert_eq!(check_count(&counting_loop(I, 1, constant(6000), I32_NE, &[])), 1);
+}
+
+#[test]
+fn a_short_loop_loses_its_check_wherever_it_is() {
+ assert_eq!(check_count(&counting_loop(I, 1, constant(4000), I32_NE, &[])), 0);
+ assert_eq!(check_count(&counting_loop(I, 1, constant(4000), I32_LT_S, &[])), 0);
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 1, constant(4000), I32_NE, &[]))),
+ 1
+ );
+}
+
+#[test]
+fn a_test_of_inequality_that_starts_past_its_bound_goes_all_the_way_around() {
+ let body = [constant(4000), set(I), counting_loop(I, 1, constant(100), I32_NE, &[])].concat();
+ assert_eq!(check_count(&body), 1);
+}
+
+#[test]
+fn a_counting_loop_in_a_loop_loses_its_check() {
+ assert_eq!(check_count(&in_a_loop(counting_loop(J, 1, get(BOUND), I32_NE, &[]))), 1);
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 1, get(BOUND), I32_LT_S, &[]))),
+ 1
+ );
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, -1, get(BOUND), I32_GT_U, &[]))),
+ 1
+ );
+ // The value itself is the test.
+ let down = [LOOP.to_vec(), step(J, -1), BR_IF_0.to_vec(), vec![END]].concat();
+ assert_eq!(check_count(&in_a_loop(down)), 1);
+}
+
+#[test]
+fn what_can_go_past_its_bound_keeps_its_check() {
+ // A step of two can skip the bound, and wrapping around gets past any `<`.
+ assert_eq!(check_count(&in_a_loop(counting_loop(J, 2, get(BOUND), I32_NE, &[]))), 2);
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 2, get(BOUND), I32_LT_S, &[]))),
+ 2
+ );
+ // Everything is at most the largest number.
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 1, get(BOUND), I32_LE_S, &[]))),
+ 2
+ );
+ // The wrong way.
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, -1, get(BOUND), I32_LT_S, &[]))),
+ 2
+ );
+}
+
+#[test]
+fn a_bound_that_runs_away_keeps_its_check() {
+ // BOUND goes up with J, so that `!=` never holds it to anything.
+ let around = step(BOUND, 1);
+ let body = [around, vec![DROP]].concat();
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 1, get(BOUND), I32_NE, &body))),
+ 2
+ );
+}
+
+#[test]
+fn a_loop_that_calls_keeps_its_check() {
+ let body = [constant(0), CALL_0.to_vec()].concat();
+ assert_eq!(
+ check_count(&in_a_loop(counting_loop(J, 1, get(BOUND), I32_NE, &body))),
+ 2
+ );
+}
+
+#[test]
+fn a_subtraction_counts_too() {
+ let inner = [
+ LOOP.to_vec(),
+ get(J),
+ constant(1),
+ vec![I32_SUB],
+ tee(J),
+ get(BOUND),
+ vec![I32_NE],
+ BR_IF_0.to_vec(),
+ vec![END],
+ ]
+ .concat();
+ assert_eq!(check_count(&in_a_loop(inner)), 1);
+}