Skip to content

Truly independent web browser

LibJS/JIT: Create the closures of inlined callees in compiled code

Andreas Kling6a9b72351755
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
index 99ee05ec5d6..329baec5717 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
@@ -163,7 +163,7 @@ impl GraphBuilder<'_> {
}
impl GraphBuilder<'_> {
- /// Builds `NewFunction` of the compiled function as an
+ /// Builds `NewFunction` of the compiled function or an inlined one as an
/// `AllocateFunction`, if it has a closure template and creates no
/// method. Returns false, having built nothing, otherwise.
pub(super) fn try_build_new_function(
@@ -172,7 +172,7 @@ impl GraphBuilder<'_> {
shared_function_data_index: u32,
has_home_object: bool,
) -> Result<bool, CompileFailure> {
- if self.function.is_virtual() || has_home_object {
+ if has_home_object {
return Ok(false);
}
let Some((sample, inline_executable)) = self
@@ -192,9 +192,17 @@ impl GraphBuilder<'_> {
inline_executable.is_some_and(|index| self.snapshot.executables[index as usize].is_non_strict_function());
self.embed(sample);
let environment = self.frame_field(FrameField::LexicalEnvironment)?;
- let private_environment = self.frame_field(FrameField::PrivateEnvironment)?;
+ // NB: Only inlined functions without a private environment have closure templates, but the frames of inlined
+ // closures have the environments of the closure.
+ let inlined_closure = self.function.inline.as_ref().is_some_and(|call| call.closure.is_some());
+ let private_environment = if self.function.is_virtual() && !inlined_closure {
+ self.typed_constant(0, Repr::Pointer)
+ } else {
+ self.frame_field(FrameField::PrivateEnvironment)?
+ };
let function = self.emit(
Op::AllocateFunction {
+ executable: self.function.index,
shared_function_data_index,
sample,
legacy_caller,
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 467b0fadc0c..cb30d727aab 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -1477,13 +1477,14 @@ impl<'a> GraphBuilder<'a> {
return Ok(None);
};
let Op::AllocateFunction {
+ executable,
shared_function_data_index,
..
} = self.graph.node(closure).op
else {
return Ok(None);
};
- let Some(index) = self.snapshot.executables[0]
+ let Some(index) = self.snapshot.executables[executable as usize]
.closure_templates
.get(shared_function_data_index as usize)
.and_then(Option::as_ref)
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 7545315a0cb..3638252a197 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -308,7 +308,8 @@ pub enum ValueLocation {
/// A slot of the compiled function's frame (an operand) that holds the value wherever compiled code runs, which
/// is tagged: one of its arguments or its `this` value register that nothing writes.
Frame(u32),
- /// A NaN-boxed constant.
+ /// A NaN-boxed constant, or for the environments of a closure the code never created (see
+ /// `VirtualObjectDescriptorKind::Closure`), the address of a cell the code embeds, or null.
Constant(u64),
/// The frame's arguments object, which the compiled code never created:
/// the runtime creates it from the frame's arguments like
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
index 4fadd56b749..bc44f35c5aa 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
@@ -604,10 +604,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
pub(super) fn emit_allocate_function(
&mut self,
node: NodeId,
+ executable: u32,
shared_function_data_index: u32,
) -> Result<(), CompileFailure> {
let info = self.runtime.function_allocation;
- let closure = self.executables[0]
+ let closure = self
+ .executables
+ .get(executable as usize)
+ .ok_or(CompileFailure::CodeGeneration)?
.closure_templates
.get(shared_function_data_index as usize)
.and_then(Option::as_ref)
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 6396d0db6d0..234f808edf4 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -1639,9 +1639,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::InitializeNamed { offset } => self.emit_initialize_named(node_id, *offset)?,
Op::AllocateArray { count } => self.emit_allocate_array(node_id, *count)?,
Op::AllocateFunction {
+ executable,
shared_function_data_index,
..
- } => self.emit_allocate_function(node_id, *shared_function_data_index)?,
+ } => self.emit_allocate_function(node_id, *executable, *shared_function_data_index)?,
Op::AllocateEnvironment { shape_cache, capacity } => {
self.emit_allocate_environment(node_id, *shape_cache, *capacity)?;
}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 5b204adaa62..543725441af 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -243,9 +243,10 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
with_inputs(&format!("AllocateEnvironment {shape_cache} capacity {capacity}"))
}
Op::AllocateFunction {
+ executable,
shared_function_data_index,
..
- } => with_inputs(&format!("AllocateFunction {shared_function_data_index}")),
+ } => with_inputs(&format!("AllocateFunction e{executable}:{shared_function_data_index}")),
Op::InitializeElement { index } => with_inputs(&format!("InitializeElement [{index}]")),
Op::CheckObject => with_inputs("CheckObject"),
Op::CheckValue { expected, .. } => with_inputs(&format!("CheckValue {expected:#x}")),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index d4e2aaa402a..afee2c9d6a6 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -812,8 +812,9 @@ define_ops! {
InitializeElement {
index: u32,
},
- /// A new closure of the compiled function's `NewFunction` of
- /// `shared_function_data_index`, a copy of its closure template (see
+ /// A new closure of the `NewFunction` of `shared_function_data_index`
+ /// of snapshot executable `executable` (the compiled function's, or
+ /// an inlined one's), a copy of its closure template (see
/// `FunctionAllocationInfo`) with the lexical environment (a cell
/// pointer) in input 0 and the private environment in input 1. Like
/// `AllocateObject`, the node only allocates. `sample` is the sample
@@ -821,6 +822,7 @@ define_ops! {
/// inlined calls of the closure show it as the legacy "caller" of the
/// functions they call.
AllocateFunction {
+ executable: u32,
shared_function_data_index: u32,
sample: CellId,
legacy_caller: bool,
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index f8937a81534..0c0ffb8b5b9 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -98,7 +98,7 @@ struct Entry {
struct SnapshotBuilder<'vm> {
vm: &'vm Vm,
- _defer_gc: &'vm DeferGc<'vm>,
+ defer_gc: &'vm DeferGc<'vm>,
cells: Vec<Gc<CellHeader>>,
entries: Vec<Entry>,
indices: HashMap<InlinedFunction, u32>,
@@ -106,9 +106,11 @@ struct SnapshotBuilder<'vm> {
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.
+ /// The closure templates of the compiled executable, until its snapshot takes them.
closure_templates: Vec<Option<ClosureTemplateSnapshot>>,
+ /// The samples of the closure templates of inlined functions, by executable and template index, until the
+ /// inlining candidates they are get their indices.
+ closure_samples: Vec<(u32, usize, Gc<EcmascriptFunctionObject>)>,
/// The lexical environment templates of the compiled executable, until its snapshot takes them.
lexical_environment_templates: Vec<Option<LexicalEnvironmentTemplateSnapshot>>,
/// The environment templates of the direct calls of the executable whose snapshot is being made.
@@ -1171,6 +1173,27 @@ impl SnapshotBuilder<'_> {
})
}
+ /// The closure templates of an inlined function, whose frames JIT code creates closures in like the compiled
+ /// function's. Inlined frames have no private environment of their own, so a function with one has none.
+ fn inlined_closure_templates(
+ &mut self,
+ entry: &Entry,
+ function: Gc<EcmascriptFunctionObject>,
+ ) -> Vec<Option<ClosureTemplateSnapshot>> {
+ if function.private_environment().is_some() {
+ return Vec::new();
+ }
+ let index = self.indices[&InlinedFunction::Ecmascript(function)];
+ let defer_gc = self.defer_gc;
+ let templates = closure_templates(self.vm, entry.executable, function, defer_gc);
+ for (template_index, template) in templates.iter().enumerate() {
+ if let Some((sample, _)) = template {
+ self.closure_samples.push((index, template_index, *sample));
+ }
+ }
+ closure_template_snapshots(templates.into_inner(), |sample| self.cell(sample), defer_gc)
+ }
+
/// The snapshot of an executable of the snapshot.
fn executable_snapshot(&mut self, entry: &Entry) -> ExecutableSnapshot {
let vm = self.vm;
@@ -1298,10 +1321,10 @@ impl SnapshotBuilder<'_> {
number_prototype: Some(self.cell(realm.number_prototype(vm))),
boolean_prototype: Some(self.cell(realm.boolean_prototype(vm))),
object_shape_caches,
- closure_templates: if entry.function.is_none() {
- core::mem::take(&mut self.closure_templates)
- } else {
- Vec::new()
+ closure_templates: match entry.function {
+ None => core::mem::take(&mut self.closure_templates),
+ Some(InlinedFunction::Ecmascript(function)) => self.inlined_closure_templates(entry, function),
+ Some(InlinedFunction::Builtin(_)) => Vec::new(),
},
environment_templates: core::mem::take(&mut self.environment_templates),
lexical_environment_templates: if entry.function.is_none() {
@@ -1489,7 +1512,7 @@ pub fn capture_snapshot<'d>(
.collect::<Vec<_>>();
let mut builder = SnapshotBuilder {
vm,
- _defer_gc: defer_gc,
+ defer_gc,
cells: (*allocation.cells).clone(),
entries: vec![Entry {
executable,
@@ -1501,6 +1524,7 @@ pub fn capture_snapshot<'d>(
compiled_function: function,
compiled_function_fields,
closure_templates: Vec::new(),
+ closure_samples: Vec::new(),
environment_templates: Vec::new(),
bound_arguments: Vec::new(),
lexical_environment_templates: Vec::new(),
@@ -1521,23 +1545,32 @@ pub fn capture_snapshot<'d>(
executables.push(builder.executable_snapshot(&entry));
index += 1;
}
- // NB: Calls of closures the compiled function creates can be inlined without feedback, as calls of the function
- // its closure templates are samples of. These come last, so that they take what is left of the inlining budget.
- let root = builder.entries[0];
- for (template_index, sample) in closure_samples.into_iter().enumerate() {
- let Some(sample) = sample else {
- continue;
- };
- let sample_cell = sample.upcast::<CellHeader>();
- let inline_executable = builder.inline_executable_index(Some(sample_cell), &root);
- if let Some(Some(template)) = executables[0].closure_templates.get_mut(template_index) {
- template.inline_executable = inline_executable;
+ // NB: Calls of closures the code creates can be inlined without feedback, as calls of the function its closure
+ // templates are samples of. These come last, so that they take what is left of the inlining budget. Their
+ // snapshots may have closure templates in turn.
+ let mut samples = closure_samples
+ .into_iter()
+ .enumerate()
+ .filter_map(|(template_index, sample)| Some((0, template_index, sample?)))
+ .collect::<Vec<_>>();
+ samples.append(&mut builder.closure_samples);
+ while !samples.is_empty() {
+ for (executable_index, template_index, sample) in samples {
+ let creator = builder.entries[executable_index as usize];
+ let inline_executable = builder.inline_executable_index(Some(sample.upcast::<CellHeader>()), &creator);
+ if let Some(Some(template)) = executables[executable_index as usize]
+ .closure_templates
+ .get_mut(template_index)
+ {
+ template.inline_executable = inline_executable;
+ }
}
- }
- while index < builder.entries.len() {
- let entry = builder.entries[index];
- executables.push(builder.executable_snapshot(&entry));
- index += 1;
+ while index < builder.entries.len() {
+ let entry = builder.entries[index];
+ executables.push(builder.executable_snapshot(&entry));
+ index += 1;
+ }
+ samples = core::mem::take(&mut builder.closure_samples);
}
let mut runtime = super::runtime_info::runtime_info(vm, realm, allocation, defer_gc);
// NB: Code that embeds the prototypes of the runtime info lists them as embedded cells.
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 530414678f8..e8358fa0192 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -127,8 +127,15 @@ fn read_location(location: ValueLocation, dump: &RegisterDump, root: NonNull<Exe
/// Reads the cell address at `location`, null or the address of a live cell, which only the environments of a closure
/// the code never created are (see `libjs_jit::code::VirtualObjectDescriptorKind::Closure`).
fn read_cell_address<T>(location: ValueLocation, dump: &RegisterDump) -> Option<Gc<T>> {
- let (bits, repr) = read_bits(location, dump);
- assert_eq!(repr, Repr::Pointer);
+ // NB: Closures that inlined callees create have the environments of the callee, which the code embeds.
+ let bits = match location {
+ ValueLocation::Constant(bits) => bits,
+ _ => {
+ let (bits, repr) = read_bits(location, dump);
+ assert_eq!(repr, Repr::Pointer);
+ bits
+ }
+ };
// SAFETY: The code keeps the cell alive until the site, which is where it is read.
NonNull::new(bits as *mut T).map(|cell| unsafe { Gc::from_non_null(cell) })
}
diff --git a/Tests/LibJS/JIT/ir/closures-of-inlined-callees.js b/Tests/LibJS/JIT/ir/closures-of-inlined-callees.js
new file mode 100644
index 00000000000..909e4884644
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/closures-of-inlined-callees.js
@@ -0,0 +1,29 @@
+// REQUIRES: inline-allocation
+
+// An inlined callee creates closures like the compiled function does, and calls of them inline too, so a closure
+// that nothing but frames of inlined calls refer to is never allocated.
+
+function apply(f, x) {
+ return f(x);
+}
+function doubled(x) {
+ return apply(y => y * 2, x);
+}
+function sum(n) {
+ let total = 0;
+ for (let i = 0; i < n; i++) total += doubled(i);
+ 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-NOT: CallSlowPath NewFunction
+// CHECK: AllocateFunction e1:
+// CHECK-NOT: CallSlowPath Call
+// CHECK: Int32Mul
+// CHECK-PASS: escape analysis
+// CHECK-NOT: AllocateFunction
+// CHECK: Int32Mul
diff --git a/Tests/LibJS/JIT/programs/closures-of-inlined-callees.js b/Tests/LibJS/JIT/programs/closures-of-inlined-callees.js
new file mode 100644
index 00000000000..7768c164fe6
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/closures-of-inlined-callees.js
@@ -0,0 +1,120 @@
+// Closures that inlined callees create must be what the interpreter would have created, when code exits in them or
+// after them, when they escape, and when the stack is walked through them.
+
+function apply(f, x) {
+ return f(x);
+}
+
+// The inlined callee creates a closure that captures a binding of the environment the callee was created in.
+function makeScaled() {
+ let factor = 2;
+ function scaled(x) {
+ return apply(y => y * factor, x);
+ }
+ return {
+ scaled,
+ grow() {
+ factor++;
+ },
+ };
+}
+
+// Exits in the closure of the inlined callee once the values stop being int32.
+function sumScaled(scaler, values) {
+ let sum = 0;
+ for (const value of values) sum += scaler.scaled(value);
+ return sum;
+}
+
+// The closure of the inlined callee escapes into an array.
+function collect(values) {
+ const closures = [];
+ for (const value of values) closures.push(wrap(value));
+ return closures.map(f => f()).reduce((a, b) => a + b, 0);
+}
+function wrap(value) {
+ return () => value;
+}
+
+// The closure of the inlined callee is held across a call that exits.
+function twice(x) {
+ const f = y => y + 1;
+ return apply(f, x) + apply(f, x * 2);
+}
+function sumTwice(values) {
+ let sum = 0;
+ for (const value of values) sum += twice(value);
+ return sum;
+}
+
+// Sloppy closures of inlined callees show their frames as the legacy caller.
+function whoCalled() {
+ return whoCalled.caller;
+}
+function sloppyInner(x) {
+ return apply(function (y) {
+ return [whoCalled(), whoCalled(), y];
+ }, x);
+}
+function legacyCaller(count) {
+ let same = 0;
+ for (let i = 0; i < count; i++) {
+ const result = sloppyInner(i);
+ if (result[0] === result[1] && typeof result[0] === "function") same++;
+ }
+ return same;
+}
+
+// Stack traces through the frames of closures of inlined callees name the closures.
+function tracedInner(x, last) {
+ return apply(function named(y) {
+ return y === last ? new Error().stack : "";
+ }, x);
+}
+function traced(count) {
+ let names = "";
+ for (let i = 0; i < count; i++) {
+ const stack = tracedInner(i, count - 1);
+ if (stack)
+ names = stack
+ .split("\n")
+ .slice(1, 4)
+ .join(" | ")
+ .replace(/\(.*?\)/g, "");
+ }
+ return names;
+}
+
+// Methods of classes with private names have a private environment, which their closures keep.
+class Counter {
+ #step = 3;
+ scaled(x) {
+ return apply(y => y * this.#step, x);
+ }
+}
+function sumCounter(counter, values) {
+ let sum = 0;
+ for (const value of values) sum += counter.scaled(value);
+ return sum;
+}
+
+const ints = Array.from({ length: 50 }, (_, i) => i);
+const mixed = ints.concat([1.5, 2.5, "3", 4]);
+const scaler = makeScaled();
+const counter = new Counter();
+for (let i = 0; i < 300; i++) {
+ sumScaled(scaler, ints);
+ collect(ints);
+ sumTwice(ints);
+ sumCounter(counter, ints);
+}
+print(sumScaled(scaler, ints), sumScaled(scaler, mixed));
+scaler.grow();
+print(sumScaled(scaler, ints), sumScaled(scaler, mixed));
+print(collect(ints), collect(mixed));
+print(sumTwice(ints), sumTwice(mixed));
+print(sumCounter(counter, ints), sumCounter(counter, mixed));
+for (let i = 0; i < 300; i++) legacyCaller(5);
+print(legacyCaller(10));
+for (let i = 0; i < 300; i++) traced(3);
+print(traced(3));