Skip to content

Truly independent web browser

LibJS: Inline callees that contain exception handlers

Aliaksandr Kalenikdaec8542a5bf
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 1c0fef3de23..0a05956edef 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -348,6 +348,13 @@ after the `Catch`, so a frame never enters and exits at the same pc. A catch whe
entry counts like an exit, so that code compiled before the handler first caught is discarded and
compiled again with the entry once catches keep happening there.
+Callees with handlers are inlined only if none of their handlers caught an exception before the
+compile, and their handlers get no blocks at all. An exception that one of them catches unwinds into
+the callee's materialized frame, the leave writes the frames, and the interpreter runs the handler.
+Inlined frames do not list their exception register in frame states, so the leave keeps the
+exception the unwinder put there. The leave counts such a catch like an exit, so that the code is
+compiled again once catches keep happening there, and the recompile calls the callee instead.
+
## 5. Dependencies and invalidation
Compiled code may assume facts that hold until a rare runtime event (`code::Dependency`): a
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
index f2347d326f2..74d1420161d 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
@@ -123,7 +123,8 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::GetArgumentCount => Handling::Native,
// NB: The interpreter runs it, and compiled code is entered after it
- // (see `build_catch_entries()`).
+ // (see `build_catch_entries()`). Handlers of inlined callees run
+ // in the interpreter to their end (see `can_inline()`).
O::Catch => Handling::Unsupported("starts an exception handler, which the interpreter runs"),
// Calls.
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 47290601374..462272eabe4 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -15,7 +15,9 @@
//! their operands as values and run in the frames of the inlined calls,
//! which the runtime publishes from their frame state (see
//! `SiteKind::Publish`) and compiled code pops again; calls that can, run
-//! without them (see `Op::CallDirect`).
+//! without them (see `Op::CallDirect`). The handlers of an inlined callee
+//! are not built: an exception one of them catches leaves compiled code,
+//! and the interpreter runs the handler in the callee's materialized frame.
//!
//! Returns jump to a continuation block in the caller, where the call's
//! result is the phi of the returned values.
@@ -109,7 +111,8 @@ pub(super) struct CallbackTarget {
/// Whether the callee can be built as an inlined call: its frame must not be
/// needed in memory outside generic nodes, its environments must stay those
-/// of its function object, and it must be fully compilable.
+/// of its function object, it must be fully compilable, and its exception
+/// handlers must never have caught anything.
fn can_inline(callee: &Function<'_>, virtual_arguments: bool) -> bool {
if !callee.written_constants.is_empty() {
return false;
@@ -120,6 +123,12 @@ fn can_inline(callee: &Function<'_>, virtual_arguments: bool) -> bool {
if virtual_arguments && arguments::can_create_virtual_arguments(callee, &instruction.instruction) {
return true;
}
+ // NB: Handlers of inlined callees are never built. An exception they catch leaves compiled code, and the
+ // interpreter runs the handler in the callee's materialized frame (see `translate::leave()` in the
+ // runtime). A handler that caught before would make the code leave again and again.
+ if opcode == OpCode::Catch {
+ return !super::has_run(callee.executable, instruction.pc);
+ }
let reads_frame_fields = matches!(
opcode,
OpCode::GetLexicalEnvironment
@@ -305,13 +314,20 @@ impl GraphBuilder<'_> {
/// The values a frame state of the function being walked lists for the
/// slots in `live`: those frame memory does not hold, or every one for
- /// virtual frames. Inlined callees that are not strict list all their
- /// passed arguments too, since their legacy `arguments` shows them in
- /// the frames exits and slow paths materialize.
+ /// virtual frames but their exception register. Inlined callees that are
+ /// not strict list all their passed arguments too, since their legacy
+ /// `arguments` shows them in the frames exits and slow paths materialize.
fn frame_state_values(&self, live: &BitSet) -> Vec<(u32, NodeId)> {
let is_virtual = self.function.is_virtual();
+ // NB: Materialized frames start with an empty exception register, and only the runtime writes it: when a
+ // handler of the frame catches an exception, before a leave writes the rest of the frame.
+ let exception_register = self
+ .function
+ .layout
+ .tracked_index(Operand::from_raw(crate::bytecode::EXCEPTION_REGISTER));
let mut values = live
.iter()
+ .filter(|slot| !is_virtual || Some(*slot) != exception_register)
.filter_map(|slot| match self.frame.slots[slot] {
SlotState::Value { node, in_sync } if is_virtual || !in_sync => {
Some((self.function.layout.operand_for_tracked_index(slot).raw(), node))
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index f1904025377..84eb4e95a86 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -1775,7 +1775,7 @@ pub(crate) mod inlining {
frame states:
[[FS0]]: pc 8 at {} frame [a0]
[[FS1]]: pc 8 after -> r5 {}
- [[FS2]]: e1 pc 8 after -> r5 {r0=#empty, r1=#empty, r2=#empty, r3=#empty, r4=#empty, r5=#empty} in [[FS1]]
+ [[FS2]]: e1 pc 8 after -> r5 {r0=#empty, r2=#empty, r3=#empty, r4=#empty, r5=#empty} in [[FS1]]
",
);
@@ -1923,9 +1923,9 @@ pub(crate) mod inlining {
frame states:
[[FS0]]: pc 8 at {} frame [a0]
[[FS1]]: pc 8 after -> r5 {}
- [[FS2]]: e1 pc 32 at {r0=#empty, r1=#empty, r2=#empty, r3=#empty, r4=#empty, r5=[[V11]]} in [[FS1]]
- [[FS3]]: e1 pc 48 after -> r7 {r0=#empty, r1=#empty, r2=#empty, r3=#empty, r4=#empty, r7=#empty} in [[FS1]]
- [[FS4]]: e1 pc 64 at {r0=#empty, r1=#empty, r2=#empty, r3=#empty, r4=#empty, r7=[[V21]]} in [[FS1]]
+ [[FS2]]: e1 pc 32 at {r0=#empty, r2=#empty, r3=#empty, r4=#empty, r5=[[V11]]} in [[FS1]]
+ [[FS3]]: e1 pc 48 after -> r7 {r0=#empty, r2=#empty, r3=#empty, r4=#empty, r7=#empty} in [[FS1]]
+ [[FS4]]: e1 pc 64 at {r0=#empty, r2=#empty, r3=#empty, r4=#empty, r7=[[V21]]} in [[FS1]]
",
);
}
@@ -1977,7 +1977,7 @@ pub(crate) mod inlining {
frame states:
[[FS0]]: pc 24 at {r6=#0} frame [a0]
[[FS1]]: pc 24 after -> r5 {r6=#0}
- [[FS2]]: e1 pc 24 at {r0=#empty, r1=#empty, r2=#empty, r3=#empty, r4=#empty, l0=#10} in [[FS1]]
+ [[FS2]]: e1 pc 24 at {r0=#empty, r2=#empty, r3=#empty, r4=#empty, l0=#10} in [[FS1]]
",
);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 632489a5c83..681a02f50da 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -199,7 +199,8 @@ pub enum SiteKind {
/// A slow path did not continue in compiled code: the runtime writes the
/// frame state into the compiled function's frame and the frames
/// compiled code pushed for a slow path in an inlined callee, as far as
- /// they are still on the stack. No exit: nothing is counted or recorded.
+ /// they are still on the stack. No exit: nothing is recorded, and only
+ /// an exception that a handler of an inlined callee caught is counted.
Leave,
/// A slow path or call in an inlined callee, which runs in the frames of
/// the inlined calls with its operands as values: the runtime pushes
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 9d3c46da378..d9bf26ece48 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -686,7 +686,8 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
/// it, and the slow path did not continue in compiled code. Writes the frame state of the leave into the compiled
/// function's frame `root`, and into the frames compiled code pushed for a slow path in an inlined callee, as far as
/// they are still on the stack: an exception may have unwound inner ones (and maybe the compiled function's, which then
-/// needs nothing), and the slow path may have pushed a callee for the interpreter above them.
+/// needs nothing), and the slow path may have pushed a callee for the interpreter above them. Counts an exception that
+/// a handler of an inlined callee caught like an exit.
pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, index: u32, dump: &RegisterDump) {
let site = code.site(index);
assert_eq!(site.kind, SiteKind::Leave);
@@ -713,6 +714,22 @@ pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, in
write(frame_of(frame), &frame_states[frame_states.len() - 2 - index]);
}
code.forget_materialized_objects(root.as_ptr());
+
+ // NB: A handler of an inlined callee that caught an exception left the callee's frame running at its Catch. The
+ // code was compiled before that handler caught anything. Such catches count like exits, so that the executable
+ // is compiled again once they keep happening, and then calls the callee.
+ let handler_of_inlined_callee_caught = pushed == frames.len()
+ && frames.first().is_some_and(|running| {
+ let running = frame_of(*running);
+ executable_of(running).bytecode()[running.program_counter.get() as usize] == OpCode::Catch as u8
+ });
+ if handler_of_inlined_callee_caught
+ && code.count_exit() >= EXIT_COUNT_BEFORE_DISCARD
+ && executable_of(frame_of(root)).jit_compile_state() == CompileState::Installed
+ {
+ vm.jit.count_coverage("discard-from-inlined-catch");
+ executable_of(frame_of(root)).discard_jit_code(vm);
+ }
}
/// Header translation for a slow path or call in an inlined callee, which takes its operands as values (see
diff --git a/Tests/LibJS/JIT/ir/inlined-exception-handlers.js b/Tests/LibJS/JIT/ir/inlined-exception-handlers.js
new file mode 100644
index 00000000000..1ac9f3a3fcf
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/inlined-exception-handlers.js
@@ -0,0 +1,71 @@
+// Callees with exception handlers, like the handler that closes the iterator of a for-of loop, are inlined if none of
+// their handlers caught an exception before the compile. Their handlers get no blocks. Callees whose handler caught
+// stay calls.
+
+class Writer {
+ constructor() {
+ this.values = [0, 0, 0, 0, 0, 0, 0, 0];
+ this.position = 0;
+ }
+ write(list) {
+ for (const value of list) this.values[this.position++] = value;
+ }
+}
+function writeAll(writer, list) {
+ writer.position = 0;
+ writer.write(list);
+ return writer.position;
+}
+const writer = new Writer();
+jit.prepare(Writer.prototype.write);
+jit.prepare(writeAll);
+for (let i = 0; i < 10; ++i) writeAll(writer, [1, 2, 3]);
+jit.compile(writeAll);
+
+// CHECK-FUNCTION: writeAll
+// CHECK-PASS: frame initialization
+// CHECK-NOT: CallDirect
+// CHECK: LoadElementAt Holey
+// CHECK-NOT: CallDirect
+
+function parsed(value) {
+ try {
+ if (typeof value !== "number") throw value;
+ return value + 1;
+ } catch (e) {
+ return -1;
+ }
+}
+function sumParsed(a, b) {
+ return parsed(a) + parsed(b);
+}
+jit.prepare(parsed);
+jit.prepare(sumParsed);
+for (let i = 0; i < 10; ++i) sumParsed(i, i);
+jit.compile(sumParsed);
+
+// CHECK-FUNCTION: sumParsed
+// CHECK-PASS: frame initialization
+// CHECK-NOT: CallDirect
+// CHECK: Int32Add
+// CHECK-NOT: CallDirect
+
+function caught(value) {
+ try {
+ if (typeof value !== "number") throw value;
+ return value + 1;
+ } catch (e) {
+ return -1;
+ }
+}
+function sumCaught(a, b) {
+ return caught(a) + caught(b);
+}
+jit.prepare(caught);
+jit.prepare(sumCaught);
+for (let i = 0; i < 10; ++i) sumCaught(i, "x");
+jit.compile(sumCaught);
+
+// CHECK-FUNCTION: sumCaught
+// CHECK-PASS: frame initialization
+// CHECK: CallDirect
diff --git a/Tests/LibJS/Runtime/jit/for-of-in-inlined-callees.js b/Tests/LibJS/Runtime/jit/for-of-in-inlined-callees.js
new file mode 100644
index 00000000000..da3c70bff1b
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/for-of-in-inlined-callees.js
@@ -0,0 +1,158 @@
+// Callees with exception handlers, like the handler that closes the iterator of a for-of loop, are inlined when none
+// of their handlers caught an exception before the compile. An exception that one of them catches leaves compiled code,
+// and the interpreter runs the handler in the callee's frame.
+//
+// NB: The functions come from the Function constructor, so that each run of a test (see LIBJS_TEST_REPEAT) compiles
+// new ones, whose handlers never caught anything.
+
+function prepared(source) {
+ const functions = new Function(source)();
+ for (const f of Object.values(functions)) jit.prepare(f);
+ return functions;
+}
+
+function compile(f, warm_up) {
+ for (let i = 0; i < 10; ++i) warm_up();
+ expect(jit.compile(f)).toBe(jit.enabled);
+}
+
+function closingIterable(values, log) {
+ return {
+ [Symbol.iterator]() {
+ let index = 0;
+ return {
+ next: () => (index < values.length ? { value: values[index++], done: false } : { done: true }),
+ return: () => {
+ log.push("return");
+ return {};
+ },
+ };
+ },
+ };
+}
+
+function* closingGenerator(values, log) {
+ try {
+ yield* values;
+ } finally {
+ log.push("return");
+ }
+}
+
+describe("for-of loops in inlined callees", () => {
+ test("an exception from the loop body closes the iterator once and reaches the caller's handler", () => {
+ const { run } = prepared(`
+ function sum(iterable, error) {
+ let total = 0;
+ for (const value of iterable) {
+ if (value < 0) throw error;
+ total += value;
+ }
+ return total;
+ }
+ function run(iterable, error) {
+ try {
+ return sum(iterable, error);
+ } catch (e) {
+ return e;
+ }
+ }
+ return { sum, run };
+ `);
+ const error = new Error("negative");
+ compile(run, () => {
+ run(closingIterable([1, 2], []), error);
+ run(closingGenerator([1, 2], []), error);
+ });
+ for (const iterable of [closingIterable, closingGenerator]) {
+ const log = [];
+ expect(run(iterable([1, -1, 2], log), error)).toBe(error);
+ expect(log).toEqual(["return"]);
+ }
+ expect(run([1, 2, 3], error)).toBe(6);
+ expect(run([1, -2, 3], error)).toBe(error);
+ });
+
+ test("break and return close a generator once", () => {
+ const { run } = prepared(`
+ function firstAbove(iterable, limit) {
+ for (const value of iterable) {
+ if (value > limit) return value;
+ }
+ return -1;
+ }
+ function countUpTo(iterable, limit) {
+ let count = 0;
+ for (const value of iterable) {
+ if (value > limit) break;
+ ++count;
+ }
+ return count;
+ }
+ function run(make, values, limit, log) {
+ return [firstAbove(make(values, log), limit), countUpTo(make(values, log), limit)];
+ }
+ return { firstAbove, countUpTo, run };
+ `);
+ compile(run, () => run(closingGenerator, [1, 5, 2], 3, []));
+ let log = [];
+ expect(run(closingGenerator, [1, 5, 2], 3, log)).toEqual([5, 1]);
+ expect(log).toEqual(["return", "return"]);
+ log = [];
+ expect(run(closingGenerator, [1, 2], 3, log)).toEqual([-1, 2]);
+ expect(log).toEqual(["return", "return"]);
+ log = [];
+ expect(run(closingIterable, [7, 1], 3, log)).toEqual([7, 0]);
+ expect(log).toEqual(["return", "return"]);
+ });
+});
+
+describe("exception handlers in inlined callees", () => {
+ test("a handler of an inlined callee gets the exception it caught", () => {
+ const { run } = prepared(`
+ function doubled(value) {
+ try {
+ if (typeof value !== "number") throw value;
+ return value * 2;
+ } catch (e) {
+ return "not a number: " + e;
+ }
+ }
+ function run(values) {
+ const results = [];
+ for (let i = 0; i < values.length; ++i) results.push(doubled(values[i]));
+ return results;
+ }
+ return { doubled, run };
+ `);
+ compile(run, () => run([1, 2, 3]));
+ expect(run([1, "a", 3])).toEqual([2, "not a number: a", 6]);
+ for (let i = 0; i < 100; ++i) expect(run([i, "b"])).toEqual([2 * i, "not a number: b"]);
+ });
+
+ test("an exception thrown in a nested inlined callee reaches the handler of the callee it is inlined into", () => {
+ const { run } = prepared(`
+ function checked(value) {
+ if (value < 0) throw value;
+ return value;
+ }
+ function sum(values) {
+ let total = 0;
+ try {
+ for (const value of values) total += checked(value);
+ } catch (e) {
+ return [e, total];
+ }
+ return total;
+ }
+ function run(values) {
+ return sum(values);
+ }
+ return { checked, sum, run };
+ `);
+ compile(run, () => run([1, 2, 3]));
+ expect(run([1, 2, -3, 4])).toEqual([-3, 3]);
+ for (let i = 0; i < 100; ++i) expect(run([i, -i - 1])).toEqual([-i - 1, i]);
+ expect(run([4, 5])).toBe(9);
+ });
+});