Truly independent web browser
LibJS: Read for-in keys' properties at the offsets the cache has
Andreas Klingc28acc13d1f6
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rsindex 9d07adfd08e..e4321a6612a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs@@ -397,6 +397,61 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.bind(done);}+ /// For a probe of a for-in loop's key at an index (whose inputs 2 and 3+ /// are the loop's property iterator cache and that index): goes to `hit`+ /// with the property's value in `output` (or `true`, unless `load`) where+ /// the object (decoded in `cell`) has the cache's shape and the cache has+ /// the offset of the own property the key names, and the property holds+ /// data if `load`. Goes to `miss` otherwise, having changed only `temps`+ /// and the scratch register.+ #[allow(clippy::too_many_arguments)]+ pub(in crate::codegen) fn emit_enumerated_property(+ &mut self,+ node: NodeId,+ cell: Gpr,+ temps: [Gpr; 2],+ load: bool,+ output: Gpr,+ hit: Label,+ miss: Label,+ ) {+ let (keys, index) = (self.input(node, 2), self.input(node, 3));+ let scratch = self.pinned.scratch;+ let layout = self.runtime.layout;+ let [cache, offset] = temps;+ self.emit_unbox_cell(cache, keys);+ // NB: Both shapes are compressed.+ self.masm+ .load32(scratch, &Address::new(cell, self.runtime.offsets.object_shape as i32));+ self.masm+ .load32(offset, &Address::new(cache, layout.property_iterator_shape as i32));+ self.masm.branch32(Condition::NotEqual, scratch, offset, miss);+ self.masm.load64(+ cache,+ &Address::new(cache, layout.property_iterator_property_offsets as i32),+ );+ self.masm.branch64_imm(Condition::Equal, cache, 0, miss);+ // NB: Int32 values only have their low 32 bits defined.+ self.masm.move32(offset, index);+ self.masm+ .load32(offset, &Address::indexed(cache, offset, Scale::Four, 0));+ self.masm.branch32_imm(Condition::Equal, offset, -1, miss);+ if !load {+ self.masm.move_imm64(output, value::TRUE);+ self.masm.jump(hit);+ return;+ }+ self.masm.load64(+ cache,+ &Address::new(cell, self.runtime.offsets.object_named_properties as i32),+ );+ self.masm+ .load64(scratch, &Address::indexed(cache, offset, Scale::Eight, 0));+ self.branch_on_tag(Condition::Equal, scratch, value::ACCESSOR_TAG, offset, miss);+ self.masm.move64(output, scratch);+ self.masm.jump(hit);+ }+/// A `ProbeKeyedCache` node: an entry of the property lookup cache for/// an own data property or a missing property, or the VM's keyed lookup/// cache.@@ -413,6 +468,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let (failure, done) = (self.probe_failure_label(), self.masm.new_label());let fail = failure.0;self.unbox_object_or_branch(object, base, fail);+ if self.graph.node(node).inputs.len() == 4 {+ let probe = self.masm.new_label();+ self.emit_enumerated_property(node, object, [shape, entry], true, output, done, probe);+ self.masm.bind(probe);+ }let lookup_cache = self.masm.new_label();self.probe_keyed_cache_entry(object, key, shape, entry, executable, cache, lookup_cache)?;let missing = self.masm.new_label();@@ -528,6 +588,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {miss: failure.0,});self.branch_on_tag(Condition::NotEqual, object, value::OBJECT_TAG, scratch, failure.0);+ if own && self.graph.node(node).inputs.len() == 4 {+ let probe_cache = self.masm.new_label();+ self.emit_unbox_cell(registers.object, object);+ self.emit_enumerated_property(+ node,+ registers.object,+ [registers.shape, registers.entry],+ false,+ output,+ done,+ probe_cache,+ );+ self.masm.bind(probe_cache);+ }if !own {self.emit_has_element(object, key, ®isters, output, probe, done);}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 61fb313cdf9..89a433c19c3 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1411,6 +1411,7 @@ fn fake_object_layout() -> RuntimeLayout {property_iterator_prototype_chain_validity: 32,property_iterator_property_values: 40,property_iterator_property_value_count: 48,+ property_iterator_property_offsets: 56,property_iterator_fast_path_none: 0,property_iterator_fast_path_packed_indexed: 2,executable_property_lookup_caches: 24,diff --git a/Libraries/LibJS/JIT/Rust/src/ir/info.rs b/Libraries/LibJS/JIT/Rust/src/ir/info.rsindex 24ad3c0197a..0e9e025faa9 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/info.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/info.rs@@ -93,6 +93,8 @@ pub enum Inputs {Exactly(&'static [Repr]),/// These, then any number of `rest`.AtLeast(&'static [Repr], Repr),+ /// The first ones, then either none or all of the others.+ WithOptional(&'static [Repr], &'static [Repr]),/// The receiver and the arguments of the intrinsic's `HelperCall`.HelperCall(Intrinsic),/// Not checked by their representations: phis take one input per predecessor, of their own representation (which@@ -119,6 +121,9 @@ impl Inputs {const OBJECT_VALUE: Self = Self::Exactly(&[Repr::Tagged, Repr::Tagged, Repr::Pointer]);/// Any number of tagged values.const TAGGED_ANY: Self = Self::AtLeast(&[], Repr::Tagged);+ /// An object and a key, and if the key is the key of a for-in loop's property iterator cache at an index, that+ /// cache and the index.+ const OBJECT_KEY: Self = Self::WithOptional(&[Repr::Tagged, Repr::Tagged], &[Repr::Tagged, Repr::Int32]);/// The representations of `count` inputs, if they are of this signature, or `None` if `count` is wrong. A/// `HelperCall` of an intrinsic without one, and `Unchecked`, accept anything.@@ -134,6 +139,11 @@ impl Inputs {.collect(),)),Inputs::AtLeast(first, _) => Err(first.len()),+ Inputs::WithOptional(first, _) if count == first.len() => Ok(Some(first.to_vec())),+ Inputs::WithOptional(first, optional) if count == first.len() + optional.len() => {+ Ok(Some(first.iter().chain(optional).copied().collect()))+ }+ Inputs::WithOptional(first, _) => Err(first.len()),Inputs::HelperCall(intrinsic) => {let Some(call) = intrinsic.helper_call() else {return Ok(None);@@ -568,7 +578,7 @@ impl Op {// checks). Its input, the call, ties it there.Op::SlowPathOutput { .. } => OpInfo::pure(I::TAGGED),Op::ProbePropertyCache { .. } => OpInfo::pure(I::TAGGED).with_properties(P::reading(Locations::NAMED)),- Op::ProbeKeyedCache { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::reading(Locations::NAMED)),+ Op::ProbeKeyedCache { .. } => OpInfo::pure(I::OBJECT_KEY).with_properties(P::reading(Locations::NAMED)),// NB: Additions may grow the object's storage.Op::ProbePropertyStore { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::STORE_PROBE),Op::ProbeKeyedStore { .. } => OpInfo::pure(I::TAGGED_3).with_properties(P::STORE_PROBE),@@ -582,7 +592,7 @@ impl Op {runs_code: true,..P::PURE}),- Op::ProbeHasProperty { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::reading(Locations::ALL)),+ Op::ProbeHasProperty { .. } => OpInfo::pure(I::OBJECT_KEY).with_properties(P::reading(Locations::ALL)),}}diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 5458095e02a..2fd67441d2f 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1260,7 +1260,10 @@ define_ops! {/// `undefined`) that the string or symbol input 1 names on the object in/// input 0, where keyed property lookup cache `cache` of executable/// `executable` or the VM's keyed lookup cache has it, or the empty- /// value.+ /// value. Where the key is a for-in loop's key at an index (see+ /// `LoadPropertyIteratorKey`), inputs 2 and 3 are its property+ /// iterator cache and that index, and objects of the shape the cache+ /// has read the property at the offset it has for the key first.ProbeKeyedCache {executable: u32,cache: u32,@@ -1308,6 +1311,9 @@ define_ops! {/// the VM can tell without running code (from its keyed lookup cache,/// the elements, or the runtime's lookup of objects whose lookups run no/// code). The empty value otherwise, and for other values than objects.+ /// Like `ProbeKeyedCache`, it may have a for-in loop's property+ /// iterator cache and index as inputs 2 and 3, which tell for own+ /// properties of objects of the cache's shape.ProbeHasProperty {own: bool,},diff --git a/Libraries/LibJS/JIT/Rust/src/passes/enumerated_keys.rs b/Libraries/LibJS/JIT/Rust/src/passes/enumerated_keys.rsnew file mode 100644index 00000000000..f25e9ceab5d--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/passes/enumerated_keys.rs@@ -0,0 +1,38 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Enumerated keys: the keyed loads and `hasOwnProperty` probes of a for-in+//! loop's key, where the key comes straight from the loop's property+//! iterator cache, get the cache and the key's index as inputs too. For+//! objects of the shape the cache has, code generation then finds the+//! property at the offset the cache has for the key, without probing a+//! lookup cache.++use crate::ir::Graph;+use crate::ir::Op;++pub fn run(graph: &mut Graph) {+ for block in 0..graph.blocks.len() {+ for index in 0..graph.blocks[block].body.len() {+ let node = graph.blocks[block].body[index];+ let data = graph.node(node);+ let probes_key = match data.op {+ Op::ProbeKeyedCache { .. } => true,+ Op::ProbeHasProperty { own } => own,+ _ => false,+ };+ if !probes_key || data.inputs.len() != 2 {+ continue;+ }+ let key = graph.node(graph.unrefined(data.inputs[1]));+ if key.op != Op::LoadPropertyIteratorKey {+ continue;+ }+ let (cache, key_index) = (key.inputs[0], key.inputs[1]);+ graph.nodes[node.index()].inputs.extend([cache, key_index]);+ }+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rsindex 27f32a39f95..28bb5be61ac 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -20,6 +20,7 @@ mod check_elimination;mod dce;pub mod dominators;pub mod edit;+mod enumerated_keys;mod escape_analysis;mod exit_unboxing;mod facts;@@ -120,6 +121,10 @@ const PASSES: &[Pass] = &[name: "dead code elimination",run: dce::run,},+ Pass {+ name: "enumerated keys",+ run: enumerated_keys::run,+ },Pass {name: "branch fusion",run: branch_fusion::run,diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex ef51117a10d..ff21a472872 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -2031,6 +2031,8 @@ pub struct RuntimeLayout {pub property_iterator_property_values: u32,/// The size (u64) of `ObjectPropertyIteratorCacheData::property_values`.pub property_iterator_property_value_count: u32,+ /// `ObjectPropertyIteratorCacheData::property_offsets`, the pointer to the first `u32`, or null.+ pub property_iterator_property_offsets: u32,/// `ObjectPropertyIteratorFastPath::None`.pub property_iterator_fast_path_none: u8,/// `ObjectPropertyIteratorFastPath::PackedIndexed`.diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex f9486e91dd0..91c124d4a6c 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -1115,7 +1115,7 @@ pub struct ObjectPropertyIteratorCacheDataStorage {define_cell!(ObjectPropertyIteratorCacheData, Other, finalize: finalize);-const _: () = assert!(size_of::<ObjectPropertyIteratorCacheData>() == 64);+const _: () = assert!(size_of::<ObjectPropertyIteratorCacheData>() == 72);// SAFETY: Visits the shape, the validity, the materialized key values and the keys.unsafe impl Trace for ObjectPropertyIteratorCacheData {@@ -1154,6 +1154,7 @@ impl ObjectPropertyIteratorCacheData {shape: NullableMember::new(Some(shape)),prototype_chain_validity: NullableMember::new(prototype_chain_validity),property_values: InterpreterBuffer::new(),+ property_offsets: Self::property_offsets(&shape, properties, indexed_property_count),storage: ObjectPropertyIteratorCacheDataStorage {properties: properties.to_vec().into_boxed_slice(),},@@ -1176,6 +1177,24 @@ impl ObjectPropertyIteratorCacheData {cache_data}+ /// The offsets of the own properties of objects of `shape` that the keys name, after the indices (see+ /// `ObjectPropertyIteratorCacheData::property_offsets`).+ fn property_offsets(+ shape: &Shape,+ properties: &MarkedVec<'_, PropertyKey>,+ indexed_property_count: u32,+ ) -> ThinSlice<u32> {+ if shape.is_dictionary() {+ return ThinSlice::empty();+ }+ let indices = core::iter::repeat_n(u32::MAX, indexed_property_count as usize);+ let named = (0..properties.len()).map(|index| {+ let key = properties.get(index).expect("the index is in bounds");+ shape.lookup(&key).map_or(u32::MAX, |metadata| metadata.offset)+ });+ indices.chain(named).collect()+ }+/// Slow-path snapshot: a plain key list with no fast path. Enumeration filters deleted keys with has_property() at/// each step, so there is no shape to revalidate against.pub fn create(vm: &Vm, properties: &MarkedVec<'_, PropertyKey>) -> Gc<ObjectPropertyIteratorCacheData> {@@ -1191,6 +1210,7 @@ impl ObjectPropertyIteratorCacheData {shape: NullableMember::null(),prototype_chain_validity: NullableMember::null(),property_values: InterpreterBuffer::new(),+ property_offsets: ThinSlice::empty(),storage: ObjectPropertyIteratorCacheDataStorage {properties: properties.to_vec().into_boxed_slice(),},diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex 63502831655..cf5a91c3184 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -336,6 +336,7 @@ fn runtime_layout() -> RuntimeLayout {ObjectPropertyIteratorCacheData,property_values.size)),+ property_iterator_property_offsets: offset(offset_of!(ObjectPropertyIteratorCacheData, property_offsets)),property_iterator_fast_path_none: ObjectPropertyIteratorFastPath::None as u8,property_iterator_fast_path_packed_indexed: ObjectPropertyIteratorFastPath::PackedIndexed as u8,executable_property_lookup_caches: offset(offset_of!(ExecutableHead, property_lookup_caches.data)),diff --git a/Libraries/LibJS/Rust/src/layout/property_lookup_cache.rs b/Libraries/LibJS/Rust/src/layout/property_lookup_cache.rsindex b70fc3174d4..c5dcb2bdd1e 100644--- a/Libraries/LibJS/Rust/src/layout/property_lookup_cache.rs+++ b/Libraries/LibJS/Rust/src/layout/property_lookup_cache.rs@@ -6,7 +6,7 @@use core::cell::Cell;-use super::buffer::InterpreterBuffer;+use super::buffer::{InterpreterBuffer, ThinSlice};use super::cell::{CellHeader, Gc};use super::function_object::FunctionObject;use super::member::NullableMember;@@ -121,6 +121,11 @@ pub struct ObjectPropertyIteratorCacheData {pub shape: NullableMember<Shape>,pub prototype_chain_validity: NullableMember<WatchpointSet>,pub property_values: InterpreterBuffer<Value>,+ /// For each key, the offset of the receiver's own property it names in the named property storage of objects of+ /// the shape, or `u32::MAX` where it names none (an index, or a key of the prototype chain). Empty where the shape+ /// is a dictionary, which can change in place. JIT code reads `object[key]` and `object.hasOwnProperty(key)` for+ /// the key at an index of the loop through it, for objects of the shape.+ pub property_offsets: ThinSlice<u32>,pub storage: ObjectPropertyIteratorCacheDataStorage,}diff --git a/Tests/LibJS/JIT/ir/for-in-enumerated-keys.js b/Tests/LibJS/JIT/ir/for-in-enumerated-keys.jsnew file mode 100644index 00000000000..bcb8212bc21--- /dev/null+++ b/Tests/LibJS/JIT/ir/for-in-enumerated-keys.js@@ -0,0 +1,19 @@+// A for-in loop's keyed loads and hasOwnProperty() calls of its key get the+// loop's property iterator cache and the key's index as inputs, so code+// generation can find the property at the offset the cache has for the key.++function count(o) {+ let n = 0;+ for (const k in o) if (o.hasOwnProperty(k) && o[k] != null) n++;+ return n;+}+jit.prepare(count);+for (let i = 0; i < 10; ++i) count({ a: 1, b: null, c: i });+jit.compile(count);++// CHECK-FUNCTION: count+// CHECK-PASS: enumerated keys+// CHECK: [[CACHE:v[0-9]+]] = CallSlowPath GetObjectPropertyIterator+// CHECK: [[KEY:v[0-9]+]] = LoadPropertyIteratorKey ([[CACHE]], [[INDEX:v[0-9]+]])+// CHECK: ProbeHasOwnProperty ({{v[0-9]+}}, [[KEY]], [[CACHE]], [[INDEX]])+// CHECK: ProbeKeyedCache cache {{[0-9]+}} ({{v[0-9]+}}, [[KEY]], [[CACHE]], [[INDEX]])