Truly independent web browser
LibJS/JIT: Reuse the strings of concatenations that are keys
Andreas Kling110a08dbeff1
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex a1ca8cc7dfe..5b24015078f 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -199,7 +199,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m| StringLength, LoadStringCodeUnit | The length of a string, and a code unit of a readable string at an index in bounds, which the refinements of their branches establish. Strings never change. | | | | cse || SingleCharacterString | The VM's string of an ASCII code unit (refined below 128). | | | | cse || StringsEqual | Whether two strings are equal, as a tagged boolean, or the empty value where only the slow path can tell. | | | | cse |-| ConcatenateStrings | The concatenation of two strings, a rope or a cached short string, or the empty value where only the slow path makes it. | | | | allocates |+| ConcatenateStrings | The concatenation of two strings, a rope or a cached short string, or the empty value where only the slow path makes it. If it is a `key` (`ConcatenateKeyStrings` in dumps), it is the string that the same two strings made when it became a property key before, where the VM remembers that, which the caches of keyed accesses know. | | | | allocates || IntegerToString | The VM's cached string of an int32, or the empty value. | | | | cse || LoadPropertyIteratorKeyCount, LoadPropertyIteratorKey | The keys of a property iterator cache, at an index refined to be in bounds. The keys never change. | | | | cse || OpenArrayIteration | `GetIterator` in fast array mode, through a runtime call that preserves every register: the iterable, if it is an array that iterates with `%Array.prototype.values%` and whose array iterators have the builtin `next`, or the empty value. The iteration then keeps the index of the next element in the iterator operand and the array in the next operand, and makes no iterator. | | Any | | |@@ -425,6 +425,7 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i| Escape analysis | Allocations that do not escape become their properties' SSA values; frame states refer to `VirtualObject`s. `AssumeLegacyArgumentsUnread` nodes after calls whose frame states have virtual objects among legacy arguments become `AssumeValid` nodes; the others go away. || Dead code elimination | Again, for what escape analysis left unused. || Branch fusion | A branch on a single-use comparison (int32, float64 or tagged) compares itself, after a block that only branches on a phi of booleans hands the branch to its predecessors. |+| Key strings | A `ConcatenateStrings` whose value is the key of a `ProbeKeyedCache`, `ProbeKeyedStore` or `ProbeHasProperty`, or one of the strings of such a concatenation, through refinements and phis other than those of loop headers, becomes a `key`: the rope it would make is a new string for every access, which the caches of the access never know. A concatenation that adds to the phi of a loop header stays as it is: it makes a piece of a string that a loop puts together. || Refinement removal | Every use of a refined value becomes a use of the value itself; `Refine` nodes go away and checks lose their values; value numbering then merges what differed only in refinements (section 3.2), and dead code elimination removes what only the merged checks' frame states kept alive. || Frame initialization | Moves `InitializeFrame` to the first node that observes the frame's slots on each path, and puts `PublishFrame` before nodes that only need the frame visible (allocations, calls in inlined callees) where it may not be yet. || Frame state cleanup | Drops the frame states no node uses. |diff --git a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rsindex 6ca0fd09918..f2a99a0a51d 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs@@ -1111,7 +1111,11 @@ impl GraphBuilder<'_> {}fn finish_concatenation(&mut self, paths: &mut SlowPaths, lhs: NodeId, rhs: NodeId) {- let result = self.emit(Op::ConcatenateStrings, vec![lhs, rhs], Some(Repr::Tagged));+ let result = self.emit(+ Op::ConcatenateStrings { key: false },+ vec![lhs, rhs],+ Some(Repr::Tagged),+ );let result = self.test_not_empty(paths, result);self.end_hot_path(paths, vec![result]);}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rsindex 633c4c0d704..b4528d1753b 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs@@ -12,7 +12,9 @@//! flat strings (whose ASCII bytes are in their storage word) find them in//! the VM's cache of fly strings if both strings are short. Everything else//! results in the empty value, for the slow path, which also fills that-//! cache.+//! cache. A concatenation that is the key of a property access looks for the+//! string that it made before in the VM's cache of such concatenations+//! first.use super::Codegen;use super::allocation::AllocationCall;@@ -30,8 +32,8 @@ use crate::snapshot::RopeAllocationInfo;impl<M: PortableMacroAssembler> Codegen<'_, M> {/// `ConcatenateStrings`: the concatenation of two strings, or the empty- /// value. Needs three temps.- pub(in crate::codegen) fn emit_concatenate_strings(&mut self, node: NodeId) {+ /// value, as the key of a property access if `key`. Needs three temps.+ pub(in crate::codegen) fn emit_concatenate_strings(&mut self, node: NodeId, key: bool) {let (lhs, rhs, output) = (self.input(node, 0), self.input(node, 1), self.output(node));let temps = [self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)];let (slow, done) = (self.masm.new_label(), self.masm.new_label());@@ -44,7 +46,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {} else {slow};- self.emit_concatenation_of_strings(node, [lhs, rhs], temps, no_free_cell, slow, done);+ self.emit_concatenation_of_strings(node, [lhs, rhs], temps, key, no_free_cell, slow, done);}self.masm.bind(slow);self.masm.move_imm64(output, value::EMPTY);@@ -131,13 +133,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// The concatenation of the strings `lhs` and `rhs` into the node's/// output, continuing at `done`, with the temps `cell`, `other` and- /// `length`. Branches to `no_free_cell` where the rope string's cell- /// cannot be allocated inline.+ /// `length`, as the key of a property access if `key`. Branches to+ /// `no_free_cell` where the rope string's cell cannot be allocated+ /// inline.+ #[allow(clippy::too_many_arguments)]fn emit_concatenation_of_strings(&mut self,node: NodeId,[lhs, rhs]: [Gpr; 2],[cell, other, length]: [Gpr; 3],+ key: bool,no_free_cell: Label,slow: Label,done: Label,@@ -172,6 +177,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let short = self.masm.new_label();self.masm.branch64_imm(Condition::Below, length, i64::from(rope.min_length), short);+ if key {+ self.emit_key_concatenation_cache_lookup(node, [lhs, rhs], [cell, other], done);+ }self.masm.add64_imm(scratch, length, 1);self.masm.shr64_imm(scratch, scratch, 32);self.masm.branch_test64(Condition::NonZero, scratch, u64::MAX, slow);@@ -196,6 +204,45 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_short_string_concatenation(node, [lhs, rhs], [cell, other, length], slow, done);}+ /// The string that the concatenation of the strings `lhs` and `rhs` made+ /// when it became a property key, into the node's output if the VM's+ /// cache of such concatenations has it (see+ /// `RuntimeLayout::key_concatenation_cache`), continuing at `done`; falls+ /// through otherwise. Uses `entry` and `other`.+ fn emit_key_concatenation_cache_lookup(+ &mut self,+ node: NodeId,+ [lhs, rhs]: [Gpr; 2],+ [entry, other]: [Gpr; 2],+ done: Label,+ ) {+ let layout = self.runtime.layout;+ let entry_size = layout.key_concatenation_cache_entry_size;+ if layout.key_concatenation_cache == 0 || !entry_size.is_power_of_two() {+ return;+ }+ let output = self.output(node);+ let miss = self.masm.new_label();+ // The index, ((lhs >> 4) ^ ((rhs >> 4) * 33)) & mask.+ self.masm.shr64_imm(entry, rhs, 4);+ self.masm.shl64_imm(other, entry, 5);+ self.masm.add64(entry, entry, other);+ self.masm.shr64_imm(other, lhs, 4);+ self.masm.xor64(entry, entry, other);+ self.masm.and32_imm(entry, entry, layout.key_concatenation_cache_mask);+ self.masm.shl64_imm(entry, entry, entry_size.trailing_zeros() as u8);+ self.masm.move_imm64(other, layout.key_concatenation_cache);+ self.masm.add64(entry, entry, other);+ let entry_lhs = Address::new(entry, layout.key_concatenation_cache_lhs as i32);+ let entry_rhs = Address::new(entry, layout.key_concatenation_cache_rhs as i32);+ let entry_string = Address::new(entry, layout.key_concatenation_cache_string as i32);+ self.masm.branch64_memory(Condition::NotEqual, &entry_lhs, lhs, miss);+ self.masm.branch64_memory(Condition::NotEqual, &entry_rhs, rhs, miss);+ self.masm.load64(output, &entry_string);+ self.masm.jump(done);+ self.masm.bind(miss);+ }+/// The concatenation of the non-empty strings `lhs` and `rhs`, whose/// lengths add up to that of a short string, into the node's output if/// both are short strings and the VM's fly string cache has the result,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rsindex 4bb67365bea..d81c169b47c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs@@ -417,7 +417,7 @@ pub fn lowering_info(node: &Node) -> LoweringInfo {// The first string's address, then its length or its storage word.Op::StringsEqual => plain.with_temps(1),// The new rope string, its length and a temp.- Op::ConcatenateStrings => plain.with_temps(3).saving_registers(),+ Op::ConcatenateStrings { .. } => plain.with_temps(3).saving_registers(),Op::IntegerToString => plain,// The array, then its prototypes.Op::CheckAppendableArray => plain.with_temps(2),diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 234f808edf4..d0cd8428100 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -1891,7 +1891,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Op::Uint32ShiftRight => self.emit_uint32_shift_right(node_id),Op::Uint32ToFloat64 => self.emit_uint32_to_float64(node_id),Op::StringsEqual => self.emit_strings_equal(node_id),- Op::ConcatenateStrings => self.emit_concatenate_strings(node_id),+ Op::ConcatenateStrings { key } => self.emit_concatenate_strings(node_id, *key),Op::IntegerToString => self.emit_integer_to_string(node_id),Op::StringAddress => {let (output, input) = (self.output(node_id), self.input(node_id, 0));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 2a359f90d21..6829ffd0b35 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1354,6 +1354,12 @@ fn fake_object_layout() -> RuntimeLayout {typeof_strings: crate::snapshot::TypeofStrings::default(),fly_string_cache: 0,fly_string_cache_mask: 0,+ key_concatenation_cache: 0,+ key_concatenation_cache_mask: 0,+ key_concatenation_cache_entry_size: 0,+ key_concatenation_cache_lhs: 0,+ key_concatenation_cache_rhs: 0,+ key_concatenation_cache_string: 0,numeric_string_cache: 0,numeric_string_cache_size: 0,large_numeric_string_cache: 0,@@ -4640,3 +4646,107 @@ fn rope_strings_come_from_the_runtime_without_a_local_free_cell() {assert_eq!(strings, [pointer(lhs), pointer(rhs)]);}}++#[test]+fn concatenations_that_are_keys_take_the_strings_the_vm_remembers() {+ // The VM's cache of the concatenations that became keys, with entries+ // of four words.+ const MASK: u64 = 7;+ let index = |lhs: u64, rhs: u64| (((lhs >> 4) ^ (rhs >> 4).wrapping_mul(33)) & MASK) as usize;+ // A concatenation, which is the key of a keyed access if `key`, with a+ // local free cell for a rope string.+ let concatenate = |cache: &[u64], lhs: u64, rhs: u64, key: bool| {+ let mut heap = vec![100u64, 10_000, 1000];+ let block = FakeBlock::new(8, 0);+ let address = block.cell().as_ptr() as u64;+ let mut free_list = vec![0, address, address + 64, 64];+ let program = assemble(|_| {+ let mut instructions = vec![+ Instruction::Enter,+ Instruction::Add {+ arith_feedback: 0,+ dst: r(5),+ lhs: argument(0),+ rhs: argument(1),+ },+ ];+ if key {+ instructions.push(Instruction::GetByValue {+ keyed_feedback: 0,+ dst: r(6),+ base: argument(2),+ property: r(5),+ cache: 0,+ });+ }+ instructions.push(Instruction::Return { value: r(5) });+ instructions+ });+ let (result, _) = run_program_with_snapshot(+ &program,+ &[lhs, rhs, value::int32(0)],+ |snapshot| {+ snapshot.runtime.rope_allocation = crate::snapshot::RopeAllocationInfo {+ allocator: free_list.as_mut_ptr() as u64,+ cell_size: 64,+ template: vec![0x1234; 8],+ lhs_offset: 32,+ rhs_offset: 36,+ length_offset: 16,+ min_length: 8,+ slow_path: fake_create_rope_string as *const () as u64,+ };+ snapshot.runtime.layout.key_concatenation_cache = cache.as_ptr() as u64;+ snapshot.runtime.layout.key_concatenation_cache_mask = MASK as u32;+ snapshot.runtime.layout.key_concatenation_cache_entry_size = 32;+ snapshot.runtime.layout.key_concatenation_cache_lhs = 0;+ snapshot.runtime.layout.key_concatenation_cache_rhs = 8;+ snapshot.runtime.layout.key_concatenation_cache_string = 16;+ let allocation = &mut snapshot.runtime.object_allocation;+ allocation.heap = heap.as_mut_ptr() as u64;+ allocation.heap_allocated_bytes_offset = 0;+ allocation.heap_threshold_offset = 8;+ allocation.heap_total_allocated_bytes_offset = 16;+ allocation.local_free_list_offset = 0;+ allocation.freelist_next_offset = 0;+ allocation.freelist_link_mask = FakeBlock::LINK_MASK;+ allocation.local_cursor_offset = 8;+ allocation.local_end_offset = 16;+ allocation.local_cell_size_offset = 24;+ // ArithFeedback::String.+ snapshot.executables[0].feedback.arith = vec![1 << 3];+ },+ |_| {},+ );+ assert_eq!(result.status, RETURNED);+ (result.value, u64::from(STRING_TAG) << 48 | address)+ };+ let (lhs, rhs) = (fake_string_of_length(5, 0), fake_string_of_length(4, 0));+ let remembered = fake_string_of_length(9, 0);+ let mut cache = vec![0u64; 4 * (MASK as usize + 1)];++ // Nothing is remembered: a rope string.+ let (result, rope) = concatenate(&cache, lhs, rhs, true);+ assert_eq!(result, rope);++ // The string that is remembered for both strings is the key.+ let entry = 4 * index(lhs, rhs);+ cache[entry..entry + 3].copy_from_slice(&[lhs, rhs, remembered]);+ assert_eq!(concatenate(&cache, lhs, rhs, true).0, remembered);++ // Other concatenations make rope strings, and so does a key whose+ // entry remembers another string on either side.+ let (result, rope) = concatenate(&cache, lhs, rhs, false);+ assert_eq!(result, rope);+ for other in [[rhs, rhs], [lhs, lhs]] {+ cache[entry..entry + 2].copy_from_slice(&other);+ let (result, rope) = concatenate(&cache, lhs, rhs, true);+ assert_eq!(result, rope);+ }++ // Short strings never come from this cache.+ let (short_lhs, short_rhs) = (fake_string_of_length(3, 0), fake_string_of_length(4, 0));+ let entry = 4 * index(short_lhs, short_rhs);+ cache[entry..entry + 3].copy_from_slice(&[short_lhs, short_rhs, remembered]);+ assert_eq!(concatenate(&cache, short_lhs, short_rhs, true).0, MARKER);+}diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex 543725441af..1ab23f324eb 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -327,7 +327,6 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {| Op::Uint32ShiftRight| Op::Uint32ToFloat64| Op::StringsEqual- | Op::ConcatenateStrings| Op::IntegerToString| Op::CheckAppendableArray| Op::LoadElementsLength@@ -355,6 +354,8 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {| Op::LoadTypedArrayDataOffset| Op::TypedArrayDataAddress| Op::CheckTypedArrayStorage => with_inputs(op.name()),+ Op::ConcatenateStrings { key: false } => with_inputs("ConcatenateStrings"),+ Op::ConcatenateStrings { key: true } => with_inputs("ConcatenateKeyStrings"),Op::ProbeHasProperty { own: true } => with_inputs("ProbeHasOwnProperty"),Op::ProbeHasProperty { own: false } => with_inputs("ProbeHasProperty"),Op::ProbeGlobalCache { cache } | Op::ProbeGlobalStore { cache } => {diff --git a/Libraries/LibJS/JIT/Rust/src/ir/info.rs b/Libraries/LibJS/JIT/Rust/src/ir/info.rsindex c1eebffe5eb..24ad3c0197a 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/info.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/info.rs@@ -511,7 +511,7 @@ impl Op {// NB: A cache miss and strings whose characters only the slow// path reads stay that way until the slow path ran.Op::StringsEqual => OpInfo::pure(I::TAGGED_2),- Op::ConcatenateStrings => OpInfo::pure(I::TAGGED_2).with_properties(P {+ Op::ConcatenateStrings { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P {allocates: true,..P::PURE}),diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex afee2c9d6a6..5458095e02a 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1148,8 +1148,14 @@ define_ops! {/// there is no local free cell (see `RopeAllocationInfo`), but for/// results short enough to be short/// strings, which come from the VM's cache of fly strings (when both- /// strings are short).- ConcatenateStrings,+ /// strings are short). If `key`, the string is the key of a property+ /// access or a part of one (see `passes::key_strings`): instead of a+ /// new rope string, it is the string that the same two strings made+ /// when it was a key before, where the VM remembers that (see+ /// `RuntimeLayout::key_concatenation_cache`).+ ConcatenateStrings {+ key: bool,+ },/// The VM's string of the `Repr::Int32` input 0, from its caches of the/// strings of non-negative integers, or the empty value if they have/// none.diff --git a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rsindex 122b40fc2f4..ab8a53792c5 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs@@ -317,7 +317,10 @@ fn visit_block(// them are strings where they are not.if let BranchCondition::TaggedEquals { equal } = condition&& graph.constant_value(inputs[1]) == Some(value::EMPTY)- && matches!(graph.node(inputs[0]).op, Op::ConcatenateStrings | Op::IntegerToString)+ && matches!(+ graph.node(inputs[0]).op,+ Op::ConcatenateStrings { .. } | Op::IntegerToString+ ){let not_empty = if equal { &mut facts } else { &mut passed };not_empty.set_value_kind(inputs[0], ValueKind::String);diff --git a/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs b/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rsnew file mode 100644index 00000000000..a798cad9335--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/passes/key_strings.rs@@ -0,0 +1,83 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Key strings: concatenations that are the keys of property accesses look+//! for the strings that they made before.+//!+//! `object["on" + type]` concatenates two strings into a rope string, which+//! the access resolves right away to find the property key. The rope string+//! is a new string every time, so the caches of the access, which know keys+//! by their strings, never have it, and the access takes its slow path every+//! time. The VM remembers the two strings of a rope that became a key, and+//! the string that it became. A concatenation whose value is the key of a+//! keyed access is marked (`Op::ConcatenateStrings::key`), and then takes+//! the string that the VM remembers for its two strings, if any, which the+//! caches of the access know by now.+//!+//! The key of an access is a phi of the concatenation and of what the slow+//! path of its instruction made, and may be one of several concatenations,+//! so the pass looks through phis and refinements. A string that a loop puts+//! together piece by piece is a key once, and its pieces never are, so the+//! pass does not look through the phis of loop headers, and leaves alone a+//! concatenation that adds to one. The strings of a marked concatenation+//! are looked at as well: the key `a + b + c` only finds its string if+//! `a + b` is the same string every time, which the VM remembers too. A+//! concatenation with other uses than keys is marked all the same: its+//! string has the same characters either way.++use crate::bitset::BitSet;+use crate::ir::Graph;+use crate::ir::NodeId;+use crate::ir::Op;++pub fn run(graph: &mut Graph) {+ let mut pending = Vec::new();+ for block in &graph.blocks {+ for node in block.nodes() {+ let node = graph.node(node);+ if matches!(+ node.op,+ Op::ProbeKeyedCache { .. } | Op::ProbeKeyedStore { .. } | Op::ProbeHasProperty { .. }+ ) {+ pending.push(node.inputs[1]);+ }+ }+ }+ let mut loop_phis = BitSet::new(graph.nodes.len());+ for block in graph.blocks.iter().filter(|block| block.is_loop_header) {+ for phi in &block.phis {+ loop_phis.insert(phi.index());+ }+ }+ let mut seen = BitSet::new(graph.nodes.len());+ let mut concatenations: Vec<NodeId> = Vec::new();+ while let Some(value) = pending.pop() {+ let value = graph.unrefined(value);+ if seen.contains(value.index()) {+ continue;+ }+ seen.insert(value.index());+ let node = graph.node(value);+ match node.op {+ Op::Phi if !loop_phis.contains(value.index()) => pending.extend(&node.inputs),+ Op::ConcatenateStrings { key: false } => {+ let adds_to_loop_phi = node+ .inputs+ .iter()+ .any(|&input| loop_phis.contains(graph.unrefined(input).index()));+ if adds_to_loop_phi {+ continue;+ }+ concatenations.push(value);+ pending.extend(&node.inputs);+ }+ _ => {}+ }+ }+ for concatenation in concatenations {+ graph.nodes[concatenation.index()].op = Op::ConcatenateStrings { key: true };+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rsindex 297bd620fef..25436d740dd 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -25,6 +25,7 @@ mod facts;mod frame_initialization;mod gvn;mod interrupt_check_elimination;+mod key_strings;mod licm;mod loop_rotation;mod representation;@@ -118,6 +119,10 @@ const PASSES: &[Pass] = &[name: "branch fusion",run: branch_fusion::run,},+ Pass {+ name: "key strings",+ run: key_strings::run,+ },];/// Runs every pass over `graph`, whose compiled function has frame layoutdiff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex ca1dc1871f0..ef51117a10d 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -1906,6 +1906,21 @@ pub struct RuntimeLayout {/// if it is there, where `u64_hash` is the MurmurHash3 64-bit finalizer.pub fly_string_cache: u64,pub fly_string_cache_mask: u32,+ /// The address of the VM's cache of the concatenations that became+ /// property keys, or 0 for code without one. Its entries are+ /// `key_concatenation_cache_entry_size` bytes, and have the two strings+ /// of a concatenation at `key_concatenation_cache_lhs` and+ /// `key_concatenation_cache_rhs` and the string that it made at+ /// `key_concatenation_cache_string`, as values (0 in an empty entry).+ /// The concatenation of the string values `l` and `r` is at index+ /// `((l >> 4) ^ ((r >> 4) * 33)) & key_concatenation_cache_mask` if it is+ /// there.+ pub key_concatenation_cache: u64,+ pub key_concatenation_cache_mask: u32,+ pub key_concatenation_cache_entry_size: u32,+ pub key_concatenation_cache_lhs: u32,+ pub key_concatenation_cache_rhs: u32,+ pub key_concatenation_cache_string: u32,/// The address of the VM's strings of the integers below/// `numeric_string_cache_size` (cell pointers, or null where it made/// none yet), or 0 for code without them.diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 5a2741be9c4..a88b8961fd6 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -458,6 +458,7 @@ pub(crate) fn default_host_enqueue_finalization_registry_cleanup_job(pub const STRING_TO_ATOM_CACHE_SIZE: usize = 256;pub const CHARACTERS_TO_ATOM_CACHE_SIZE: usize = 256;+pub const KEY_CONCATENATION_CACHE_SIZE: usize = 256;pub const FLY_STRING_CACHE_SIZE: usize = 1024;pub const NUMERIC_STRING_CACHE_SIZE: usize = 1000;pub const LARGE_NUMERIC_STRING_CACHE_SIZE: usize = 1024;@@ -481,6 +482,26 @@ pub struct CharactersToAtomCacheEntry {pub fly_string: Option<Utf16FlyString>,}+/// Remembers the string that the concatenation of the strings `lhs` and `rhs` made when it became a property key, so+/// that JIT code takes that string for a later concatenation of the same two strings (see+/// RopeString::remember_key_concatenations()). The three are string values, or 0 in an entry that remembers nothing.+/// JIT code reads the entries, which it finds by a shift, so their size is a power of two (see+/// RuntimeLayout::key_concatenation_cache).+#[repr(align(32))]+pub struct KeyConcatenationCacheEntry {+ pub lhs: Cell<u64>,+ pub rhs: Cell<u64>,+ pub string: Cell<u64>,+}++const _: () = assert!(size_of::<KeyConcatenationCacheEntry>().is_power_of_two());++/// Where the VM's cache of the concatenations that became property keys has the concatenation of the string values+/// `lhs` and `rhs`, if it has it. JIT code computes the same index.+fn key_concatenation_cache_index(lhs: u64, rhs: u64) -> usize {+ (((lhs >> 4) ^ (rhs >> 4).wrapping_mul(33)) as usize) & (KEY_CONCATENATION_CACHE_SIZE - 1)+}+#[derive(Trace)]pub struct NumericStringCacheEntry {pub number: Cell<u64>,@@ -569,6 +590,8 @@ pub struct Vm {/// The fly strings of short ASCII strings that became property keys before they had storage, found by a hash of/// their characters. Every collection empties this cache, so that it keeps no fly string alive for long.characters_to_atom_cache: RefCell<Box<[CharactersToAtomCacheEntry; CHARACTERS_TO_ATOM_CACHE_SIZE]>>,+ /// The strings in this cache are weak: every collection empties it.+ key_concatenation_cache: Box<[KeyConcatenationCacheEntry; KEY_CONCATENATION_CACHE_SIZE]>,/// The strings in these two caches are weak: the sweep callback drops the ones that die.string_to_atom_cache: RefCell<Box<[StringToAtomCacheEntry; STRING_TO_ATOM_CACHE_SIZE]>>,fly_string_cache: Box<[Cell<Option<Gc<PrimitiveString>>>; FLY_STRING_CACHE_SIZE]>,@@ -741,6 +764,15 @@ impl Vm {characters_to_atom_cache: RefCell::new(Box::new(core::array::from_fn(|_| {CharactersToAtomCacheEntry::default()}))),+ key_concatenation_cache: Box::new(+ [const {+ KeyConcatenationCacheEntry {+ lhs: Cell::new(0),+ rhs: Cell::new(0),+ string: Cell::new(0),+ }+ }; KEY_CONCATENATION_CACHE_SIZE],+ ),fly_string_cache: Box::new([const { Cell::new(None) }; FLY_STRING_CACHE_SIZE]),numeric_string_cache: Box::new([const { Cell::new(None) }; NUMERIC_STRING_CACHE_SIZE]),large_numeric_string_cache: Box::new(@@ -1592,6 +1624,11 @@ impl Vm {self.characters_to_atom_cache.borrow_mut().fill_with(CharactersToAtomCacheEntry::default);+ for entry in self.key_concatenation_cache.iter() {+ entry.lhs.set(0);+ entry.rhs.set(0);+ entry.string.set(0);+ }}/// Forgets the cells that died in this collection from the inline caches of executables and static call sites.@@ -1975,6 +2012,24 @@ impl Vm {&self.characters_to_atom_cache}+ pub fn key_concatenation_cache(&self) -> &[KeyConcatenationCacheEntry; KEY_CONCATENATION_CACHE_SIZE] {+ &self.key_concatenation_cache+ }++ /// Remembers that `string` is the concatenation of `lhs` and `rhs`, see KeyConcatenationCacheEntry.+ pub fn remember_key_concatenation(+ &self,+ lhs: Gc<PrimitiveString>,+ rhs: Gc<PrimitiveString>,+ string: Gc<PrimitiveString>,+ ) {+ let (lhs, rhs) = (Value::from_string(lhs).0, Value::from_string(rhs).0);+ let entry = &self.key_concatenation_cache[key_concatenation_cache_index(lhs, rhs)];+ entry.lhs.set(lhs);+ entry.rhs.set(rhs);+ entry.string.set(Value::from_string(string).0);+ }+pub fn fly_string_cache(&self) -> &[Cell<Option<Gc<PrimitiveString>>>; FLY_STRING_CACHE_SIZE] {&self.fly_string_cache}diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex 1fcf30471c9..63502831655 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -32,7 +32,8 @@ use crate::gc::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, Clause crate::gc::defer_gc::DeferGc;use crate::interpreter::runtime_functions::runtime_function_addresses;use crate::interpreter::vm::{- FLY_STRING_CACHE_SIZE, LARGE_NUMERIC_STRING_CACHE_SIZE, NUMERIC_STRING_CACHE_SIZE, NumericStringCacheEntry, Vm,+ FLY_STRING_CACHE_SIZE, KEY_CONCATENATION_CACHE_SIZE, KeyConcatenationCacheEntry, LARGE_NUMERIC_STRING_CACHE_SIZE,+ NUMERIC_STRING_CACHE_SIZE, NumericStringCacheEntry, Vm,};use crate::layout::accessor::Accessor;use crate::layout::cell::Gc;@@ -257,6 +258,12 @@ fn runtime_layout() -> RuntimeLayout {typeof_strings: TypeofStrings::default(),fly_string_cache: 0,fly_string_cache_mask: (FLY_STRING_CACHE_SIZE - 1) as u32,+ key_concatenation_cache: 0,+ key_concatenation_cache_mask: (KEY_CONCATENATION_CACHE_SIZE - 1) as u32,+ key_concatenation_cache_entry_size: size_of::<KeyConcatenationCacheEntry>() as u32,+ key_concatenation_cache_lhs: offset(offset_of!(KeyConcatenationCacheEntry, lhs)),+ key_concatenation_cache_rhs: offset(offset_of!(KeyConcatenationCacheEntry, rhs)),+ key_concatenation_cache_string: offset(offset_of!(KeyConcatenationCacheEntry, string)),numeric_string_cache: 0,numeric_string_cache_size: NUMERIC_STRING_CACHE_SIZE as u32,large_numeric_string_cache: 0,@@ -488,6 +495,7 @@ pub fn runtime_info(layout.keyed_lookup_cache_new_shape = keyed_lookup_cache.new_shape;layout.single_ascii_character_strings = vm.single_ascii_character_strings_address();layout.fly_string_cache = vm.fly_string_cache().as_ptr().expose_provenance() as u64;+ layout.key_concatenation_cache = vm.key_concatenation_cache().as_ptr().expose_provenance() as u64;layout.numeric_string_cache = vm.numeric_string_cache().as_ptr().expose_provenance() as u64;layout.large_numeric_string_cache = vm.large_numeric_string_cache().as_ptr().expose_provenance() as u64;let strings = vm.cached_strings();diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rsindex 2b24fa0a6ce..05408d15e9c 100644--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs@@ -133,6 +133,10 @@ fn is_ascii(code_unit: u16) -> bool {/// Vm::characters_to_atom_cache().pub const KEY_STRING_MAX_LENGTH: usize = INLINE_STRING_CAPACITY;+/// How deep the ropes in a rope that becomes a property key are remembered as concatenations: enough for the ropes+/// that a template literal with a few substitutions makes on the way to its string.+const REMEMBERED_KEY_CONCATENATION_DEPTH: usize = 3;+impl PrimitiveString {fn fly_string_cache_hash(string: &Utf16FlyString) -> usize {u64_hash(string.raw_identity() as u64) as usize@@ -598,6 +602,10 @@ impl PrimitiveString {/// returns that fly string.#[inline(never)]fn resolve_into_fly_string(&self, vm: &Vm) -> Utf16FlyString {+ if self.deferred_kind() == DeferredKind::Rope {+ self.as_rope_string()+ .remember_key_concatenations(vm, REMEMBERED_KEY_CONCATENATION_DEPTH);+ }// NB: Only the pieces of a rope have to be put together to look at its characters.let mut rope_characters = [0; KEY_STRING_MAX_LENGTH];let length = self.length_in_utf16_code_units();@@ -815,6 +823,26 @@ impl RopeString {self.rhs.set(None);}+ /// Remembers this rope, which is about to become a property key, as the concatenation of its halves, and the+ /// ropes among its halves as the concatenations of theirs, `depth` ropes deep.+ ///+ /// OPTIMIZATION: Programs put the same key together for every access, like "on" + type, and each time the key is+ /// a new rope that has to be resolved. JIT code looks up the two strings of a concatenation that is+ /// a key in the VM's cache of these concatenations, and takes the string that was the key before,+ /// which the caches of keyed accesses know by now.+ fn remember_key_concatenations(&self, vm: &Vm, depth: usize) {+ let (lhs, rhs) = (self.lhs(), self.rhs());+ vm.remember_key_concatenation(lhs, rhs, Gc::from_ref(&self.base));+ if depth == 0 {+ return;+ }+ for half in [lhs, rhs] {+ if half.deferred_kind() == DeferredKind::Rope {+ half.as_rope_string().remember_key_concatenations(vm, depth - 1);+ }+ }+ }+fn concatenate_pieces(&self) -> Utf16String {// OPTIMIZATION: Most ropes have a few pieces, which are gathered without allocating.const INLINE_PIECES: usize = 8;diff --git a/Tests/LibJS/JIT/ir/key-strings.js b/Tests/LibJS/JIT/ir/key-strings.jsnew file mode 100644index 00000000000..a8ec33a0a65--- /dev/null+++ b/Tests/LibJS/JIT/ir/key-strings.js@@ -0,0 +1,98 @@+// REQUIRES: inline-allocation+// A concatenation that is the key of a keyed access looks for the string that it made before, which the caches of the+// access know. Other concatenations make rope strings.++function read(object, name) {+ return object["on" + name];+}+jit.prepare(read);+const handlers = { onchange: 1, onkeydown: 2 };+for (let i = 0; i < 10; ++i) read(handlers, i & 1 ? "change" : "keydown");+jit.compile(read);++// CHECK-FUNCTION: read+// CHECK-PASS: branch fusion+// CHECK: [[KEY:v[0-9]+]] = ConcatenateStrings+// CHECK-PASS: key strings+// CHECK-NOT: ConcatenateStrings+// CHECK: [[KEY]] = ConcatenateKeyStrings+// CHECK: ProbeKeyedCache++// The key is a local variable that a loop assigns, and the store and the `in` take it too.+function count(object, names) {+ let key = "";+ let found = 0;+ for (let i = 0; i < names.length; ++i) {+ key = "data-" + names[i];+ if (key in object) ++found;+ object[key] = i;+ }+ return found;+}+jit.prepare(count);+for (let i = 0; i < 10; ++i) count({}, ["first", "second", "first"]);+jit.compile(count);++// CHECK-FUNCTION: count+// CHECK-PASS: key strings+// CHECK-COUNT-1: ConcatenateKeyStrings+// CHECK-COUNT-0: = ConcatenateStrings++// The strings of a key that are concatenations themselves look for their strings too, like those of a template literal.+function readEvent(object, name) {+ return object[`handle_${name}_event`] + object["before_" + name + "_event"];+}+jit.prepare(readEvent);+for (let i = 0; i < 10; ++i) readEvent({ handle_change_event: 1 }, i & 1 ? "change" : "keydown");+jit.compile(readEvent);++// CHECK-FUNCTION: readEvent+// CHECK-PASS: key strings+// CHECK-COUNT-4: ConcatenateKeyStrings+// CHECK-COUNT-0: = ConcatenateStrings++// A string that a loop puts together is a key once, and its pieces are rope strings.+function lookUp(object, names) {+ let path = "";+ for (let i = 0; i < names.length; ++i) path = path + names[i];+ return object[path];+}+jit.prepare(lookUp);+for (let i = 0; i < 10; ++i) lookUp({}, ["first_piece", "second_piece", "third_piece"]);+jit.compile(lookUp);++// CHECK-FUNCTION: lookUp+// CHECK-PASS: key strings+// CHECK-COUNT-1: = ConcatenateStrings+// CHECK-COUNT-0: ConcatenateKeyStrings++// The same goes for a loop that has more than one way out.+function lookUpUntil(object, names, last) {+ let path = "";+ for (let i = 0; i < names.length; ++i) {+ path = path + names[i];+ if (i === last) break;+ }+ return object[path];+}+jit.prepare(lookUpUntil);+for (let i = 0; i < 10; ++i) lookUpUntil({}, ["first_piece", "second_piece", "third_piece"], i & 1 ? 1 : 5);+jit.compile(lookUpUntil);++// CHECK-FUNCTION: lookUpUntil+// CHECK-PASS: key strings+// CHECK-COUNT-1: = ConcatenateStrings+// CHECK-COUNT-0: ConcatenateKeyStrings++// A concatenation that is no key stays a rope string.+function join(first, second) {+ return first + second;+}+jit.prepare(join);+for (let i = 0; i < 10; ++i) join("first_half_", "second_half");+jit.compile(join);++// CHECK-FUNCTION: join+// CHECK-PASS: key strings+// CHECK-COUNT-1: = ConcatenateStrings+// CHECK-COUNT-0: ConcatenateKeyStringsdiff --git a/Tests/LibJS/Runtime/string-keys-made-at-run-time.js b/Tests/LibJS/Runtime/string-keys-made-at-run-time.jsindex 4c91dd1499c..11eb0b87367 100644--- a/Tests/LibJS/Runtime/string-keys-made-at-run-time.js+++ b/Tests/LibJS/Runtime/string-keys-made-at-run-time.js@@ -88,6 +88,77 @@ describe("string keys made at run time", () => {expect(read(object, "a_" + "9" + ("_nested_" + "9") + "_rope")).toBe(399);});+ test("keys that the access itself puts together", () => {+ const names = ["click", "change", "keydown", "focus", "blur", "input", "submit", "dblclick"];+ const unicode = "äöü中文";+ const object = {};+ const array = [];+ const keys = [];+ let sum = 0;+ let found = 0;+ for (let i = 0; i < 4000; ++i) {+ const name = names[i & 7];+ object["on" + name] = i;+ sum += object["on" + name];+ if ("on" + name in object) ++found;+ if (Object.hasOwn(object, "off" + name)) --found;+ // A key that is used as a value too is the same string either way.+ const key = "data-" + name;+ object[key] = key;+ if (i < 8) keys.push(key);+ // Keys that are not ASCII, that are too long for the VM to remember, or that are indices.+ object[unicode + name] = i;+ object["a_key_of_more_than_32_characters_" + name] = i;+ array["1000" + "0000" + (i & 7)] = i;+ // A key in a local variable that the paths of a branch assign.+ let either;+ if (i & 1) either = "odd_" + name;+ else either = "even_" + name;+ object[either] = i;+ }+ expect(sum).toBe((3999 * 4000) / 2);+ expect(found).toBe(4000);+ expect(keys).toEqual(names.map(name => `data-${name}`));+ for (let i = 0; i < 8; ++i) {+ const name = names[i];+ expect(object[["on", name].join("")]).toBe(3992 + i);+ expect(object[["data-", name].join("")]).toBe(`data-${name}`);+ expect(object[[unicode, name].join("")]).toBe(3992 + i);+ expect(object[["a_key_of_more_than_32_characters_", name].join("")]).toBe(3992 + i);+ expect(object[[i & 1 ? "odd_" : "even_", name].join("")]).toBe(3992 + i);+ expect(array[100000000 + i]).toBe(3992 + i);+ expect(keys[i].length).toBe(5 + name.length);+ expect(keys[i] + "!").toBe(`data-${name}!`);+ }+ expect(Object.keys(object).length).toBe(40);+ expect(array.length).toBe(100000008);+ });++ test("keys that are put together while garbage is collected", () => {+ const names = ["click", "change", "keydown", "focus", "blur", "input", "submit", "dblclick"];+ // Most of these strings are never keys, and the ones that are have many different characters.+ function touch(object, i) {+ const key = "rarely_" + names[i & 7] + (i & 63);+ if ((i & 3) === 0) object[key] = i;+ return key.length;+ }+ const object = {};+ let length = 0;+ let expectedLength = 0;+ for (let i = 0; i < 2000; ++i) {+ length += touch(object, i);+ expectedLength += ["rarely_", names[i & 7], i & 63].join("").length;+ }+ collectGarbageOnEveryAllocation(() => {+ for (let i = 0; i < 256; ++i) length += touch(object, i);+ });+ for (let i = 0; i < 256; ++i) expectedLength += ["rarely_", names[i & 7], i & 63].join("").length;+ expect(length).toBe(expectedLength);+ expect(Object.keys(object).length).toBe(16);+ expect(object.rarely_click0).toBe(192);+ expect(object.rarely_blur60).toBe(252);+ });+test("index keys", () => {const array = [];for (let i = 0; i < 100; ++i) {