Truly independent web browser
LibJS/JIT: Discard code that leaves a long call in the interpreter
Andreas Klingd8add8cd0c98
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex f2534f7a5b1..f73fcf64b17 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -8,6 +8,8 @@use core::cell::{Cell, OnceCell, RefCell};use core::ffi::c_void;+use core::ops::ControlFlow;+use core::ptr::NonNull;use libjs_jit::bytecode::{EnvironmentCoordinate, decode_instruction};pub use libjs_jit::code::INLINED_CALL_SITE_BIT;@@ -132,6 +134,10 @@ pub enum InlinedFunction {/// `libjs_jit_exit()` finds it through the frame's executable), even once discarded.pub struct JitCode {exit_count: Cell<u32>,+ /// The frames of the executable running in the interpreter after the code exited into them or was installed+ /// in them, and how many more tier-up checks each may make at back edges from where it reaches no on-stack+ /// replacement entry before the code is discarded. Frame addresses are identities only, never dereferenced.+ interpreted_frames: RefCell<Vec<(usize, u32)>>,memory: ExecutableMemory,entry: JitEntry,sites: Vec<Site>,@@ -202,6 +208,7 @@ impl JitCode {.collect();Self {exit_count: Cell::new(0),+ interpreted_frames: RefCell::new(Vec::new()),memory,entry,sites,@@ -359,6 +366,50 @@ impl JitCode {self.exit_count.set(count);count}++ /// Notes that `frame`, a frame of the code's executable, runs in the interpreter after the code exited into it or+ /// was installed in it, and may make `checks` tier-up checks at back edges from where it reaches no on-stack+ /// replacement entry before the code is discarded.+ pub fn note_interpreted_frame(&self, frame: NonNull<ExecutionContext>, checks: u32) {+ let identity = frame.as_ptr() as usize;+ let mut frames = self.interpreted_frames.borrow_mut();+ if let Some((_, left)) = frames.iter_mut().find(|(frame, _)| *frame == identity) {+ *left = checks;+ } else {+ frames.push((identity, checks));+ }+ }++ /// Forgets returned frames before an exit records another one, so a long-lived callee's code cannot accumulate+ /// identities of frames materialized by exits from many different inlined callers.+ pub fn forget_inactive_interpreted_frames(&self, vm: &Vm) {+ self.interpreted_frames.borrow_mut().retain(|(identity, _)| {+ let mut live = false;+ vm.for_each_live_execution_context(|frame| {+ if core::ptr::from_ref(frame) as usize == *identity {+ live = true;+ ControlFlow::Break(())+ } else {+ ControlFlow::Continue(())+ }+ });+ live+ });+ }++ /// Counts a tier-up check of `frame` at a back edge from where it reaches no on-stack replacement entry, and+ /// returns whether the frame made all it may. Other frames that run in the interpreter finish there like before.+ pub fn count_fruitless_loop_check(&self, frame: NonNull<ExecutionContext>) -> bool {+ let mut frames = self.interpreted_frames.borrow_mut();+ let Some((_, left)) = frames+ .iter_mut()+ .find(|(identity, _)| *identity == frame.as_ptr() as usize)+ else {+ return false;+ };+ *left = left.saturating_sub(1);+ *left == 0+ }}unsafe impl Trace for JitCode {@@ -420,6 +471,17 @@ pub const EXIT_COUNT_BEFORE_DISCARD: u32 = 10;/// costs more than code that exits as often elsewhere.pub const EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP: u32 = 5;+/// After this many tier-up checks of the frame that JIT code last exited into, at back edges from where it reaches no+/// on-stack replacement entry, the code is discarded even if it exited fewer times: a long call that exited once into+/// a loop that never ran before the compile (like a driver running one loop after another) would otherwise run the+/// rest of the loop in the interpreter.+pub const FRUITLESS_LOOP_CHECKS_AFTER_EXIT: u32 = 8;++/// Like FRUITLESS_LOOP_CHECKS_AFTER_EXIT, for the frame whose tier-up check installed the code. It is higher: a frame+/// that moved on from the loop its compile was for may soon return, and later calls enter the code at its start+/// rather than at a loop nested in others, where the code optimizes less.+pub const FRUITLESS_LOOP_CHECKS_AFTER_INSTALL: u32 = 256;+/// An executable whose code was discarded this often in a row without its exits teaching it anything is not compiled/// again. Discards after exits at sites the code did not know of make progress: each site is recorded once, and/// recompiles no longer speculate there, so code that keeps reaching new paths (like a dispatcher whose program movesdiff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rsindex 2744960d236..1e4176d0123 100644--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs@@ -94,8 +94,10 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32let runs_once = frame_ref.function.get().is_none();if code.reaches_osr_entry_from(pc) {executable.head.tier_up_budget.set(tier_up_costs::LOOP_ITERATION);- } else if (runs_once || code.exit_count() >= EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP)- && !code.may_reach_osr_entry_from(pc)+ } else if !code.may_reach_osr_entry_from(pc)+ && (runs_once+ || code.exit_count() >= EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP+ || code.count_fruitless_loop_check(frame)){// NB: The frame may have exited into this loop, and no later iteration of a loop it is in reaches an entry.// Once the code is detached, a later check here compiles the executable again, with what the exits@@ -103,6 +105,8 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32vm.jit.count_coverage("discard-from-loop");// NB: Top-level code that moved on to a later loop recompiles with an entry there, which is progress, so// scripts with many long loops are not refused after MAX_FRUITLESS_DISCARD_COUNT of them.+ // A function's frame that ran out of fruitless loop checks does not count as progress: every call may+ // exit into the same loop again.if runs_once {executable.note_learned_jit_exit_site();}diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex 8116711582a..cfc754c08d0 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -6,15 +6,16 @@//! The tier-up policy, which runs when an executable has used up its tier-up budget.+use core::ops::ControlFlow;use core::ptr::NonNull;use libjs_jit::code::CompiledCode;-use super::code::{CompileState, JitCode, SnapshotExecutable};+use super::code::{CompileState, FRUITLESS_LOOP_CHECKS_AFTER_INSTALL, JitCode, SnapshotExecutable};use super::compile_queue::CompileResult;use super::executable_memory::ExecutableMemory;use super::snapshot::{CapturedSnapshot, capture_snapshot};-use super::{CompileJob, JitState};+use super::{CompileJob, JitState, executable_of};use crate::bytecode::executable::Executable;use crate::bytecode::feedback::tier_up_costs;use crate::gc::defer_gc::DeferGc;@@ -368,6 +369,14 @@ fn install(code.set_osr_outer_loop_back_edges(compiled.osr_outer_loop_back_edges);code.set_uncaught_handlers(compiled.uncaught_handlers);vm.jit.dependents.register(vm, executable, id, &compiled.dependencies);+ // NB: A callee's tier-up check may install the code while its caller still runs in the interpreter, possibly+ // past the loop the code has an on-stack replacement entry at.+ vm.for_each_live_execution_context(|frame| {+ if !frame.runs_jit_code.get() && frame.executable.get().is_some() && executable_of(frame) == executable {+ code.note_interpreted_frame(NonNull::from(frame), FRUITLESS_LOOP_CHECKS_AFTER_INSTALL);+ }+ ControlFlow::Continue(())+ });// 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 the// code before. Those frames keep counting, so that they continue in the code at its on-stack replacementdiff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex ec6902e35e9..426b74fb0f0 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -27,7 +27,9 @@ use libjs_abi::register;use libjs_jit::code::{CALLEE_SLOT, FrameState, Repr, ResumeMode, Site, SiteKind, ValueLocation};use libjs_runtime_macros::Trace;-use super::code::{CompileState, EXIT_COUNT_BEFORE_DISCARD, InlinedFunction, JitCode};+use super::code::{+ CompileState, EXIT_COUNT_BEFORE_DISCARD, FRUITLESS_LOOP_CHECKS_AFTER_EXIT, InlinedFunction, JitCode,+};use super::{executable_of, frame_of, frames_above};use crate::bytecode::executable::Executable;use crate::bytecode::instruction::{OpCode, instruction_length_from_bytes};@@ -659,6 +661,19 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indvm.jit.count_coverage(format_args!("stress-exit.{kind:?}"));return;}+ // NB: Every frame materialized by an exit runs in the interpreter, including intermediate inlined callers whose+ // own code may continue them after their callees return.+ let mut frame = innermost;+ loop {+ if let Some(frame_code) = executable_of(frame_of(frame)).jit_code(vm) {+ frame_code.forget_inactive_interpreted_frames(vm);+ frame_code.note_interpreted_frame(frame, FRUITLESS_LOOP_CHECKS_AFTER_EXIT);+ }+ if frame == root {+ break;+ }+ frame = NonNull::new(frame_of(frame).caller_frame.get()).expect("materialized frames are linked to the root");+ }vm.jit.count_coverage(format_args!("exit.{kind:?}"));if site.frames.len() > 1 {vm.jit.count_coverage("exit.from-inlined-code");diff --git a/Tests/LibJS/JIT/ir/osr-exits-once-into-loop.js b/Tests/LibJS/JIT/ir/osr-exits-once-into-loop.jsnew file mode 100644index 00000000000..e366a3f016e--- /dev/null+++ b/Tests/LibJS/JIT/ir/osr-exits-once-into-loop.js@@ -0,0 +1,23 @@+// A call that exits once into a long loop that never ran before its code was compiled, like a driver that runs one+// loop after another, does not run the rest of that loop in the interpreter: once it keeps looping where no entry is+// reachable, the code is discarded and compiled again with an entry at that loop.++function runsLoopsInTurn(warm) {+ let sum = 0;+ for (let i = 0; i < 10; ++i) sum += i;+ if (warm) return sum;+ for (let j = 0; j < 100000; ++j) {+ if (jit.inCompiledCode()) return -1;+ sum += j;+ }+ return sum;+}+jit.prepare(runsLoopsInTurn);+runsLoopsInTurn(true);+jit.compile(runsLoopsInTurn);+if (runsLoopsInTurn(false) !== -1) throw new Error("The loop never continued in recompiled code");+if (jit.discardCount(runsLoopsInTurn) !== 1) throw new Error("The code was not discarded once");++// CHECK-FUNCTION: runsLoopsInTurn+// CHECK-PASS: graph building+// CHECK: osr entry at pcdiff --git a/Tests/LibJS/JIT/ir/osr-installed-from-callee.js b/Tests/LibJS/JIT/ir/osr-installed-from-callee.jsnew file mode 100644index 00000000000..ecc20751dff--- /dev/null+++ b/Tests/LibJS/JIT/ir/osr-installed-from-callee.js@@ -0,0 +1,28 @@+// Installing code from a callee must give the suspended interpreted caller a chance to discard it when its next+// loop cannot reach an OSR entry. The caller has never entered the code, so no JIT exit can give it that budget.++function installCaller() {+ if (!jit.compile(runsLoopsAcrossInstall)) throw new Error("The caller was not compiled");+}+jit.neverCompile(installCaller);++function runsLoopsAcrossInstall(warm) {+ let sum = 0;+ for (let i = 0; i < 10; ++i) sum += i;+ if (warm) return sum;+ installCaller();+ for (let j = 0; j < 1000000; ++j) {+ if (jit.inCompiledCode()) return -1;+ sum += j & 1;+ }+ return sum;+}+jit.prepare(runsLoopsAcrossInstall);+runsLoopsAcrossInstall(true);+if (runsLoopsAcrossInstall(false) !== -1) throw new Error("The caller stayed in the interpreter after installation");+const discards = jit.discardCount(runsLoopsAcrossInstall);+if (discards !== 1) throw new Error(`The caller code was discarded ${discards} times instead of once`);++// CHECK-FUNCTION: runsLoopsAcrossInstall+// CHECK-PASS: graph building+// CHECK: osr entry at pcdiff --git a/Tests/LibJS/JIT/ir/osr-installed-in-recursive-callee.js b/Tests/LibJS/JIT/ir/osr-installed-in-recursive-callee.jsnew file mode 100644index 00000000000..18fe672e93d--- /dev/null+++ b/Tests/LibJS/JIT/ir/osr-installed-in-recursive-callee.js@@ -0,0 +1,33 @@+// Installing code in an inner recursive frame must also give the suspended outer frame a discard budget.+// The inner frame returns without using its budget, while the outer frame continues past the code's OSR entry.++function installRecursiveCaller() {+ if (!jit.compile(recursiveLoopsAcrossInstall)) throw new Error("The recursive caller was not compiled");+}+jit.neverCompile(installRecursiveCaller);++function recursiveLoopsAcrossInstall(warm, depth) {+ let sum = 0;+ for (let i = 0; i < 10; ++i) sum += i;+ if (warm) return sum;+ if (depth === 0) {+ installRecursiveCaller();+ return sum;+ }+ recursiveLoopsAcrossInstall(false, depth - 1);+ for (let j = 0; j < 1000000; ++j) {+ if (jit.inCompiledCode()) return -1;+ sum += j & 1;+ }+ return sum;+}+jit.prepare(recursiveLoopsAcrossInstall);+recursiveLoopsAcrossInstall(true, 0);+if (recursiveLoopsAcrossInstall(false, 1) !== -1)+ throw new Error("The outer recursive caller stayed in the interpreter after installation");+const discards = jit.discardCount(recursiveLoopsAcrossInstall);+if (discards !== 1) throw new Error(`The recursive caller code was discarded ${discards} times instead of once`);++// CHECK-FUNCTION: recursiveLoopsAcrossInstall+// CHECK-PASS: graph building+// CHECK: osr entry at pcdiff --git a/Tests/LibJS/JIT/ir/osr-intermediate-inlined-frame.js b/Tests/LibJS/JIT/ir/osr-intermediate-inlined-frame.jsnew file mode 100644index 00000000000..ed87bad6a50--- /dev/null+++ b/Tests/LibJS/JIT/ir/osr-intermediate-inlined-frame.js@@ -0,0 +1,34 @@+// An exit from outer -> middle -> leaf must give the materialized middle frame its own discard budget.+// Only middle has a long loop after the exit; neither the compiled root nor the innermost frame can use its budget.++function leafForLoop(value) {+ return value + 1;+}+function middleWithLoop(warm, value) {+ let sum = 0;+ for (let i = 0; i < 10; ++i) sum += i;+ leafForLoop(value);+ if (warm) return sum;+ for (let j = 0; j < 1000000; ++j) {+ if (jit.inCompiledCode()) return -1;+ sum += j & 1;+ }+ return sum;+}+function outerWithLoop(warm, value) {+ return middleWithLoop(warm, value);+}+jit.prepare(leafForLoop);+jit.prepare(middleWithLoop);+jit.prepare(outerWithLoop);+outerWithLoop(true, 1);+if (!jit.compile(middleWithLoop) || !jit.compile(outerWithLoop)) throw new Error("The call chain was not compiled");+if (outerWithLoop(false, "different type") !== -1)+ throw new Error("The intermediate inlined frame stayed in the interpreter");+if (jit.discardCount(middleWithLoop) !== 1) throw new Error("The intermediate code was not discarded once");++// CHECK-FUNCTION: outerWithLoop+// CHECK-PASS: graph building+// CHECK: Int32Add+// CHECK: fs[[MIDDLE:[0-9]+]]: e1 pc {{[0-9]+}} after+// CHECK: e2 pc {{.*}} in fs[[MIDDLE]]