Truly independent web browser
LibJS/JIT: Call method constants directly when they are not inlined
Andreas Klingc6997876bdde
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rsindex ca9dede44f8..cdc0bdfa707 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs@@ -94,6 +94,9 @@ pub(super) struct CacheEntry {/// The snapshot executable of the function `prototype_property` holds,/// if calls of it may be inlined.pub prototype_property_inline_executable: Option<u32>,+ /// The target through which code may call the function+ /// `prototype_property` holds directly.+ pub prototype_property_direct_call: Option<crate::snapshot::DirectCallTarget>,/// The watchpoint set that stays valid while the prototype holds/// `prototype_property`, if there is one.pub prototype_property_watchpoint: Option<CellId>,@@ -172,6 +175,7 @@ impl CacheEntry {.prototype_property.map(|cell| (cell, entry.prototype_property_intrinsic)),prototype_property_inline_executable: entry.prototype_property_inline_executable,+ prototype_property_direct_call: entry.prototype_property_direct_call,prototype_property_watchpoint: entry.prototype_property_watchpoint,})}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex a2a75986c98..d02b6320fff 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -523,8 +523,64 @@ impl GraphBuilder<'_> {return Ok(None);}let Some(target) = feedback.direct_call else {+ return self.try_direct_call_of_constant(instruction);+ };+ self.build_direct_call(instruction, target, None)+ }++ /// Builds a `Call` of a function the code holds as a constant, like a+ /// method of a prototype, as a `CallDirect` node, or returns `None` if+ /// it cannot call the callee directly.+ fn try_direct_call_of_constant(&mut self, instruction: &Instruction) -> Result<Option<Flow>, CompileFailure> {+ let Instruction::Call { callee, .. } = instruction else {+ return Ok(None);+ };+ let SlotState::Value { node, .. } = self.peek(*callee) else {+ return Ok(None);+ };+ match self.graph.constant_value(node) {+ Some(bits) => self.try_direct_call_of_function(instruction, bits),+ None => Ok(None),+ }+ }++ /// Builds a `Call` whose callee is the function `bits` as a `CallDirect`+ /// node, or returns `None` if it cannot call the function directly.+ fn try_direct_call_of_function(+ &mut self,+ instruction: &Instruction,+ bits: u64,+ ) -> Result<Option<Flow>, CompileFailure> {+ let Some(target) = self.direct_call_functions.get(&bits).copied() else {return Ok(None);};+ let index = u32::try_from(self.graph.direct_call_targets.len()).expect("target count fits in u32");+ self.graph.direct_call_targets.push(target);+ self.build_direct_call(instruction, target, Some(index))+ }++ /// Builds a `Call` that calls `target` directly as a `CallDirect` node,+ /// whose `target` is `constant_target` (see `Op::CallDirect`).+ fn build_direct_call(+ &mut self,+ instruction: &Instruction,+ target: crate::snapshot::DirectCallTarget,+ constant_target: Option<u32>,+ ) -> Result<Option<Flow>, CompileFailure> {+ let Instruction::Call {+ argument_count,+ callee,+ this_value,+ arguments,+ ..+ } = instruction+ else {+ unreachable!("direct calls are of Call instructions");+ };+ let Handling::Generic(info) = handling(OpCode::Call) else {+ unreachable!("calls are generic instructions");+ };+ let slots_offset = u64::from(self.runtime.offsets.execution_context_slots);let slot_count = u64::from(target.registers_and_locals_and_constants_count)+ u64::from((*argument_count).max(target.function.formal_parameter_count));self.reserve_call_frame(slots_offset + 8 * slot_count);@@ -564,6 +620,7 @@ impl GraphBuilder<'_> {pc: self.function.pc,inlined_frame_bytes,stores_operands: false,+ target: constant_target,};return self.build_call_without_inlined_frames(instruction, op, &inputs)@@ -578,6 +635,7 @@ impl GraphBuilder<'_> {pc: self.function.pc,inlined_frame_bytes: 0,stores_operands: stores_operands && !inputs.is_empty(),+ target: constant_target,};self.build_generic_node_with_inputs(instruction, info, op, &inputs, None).map(Some)@@ -888,7 +946,12 @@ impl GraphBuilder<'_> {cases.push((bits, self.inlinable_functions.get(&bits).copied()));}}- if cases.len() < 2 || cases.len() > MAX_CALLEE_CASES || cases.iter().all(|(_, index)| index.is_none()) {+ if cases.len() < 2+ || cases.len() > MAX_CALLEE_CASES+ || cases+ .iter()+ .all(|(bits, index)| index.is_none() && !self.direct_call_functions.contains_key(bits))+ {return None;}Some(cases)@@ -992,12 +1055,12 @@ impl GraphBuilder<'_> {let Some(cases) = self.callee_cases(*callee) else {return Ok(None);};- // NB: Without a case to inline, one generic call does better than a- // slow path call for each case.- if !cases- .iter()- .any(|(_, index)| index.is_some_and(|index| self.may_inline_callee_case(index)))- {+ // NB: Without a case to inline or call directly, one generic call does+ // better than a slow path call for each case.+ if !cases.iter().any(|(bits, index)| {+ index.is_some_and(|index| self.may_inline_callee_case(index))+ || self.direct_call_functions.contains_key(bits)+ }) {return Ok(None);}let Handling::Generic(info) = handling(OpCode::Call) else {@@ -1087,6 +1150,10 @@ impl GraphBuilder<'_> {))?,_ => None,};+ let inlined = match inlined {+ Some(flow) => Some(flow),+ None => self.try_direct_call_of_function(instruction, *bits)?,+ };let flow = match inlined {Some(flow) => flow,None => selfdiff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 104a0ac4407..ddd24efbb0f 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -552,6 +552,9 @@ struct GraphBuilder<'a> {/// The functions among the constants that calls may inline, by value:/// their indices in `Snapshot::executables`.inlinable_functions: HashMap<u64, u32>,+ /// The functions among the constants that calls may call directly, by+ /// value.+ direct_call_functions: HashMap<u64, crate::snapshot::DirectCallTarget>,/// How `instanceof` runs with the functions the code uses as constants/// on its right-hand side (see `GlobalValueSnapshot::has_instance`), by/// their bits.@@ -598,6 +601,7 @@ impl<'a> GraphBuilder<'a> {build_osr_entries,intrinsics: HashMap::default(),inlinable_functions: HashMap::default(),+ direct_call_functions: HashMap::default(),has_instance: HashMap::default(),})}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rsindex 08bf1e4e261..d2923ea0f6f 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs@@ -207,6 +207,9 @@ impl GraphBuilder<'_> {if let Some(index) = entry.prototype_property_inline_executable {self.inlinable_functions.insert(bits, index);}+ if let Some(target) = entry.prototype_property_direct_call {+ self.direct_call_functions.insert(bits, target);+ }// NB: While the watchpoint set is valid, the prototype holds// the object in the property, which needs no load.if let Some(watchpoint) = entry.prototype_property_watchpoint {diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 28eaf6baab9..32e21d55cb7 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -839,6 +839,7 @@ pub(crate) mod property_access {prototype_property: None,prototype_property_intrinsic: None,prototype_property_inline_executable: None,+ prototype_property_direct_call: None,prototype_property_watchpoint: None,accessor_function: None,property_holds_data: false,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex 5f88257c6a8..6e5bbf9e9db 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -168,11 +168,26 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let Instruction::Call { call_feedback, .. } = decoded.instruction else {return Err(invalid("direct call of a non-Call instruction"));};- let target: DirectCallTarget = snapshot- .feedback- .call- .get(usize::from(call_feedback))- .and_then(|feedback| feedback.direct_call)+ let constant_target = match self.graph.node(node).op {+ Op::CallDirect {+ target: Some(target), ..+ } => Some(+ *self+ .graph+ .direct_call_targets+ .get(target as usize)+ .ok_or(invalid("direct call of a missing constant target"))?,+ ),+ _ => None,+ };+ let target: DirectCallTarget = constant_target+ .or_else(|| {+ snapshot+ .feedback+ .call+ .get(usize::from(call_feedback))+ .and_then(|feedback| feedback.direct_call)+ }).ok_or(invalid("direct call without a target"))?;if self.stores_operands(node) {let operands = crate::builder::js_call_operands(&decoded.instruction).inputs;diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex 15a36c6373c..f4463ea0274 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -176,6 +176,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {pc,inlined_frame_bytes,stores_operands,+ target,} => {let location = if *executable == 0 {format!("@{pc}")@@ -188,7 +189,8 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {format!(" without inlined frames ({inlined_frame_bytes} bytes)")};let stores = if *stores_operands { " storing operands" } else { "" };- with_inputs(&format!("CallDirect {location}{frames}{stores}"))+ let target = target.map_or(String::new(), |target| format!(" of constant target {target}"));+ with_inputs(&format!("CallDirect {location}{frames}{stores}{target}"))}Op::CallNative {executable,diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 8f1989ac517..c9f19762fbd 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -558,11 +558,16 @@ pub enum Op {/// holding an arguments object the code never created), the node reads/// its operands from the frame and writes the result there, like a/// `Generic` node.+ ///+ /// The callee it calls is its call feedback's `DirectCallTarget`, or+ /// with `target`, the graph's `direct_call_targets[target]`, a function+ /// the code holds as a constant.CallDirect {executable: u32,pc: u32,inlined_frame_bytes: u32,stores_operands: bool,+ target: Option<u32>,},/// The `Call` instruction at `pc` of `executable`, like `Generic`, but/// calling its call feedback's `NativeCallTarget` directly, in the@@ -2067,6 +2072,8 @@ pub struct Graph {/// Immutable properties of embedded typed arrays. Their fixed lengths/// require a valid cached storage offset before each access.pub typed_array_constants: Vec<(u64, crate::snapshot::TypedArraySnapshot)>,+ /// The targets of `Op::CallDirect` nodes that call function constants.+ pub direct_call_targets: Vec<crate::snapshot::DirectCallTarget>,/// The most bytes of interpreter stack that materializing the frames of/// inlined calls, and the frames of direct and native calls on top of/// them, take at once. Compiled code checks at entry that they fit.diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 4e0d5b8b321..7f707920356 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -691,6 +691,11 @@ pub struct PropertyCacheEntrySnapshot {/// it is a function JIT code may inline: code that calls the property's/// value as a constant can inline the call without feedback for it.pub prototype_property_inline_executable: Option<u32>,+ /// `prototype_property`, if it is a function JIT code can call directly+ /// whose calls need no function environment: code that calls the+ /// property's value as a constant can call it directly without feedback+ /// for it.+ pub prototype_property_direct_call: Option<DirectCallTarget>,/// The `WatchpointSet` cell that stays valid while `prototype` keeps/// `prototype_property` in the property and its shape (see/// `Shape::watch_slot_for_replacements()` in the runtime), if there isdiff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 339fd4289d5..7f89a2dd8ea 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -491,6 +491,8 @@ impl SnapshotBuilder<'_> {prototype_property_inline_executable: prototype_property.and_then(|object| {self.inline_executable_index(Some(Value::from_object(object).as_cell()), caller)}),+ prototype_property_direct_call: prototype_property+ .and_then(|object| self.prototype_method_direct_call(object)),// NB: Watching a slot allocates, which collects no garbage while the snapshot is taken. Slots// replaced while watched are checked instead, as invalidated code learns nothing, while the// check learns from its exit.@@ -855,6 +857,42 @@ impl SnapshotBuilder<'_> {Some(Some(index))}+ fn direct_call_target_snapshot(+ &mut self,+ function: Gc<EcmascriptFunctionObject>,+ environment: Option<u32>,+ closures: bool,+ ) -> DirectCallTarget {+ let executable = function.inline_call_executable();+ let entry = self+ .vm+ .jit+ .entry_table+ .as_ref()+ .expect("the VM has a JIT entry table while the JIT is on")+ .entry_address(executable.head.jit_entry_slot.get());+ DirectCallTarget {+ function: self.inlined_function(function),+ executable: self.cell(executable),+ entry,+ registers_and_locals_count: executable.registers_and_locals_count(),+ registers_and_locals_and_constants_count: executable.head.registers_and_locals_and_constants_count.get(),+ function_fields: function_frame_fields(function),+ environment,+ closures,+ }+ }++ /// The target through which JIT code may call `object`, a method a prototype held, directly, if it can and its+ /// calls need no function environment (whose template would belong to the executable of the call).+ fn prototype_method_direct_call(&mut self, object: Gc<Object>) -> Option<DirectCallTarget> {+ let function = as_ecmascript_function_object(object)?;+ if !function.can_inline_call() || function.function_environment_needed() {+ return None;+ }+ Some(self.direct_call_target_snapshot(function, None, false))+ }+fn call_feedback(&mut self, call: &CallFeedback, entry: &Entry) -> CallFeedbackSnapshot {let target = call.target();let flags = call.flags.get();@@ -883,28 +921,7 @@ impl SnapshotBuilder<'_> {&& let Some(environment) = self.direct_call_environment(function)&& !(closures && environment.is_some()){- let executable = function.inline_call_executable();- let function_fields = function_frame_fields(function);- let entry = self- .vm- .jit- .entry_table- .as_ref()- .expect("the VM has a JIT entry table while the JIT is on")- .entry_address(executable.head.jit_entry_slot.get());- snapshot.direct_call = Some(DirectCallTarget {- function: self.inlined_function(function),- executable: self.cell(executable),- entry,- registers_and_locals_count: executable.registers_and_locals_count(),- registers_and_locals_and_constants_count: executable- .head- .registers_and_locals_and_constants_count- .get(),- function_fields,- environment,- closures,- });+ snapshot.direct_call = Some(self.direct_call_target_snapshot(function, environment, closures));} else if let Some(function) = native_call_target(self.vm, call) {let entry = function.native_function(self.vm)