Truly independent web browser
LibJS: Continue frames in JIT code after the Catch of their handler
Andreas Kling53e0c58a2548
diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flapindex f83e13f9684..cb2e1573776 100644--- a/Libraries/LibJS/Interpreter/interpreter.flap+++ b/Libraries/LibJS/Interpreter/interpreter.flap@@ -1187,6 +1187,23 @@ inline fn continue_running_execution_context() @profiling {goto_handler(pc);}+# Continues the running frame in its executable's JIT code after the Catch+# that just ran, if the code has an entry there. Like at loop back edges, an+# exit from that code resumes after the Catch, so the frame always makes+# progress.+inline fn enter_jit_code_after_catch() @profiling {+ let executable = exec_ctx.executable;+ if executable.jit_compile_state == JIT_COMPILE_STATE_INSTALLED {+ let control: i32 = call_helper_with_two_arguments(asm_helper_enter_jit_code_after_catch, current_vm(), pc);+ if control != 0 {+ guard control > 0 else @cold {+ exit;+ };+ continue_running_execution_context();+ }+ }+}+# Starts running the frame that just became the running execution context,# at its entry: in its executable's JIT code if it has some, and in the# interpreter otherwise.@@ -2057,6 +2074,7 @@ handler Catch(record_value_feedback(value_feedback, exception);store(dst, exception);exec_ctx.exception = Value<Empty>;+ enter_jit_code_after_catch();dispatch_next;}diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex c2c0021f11b..74df30e7580 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -14,8 +14,8 @@ LibJS has two tiers: the bytecode interpreter, whose instructions keep per-sitefeedback, and this optimizing JIT. An executable that uses up its tier-up budget (calls and loopiterations) is snapshotted and compiled on one of the compile threads. The interpreter keeps runningit meanwhile; the main thread installs the code when the job finishes. Loops that run long enough-enter compiled code at their back edges (on-stack replacement), and generators and async functions-enter it where they resume (section 4.1). A call from compiled code into a function the interpreter+enter compiled code at their back edges (on-stack replacement), generators and async functions+enter it where they resume (section 4.1), and exception handlers after their `Catch` (section 4.2). A call from compiled code into a function the interpreterruns counts as several invocations of it (`callee-boost`): code hot enough to be compiled calls it,so it is likely to be hot as well, and there is no baseline tier to run it in meanwhile.@@ -42,8 +42,9 @@ and are rematerialized at every use. Every value has a representation (`Repr`):float64, bool or pointer. Cold blocks hold code that rarely runs (slow paths of checks); they come lastin the final block order.-Blocks without predecessors are entries: block 0, the on-stack replacement entries and the resume-entries of generators (section 4.1). Every block is reachable from one.+Blocks without predecessors are entries: block 0, the on-stack replacement entries, the resume+entries of generators (section 4.1) and the catch entries of exception handlers (section 4.2). Every+block is reachable from one.The compiled function's slots are SSA values. The builder tracks, per slot, whether only framememory holds it or which value holds it (and whether memory holds that too). Merges and loop@@ -300,6 +301,27 @@ generator's completion comes from its `AsyncGenerator` through the slow path. This compiled like any function's: its `Enter`, and for generators and async generators the initial`Yield`. Async functions have no initial `Yield`; their call runs the body until it first awaits.+### 4.2 Exception handlers++The graph has no exceptional edges. An exception thrown in compiled code, or in a call it makes,+leaves the code like any slow path that does not continue: the runtime unwinds to the handler+(`Vm::handle_exception()`), which puts the exception in the frame and moves its pc to the handler,+and the leave writes the frame state of the throwing node, whose live slots include everything live+into the handler (`bytecode/liveness.rs`). The interpreter then runs the handler's `Catch`, which+compiled code never builds.++Handlers start with a `Catch`, and the block after it is where the handler continues. Each handler+that caught an exception before the compile (the value feedback of its `Catch`) gets a catch entry+there (`builder/osr.rs`), like a resume entry: a block without predecessors that loads the slots live+there from the frame. Handlers that never caught anything get none, so their blocks are not built+and do not merge into the paths after them. Catch entries are listed in `Graph::osr_entries` too.++The profiling interpreter's `Catch` continues the frame in compiled code at the catch entry after it,+if the code has one (`entry_exit::helper_enter_jit_code_after_catch()`). An exit from there resumes+after the `Catch`, so a frame never enters and exits at the same pc. A catch where the code has no+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.+## 5. Dependencies and invalidationCompiled code may assume facts that hold until a rare runtime event (`code::Dependency`): adiff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rsindex c1e5830926c..950fa6f5832 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs@@ -122,7 +122,9 @@ pub fn handling(opcode: OpCode) -> Handling {| O::IsCallable| O::GetArgumentCount => Handling::Native,- O::Catch => Handling::Unsupported("starts an exception handler; handler blocks are not built"),+ // NB: The interpreter runs it, and compiled code is entered after it+ // (see `build_catch_entries()`).+ O::Catch => Handling::Unsupported("starts an exception handler, which the interpreter runs"),// Calls.O::Calldiff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 0a85862c44b..c03fc568b6a 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -610,6 +610,7 @@ impl<'a> GraphBuilder<'a> {if self.build_osr_entries {self.build_osr_entries()?;self.build_resume_entries()?;+ self.build_catch_entries()?;}self.build_function()?;diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rsindex 42def8b10ac..4903d047995 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs@@ -26,12 +26,20 @@//! entry block that loads them and jumps to the continuation's block, which//! compiled code reaches from nowhere else. The runtime enters there like at//! an on-stack replacement entry.+//!+//! Exception handlers are entered the same way. An exception thrown in+//! compiled code leaves it with the frame state of the throwing instruction,+//! which lists every value live into the handler, and the interpreter runs+//! the handler's `Catch`. Each handler that caught an exception before the+//! compile gets an entry block after its `Catch`, where the interpreter then+//! continues the frame in compiled code.use super::AbstractFrame;use super::Flow;use super::GraphBuilder;use crate::CompileFailure;use crate::bytecode::Instruction;+use crate::bytecode::Label;use crate::bytecode::OpCode;use crate::bytecode::RESERVED_REGISTER_COUNT;use crate::bytecode::cfg::BlockIndex;@@ -178,28 +186,73 @@ impl GraphBuilder<'_> {reason: "continuation that does not start a block",});}- // NB: An on-stack replacement entry at a back edge that starts the- // block resumes the frame there just the same.- if target_block.rpo_number.is_none() || self.graph.osr_entries.iter().any(|(entry_pc, _)| *entry_pc == pc) {+ if target_block.rpo_number.is_some() {+ self.build_entry_into_block(target)?;+ }+ }+ Ok(())+ }++ /// Builds an entry block for every exception handler of the compiled+ /// function that caught an exception and whose handler range is+ /// reachable, after the resume entries, before any of its bytecode blocks+ /// is started. Handlers start with a `Catch`, which the interpreter runs:+ /// compiled code never builds it, and is entered after it, where the+ /// handler's block continues. Handlers that never caught anything get no+ /// entry, which would merge into the paths after them.+ pub(super) fn build_catch_entries(&mut self) -> Result<(), CompileFailure> {+ debug_assert!(!self.function.is_virtual());+ for handler in 0..self.function.cfg.blocks.len() {+ let handler_block = &self.function.cfg.blocks[handler];+ let reachable = handler_block+ .exception_predecessors+ .iter()+ .any(|predecessor| self.function.cfg.blocks[*predecessor].rpo_number.is_some());+ let catch = &self.function.instructions[handler_block.instructions.start];+ if !reachable || catch.instruction.opcode() != OpCode::Catch {continue;}- let block = self.start_new_block(Vec::new());- self.frame = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());- let start = target_block.instructions.start;- self.function.instruction_index = start;- self.function.pc = pc;- self.function.eager_frame_state = None;- let live = self.function.liveness.live_in(start).clone();- for slot in live.iter() {- if slot >= RESERVED_REGISTER_COUNT as usize {- let operand = self.function.layout.operand_for_tracked_index(slot);- self.read_tracked(slot, operand);- }+ if !(self.has_run)(catch.pc) {+ self.graph.uncaught_handlers.push(catch.pc);+ continue;+ }+ // NB: The Catch ends its block, which falls through to the block+ // that continues the handler.+ let Ok(target) = self.block_for_label(Label(catch.next_pc())) else {+ continue;+ };+ self.build_entry_into_block(target)?;+ }+ Ok(())+ }++ /// Builds an entry block for a frame whose memory holds every value live+ /// at the start of `target`: it loads them and jumps there. The runtime+ /// enters it like an on-stack replacement entry.+ fn build_entry_into_block(&mut self, target: BlockIndex) -> Result<(), CompileFailure> {+ let target_block = &self.function.cfg.blocks[target];+ let pc = target_block.start_pc;+ // NB: An on-stack replacement entry at a back edge that starts the+ // block enters the frame there just the same.+ if self.graph.osr_entries.iter().any(|(entry_pc, _)| *entry_pc == pc) {+ return Ok(());+ }+ let block = self.start_new_block(Vec::new());+ self.frame = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());+ let start = target_block.instructions.start;+ self.function.instruction_index = start;+ self.function.pc = pc;+ self.function.eager_frame_state = None;+ let live = self.function.liveness.live_in(start).clone();+ for slot in live.iter() {+ if slot >= RESERVED_REGISTER_COUNT as usize {+ let operand = self.function.layout.operand_for_tracked_index(slot);+ self.read_tracked(slot, operand);}- self.end_with_jump(target)?;- self.graph.osr_entries.push((pc, block));- self.note_loops_entered_at(&[target]);}+ self.end_with_jump(target)?;+ self.graph.osr_entries.push((pc, block));+ self.note_loops_entered_at(&[target]);Ok(())}diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rsindex 2f1b5b0708a..dc8e9d9b23b 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs@@ -6,11 +6,12 @@//! Control flow graph of an executable's bytecode.//!-//! Blocks start at the entry, at jump targets, after terminators, and at the-//! start, end and target of every exception handler range, so every block lies-//! entirely inside or outside each handler range. Edges come in two kinds:-//! normal control flow (jumps and fallthrough) and exceptional control flow-//! from a block inside a handler range to the handler.+//! Blocks start at the entry, at jump targets, after terminators, after+//! `Catch`, and at the start, end and target of every exception handler range,+//! so every block lies entirely inside or outside each handler range. Edges+//! come in two kinds: normal control flow (jumps and fallthrough) and+//! exceptional control flow from a block inside a handler range to the+//! handler.//!//! Generator continuations (the labels of `Await`, `Yield` and//! `YieldIteratorResult`) are treated as ordinary successors: the frame@@ -19,6 +20,7 @@use super::DecodedInstruction;use super::ExceptionHandler;use super::FrameLayout;+use super::OpCode;use super::RESERVED_REGISTER_COUNT;use crate::bitset::BitSet;use std::ops::Range;@@ -146,7 +148,11 @@ impl Cfg {}});result?;- if instruction.instruction.is_terminator() && index + 1 < instructions.len() {+ // NB: Compiled code enters handlers after their Catch, which the+ // interpreter runs (see `build_catch_entries()`).+ let ends_block =+ instruction.instruction.is_terminator() || instruction.instruction.opcode() == OpCode::Catch;+ if ends_block && index + 1 < instructions.len() {is_leader[index + 1] = true;}}@@ -497,14 +503,16 @@ mod tests {.iter().map(|block| block.instructions.clone()).collect::<Vec<_>>();- assert_eq!(instruction_ranges, [0..1, 1..3, 3..5, 5..6]);+ // The Catch ends its block.+ assert_eq!(instruction_ranges, [0..1, 1..3, 3..4, 4..5, 5..6]);assert_eq!(cfg.blocks[0].successors, [1]);assert!(cfg.blocks[1].successors.is_empty());assert_eq!(cfg.blocks[1].exception_handler, Some(2));assert_eq!(cfg.blocks[2].exception_predecessors, [1]);assert_eq!(cfg.blocks[2].predecessor_count(), 0);- assert_eq!(cfg.reverse_post_order, [0, 1, 2]);- assert_eq!(cfg.blocks[3].rpo_number, None);+ assert_eq!(cfg.blocks[2].successors, [3]);+ assert_eq!(cfg.reverse_post_order, [0, 1, 2, 3]);+ assert_eq!(cfg.blocks[4].rpo_number, None);}#[test]diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex ed064b36851..5314c6bd7df 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -31,6 +31,8 @@ pub struct CompiledCode {/// from where a frame running in the interpreter may reach one of them/// on a later iteration.pub osr_outer_loop_back_edges: Vec<u32>,+ /// See `ir::Graph::uncaught_handlers`.+ pub uncaught_handlers: Vec<u32>,/// The sites of the code, by index: exit and leave stubs pass the index of/// theirs to the runtime, and calls in inlined callees name theirs.pub sites: Vec<Site>,diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex be1c447a847..eaed95f3d1d 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -2001,8 +2001,10 @@ pub struct Graph {/// them, take at once. Compiled code checks at entry that they fit.pub materialized_frame_bytes: u64,/// On-stack replacement entries: blocks without predecessors where code- /// already running in the interpreter enters compiled code, with the pc of- /// the loop back edge each one starts at. The frame holds every value.+ /// already running in the interpreter enters compiled code, with the pc+ /// each one starts at: a loop back edge, the continuation of a generator,+ /// or the instruction after the `Catch` of an exception handler. The frame+ /// holds every value.pub osr_entries: Vec<(u32, BlockId)>,/// The pcs of the loop back edges in the loops of the on-stack/// replacement entries (including those of the entries), from where a@@ -2012,6 +2014,10 @@ pub struct Graph {/// on-stack replacement entries, from where a frame running in the/// interpreter may reach an entry on a later iteration.pub osr_outer_loop_back_edges: Vec<u32>,+ /// The pcs of the `Catch` of the exception handlers that got no catch+ /// entry because they never caught an exception before the compile (see+ /// `builder::osr`). A compile after they caught gives them one.+ pub uncaught_handlers: Vec<u32>,/// The register-saving `CallSlowPath` nodes that may run before the/// frame is initialized, and so initialize it first if it is not.pub slow_paths_initializing_frame: Vec<NodeId>,diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 570a29937e5..5bc26b66ec4 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -132,6 +132,7 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(},osr_loop_back_edges: graph.osr_loop_back_edges,osr_outer_loop_back_edges: graph.osr_outer_loop_back_edges,+ uncaught_handlers: graph.uncaught_handlers,embedded_cells: graph.embedded_cells,dependencies: graph.dependencies,invalidation_patches: generated.invalidation_patches,diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rsindex 50c30627573..e149b9c6d95 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs@@ -54,6 +54,10 @@ impl RuntimeFunctions for Runtime {crate::jit::entry_exit::helper_enter_jit_code(vm_from_helper_argument(vm)) as u64}+ fn helper_enter_jit_code_after_catch(vm: u64, pc: u64) -> u64 {+ crate::jit::entry_exit::helper_enter_jit_code_after_catch(vm_from_helper_argument(vm), pc as u32) as u64+ }+fn helper_empty_string(vm: u64) -> u64 {operators::helper_empty_string(vm_from_helper_argument(vm))}diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 9962ce6459b..f36cff0871e 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -118,7 +118,7 @@ pub struct JitCode {/// keep their addresses for as long as the code may run.embedded_cells: Vec<Gc<CellHeader>>,snapshot_executables: Vec<SnapshotExecutable>,- /// Where a frame running in the interpreter at the loop back edge `pc` can continue in this code.+ /// Where a frame running in the interpreter at `pc` can continue in this code (see `osr_entry()`).osr_entries: Vec<(u32, JitEntry)>,/// The loop back edges from where a frame running in the interpreter reaches one of the `osr_entries` without/// leaving the loop it is in.@@ -126,6 +126,9 @@ pub struct JitCode {/// The loop back edges in the loops around those of the `osr_entries`, from where a frame running in the/// interpreter may reach one of them on a later iteration.osr_outer_loop_back_edges: Vec<u32>,+ /// The pcs of the `Catch` of the exception handlers that have no catch entry only because they never caught an+ /// exception before the compile.+ uncaught_handlers: Vec<u32>,/// Identifies the code among all code the VM installed, for the dependencies it registers (see/// `super::dependencies`).id: u64,@@ -165,6 +168,7 @@ impl JitCode {osr_entries,osr_loop_back_edges,osr_outer_loop_back_edges: Vec::new(),+ uncaught_handlers: Vec::new(),id: 0,invalidation_patches: Vec::new(),invalidated: Cell::new(false),@@ -184,6 +188,17 @@ impl JitCode {self}+ pub fn with_uncaught_handlers(mut self, uncaught_handlers: Vec<u32>) -> Self {+ self.uncaught_handlers = uncaught_handlers;+ self+ }++ /// Whether the handler whose `Catch` is at `pc` has no catch entry only because it never caught an exception+ /// before the compile, so that a compile now would give it one.+ pub fn compiled_before_handler_caught(&self, pc: u32) -> bool {+ self.uncaught_handlers.contains(&pc)+ }+pub fn id(&self) -> u64 {self.id}@@ -207,7 +222,8 @@ impl JitCode {}/// The entry at `pc` for a frame whose memory holds every value live there: an on-stack replacement entry at a- /// loop back edge, or the resume entry at a continuation of a generator's suspension.+ /// loop back edge, the resume entry at a continuation of a generator's suspension, or the catch entry after the+ /// `Catch` of an exception handler.pub fn osr_entry(&self, pc: u32) -> Option<JitEntry> {self.osr_entries.iter()diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rsindex 124deec3847..5131f291307 100644--- a/Libraries/LibJS/Rust/src/jit/disabled.rs+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs@@ -160,6 +160,10 @@ pub mod entry_exit {pub fn helper_enter_jit_code(_vm: &Vm) -> i64 {unreachable!("only the profiling interpreter enters JIT code");}++ pub fn helper_enter_jit_code_after_catch(_vm: &Vm, _pc: u32) -> i64 {+ unreachable!("only the profiling interpreter enters JIT code");+ }}pub mod translate {diff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rsindex 9273888dfc0..9505229e7dd 100644--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs@@ -12,11 +12,14 @@ use core::ptr::NonNull;use libjs_abi::register;use libjs_jit::code::SiteKind;-use super::code::{CompileState, EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP, EntryStatus, JitEntry, JitResult};+use super::code::{+ CompileState, EXIT_COUNT_BEFORE_DISCARD, EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP, EntryStatus, JitEntry, JitResult,+};use super::translate::{self, RegisterDump};use super::{executable_of, frame_of, frames_above};use crate::bytecode::executable::Executable;use crate::bytecode::feedback::tier_up_costs;+use crate::bytecode::{instruction_at, op};use crate::interpreter::vm::Vm;use crate::layout::execution_context::ExecutionContext;use crate::layout::value::Value;@@ -106,6 +109,17 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32/// Resumes the running frame, a generator's frame suspended at the continuation `pc`, in its executable's JIT code if/// that has a resume entry there. Returns how the code returned, if it ran.pub fn enter_jit_code_at_continuation(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32) -> Option<JitResult> {+ enter_jit_code_with_frame_in_memory(vm, frame, pc, "resume-entry")+}++/// Continues the running frame at `pc`, where its memory holds every value live, in its executable's JIT code if that+/// has an entry there. Returns how the code returned, if it ran.+fn enter_jit_code_with_frame_in_memory(+ vm: &Vm,+ frame: NonNull<ExecutionContext>,+ pc: u32,+ coverage_key: &str,+) -> Option<JitResult> {assert_eq!(vm.running_execution_context(), Some(frame));let frame_ref = frame_of(frame);let executable = executable_of(frame_ref);@@ -116,11 +130,53 @@ pub fn enter_jit_code_at_continuation(vm: &Vm, frame: NonNull<ExecutionContext>,.jit_code(vm).expect("the executable has JIT code").osr_entry(pc)?;- vm.jit.count_coverage("resume-entry");+ vm.jit.count_coverage(coverage_key);frame_ref.program_counter.set(pc);Some(enter_from_native_code(vm, frame, entry))}+/// `asm_helper_enter_jit_code_after_catch`: the interpreter calls this when it ran the `Catch` at `pc` in the running+/// frame, whose executable has JIT code. Continues the frame in the code's catch entry after the Catch, if it has one+/// (see `libjs_jit::builder::osr`). Returns the interpreter's control word: 0 to continue interpreting after the+/// Catch, and otherwise what `control_after_entry()` returns.+pub fn helper_enter_jit_code_after_catch(vm: &Vm, pc: u32) -> i64 {+ let frame = vm.running_execution_context().expect("a frame is running");+ let executable = executable_of(frame_of(frame));+ let next_pc = pc + instruction_at::<op::Catch>(&executable, pc).length();+ if let Some(result) = enter_jit_code_with_frame_in_memory(vm, frame, next_pc, "catch-entry") {+ return control_after_entry(vm, result);+ }+ // NB: Code compiled before the handler first caught an exception has no entry after its Catch. Catches there count+ // like exits, so that the executable is compiled again with the entry once they keep happening. Handlers+ // without an entry for other reasons would get none from a compile either.+ if !can_enter_jit_code(vm, &executable) {+ return 0;+ }+ let code = executable.jit_code(vm).expect("the executable has JIT code");+ if code.compiled_before_handler_caught(pc) && code.count_exit() >= EXIT_COUNT_BEFORE_DISCARD {+ vm.jit.count_coverage("discard-from-catch");+ executable.discard_jit_code(vm);+ }+ 0+}++/// The interpreter's control word after JIT code it entered in the running frame returned: 1 to continue interpreting+/// the running execution context, negative to leave the interpreter.+pub fn control_after_entry(vm: &Vm, result: JitResult) -> i64 {+ match result.status {+ EntryStatus::Returned => {+ // NB: Like the interpreter's Return, a frame without a caller, or whose caller waits in native code,+ // returns from the interpreter.+ let frame = vm.running_execution_context_ref();+ let exits_interpreter = frame.caller_frame.get().is_null() || frame.returns_to_native_caller.get();+ vm.return_from_running_frame(Value(result.value));+ if exits_interpreter { -1 } else { 1 }+ }+ EntryStatus::Resume => 1,+ EntryStatus::ExitInterpreter => -1,+ }+}+/// Runs the frame that just became the running execution context in its executable's JIT code, if it can, for the/// interpreter's Call, which found that the executable has JIT code. Returns the control word of the interpreter's/// `asm_helper_enter_jit_code`: negative if the interpreter leaves, 1 if the code returned (the frame is still thediff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex 4c9593ff5c1..d00306af0ad 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -10,7 +10,7 @@ use core::ptr::NonNull;use libjs_jit::code::CompiledCode;-use super::code::{CompileState, EntryStatus, JitCode, SnapshotExecutable};+use super::code::{CompileState, JitCode, SnapshotExecutable};use super::compile_queue::CompileResult;use super::executable_memory::ExecutableMemory;use super::snapshot::capture_snapshot;@@ -22,7 +22,6 @@ use crate::jit::InterpreterTier;use crate::jit::options::Options;use crate::layout::cell::{CellHeader, Gc};use crate::layout::function_object::EcmascriptFunctionObject;-use crate::layout::value::Value;use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;use crate::runtime::realm_watchpoints;@@ -264,18 +263,7 @@ pub fn tier_up_check(vm: &Vm, encoded_pc: u64) -> i64 {}return 0;};- match result.status {- EntryStatus::Returned => {- // NB: Like the interpreter's Return, a frame without a caller, or whose caller waits in native code,- // returns from the interpreter.- let frame = vm.running_execution_context_ref();- let exits_interpreter = frame.caller_frame.get().is_null() || frame.returns_to_native_caller.get();- vm.return_from_running_frame(Value(result.value));- if exits_interpreter { -1 } else { 1 }- }- EntryStatus::Resume => 1,- EntryStatus::ExitInterpreter => -1,- }+ super::entry_exit::control_after_entry(vm, result)}/// Whether the code of a finished compile goes into executable memory. Code whose dependencies stopped holding since@@ -315,7 +303,8 @@ fn install(snapshot,).with_invalidation(id, compiled.invalidation_patches)- .with_osr_outer_loop_back_edges(compiled.osr_outer_loop_back_edges);+ .with_osr_outer_loop_back_edges(compiled.osr_outer_loop_back_edges)+ .with_uncaught_handlers(compiled.uncaught_handlers);vm.jit.dependents.register(vm, executable, id, &compiled.dependencies);// NB: Code may be installed while frames of the executable loop in the interpreter, because the compile was// queued (from the tier-up check of another executable, like a callee's), or because they exited from thediff --git a/Tests/LibJS/JIT/ir/catch-entries.js b/Tests/LibJS/JIT/ir/catch-entries.jsnew file mode 100644index 00000000000..e9d594f3a5b--- /dev/null+++ b/Tests/LibJS/JIT/ir/catch-entries.js@@ -0,0 +1,44 @@+// An exception thrown in compiled code leaves it, and the interpreter runs the Catch of the handler, which continues+// the frame in compiled code at an entry block after it. The entry loads the slots live there from the frame, like the+// resume entry of a generator, and jumps to the block that continues the handler. A handler that never caught an+// exception gets no entry, and its blocks are not built.++function thrower(x) {+ if (x & 1) throw x;+ return x;+}++function sum(n) {+ let total = 0;+ for (let i = 0; i < n; ++i) {+ try {+ total += thrower(i);+ } catch (e) {+ total -= e;+ }+ try {+ total += thrower(0);+ } catch (e) {+ total = 0;+ }+ }+ return total;+}+jit.prepare(sum);+for (let i = 0; i < 10; ++i) sum(10);+jit.compile(sum);++// CHECK-FUNCTION: sum+// CHECK-PASS: graph building+// CHECK: {{^}}b0:+// CHECK: {{^}}[[ENTRY:b[0-9]+]]:{{$}}+// CHECK-NEXT: LoadSlot+// CHECK: Jump [[HANDLER:b[0-9]+]]+// CHECK: {{^}}[[HANDLER]] (pc [[PC:[0-9]+]]) <- [[ENTRY]]:+// CHECK-NEXT: LoadSlot r4+// CHECK-NEXT: SetLexicalEnvironment+// CHECK: osr entry at pc [[PC]]: [[ENTRY]]+// CHECK-COUNT-1: osr entry at pc+// CHECK-COUNT-1: SetLexicalEnvironment++console.log(sum(100));diff --git a/Tests/LibJS/Runtime/jit/exception-handlers.js b/Tests/LibJS/Runtime/jit/exception-handlers.jsnew file mode 100644index 00000000000..a940a8424ee--- /dev/null+++ b/Tests/LibJS/Runtime/jit/exception-handlers.js@@ -0,0 +1,177 @@+// Exception handlers run in compiled code: an exception thrown in compiled code leaves it with every value live into+// the handler written to the frame, the interpreter runs the handler's Catch, and the frame continues in compiled code+// after it. Finally blocks are handlers too, and so are the handlers that close iterators.+//+// NB: The functions come from the Function constructor, so that each run of a test (see LIBJS_TEST_REPEAT) compiles+// new ones.++function prepared(...parameters_and_body) {+ const make = new Function(+ "jit",+ "thrower",+ `const f = function (${parameters_and_body.slice(0, -1).join(", ")}) { ${parameters_and_body.at(-1)} }; jit.prepare(f); return f;`+ );+ return make(jit, thrower);+}++function thrower(value) {+ if (value & 1) throw value;+ return value;+}++function compile(f, warm_up) {+ for (let i = 0; i < 10; ++i) warm_up();+ expect(jit.compile(f)).toBe(jit.enabled);+}++const checksCompiledCode = () => jit.enabled && !jit.forcesExits;++describe("exception handlers in compiled code", () => {+ test("catch exceptions of calls, with the values live into the handler", () => {+ const sum = prepared(+ "n",+ "let total = 0; let caught = 0; let compiled = true; for (let i = 0; i < n; ++i) { const before = total; try { total += 100; total += thrower(i); } catch (e) { total = before - e; ++caught; compiled &&= jit.inCompiledCode(); } } return [total, caught, compiled];"+ );+ compile(sum, () => sum(10));+ const [total, caught, compiled] = sum(1000);+ let expected = 0;+ for (let i = 0; i < 1000; ++i) expected = i & 1 ? expected - i : expected + 100 + i;+ expect(total).toBe(expected);+ expect(caught).toBe(500);+ if (checksCompiledCode()) expect(compiled).toBeTrue();+ });++ test("run finally blocks after normal completions, returns, breaks and exceptions", () => {+ const run = prepared(+ "n",+ "const log = []; for (let i = 0; i < n; ++i) { try { if (i % 4 === 1) continue; if (i % 4 === 2) break; thrower(i); log.push('try ' + i); } catch (e) { log.push('catch ' + e); } finally { log.push('finally ' + i); } } return log;"+ );+ const returns = prepared(+ "x",+ "let state = 'start'; try { state = 'try'; if (x) return state; thrower(1); } catch (e) { state = 'catch ' + e; return state; } finally { state += ' finally'; } return state;"+ );+ compile(run, () => run(3));+ compile(returns, () => [returns(true), returns(false)]);+ expect(run(2)).toEqual(["try 0", "finally 0", "finally 1"]);+ expect(run(10)).toEqual(["try 0", "finally 0", "finally 1", "finally 2"]);+ expect(returns(true)).toBe("try");+ expect(returns(false)).toBe("catch 1");+ });++ test("rethrow from catch and finally blocks to outer handlers", () => {+ const nested = prepared(+ "n",+ "let log = ''; for (let i = 0; i < n; ++i) { try { try { thrower(i); log += 'a'; } catch (e) { log += 'b'; throw e + 1; } finally { log += 'c'; } } catch (e) { log += e; } } return log;"+ );+ const propagates = prepared("x", "try { thrower(x); } finally { if (x === 3) return 'overridden'; }");+ compile(nested, () => nested(4));+ compile(propagates, () => {+ try {+ propagates(1);+ } catch {}+ propagates(2);+ });+ expect(nested(6)).toBe("acbc2acbc4acbc6");+ let thrown;+ try {+ propagates(5);+ } catch (e) {+ thrown = e;+ }+ expect(thrown).toBe(5);+ expect(propagates(3)).toBe("overridden");+ expect(propagates(4)).toBeUndefined();+ });++ test("catch exceptions thrown by property accesses, builtins and checks", () => {+ const access = prepared(+ "values",+ "const results = []; for (const value of values) { try { results.push(value.x.y); } catch (e) { results.push(e.constructor.name); } try { results.push(JSON.parse(value.text)); } catch (e) { results.push(e.constructor.name); } } return results;"+ );+ const getter = {+ get x() {+ throw new RangeError();+ },+ };+ compile(access, () =>+ access([+ { x: { y: 1 }, text: "1" },+ { x: null, text: "{" },+ ])+ );+ expect(access([{ x: { y: 2 }, text: "[3]" }, {}, getter, { x: { y: 4 }, text: "}" }])).toEqual([+ 2,+ [3],+ "TypeError",+ "SyntaxError",+ "RangeError",+ "SyntaxError",+ 4,+ "SyntaxError",+ ]);+ });++ test("catch exceptions thrown with throw statements in the same function", () => {+ const classify = prepared(+ "values",+ "let total = 0; for (const value of values) { try { if (typeof value !== 'number') throw value; total += value; } catch (e) { total += e.length; } } return total;"+ );+ compile(classify, () => classify([1, "ab", 2]));+ expect(classify([1, 2, "abc", 3, "de", [1, 2, 3, 4]])).toBe(15);+ });++ test("handle exceptions in handlers that first catch after the code was compiled", () => {+ const late = prepared(+ "n, limit",+ "let total = 0; for (let i = 0; i < n; ++i) { try { if (i >= limit) throw i; total += i; } catch (e) { total -= e; } } return total;"+ );+ compile(late, () => late(10, 100));+ let expected = 0;+ for (let i = 0; i < 300; ++i) expected += i < 50 ? i : -i;+ for (let run = 0; run < 20; ++run) expect(late(300, 50)).toBe(expected);+ });++ test("close iterators of loops left by exceptions", () => {+ const closes = prepared(+ "iterable",+ "let total = 0; try { for (const value of iterable) { total += thrower(value); } } catch (e) { total += 1000 * e; } return total;"+ );+ let closed = 0;+ const iterable = values => ({+ [Symbol.iterator]() {+ let index = 0;+ return {+ next: () => (index < values.length ? { value: values[index++], done: false } : { done: true }),+ return: () => {+ ++closed;+ return {};+ },+ };+ },+ });+ compile(closes, () => [closes(iterable([2, 4])), closes(iterable([2, 3]))]);+ closed = 0;+ expect(closes(iterable([2, 4, 6]))).toBe(12);+ expect(closes(iterable([2, 4, 5, 6]))).toBe(5006);+ expect(closed).toBe(1);+ });+});++describe("exception handlers in compiled generators", () => {+ test("catch exceptions between yields and thrown into them", () => {+ const GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor;+ const generator = new GeneratorFunction(+ "thrower",+ "n",+ "for (let i = 0; i < n; ++i) { try { yield thrower(i); } catch (e) { yield 'caught ' + e; } }"+ );+ jit.prepare(generator);+ compile(generator, () => [...generator(thrower, 4)]);+ expect([...generator(thrower, 4)]).toEqual([0, "caught 1", 2, "caught 3"]);+ const resumed = generator(thrower, 2);+ expect(resumed.next()).toEqual({ value: 0, done: false });+ expect(resumed.throw("thrown")).toEqual({ value: "caught thrown", done: false });+ expect(resumed.next()).toEqual({ value: "caught 1", done: false });+ expect(resumed.next()).toEqual({ value: undefined, done: true });+ });+});