Skip to content

Truly independent web browser

LibJS/JIT: Compile the top-level code of scripts and modules

Andreas Kling4aa1a36c7f6a
diff --git a/Libraries/LibJS/Rust/src/interpreter/run.rs b/Libraries/LibJS/Rust/src/interpreter/run.rs
index d13e4e7a520..9bc0fb876e9 100644
--- a/Libraries/LibJS/Rust/src/interpreter/run.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/run.rs
@@ -319,6 +319,7 @@ impl Vm {
if result.is_ok() {
// a. Set result to Completion(Evaluation of script).
result = vm.run_executable(script_context, executable, 0).map_err(Throw::new);
+ crate::jit::tier_up::finish_top_level_code(vm, &executable);
// b. If result is a normal completion and result.[[Value]] is empty, then
if result.is_ok_and(Value::is_empty) {
diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rs
index ce698e38af5..fb228681c05 100644
--- a/Libraries/LibJS/Rust/src/jit/disabled.rs
+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs
@@ -144,6 +144,8 @@ pub mod tier_up {
pub fn tier_up_check(_vm: &Vm, _encoded_pc: u64) -> i64 {
unreachable!("only the profiling interpreter checks tier-up budgets");
}
+
+ pub fn finish_top_level_code(_vm: &Vm, _executable: &crate::bytecode::executable::Executable) {}
}
pub mod entry_exit {
diff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
index 9505229e7dd..bdf35b3bd46 100644
--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs
+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
@@ -90,13 +90,22 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32
// NB: A fixed budget can keep expiring at the same back edge in nested loops, missing the code's OSR entry
// forever. Try the next back edge when the code has an entry at a loop this one is in. Frames in other
// loops would check at every back edge without ever reaching an entry.
+ // NB: Top-level code runs once, so no later frame would enter its code at the start.
+ let 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 code.exit_count() >= EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP && !code.may_reach_osr_entry_from(pc) {
+ } else if (runs_once || code.exit_count() >= EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP)
+ && !code.may_reach_osr_entry_from(pc)
+ {
// 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
// taught it and an entry at this loop.
vm.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.
+ if runs_once {
+ executable.note_learned_jit_exit_site();
+ }
executable.discard_jit_code(vm);
}
return None;
diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rs
index 94d736da109..e93cc91aab5 100644
--- a/Libraries/LibJS/Rust/src/jit/mod.rs
+++ b/Libraries/LibJS/Rust/src/jit/mod.rs
@@ -391,6 +391,13 @@ impl JitState {
self.jobs.borrow_mut().clear();
}
+ /// Forgets the compile job of `executable`, whose result is dropped when it finishes.
+ pub(crate) fn abandon_compile_job_of(&self, executable: &Executable) {
+ self.jobs
+ .borrow_mut()
+ .retain(|_, job| !core::ptr::eq(job.executable.as_ptr(), executable));
+ }
+
pub(crate) fn take_job(&self, id: u64) -> Option<CompileJob> {
self.jobs.borrow_mut().remove(&id)
}
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 248d9e171f3..e7d55351905 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -36,6 +36,7 @@ use crate::gc::class::Extends;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::environment::DeclarativeEnvironment;
+use crate::layout::execution_context::ExecutionContext;
use crate::layout::function_object::{
DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, RawNativeFunction,
};
@@ -99,7 +100,10 @@ struct SnapshotBuilder<'vm> {
cells: Vec<Gc<CellHeader>>,
entries: Vec<Entry>,
indices: HashMap<InlinedFunction, u32>,
- compiled_function: Gc<EcmascriptFunctionObject>,
+ /// The function the compiled executable runs, or `None` for the top-level code of a script or of a module.
+ compiled_function: Option<Gc<EcmascriptFunctionObject>>,
+ /// The words the compiled executable's frames start with (see `FunctionFrameFields`).
+ compiled_function_fields: FunctionFrameFields,
/// The closure templates of the compiled executable, until its snapshot takes them. Only the compiled function
/// allocates closures itself.
closure_templates: Vec<Option<ClosureTemplateSnapshot>>,
@@ -338,6 +342,13 @@ fn function_frame_fields(function: Gc<EcmascriptFunctionObject>) -> FunctionFram
}
}
+/// The words of the `[[ScriptOrModule]]` of a frame, like `function_frame_fields()` has them of a function.
+fn script_or_module_words(frame: &ExecutionContext) -> [u64; 2] {
+ let address = core::ptr::from_ref(&frame.script_or_module).cast::<u64>();
+ // SAFETY: The field is two words.
+ unsafe { [address.read_unaligned(), address.add(1).read_unaligned()] }
+}
+
/// The words at `offset` of a cell.
fn word_of<T>(cell: Gc<T>, offset: usize) -> u64 {
// SAFETY: The callers read fields of the cell that are words.
@@ -906,7 +917,7 @@ impl SnapshotBuilder<'_> {
let Entry { executable, realm, .. } = *entry;
// NB: Builtins never create arguments objects.
let arguments_function = match entry.function {
- None => Some(self.compiled_function),
+ None => self.compiled_function,
Some(InlinedFunction::Ecmascript(function)) => Some(function),
Some(InlinedFunction::Builtin(_)) => None,
};
@@ -998,7 +1009,7 @@ impl SnapshotBuilder<'_> {
Some(InlinedFunction::Ecmascript(function)) => Some(function_frame_fields(function)),
// NB: The compiled function's script tells which inlined calls
// run in it.
- None => Some(function_frame_fields(self.compiled_function)),
+ None => Some(self.compiled_function_fields),
Some(InlinedFunction::Builtin(_)) => None,
},
environment: match entry.function {
@@ -1179,18 +1190,30 @@ fn captured_binding_accesses(executable: &Executable) -> CapturedBindingAccesses
}
}
-/// Captures the snapshot of a compile job for `executable`, whose frames run `function`. `osr_pc` is the loop back
-/// edge whose tier-up budget ran out, if a loop triggered the compile.
+/// Captures the snapshot of a compile job for `executable`, whose frames run `function` in `realm`, or the top-level
+/// code of a script or of a module without one, in the running frame. `osr_pc` is the loop back edge whose tier-up
+/// budget ran out, if a loop triggered the compile.
pub fn capture_snapshot(
vm: &Vm,
executable: Gc<Executable>,
- function: Gc<EcmascriptFunctionObject>,
+ function: Option<Gc<EcmascriptFunctionObject>>,
+ realm: Gc<Realm>,
osr_pc: Option<u32>,
) -> CapturedSnapshot {
- let realm = function.realm().expect("an ECMAScript function has a realm");
+ let compiled_function_fields = match function {
+ Some(function) => function_frame_fields(function),
+ None => FunctionFrameFields {
+ script_or_module: script_or_module_words(vm.running_execution_context_ref()),
+ ..FunctionFrameFields::default()
+ },
+ };
// NB: These allocate (and so may collect garbage), which they do before anything is captured.
let allocation = allocation_infos(vm, realm);
- let closure_templates = closure_templates(vm, executable, function);
+ // NB: Closures that top-level code creates have its environments, which the code does not know.
+ let closure_templates = match function {
+ Some(function) => closure_templates(vm, executable, function),
+ None => (0..executable.shared_function_data_count()).map(|_| None).collect(),
+ };
let closure_samples = closure_templates
.iter()
.map(|template| template.as_ref().map(|(sample, _)| *sample))
@@ -1206,6 +1229,7 @@ pub fn capture_snapshot(
}],
indices: HashMap::new(),
compiled_function: function,
+ compiled_function_fields,
closure_templates: Vec::new(),
environment_templates: Vec::new(),
lexical_environment_templates: Vec::new(),
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index ac2fd65867b..c968325f12d 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -21,10 +21,12 @@ use crate::interpreter::vm::Vm;
use crate::jit::InterpreterTier;
use crate::jit::options::Options;
use crate::layout::cell::{CellHeader, Gc};
+use crate::layout::execution_context::ScriptOrModule;
use crate::layout::function_object::EcmascriptFunctionObject;
use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
use crate::runtime::realm_watchpoints;
+use crate::runtime::source_text_module::SourceTextModule;
/// `threshold` invocations.
fn threshold_budget(options: &Options) -> i32 {
@@ -106,16 +108,44 @@ pub fn charge_call_from_compiled_code(vm: &Vm, executable: &Executable) {
budget.set(budget.get().saturating_sub(extra));
}
-/// The function to compile the running frame's executable for, if it should be compiled at all.
-fn function_to_compile(vm: &Vm) -> Option<Gc<EcmascriptFunctionObject>> {
+/// What the running frame's executable is compiled for.
+#[derive(Clone, Copy)]
+enum CompileTarget {
+ /// The executable of a function, whose frames run it.
+ Function(Gc<EcmascriptFunctionObject>),
+ /// The top-level code of a script or of a module, which runs once, in the running frame.
+ TopLevel,
+}
+
+impl CompileTarget {
+ fn function(self) -> Option<Gc<EcmascriptFunctionObject>> {
+ match self {
+ CompileTarget::Function(function) => Some(function),
+ CompileTarget::TopLevel => None,
+ }
+ }
+}
+
+/// What to compile the running frame's executable for, if it should be compiled at all.
+fn code_to_compile(vm: &Vm) -> Option<CompileTarget> {
if vm.debugging_enabled() {
return None;
}
- // NB: Top-level code runs once, like the body of a module with top-level await, which runs as an async function.
- // Generators, async functions and async generators resume in their code at the entries of their
- // continuations.
- let function = as_ecmascript_function_object(vm.running_execution_context_ref().function.get()?)?;
- (!function.shared_data().is_module_wrapper()).then_some(function)
+ let frame = vm.running_execution_context_ref();
+ let Some(function) = frame.function.get() else {
+ // NB: The top-level code of a script or of a module runs once, but its loops can run long. Other code without
+ // a function, like that of eval, is not compiled.
+ let top_level_executable = match frame.script_or_module.get() {
+ ScriptOrModule::Script(script) => Some(script.cached_executable()),
+ ScriptOrModule::Module(module) => module.downcast_ref::<SourceTextModule>()?.cached_executable(),
+ _ => None,
+ };
+ return (top_level_executable? == vm.current_executable()).then_some(CompileTarget::TopLevel);
+ };
+ // NB: The body of a module with top-level await runs once, as an async function. Generators, async functions and
+ // async generators resume in their code at the entries of their continuations.
+ let function = as_ecmascript_function_object(function)?;
+ (!function.shared_data().is_module_wrapper()).then_some(CompileTarget::Function(function))
}
/// Whether the running frame runs a builtin written in JavaScript.
@@ -138,6 +168,34 @@ pub fn refuse_jit_compile(vm: &Vm, executable: &Executable) {
}
}
+/// Drops the JIT code of the top-level code of a script or of a module whose frame returned, or its compile job, and
+/// never compiles it again: the code never runs again, but its executable lives as long as the functions it created.
+pub fn finish_top_level_code(vm: &Vm, executable: &Executable) {
+ match executable.jit_compile_state() {
+ CompileState::None | CompileState::Refused => {
+ // NB: Code that was never compiled has nothing to drop, and keeps its tier: refuse_jit_compile() would
+ // give it feedback arrays that nothing ever fills.
+ executable.set_jit_compile_state(CompileState::Refused);
+ executable.head.tier_up_budget.set(i32::MAX);
+ return;
+ }
+ CompileState::Queued => {
+ vm.jit.abandon_compile_job_of(executable);
+ executable.set_jit_compile_state(CompileState::None);
+ }
+ CompileState::Installed => executable.discard_jit_code(vm),
+ // NB: No tier-up check of this executable would detach its code later.
+ CompileState::Discarding => {
+ executable.detach_discarded_jit_code_if_unused(vm);
+ }
+ }
+ if executable.jit_compile_state() == CompileState::Discarding {
+ executable.refuse_jit_compile_once_detached();
+ } else {
+ refuse_jit_compile(vm, executable);
+ }
+}
+
/// Called by the interpreter once the running frame's executable has used up its tier-up budget. `pc` is the entry pc
/// for function entries and the pc of the loop back edge instruction for loops.
pub fn on_budget_exhausted(vm: &Vm, pc: u32, is_loop: bool) {
@@ -170,7 +228,7 @@ pub fn on_budget_exhausted(vm: &Vm, pc: u32, is_loop: bool) {
// A warm executable starts collecting feedback, and the tier-up threshold counts from here, unless the JIT would
// never compile it.
if executable.interpreter_tier() == InterpreterTier::WarmingUp {
- if options.enabled && !vm.debugging_enabled() && function_to_compile(vm).is_none() {
+ if options.enabled && !vm.debugging_enabled() && code_to_compile(vm).is_none() {
if runs_builtin(vm) {
// NB: Builtins written in JavaScript are never compiled on their own, but code that calls them
// inlines them, and needs their feedback.
@@ -228,11 +286,11 @@ pub fn on_budget_exhausted(vm: &Vm, pc: u32, is_loop: bool) {
return;
}
}
- let Some(function) = function_to_compile(vm) else {
+ let Some(code) = code_to_compile(vm) else {
refuse_jit_compile(vm, &executable);
return;
};
- compile(vm, executable, function, is_loop.then_some(pc), options.sync);
+ compile(vm, executable, code.function(), is_loop.then_some(pc), options.sync);
if executable.jit_compile_state() == CompileState::Queued {
executable.head.tier_up_budget.set(QUEUED_BUDGET);
}
@@ -360,12 +418,12 @@ fn finish_compile(
}
}
-/// Compiles `executable`, whose frames run `function`: right away if `sync`, otherwise on a compile thread, whose
-/// code a later tier-up check installs.
+/// Compiles `executable`, whose frames run `function`, or top-level code without one, in the running frame:
+/// right away if `sync`, otherwise on a compile thread, whose code a later tier-up check installs.
fn compile(
vm: &Vm,
executable: Gc<Executable>,
- function: Gc<EcmascriptFunctionObject>,
+ function: Option<Gc<EcmascriptFunctionObject>>,
osr_pc: Option<u32>,
sync: bool,
) {
@@ -374,14 +432,21 @@ fn compile(
// NB: Asking the realm watches its intrinsics anew with new sets where the old ones fired, which allocates, so it
// happens before the snapshot captures which valid sets the realm holds.
- let realm = function.realm().expect("an ECMAScript function has a realm");
+ let realm = match function {
+ Some(function) => function.realm().expect("an ECMAScript function has a realm"),
+ None => vm
+ .running_execution_context_ref()
+ .realm
+ .get()
+ .expect("the frame of top-level code has a realm"),
+ };
realm_watchpoints::array_iterators_have_no_return(vm, realm);
realm_watchpoints::array_iterators_have_builtin_next(vm, realm);
realm_watchpoints::arrays_have_builtin_iterator_method(vm, realm);
// NB: Nothing may collect the cells the snapshot captured before something keeps them alive.
let defer_gc = DeferGc::new(vm);
- let captured = capture_snapshot(vm, executable, function, osr_pc);
+ let captured = capture_snapshot(vm, executable, function, realm, osr_pc);
if sync {
// NB: Nothing collects garbage while compiling on this thread, so the snapshot's cells stay alive.
let result = libjs_jit::compile(&captured.snapshot);
@@ -424,7 +489,7 @@ pub fn compile_now(vm: &Vm, function: Gc<EcmascriptFunctionObject>) -> bool {
}
if executable.jit_compile_state() == CompileState::None {
executable.ensure_feedback().update_value_feedback();
- compile(vm, executable, function, None, true);
+ compile(vm, executable, Some(function), None, true);
}
executable.jit_compile_state() == CompileState::Installed
}
diff --git a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
index d080a368ad1..9f6a4e7540b 100644
--- a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
+++ b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
@@ -1281,6 +1281,7 @@ impl SourceTextModule {
Ok(value) if value.is_empty() => Completion::normal(Value::UNDEFINED),
Ok(value) => Completion::normal(value),
};
+ crate::jit::tier_up::finish_top_level_code(vm, &executable);
// d. Let env be moduleContext's LexicalEnvironment.
let env = module_context_ref
diff --git a/Tests/LibJS/JIT/matrix.py b/Tests/LibJS/JIT/matrix.py
index 08aa8e34e6b..7b141f3dbac 100755
--- a/Tests/LibJS/JIT/matrix.py
+++ b/Tests/LibJS/JIT/matrix.py
@@ -13,8 +13,9 @@ Suites:
interpreter's with the same repeat count.
test262 The whole test262 suite through libjs-test262's main.py; the per-file results must match the
interpreter's.
- programs Every .js file in the --programs directories (Tests/LibJS/JIT/programs by default), run with js; the exit
- code and the output must match the interpreter's (lines with timings are ignored).
+ programs Every .js file (and .mjs file, as a module) in the --programs directories (Tests/LibJS/JIT/programs by
+ default), run with js; the exit code and the output must match the interpreter's (lines with timings are
+ ignored).
Every mismatch is printed with a command that reproduces it. The exit code is 1 if there were any.
"""
@@ -198,7 +199,8 @@ class ProgramsSuite(Suite):
self.files = sorted(
path
for directory in directories
- for path in Path(directory).rglob("*.js")
+ for pattern in ("*.js", "*.mjs")
+ for path in Path(directory).rglob(pattern)
if all(f in str(path) for f in arguments.filter)
)
@@ -206,7 +208,7 @@ class ProgramsSuite(Suite):
wait_until_machine_is_free()
try:
process = subprocess.run(
- [self.js, "--expose-jit-testing", path.name],
+ self.command(path),
cwd=path.parent,
env=environment_for(mode, self.arguments.seed),
stdout=subprocess.PIPE,
@@ -228,10 +230,15 @@ class ProgramsSuite(Suite):
path = Path(key)
return command_line(
{"LIBJS_JIT": mode.environment_value(self.arguments.seed)},
- [self.js, "--expose-jit-testing", path.name],
+ self.command(path),
cwd=path.parent,
)
+ def command(self, path: Path) -> List:
+ """The js command line that runs the program at `path`, as a module if it is a .mjs file."""
+ module = ["--as-module"] if path.suffix == ".mjs" else []
+ return [self.js, "--expose-jit-testing", *module, path.name]
+
SUITES = {suite.name: suite for suite in (TestJsSuite, Test262Suite, ProgramsSuite)}
diff --git a/Tests/LibJS/JIT/programs/top-level-loops.js b/Tests/LibJS/JIT/programs/top-level-loops.js
new file mode 100644
index 00000000000..de53e472119
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/top-level-loops.js
@@ -0,0 +1,37 @@
+// The code of a script is compiled once its loops run long, with its global bindings, its this value, closures it
+// creates, and exceptions it throws and catches, and leaves to the interpreter for what it had not seen.
+var total = 0;
+let count = 0;
+const results = [];
+const holes = new Array(5000);
+function add(value) {
+ total += value;
+ return total;
+}
+for (let i = 0; i < 20000; ++i) {
+ count++;
+ add(i % 7);
+ if (this !== globalThis) throw new Error("wrong this");
+ if (i % 1000 === 0) results.push(() => i);
+ try {
+ if (i === 15000) throw new Error(`thrown at ${i}`);
+ } catch (e) {
+ results.push(e.message);
+ }
+ if (i === 17000) total += 0.5;
+}
+let undefinedCount = 0;
+for (const value of holes) {
+ if (value === undefined) ++undefinedCount;
+}
+let text = "";
+for (let i = 0; i < 3000; ++i) text += String.fromCharCode(97 + (i % 26));
+print(
+ total,
+ count,
+ results.length,
+ results[3](),
+ results.filter(r => typeof r === "string").join(),
+ undefinedCount,
+ text.length
+);
diff --git a/Tests/LibJS/JIT/programs/top-level-module-loops.mjs b/Tests/LibJS/JIT/programs/top-level-module-loops.mjs
new file mode 100644
index 00000000000..1aff5172ffa
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/top-level-module-loops.mjs
@@ -0,0 +1,39 @@
+// The top-level code of a module is compiled once its loops run long, with its module bindings, exported ones too,
+// its undefined this value, closures it creates, and exceptions it throws and catches, and leaves to the interpreter
+// for what it had not seen.
+export let total = 0;
+let count = 0;
+const results = [];
+const holes = new Array(5000);
+function add(value) {
+ total += value;
+ return total;
+}
+for (let i = 0; i < 20000; ++i) {
+ count++;
+ add(i % 7);
+ if (this !== undefined) throw new Error("wrong this");
+ if (i % 1000 === 0) results.push(() => i + count);
+ try {
+ if (i === 15000) throw new Error(`thrown at ${i}`);
+ } catch (e) {
+ results.push(e.message);
+ }
+ if (i === 17000) total += 0.5;
+ if (i === 18000) results.push(typeof import.meta);
+}
+let undefinedCount = 0;
+for (const value of holes) {
+ if (value === undefined) ++undefinedCount;
+}
+let text = "";
+for (let i = 0; i < 3000; ++i) text += String.fromCharCode(97 + (i % 26));
+print(
+ total,
+ count,
+ results.length,
+ results[3](),
+ results.filter(r => typeof r !== "function").join(),
+ undefinedCount,
+ text.length
+);