Skip to content

Truly independent web browser

LibJS/JIT: Never allocate closures that only inlined frames refer to

Andreas Kling30520f913831
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
index ab820bfccd6..99ee05ec5d6 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
@@ -175,22 +175,29 @@ impl GraphBuilder<'_> {
if self.function.is_virtual() || has_home_object {
return Ok(false);
}
- let Some(sample) = self
+ let Some((sample, inline_executable)) = self
.function
.executable
.closure_templates
.get(shared_function_data_index as usize)
.and_then(Option::as_ref)
- .map(|closure| closure.sample)
+ .map(|closure| (closure.sample, closure.inline_executable))
else {
return Ok(false);
};
+ // NB: Only frames of inlined calls of the closure show it, so the closure of a function that is never inlined
+ // is no frame's legacy caller. Closure templates are of normal functions, which are legacy callers when
+ // they are not strict, arrow functions and methods included.
+ let legacy_caller =
+ 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)?;
let function = self.emit(
Op::AllocateFunction {
shared_function_data_index,
+ sample,
+ legacy_caller,
},
vec![environment, private_environment],
Some(Repr::Tagged),
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 8fb75d4405c..baf4e7da5d9 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -1422,6 +1422,7 @@ impl<'a> GraphBuilder<'a> {
};
let Op::AllocateFunction {
shared_function_data_index,
+ ..
} = self.graph.node(closure).op
else {
return Ok(None);
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 84baec65461..7545315a0cb 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -223,20 +223,32 @@ pub enum SiteKind {
Call,
}
-/// An object the compiled code never allocated, which an exit creates: a
-/// plain object of `shape` with the values of its properties in offset
-/// order. Each one is created once per exit, before any is given its
+/// An object the compiled code never allocated, which an exit creates as
+/// `kind` says. Each one is created once per exit, before any is given its
/// properties, so objects may refer to each other.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VirtualObjectDescriptor {
- pub shape: CellId,
+ pub kind: VirtualObjectDescriptorKind,
/// The node index of the allocation the object stands for, which is the
/// same at every site of the code: the runtime may have created the
/// object at another site of the same frame already, and then uses that.
pub allocation: u32,
+ /// The values `kind` describes.
pub properties: Box<[ValueLocation]>,
}
+/// What kind of object a `VirtualObjectDescriptor` describes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum VirtualObjectDescriptorKind {
+ /// A plain object of `shape`, with the values of its properties in
+ /// offset order.
+ Object { shape: CellId },
+ /// A closure like `sample`, the sample of a closure template, with the
+ /// lexical and private environments at the two locations, which are
+ /// `Repr::Pointer`, the latter null for none.
+ Closure { sample: CellId },
+}
+
/// Set in the return pc (`ExecutionContext::caller_return_pc`) of the frame of
/// a callee that a call in an inlined callee made without the frames of the
/// inlined calls it is in (see `SiteKind::Call`): the other bits are the
@@ -314,6 +326,7 @@ pub enum Repr {
Int32,
Float64,
Bool,
- /// The address of a GC cell. Never in frame states.
+ /// The address of a GC cell. In frame states, only as an environment of a
+ /// closure the code never allocated (see `VirtualObjectDescriptorKind`).
Pointer,
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 8f2a8fa1512..6396d0db6d0 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -1640,6 +1640,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::AllocateArray { count } => self.emit_allocate_array(node_id, *count)?,
Op::AllocateFunction {
shared_function_data_index,
+ ..
} => self.emit_allocate_function(node_id, *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/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
index 4f95412bc96..78e179bcf10 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
@@ -13,9 +13,11 @@ use crate::code::Site;
use crate::code::SiteKind;
use crate::code::ValueLocation;
use crate::code::VirtualObjectDescriptor;
+use crate::code::VirtualObjectDescriptorKind;
use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
+use crate::ir::VirtualObjectKind;
use crate::regalloc::Allocation;
use crate::regalloc::FPR_BASE;
use crate::regalloc::Location;
@@ -93,9 +95,13 @@ pub(crate) fn site(
let objects = objects
.iter()
.map(|object| {
- let Op::VirtualObject { shape, allocation } = graph.node(*object).op else {
+ let Op::VirtualObject { kind, allocation } = graph.node(*object).op else {
unreachable!("virtual objects are VirtualObject nodes");
};
+ let kind = match kind {
+ VirtualObjectKind::Object { shape } => VirtualObjectDescriptorKind::Object { shape },
+ VirtualObjectKind::Closure { sample } => VirtualObjectDescriptorKind::Closure { sample },
+ };
let properties = graph
.node(*object)
.inputs
@@ -103,7 +109,7 @@ pub(crate) fn site(
.map(|property| location_of(*property).1)
.collect();
VirtualObjectDescriptor {
- shape,
+ kind,
allocation: allocation.0,
properties,
}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 2daf28b7b48..5b204adaa62 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -13,6 +13,7 @@ use super::NodeId;
use super::Op;
use super::ShapeCheck;
use super::SuspendKind;
+use super::VirtualObjectKind;
use super::value;
use crate::bytecode::FrameLayout;
use crate::bytecode::Operand;
@@ -230,12 +231,20 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
}
Op::InitializeNamed { offset } => with_inputs(&format!("InitializeNamed +{offset}")),
Op::AllocateArray { count } => format!("AllocateArray with {count} elements"),
- Op::VirtualObject { shape, .. } => with_inputs(&format!("VirtualObject {:#x}", shape.0)),
+ Op::VirtualObject {
+ kind: VirtualObjectKind::Object { shape },
+ ..
+ } => with_inputs(&format!("VirtualObject {:#x}", shape.0)),
+ Op::VirtualObject {
+ kind: VirtualObjectKind::Closure { sample },
+ ..
+ } => with_inputs(&format!("VirtualObject closure {:#x}", sample.0)),
Op::AllocateEnvironment { shape_cache, capacity } => {
with_inputs(&format!("AllocateEnvironment {shape_cache} capacity {capacity}"))
}
Op::AllocateFunction {
shared_function_data_index,
+ ..
} => with_inputs(&format!("AllocateFunction {shared_function_data_index}")),
Op::InitializeElement { index } => with_inputs(&format!("InitializeElement [{index}]")),
Op::CheckObject => with_inputs("CheckObject"),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 1c468c66dd1..d4e2aaa402a 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -418,6 +418,19 @@ impl Comparison {
}
}
+/// What the runtime creates for a `VirtualObject`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum VirtualObjectKind {
+ /// A plain object of `shape`, whose properties are the inputs in offset
+ /// order.
+ Object { shape: CellId },
+ /// A closure like `sample`, the sample of the closure template the
+ /// `AllocateFunction` it stands for copies, with the lexical and private
+ /// environments in inputs 0 and 1: cell pointers, the latter null for
+ /// none.
+ Closure { sample: CellId },
+}
+
/// Defines `Op` and `Op::name()`, the name of each variant, so that names cannot drift from the variants. Everything
/// else the compiler knows about an op is in `Op::info()` and `codegen::lowering_info()`.
macro_rules! define_ops {
@@ -776,15 +789,15 @@ define_ops! {
InitializeNamed {
offset: u32,
},
- /// An object that escape analysis replaced by the values of its
- /// properties (the inputs, in offset order), as an exit needs it: the
- /// runtime creates it with `shape` when the exit is taken. Frame states
- /// refer to it; it is in no block and has no code. An input may be
- /// another virtual object. Every frame state refers to the object the
- /// `AllocateObject` node `allocation` made with a virtual object of its
- /// own, and `allocation` tells the runtime they are the same object.
+ /// An object that escape analysis replaced by its inputs, as an exit
+ /// needs it: the runtime creates it as `kind` says when the exit is
+ /// taken. Frame states refer to it; it is in no block and has no code.
+ /// An input may be another virtual object. Every frame state refers to
+ /// the object the allocation node `allocation` made with a virtual
+ /// object of its own, and `allocation` tells the runtime they are the
+ /// same object.
VirtualObject {
- shape: CellId,
+ kind: VirtualObjectKind,
allocation: NodeId,
},
/// A new array of `count` packed elements, all `undefined`, of the
@@ -803,9 +816,14 @@ define_ops! {
/// `shared_function_data_index`, 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.
+ /// `AllocateObject`, the node only allocates. `sample` is the sample
+ /// of the template. `legacy_caller` tells whether the frames of
+ /// inlined calls of the closure show it as the legacy "caller" of the
+ /// functions they call.
AllocateFunction {
shared_function_data_index: u32,
+ sample: CellId,
+ legacy_caller: bool,
},
/// A new lexical environment of the compiled function's
/// `CreateLexicalEnvironment` with environment shape cache `shape_cache`
@@ -1949,7 +1967,7 @@ mod tests {
let value = graph.add_node(Node::new(Op::Constant(value::UNDEFINED), vec![], Some(Repr::Tagged), 0));
let inner = graph.add_node(Node::new(
Op::VirtualObject {
- shape: CellId(1),
+ kind: VirtualObjectKind::Object { shape: CellId(1) },
allocation: NodeId(0),
},
vec![value],
@@ -1958,7 +1976,7 @@ mod tests {
));
let outer = graph.add_node(Node::new(
Op::VirtualObject {
- shape: CellId(2),
+ kind: VirtualObjectKind::Object { shape: CellId(2) },
allocation: NodeId(1),
},
vec![inner, value],
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs b/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
index 8ca29a58758..2a28fa7c873 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/dce.rs
@@ -123,7 +123,7 @@ mod tests {
));
let object = graph.add_node(crate::ir::Node::new(
Op::VirtualObject {
- shape: CellId(1),
+ kind: crate::ir::VirtualObjectKind::Object { shape: CellId(1) },
allocation: NodeId(0),
},
vec![boxed],
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
index 7caad4d1a5a..a98efcc9300 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
@@ -6,7 +6,8 @@
//! Escape analysis and scalar replacement of allocations.
//!
-//! An object an `AllocateObject` makes escapes when anything could see it
+//! An object an `AllocateObject` makes, or a closure an `AllocateFunction`
+//! makes, escapes when anything could see it
//! besides accesses of its named properties: when it is stored into the
//! frame or into an object that escapes, passed to anything but property
//! accesses and checks (an operand of a slow path or a call included),
@@ -32,6 +33,16 @@
//! holds one in a phi, the object escapes and the pass starts over: a phi
//! of objects that are never allocated cannot be the value of a property
//! of a virtual object.
+//!
+//! A closure escapes when anything but a frame state refers to it: the frame
+//! of an inlined call of it, which has its environments as the inputs of the
+//! `AllocateFunction` (see `GraphBuilder::frame_field()`), needs no more. It
+//! escapes where frame states that refer to it are published with their
+//! headers too (see `codegen::lowering_info::LoweringInfo::publishes_frames`),
+//! since only the runtime could write them, every time. Calls without the
+//! frames of inlined calls (see `Op::CallDirect`) leave those frames to stack
+//! walks, which would show a closure created for them as the legacy caller
+//! of the callee, so closures that would be one escape at those too.
use super::edit;
use super::edit::Constants;
@@ -39,6 +50,7 @@ use super::edit::Replacements;
use crate::bitset::BitSet;
use crate::code::ExitKind;
use crate::code::Repr;
+use crate::codegen::lowering_info::lowering_info;
use crate::fast_hash::HashMap;
use crate::fast_hash::HashSet;
use crate::ir::Block;
@@ -49,6 +61,7 @@ use crate::ir::Graph;
use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
+use crate::ir::VirtualObjectKind;
use crate::ir::value;
use crate::snapshot::CellId;
@@ -60,6 +73,8 @@ type Shapes = HashMap<NodeId, (CellId, u32)>;
struct Analysis {
/// The allocations that may be replaced.
candidates: HashSet<NodeId>,
+ /// The candidates that are closures.
+ closures: HashSet<NodeId>,
/// For every value that is a candidate or stands for one (a candidate
/// with empty values made undefined, or its cell address): the candidate.
roots: HashMap<NodeId, NodeId>,
@@ -80,12 +95,18 @@ fn placed_nodes(graph: &Graph) -> Vec<NodeId> {
fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
let mut candidates = HashSet::default();
+ let mut closures = HashSet::default();
let mut roots = HashMap::default();
for node in placed {
- if let Op::AllocateObject { .. } = graph.node(*node).op {
- candidates.insert(*node);
- roots.insert(*node, *node);
+ match graph.node(*node).op {
+ Op::AllocateObject { .. } => {}
+ Op::AllocateFunction { .. } => {
+ closures.insert(*node);
+ }
+ _ => continue,
}
+ candidates.insert(*node);
+ roots.insert(*node, *node);
}
let mut escaped = BitSet::new(graph.nodes.len());
for object in escaping {
@@ -94,6 +115,7 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
if candidates.is_empty() {
return Analysis {
candidates,
+ closures,
roots,
escaped,
has_nested_objects: false,
@@ -148,6 +170,38 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
let shapes_before = shapes_before_uses(graph, &candidates, &roots, &mut escaped);
+ // NB: Only closures escape from frame states.
+ for node in placed.iter().filter(|_| !closures.is_empty()) {
+ let data = graph.node(*node);
+ let Some(frame_state) = data.frame_state else {
+ continue;
+ };
+ let is_published = graph.frame_state(frame_state).parent.is_some() && lowering_info(data).publishes_frames;
+ let is_call_without_frames = matches!(
+ data.op,
+ Op::CallDirect { inlined_frame_bytes, .. } | Op::CallNative { inlined_frame_bytes, .. }
+ if inlined_frame_bytes != 0
+ );
+ if !is_published && !is_call_without_frames {
+ continue;
+ }
+ for value in frame_state_values(graph, frame_state) {
+ let Some(root) = roots.get(&value).copied().filter(|root| closures.contains(root)) else {
+ continue;
+ };
+ let legacy_caller = matches!(
+ graph.node(root).op,
+ Op::AllocateFunction {
+ legacy_caller: true,
+ ..
+ }
+ );
+ if is_published || legacy_caller {
+ escaped.insert(root.index());
+ }
+ }
+ }
+
// Values stored into candidates: (value's candidate, the candidate it is stored into).
let mut stored_into = Vec::new();
for node in placed {
@@ -161,6 +215,13 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
escaped.insert(root.index());
continue;
};
+ // NB: Closures have no properties that this pass knows.
+ if closures.contains(&root) {
+ if !matches!(data.op, Op::EmptyToUndefined | Op::CellAddress | Op::CheckObject) {
+ escaped.insert(root.index());
+ }
+ continue;
+ }
let accesses_object = match &data.op {
Op::EmptyToUndefined | Op::CellAddress | Op::CheckObject => true,
Op::LoadNamed { offset, .. } => *offset < count,
@@ -221,6 +282,7 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
.any(|(value, target, _)| target.is_some() && !escaped.contains(value.index()));
Analysis {
candidates,
+ closures,
roots,
escaped,
has_nested_objects,
@@ -288,6 +350,10 @@ fn shapes_before_uses(
} if candidates.contains(&node) => {
shapes.insert(node, (shape, property_count));
}
+ // NB: A closure has one shape, and no properties that this pass knows.
+ Op::AllocateFunction { sample, .. } if candidates.contains(&node) => {
+ shapes.insert(node, (sample, 0));
+ }
Op::AddNamed {
shape, property_count, ..
} => {
@@ -495,6 +561,10 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nod
shapes.insert(node, (shape, property_count));
removed.insert(node.index());
}
+ Op::AllocateFunction { sample, .. } if is_replaced(node) => {
+ shapes.insert(node, (sample, 0));
+ removed.insert(node.index());
+ }
Op::AddNamed {
offset,
shape,
@@ -603,11 +673,13 @@ fn virtualize_frame_state(
return *object;
}
let (shape, _) = shapes[&root];
+ let kind = if analysis.closures.contains(&root) {
+ VirtualObjectKind::Closure { sample: shape }
+ } else {
+ VirtualObjectKind::Object { shape }
+ };
let object = graph.add_node(Node::new(
- Op::VirtualObject {
- shape,
- allocation: root,
- },
+ Op::VirtualObject { kind, allocation: root },
Vec::new(),
Some(Repr::Tagged),
graph.node(root).pc,
@@ -633,6 +705,17 @@ fn virtualize_frame_state(
.find(|(_, object)| !filled.contains(object))
{
filled.push(object);
+ // NB: The environments of a closure are what its allocation had.
+ if analysis.closures.contains(&root) {
+ let inputs = graph
+ .node(root)
+ .inputs
+ .iter()
+ .map(|input| replacements.resolve(*input))
+ .collect();
+ graph.nodes[object.index()].inputs = inputs;
+ continue;
+ }
let (_, property_count) = shapes[&root];
let inputs = (0..property_count)
.map(|offset| {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index ab8977f8a15..f0c7d1637cf 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -316,7 +316,8 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>]) -> Result<(), String> {
node_id.0, value.0
));
}
- if graph.node(value).repr == Some(Repr::Pointer) {
+ // NB: Only the environments of virtual closures are cell addresses (see `VirtualObjectKind`).
+ if graph.node(value).repr == Some(Repr::Pointer) && slot != crate::ir::VIRTUAL_OBJECT_PROPERTY {
errors.push(format!(
"the frame state of v{} has the cell address v{} for slot {slot}",
node_id.0, value.0
diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rs
index bf4f2f9c6e1..7cee69a5bc3 100644
--- a/Libraries/LibJS/Rust/src/jit/allocation.rs
+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs
@@ -614,14 +614,23 @@ pub extern "C" fn libjs_jit_clone_function(
environment: Option<Gc<Environment>>,
private_environment: Option<Gc<PrivateEnvironment>>,
) -> *mut EcmascriptFunctionObject {
+ clone_function(vm, sample, environment, private_environment).as_ptr()
+}
+
+/// A closure like the sample of a closure template, with the given environments.
+pub fn clone_function(
+ vm: &Vm,
+ sample: Gc<EcmascriptFunctionObject>,
+ environment: Option<Gc<Environment>>,
+ private_environment: Option<Gc<PrivateEnvironment>>,
+) -> Gc<EcmascriptFunctionObject> {
let realm = sample.realm().expect("an ECMAScript function has a realm");
- let closure = EcmascriptFunctionObject::create_from_function_data_with_prototype(
+ EcmascriptFunctionObject::create_from_function_data_with_prototype(
vm,
realm,
sample.shared_data(),
environment,
private_environment,
realm.function_prototype(),
- );
- closure.as_ptr()
+ )
}
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 224b54106e2..530414678f8 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -24,9 +24,12 @@ use core::ptr::NonNull;
use std::collections::HashMap;
use libjs_abi::register;
-use libjs_jit::code::{CALLEE_SLOT, FrameState, Repr, ResumeMode, Site, SiteKind, ValueLocation};
+use libjs_jit::code::{
+ CALLEE_SLOT, FrameState, Repr, ResumeMode, Site, SiteKind, ValueLocation, VirtualObjectDescriptorKind,
+};
use libjs_runtime_macros::Trace;
+use super::allocation::clone_function;
use super::code::{
CompileState, EXIT_COUNT_BEFORE_DISCARD, FRUITLESS_LOOP_CHECKS_AFTER_EXIT, InlinedFunction, JitCode,
};
@@ -110,6 +113,29 @@ fn read_location(location: ValueLocation, dump: &RegisterDump, root: NonNull<Exe
ValueLocation::Constant(bits) => return Value::from_bits(bits),
// NB: Nothing writes such a slot, so it still holds the value while frames are written.
ValueLocation::Frame(slot) => return frame_of(root).slots()[slot as usize].get(),
+ _ => read_bits(location, dump),
+ };
+ match repr {
+ Repr::Tagged => Value::from_bits(bits),
+ Repr::Int32 => Value::from_i32(bits as i32),
+ Repr::Float64 => Value::from_f64(f64::from_bits(bits)),
+ Repr::Bool => Value::from_bool(bits as u32 != 0),
+ Repr::Pointer => unreachable!("only virtual closures have cell addresses in frame states"),
+ }
+}
+
+/// 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);
+ // 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) })
+}
+
+/// The bits and representation of a value in a register or stack slot.
+fn read_bits(location: ValueLocation, dump: &RegisterDump) -> (u64, Repr) {
+ match location {
ValueLocation::Register(encoding, repr) => {
let bits = if repr == Repr::Float64 {
dump.fprs[usize::from(encoding)]
@@ -124,16 +150,12 @@ fn read_location(location: ValueLocation, dump: &RegisterDump, root: NonNull<Exe
// SAFETY: The JIT frame of the site is still on the stack, and the slot holds the value.
(unsafe { address.read() }, repr)
}
+ ValueLocation::Constant(_) | ValueLocation::Frame(_) => {
+ unreachable!("only registers and stack slots hold bits")
+ }
ValueLocation::ArgumentsObject { .. } | ValueLocation::VirtualObject(_) => {
unreachable!("objects are created by SiteValues")
}
- };
- match repr {
- Repr::Tagged => Value::from_bits(bits),
- Repr::Int32 => Value::from_i32(bits as i32),
- Repr::Float64 => Value::from_f64(f64::from_bits(bits)),
- Repr::Bool => Value::from_bool(bits as u32 != 0),
- Repr::Pointer => unreachable!("frame states hold no pointers"),
}
}
@@ -192,8 +214,28 @@ impl<'a> SiteValues<'a> {
self.created.insert(index, object);
return Value::from_object(object);
}
+ let shape = match description.kind {
+ VirtualObjectDescriptorKind::Object { shape } => shape,
+ VirtualObjectDescriptorKind::Closure { sample } => {
+ // SAFETY: The code embeds the sample, which keeps it alive.
+ let sample = unsafe { Gc::from_non_null(NonNull::new(sample.0 as *mut _).expect("a sample")) };
+ let closure = clone_function(
+ self.vm,
+ sample,
+ read_cell_address(description.properties[0], self.dump),
+ read_cell_address(description.properties[1], self.dump),
+ )
+ .upcast::<Object>();
+ self.created.insert(index, closure);
+ if self.remember {
+ self.code
+ .remember_materialized_object(self.root.as_ptr(), description.allocation, closure);
+ }
+ return Value::from_object(closure);
+ }
+ };
// SAFETY: The code embeds the shape, which keeps it alive.
- let shape = unsafe { Gc::from_non_null(NonNull::new(description.shape.0 as *mut _).expect("a shape")) };
+ let shape = unsafe { Gc::from_non_null(NonNull::new(shape.0 as *mut _).expect("a shape")) };
let object = Object::create_with_premade_shape(self.vm, shape);
// NB: The object exists before its properties, which may refer to it.
self.created.insert(index, object);
diff --git a/Tests/LibJS/JIT/ir/closure-escape-analysis.js b/Tests/LibJS/JIT/ir/closure-escape-analysis.js
new file mode 100644
index 00000000000..39266850393
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/closure-escape-analysis.js
@@ -0,0 +1,90 @@
+// REQUIRES: inline-allocation
+// OPTIONS: inline-depth=2
+
+// A closure that nothing but the frames of inlined calls of it refers to is never allocated.
+
+function apply(f, x) {
+ return f(x);
+}
+
+function doubled(n) {
+ let sum = 0;
+ for (let i = 0; i < n; i++) sum += apply(x => x * 2, i);
+ return sum;
+}
+jit.prepare(doubled);
+jit.prepare(apply);
+for (let i = 0; i < 10; ++i) doubled(10);
+jit.compile(doubled);
+
+// CHECK-FUNCTION: doubled
+// CHECK-PASS: graph building
+// CHECK: AllocateFunction
+// CHECK-PASS: escape analysis
+// CHECK-NOT: AllocateFunction
+// CHECK: Int32Mul
+
+// A closure that code reads as a value is allocated.
+
+function returned(n) {
+ const f = x => x + n;
+ apply(f, n);
+ return f;
+}
+jit.prepare(returned);
+for (let i = 0; i < 10; ++i) returned(i);
+jit.compile(returned);
+
+// CHECK-FUNCTION: returned
+// CHECK-PASS: escape analysis
+// CHECK: [[CLOSURE:v[0-9]+]] = AllocateFunction
+// CHECK: Return ([[CLOSURE]])
+
+// A closure of a sloppy function, arrow functions included, which shows its frames as the legacy caller of the
+// functions they call, is allocated when an inlined call of it calls a function without the frames of inlined calls.
+
+function callee() {
+ return 1;
+}
+function sloppyCaller(n) {
+ let sum = 0;
+ for (let i = 0; i < n; i++)
+ sum += apply(function (x) {
+ return callee() + x;
+ }, i);
+ return sum;
+}
+function sloppyArrowCaller(n) {
+ let sum = 0;
+ for (let i = 0; i < n; i++) sum += apply(x => callee() + x, i);
+ return sum;
+}
+function strictCaller(n) {
+ "use strict";
+ let sum = 0;
+ for (let i = 0; i < n; i++) sum += apply(x => callee() + x, i);
+ return sum;
+}
+jit.prepare(sloppyCaller);
+jit.prepare(sloppyArrowCaller);
+jit.prepare(strictCaller);
+for (let i = 0; i < 10; ++i) {
+ sloppyCaller(10);
+ sloppyArrowCaller(10);
+ strictCaller(10);
+}
+jit.compile(sloppyCaller);
+jit.compile(sloppyArrowCaller);
+jit.compile(strictCaller);
+
+// CHECK-FUNCTION: sloppyCaller
+// CHECK-PASS: escape analysis
+// CHECK: AllocateFunction
+
+// CHECK-FUNCTION: sloppyArrowCaller
+// CHECK-PASS: escape analysis
+// CHECK: AllocateFunction
+
+// CHECK-FUNCTION: strictCaller
+// CHECK-PASS: escape analysis
+// CHECK-NOT: AllocateFunction
diff --git a/Tests/LibJS/JIT/programs/closures-the-code-never-allocated.js b/Tests/LibJS/JIT/programs/closures-the-code-never-allocated.js
new file mode 100644
index 00000000000..cff124f94b3
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/closures-the-code-never-allocated.js
@@ -0,0 +1,107 @@
+// Closures that compiled code never allocates, because nothing but the frames of inlined calls of them refers to them,
+// must be created as they were when code exits in them, or after them, or walks the stack through them.
+
+function apply(f, x) {
+ return f(x);
+}
+
+// Exits in the inlined closure, which reads a binding it captured, once the values stop being int32.
+function capturing(values) {
+ let offset = 1;
+ let sum = 0;
+ for (const value of values) {
+ sum += apply(x => x * 2 + offset, value);
+ offset++;
+ }
+ return sum;
+}
+
+// Exits with the closure in a local slot, before it is called again.
+function heldInLocal(values) {
+ let sum = 0;
+ for (const value of values) {
+ const f = x => x + 1;
+ sum += apply(f, value);
+ sum += value * 3;
+ sum += apply(f, value);
+ }
+ return sum;
+}
+
+// Exits in a closure created in a method of a class, which has a private environment.
+class Counter {
+ #step = 2;
+ total(values) {
+ let sum = 0;
+ for (const value of values) sum += apply(x => x * this.#step, value);
+ return sum;
+ }
+}
+
+// Sloppy functions show the frames of inlined calls of them as the legacy caller of the functions they call.
+function whoCalled() {
+ return whoCalled.caller;
+}
+function legacyCaller(count) {
+ let same = 0;
+ for (let i = 0; i < count; i++) {
+ const caller = apply(function (x) {
+ return [whoCalled(), whoCalled(), x];
+ }, i);
+ if (caller[0] === caller[1] && typeof caller[0] === "function") same++;
+ }
+ return same;
+}
+
+// Sloppy arrow functions are legacy callers too, which must stay the same object across the calls they make.
+function countCalls() {
+ const caller = countCalls.caller;
+ caller.calls = (caller.calls | 0) + 1;
+ // NB: Too large to inline, so that it runs without the frames of inlined calls.
+ let padding = 0;
+ for (let i = 0; i < 3; i++) padding += i * 2 + 1;
+ for (let i = 0; i < 3; i++) padding -= i * 2 + 1;
+ for (let i = 0; i < 3; i++) padding += i % 2;
+ for (let i = 0; i < 3; i++) padding -= i % 2;
+ return caller.calls + padding;
+}
+function arrowCaller() {
+ const arrow = () => countCalls();
+ apply(arrow, 0);
+ return apply(arrow, 0);
+}
+
+// Stack traces through the frames of inlined calls name the closures.
+function traced(count) {
+ let names = "";
+ for (let i = 0; i < count; i++) {
+ const stack = apply(function named(x) {
+ return x === count - 1 ? new Error().stack : "";
+ }, i);
+ if (stack)
+ names = stack
+ .split("\n")
+ .slice(1, 3)
+ .join(" | ")
+ .replace(/\(.*?\)/g, "");
+ }
+ return names;
+}
+
+const ints = Array.from({ length: 50 }, (_, i) => i);
+const mixed = ints.concat([1.5, 2.5, "3", 4]);
+for (let i = 0; i < 300; i++) {
+ capturing(ints);
+ heldInLocal(ints);
+ new Counter().total(ints);
+}
+print(capturing(ints), capturing(mixed));
+print(heldInLocal(ints), heldInLocal(mixed));
+print(new Counter().total(ints), new Counter().total(mixed));
+for (let i = 0; i < 300; i++) legacyCaller(5);
+print(legacyCaller(10));
+let arrowCalls = 0;
+for (let i = 0; i < 300; i++) arrowCalls += arrowCaller();
+print(arrowCalls);
+for (let i = 0; i < 300; i++) traced(3);
+print(traced(3));