Skip to content

Truly independent web browser

LibJS: Start for-of loops over arrays without a runtime call

Aliaksandr Kalenik111c4c3464b9
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs
index f93ba8eb3f3..9df434cf411 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs
@@ -37,9 +37,20 @@ impl GraphBuilder<'_> {
}
/// Builds `GetIterator` (`Handling::Expanded`) of a synchronous iterator
- /// in fast array mode, where the instruction allows it (see
- /// `Op::OpenArrayIteration`): the index 0, the array, and not done.
- /// Returns `None`, having built nothing, where it does not.
+ /// in fast array mode (see `Op::OpenArrayIteration`), where the
+ /// instruction allows it: the index 0, the array, and not done.
+ ///
+ /// Arrays of the realm are iterated in that mode while they inherit
+ /// `%Array.prototype.values%` as their `@@iterator` and the realm's
+ /// array iterators have the builtin `next` method. The realm holds a
+ /// valid watchpoint set for each while it knows that they do, which the
+ /// code checks inline, like that the array has no named properties, of
+ /// which an own `@@iterator` would be one. Where that fails, the code
+ /// asks the runtime, which watches the intrinsics anew where unrelated
+ /// changes fired the sets. Returns `None`, having built nothing, where
+ /// the instruction does not allow fast array mode, and where the realm
+ /// held no valid set for one when the snapshot was taken: it never holds
+ /// one again then.
pub(super) fn try_build_get_iterator(
&mut self,
dst_iterator_object: Operand,
@@ -52,12 +63,41 @@ impl GraphBuilder<'_> {
if hint != SYNC_HINT || !fast_array_mode_allowed {
return Ok(None);
}
+ let (Some(next_watchpoint_set_address), Some(iterator_method_watchpoint_set_address)) = (
+ self.runtime.array_iterator_next_watchpoint_set_address,
+ self.runtime.array_iterator_method_watchpoint_set_address,
+ ) else {
+ return Ok(None);
+ };
let iterable = self.read(iterable)?;
let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;
- let array = self.emit(Op::OpenArrayIteration, vec![iterable], Some(Repr::Tagged));
- let array = self.branch_if_empty(&mut slow_paths, array);
let first_index = self.constant(value::int32(0));
let not_done = self.constant(value::FALSE);
+ self.embed(self.runtime.realm);
+ for watchpoint_set_address in [next_watchpoint_set_address, iterator_method_watchpoint_set_address] {
+ let watchpoint_set_address = self.typed_constant(watchpoint_set_address, Repr::Pointer);
+ self.branch_to_next_case(
+ &mut slow_paths,
+ BranchCondition::HoldsValidWatchpointSet,
+ vec![watchpoint_set_address],
+ true,
+ );
+ }
+ let array = self.branch_to_next_case(&mut slow_paths, BranchCondition::Object, vec![iterable], true);
+ let address = self.cell_address(array);
+ self.embed(self.runtime.array_prototype);
+ self.branch_to_next_case(
+ &mut slow_paths,
+ BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties,
+ vec![address],
+ true,
+ );
+ self.end_hot_path(&mut slow_paths, vec![first_index, array, not_done]);
+
+ let started = self.start_next_case(&mut slow_paths);
+ debug_assert!(started, "values that fail the checks go on to the next case");
+ let array = self.emit(Op::OpenArrayIteration, vec![iterable], Some(Repr::Tagged));
+ let array = self.branch_if_empty(&mut slow_paths, array);
let outputs = self.join_paths(slow_paths, vec![first_index, array, not_done], |_, outputs| outputs);
self.write(dst_iterator_object, outputs[0])?;
self.write(dst_iterator_next, outputs[1])?;
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
index 6004449b952..60ec8c73c7a 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
@@ -110,6 +110,50 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.bind(other);
}
+ /// A branch on `BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties`:
+ /// to `target` where the object at `object` is an array whose shape has
+ /// the realm's `%Array.prototype%` as its prototype and no named
+ /// properties, or where it is not, with `invert`.
+ pub(in crate::codegen) fn emit_branch_on_array_with_realm_array_prototype_and_no_named_properties(
+ &mut self,
+ node: NodeId,
+ object: Gpr,
+ target: Label,
+ invert: bool,
+ ) {
+ let shape = self.temp(node, 0);
+ let scratch = self.pinned.scratch;
+ let offsets = self.runtime.offsets;
+ let layout = self.runtime.layout;
+ let other = self.masm.new_label();
+ let fail = if invert { target } else { other };
+ self.masm
+ .load16(scratch, &Address::new(object, offsets.object_flags as i32));
+ self.masm.branch_test32(
+ Condition::Zero,
+ scratch,
+ u32::from(layout.object_flag_has_magical_length),
+ fail,
+ );
+ self.masm
+ .load64(shape, &Address::new(object, offsets.object_shape as i32));
+ self.masm
+ .load64(scratch, &Address::new(shape, layout.shape_prototype as i32));
+ self.masm.branch64_imm(
+ Condition::NotEqual,
+ scratch,
+ self.runtime.array_prototype.0 as i64,
+ fail,
+ );
+ self.masm
+ .load32(scratch, &Address::new(shape, layout.shape_property_count as i32));
+ self.masm.branch_test32(Condition::NonZero, scratch, u32::MAX, fail);
+ if !invert {
+ self.masm.jump(target);
+ }
+ self.masm.bind(other);
+ }
+
/// `LoadElementsCapacity`: the capacity of packed or holey indexed
/// storage, and 0 without storage.
pub(in crate::codegen) fn emit_load_elements_capacity(&mut self, node: NodeId) {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 5044b304d21..b7059969e2e 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -2249,6 +2249,22 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
BranchCondition::PlainArrayPrototypeChain => {
self.emit_branch_on_plain_array_prototype_chain(node, input, target, invert);
}
+ BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties => {
+ self.emit_branch_on_array_with_realm_array_prototype_and_no_named_properties(
+ node, input, target, invert,
+ );
+ }
+ BranchCondition::HoldsValidWatchpointSet => {
+ let other = self.masm.new_label();
+ let fail = if invert { target } else { other };
+ self.masm.load64(scratch, &Address::new(input, 0));
+ self.masm.branch_test64(Condition::Zero, scratch, u64::MAX, fail);
+ self.branch_unless_prototype_chain_valid(scratch, fail);
+ if !invert {
+ self.masm.jump(target);
+ }
+ self.masm.bind(other);
+ }
BranchCondition::MagicalLength | BranchCondition::Extensible => {
let flag = match condition {
BranchCondition::MagicalLength => self.runtime.layout.object_flag_has_magical_length,
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 79550645667..061dc9e7ec3 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -79,6 +79,10 @@ fn condition_text(condition: BranchCondition) -> String {
BranchCondition::ArrayIterator => "ArrayIterator".to_string(),
BranchCondition::GeneratorObject => "GeneratorObject".to_string(),
BranchCondition::PlainArrayPrototypeChain => "PlainArrayPrototypeChain".to_string(),
+ BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties => {
+ "ArrayWithRealmArrayPrototypeAndNoNamedProperties".to_string()
+ }
+ BranchCondition::HoldsValidWatchpointSet => "HoldsValidWatchpointSet".to_string(),
BranchCondition::Shape(shape) => format!("Shape {}", shapes_text(std::iter::once(&shape))),
BranchCondition::NonNegativeInt32 => "NonNegativeInt32".to_string(),
BranchCondition::Int32(comparison) => format!("Int32{comparison:?}"),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 389bfb01cab..205e65715f9 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -149,6 +149,13 @@ pub enum BranchCondition {
/// interfere with indexed property access, so that indices it has no
/// element at read undefined?
PlainArrayPrototypeChain,
+ /// The input is the `Repr::Pointer` of an object: is it an array whose
+ /// shape has the realm's `%Array.prototype%` as its prototype and no
+ /// named properties, so that it has no own `@@iterator`?
+ ArrayWithRealmArrayPrototypeAndNoNamedProperties,
+ /// The input is the `Repr::Pointer` address of a cell that holds an
+ /// optional watchpoint set: does it hold one that is still valid?
+ HoldsValidWatchpointSet,
/// Input 0 is an object and input 1 its address: does it have the
/// shape, like `Op::ShapeSwitch` cases test it? Only the refinements of
/// those cases have this condition; no branch does.
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
index 1f952b5b022..5b2f482bdff 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
@@ -284,6 +284,8 @@ fn constant_condition(graph: &Graph, condition: BranchCondition, input: NodeId,
| BranchCondition::ArrayIterator
| BranchCondition::GeneratorObject
| BranchCondition::PlainArrayPrototypeChain
+ | BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties
+ | BranchCondition::HoldsValidWatchpointSet
| BranchCondition::Shape(_) => None,
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index f9a75de0546..6a4adb891e9 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -488,7 +488,9 @@ fn branch_input_reprs(condition: crate::ir::BranchCondition) -> Vec<Repr> {
| crate::ir::BranchCondition::HoleFillableArray
| crate::ir::BranchCondition::ArrayIterator
| crate::ir::BranchCondition::GeneratorObject
- | crate::ir::BranchCondition::PlainArrayPrototypeChain => vec![Repr::Pointer],
+ | crate::ir::BranchCondition::PlainArrayPrototypeChain
+ | crate::ir::BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties
+ | crate::ir::BranchCondition::HoldsValidWatchpointSet => vec![Repr::Pointer],
crate::ir::BranchCondition::Shape(_) => vec![Repr::Tagged, Repr::Pointer],
crate::ir::BranchCondition::PropertyIteratorCacheValid => tagged(2),
crate::ir::BranchCondition::BindingMutable { .. } | crate::ir::BranchCondition::NextBindingOfShape { .. } => {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index bb210329cfc..929aa2c9598 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -441,6 +441,11 @@ fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {
condition: BranchCondition::PlainArrayPrototypeChain,
..
} => constraints.temps = 1,
+ // The object's shape.
+ Op::Branch {
+ condition: BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties,
+ ..
+ } => constraints.temps = 1,
// The object's elements.
Op::LoadElementsCapacity | Op::AppendElement => constraints.temps = 1,
// The object, then its elements or element address.
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 22c28b049b1..50e30ad4043 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -1045,6 +1045,17 @@ pub struct RuntimeInfo {
/// Code that depends on it must list it in
/// `CompiledCode::embedded_cells`.
pub array_iterator_return_watchpoint_set: Option<CellId>,
+ /// The address of the cell of the realm of the compiled code that holds
+ /// the watchpoint set that stays valid while `%ArrayIteratorPrototype%`
+ /// has its builtin `next` method, if it held a valid one. Once the set
+ /// fired, the realm watches the method anew with a new set the next
+ /// time it asks, as long as it is the builtin one, and holds none from
+ /// when it is not. Code that reads the cell must list the realm in
+ /// `CompiledCode::embedded_cells`.
+ pub array_iterator_next_watchpoint_set_address: Option<u64>,
+ /// Likewise for the watchpoint set that stays valid while
+ /// `%Array.prototype%[@@iterator]` is its `%Array.prototype.values%`.
+ pub array_iterator_method_watchpoint_set_address: Option<u64>,
/// The realm of the compiled code.
pub realm: CellId,
/// `%Array.prototype%` and `%Object.prototype%` of the realm of the
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index ff3e46b6e14..e70da3e1094 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -484,9 +484,11 @@ pub fn runtime_info(vm: &Vm, realm: Gc<Realm>, allocation: AllocationInfos) -> R
store_holey_element: super::calls::libjs_jit_store_holey_element as *const () as u64,
slice_arguments: super::calls::libjs_jit_slice_arguments as *const () as u64,
open_array_iteration: super::intrinsics::libjs_jit_open_array_iteration as *const () as u64,
- // NB: Filled in by capture_snapshot(), which lists it as an embedded cell.
+ // NB: Filled in by capture_snapshot(), which lists the cells as embedded cells.
array_iterator_next: None,
array_iterator_return_watchpoint_set: None,
+ array_iterator_next_watchpoint_set_address: None,
+ array_iterator_method_watchpoint_set_address: None,
jit_exit: super::entry_exit::libjs_jit_exit as *const () as u64,
to_boolean: addresses.to_boolean,
primitive_to_string: super::calls::libjs_jit_primitive_to_string as *const () as u64,
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 3f0f70733d1..83be44d62aa 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -56,6 +56,7 @@ use crate::runtime::object_constructor::ObjectConstructor;
use crate::runtime::object_prototype;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::realm_watchpoints;
use crate::runtime::shape::Shape;
use crate::runtime::shared_function_instance_data::ClosureCount;
use crate::runtime::shared_function_instance_data::ConstructorKind;
@@ -1207,6 +1208,12 @@ pub fn capture_snapshot(
.get()
.filter(|set| set.is_valid()),
);
+ // NB: Code that reads the cells of the realm embeds the realm.
+ builder.cell(realm);
+ runtime.array_iterator_next_watchpoint_set_address =
+ realm_watchpoints::array_iterator_next_watchpoint_set_address(realm);
+ runtime.array_iterator_method_watchpoint_set_address =
+ realm_watchpoints::array_iterator_method_watchpoint_set_address(realm);
let options = &vm.jit.options;
let snapshot = Snapshot {
executables,
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index b70c8a17073..ac2fd65867b 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -372,9 +372,12 @@ fn compile(
assert_eq!(executable.jit_compile_state(), CompileState::None);
executable.set_jit_compile_state(CompileState::Queued);
- // NB: The snapshot captures the set only while it is valid, and capturing it may not allocate a new one.
+ // NB: Asking the realm watches its intrinsics anew with new sets where the old ones fired, which allocates, so it
+ // happens before the snapshot captures which valid sets the realm holds.
let realm = function.realm().expect("an ECMAScript function has a realm");
realm_watchpoints::array_iterators_have_no_return(vm, realm);
+ realm_watchpoints::array_iterators_have_builtin_next(vm, realm);
+ realm_watchpoints::arrays_have_builtin_iterator_method(vm, realm);
// NB: Nothing may collect the cells the snapshot captured before something keeps them alive.
let defer_gc = DeferGc::new(vm);
diff --git a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
index a381cb914d9..4d11f5e605f 100644
--- a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
+++ b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
@@ -170,6 +170,14 @@ impl WatchedCondition {
self.stopped_holding.set(set.is_none());
set.is_some()
}
+
+ /// The address of the cell that holds the set that stays valid while the condition holds, if that set is valid.
+ fn valid_set_address(&self) -> Option<u64> {
+ self.set
+ .get()
+ .is_some_and(|set| set.is_valid())
+ .then_some(self.set.as_ptr() as u64)
+ }
}
/// A set that stays valid while `objects` keep their properties and prototypes, and the properties `slots` of them keep
@@ -263,6 +271,23 @@ pub fn arrays_have_builtin_iterator_method(vm: &Vm, realm: Gc<Realm>) -> bool {
.holds(vm, realm, watch_array_iterator_method)
}
+/// The address of the cell of the realm that holds the set that stays valid while %Array.prototype%[@@iterator] of the
+/// realm is its %Array.prototype.values%, if it holds a valid one. JIT code reads the cell to tell whether that held
+/// when the realm last found out (see `arrays_have_builtin_iterator_method()`).
+pub fn array_iterator_method_watchpoint_set_address(realm: Gc<Realm>) -> Option<u64> {
+ realm.storage.array_iterator_method.valid_set_address()
+}
+
+/// The address of the cell of the realm that holds the set that stays valid while array iterators of the realm have its
+/// builtin `next` method, if it holds a valid one. JIT code reads the cell to tell whether they had it when the realm
+/// last found out (see `array_iterators_have_builtin_next()`).
+pub fn array_iterator_next_watchpoint_set_address(realm: Gc<Realm>) -> Option<u64> {
+ let cell = &realm.array_iterator_next_watchpoint_set;
+ cell.get()
+ .is_some_and(|set| set.is_valid())
+ .then_some(cell.as_ptr() as u64)
+}
+
/// The set that stays valid while %Array.prototype%[@@iterator] of the realm is its %Array.prototype.values%, if it is.
fn watch_array_iterator_method(vm: &Vm, realm: Gc<Realm>) -> Option<Gc<WatchpointSet>> {
let array_prototype = realm.array_prototype();
diff --git a/Tests/LibJS/JIT/ir/array-destructuring.js b/Tests/LibJS/JIT/ir/array-destructuring.js
index 5173ec0fd9d..7eefedc9b93 100644
--- a/Tests/LibJS/JIT/ir/array-destructuring.js
+++ b/Tests/LibJS/JIT/ir/array-destructuring.js
@@ -13,7 +13,7 @@ if (sumPair([3, 4]) !== 7) throw new Error("wrong sum");
// CHECK-FUNCTION: sumPair
// CHECK-PASS: graph building
-// CHECK: OpenArrayIteration
+// CHECK: BranchArrayWithRealmArrayPrototypeAndNoNamedProperties
// CHECK-NOT: Allocate
// CHECK: CallSlowPath IteratorNextUnpack
// CHECK-NOT: Allocate
diff --git a/Tests/LibJS/JIT/ir/array-iteration-replaced-iterator-method.js b/Tests/LibJS/JIT/ir/array-iteration-replaced-iterator-method.js
new file mode 100644
index 00000000000..ec26e834a89
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/array-iteration-replaced-iterator-method.js
@@ -0,0 +1,24 @@
+// Once %Array.prototype%[@@iterator] was replaced, the realm's arrays may be iterated observably for good, and for-of
+// loops over them take the slow path of GetIterator, which calls the iterator method.
+
+const values = Array.prototype.values;
+let iteratorMethodCalls = 0;
+Array.prototype[Symbol.iterator] = function () {
+ ++iteratorMethodCalls;
+ return values.call(this);
+};
+
+function sum(array) {
+ let total = 0;
+ for (const value of array) total += value;
+ return total;
+}
+jit.prepare(sum);
+for (let i = 0; i < 10; ++i) sum([1, 2, 3]);
+jit.compile(sum);
+if (sum([4, 5]) !== 9 || iteratorMethodCalls !== 11) throw new Error("wrong iteration");
+
+// CHECK-FUNCTION: sum
+// CHECK-PASS: frame initialization
+// CHECK-NOT: BranchArrayWithRealmArrayPrototypeAndNoNamedProperties
+// CHECK: CallSlowPath GetIterator
diff --git a/Tests/LibJS/JIT/ir/array-iteration.js b/Tests/LibJS/JIT/ir/array-iteration.js
index 79497d64aea..8ac1c8fd09a 100644
--- a/Tests/LibJS/JIT/ir/array-iteration.js
+++ b/Tests/LibJS/JIT/ir/array-iteration.js
@@ -1,6 +1,9 @@
// For-of loops over arrays iterate them without array iterators and without
// calling the iterator method, and step them inline: the iterator operand
-// holds the index of the next element.
+// holds the index of the next element. Starting the loop checks inline that
+// the realm still knows its arrays to be iterated with its array iterators,
+// whose next method is the builtin one, and that the array is one of those,
+// and asks the runtime where that fails.
function sum(array) {
let total = 0;
@@ -21,8 +24,40 @@ if (sum([4, 5]) !== 9) throw new Error("wrong sum");
// CHECK-NOT: Uint32Min
// CHECK: LoadElementAt Holey
// CHECK-PASS: frame initialization
-// CHECK: [[ARRAY:v\d+]] = OpenArrayIteration
+// CHECK: BranchHoldsValidWatchpointSet (#pointer:{{[0-9a-fx]+}})
+// CHECK: BranchHoldsValidWatchpointSet (#pointer:{{[0-9a-fx]+}})
+// CHECK: BranchObject
+// CHECK: [[ADDRESS:v\d+]]:pointer = CellAddress
+// CHECK-NEXT: BranchArrayWithRealmArrayPrototypeAndNoNamedProperties ([[ADDRESS]])
+// CHECK: OpenArrayIteration
// CHECK: BranchNonNegativeInt32
// CHECK: [[INDEX:v\d+]]:int32 = UnboxInt32
// CHECK: LoadElementAt Holey ({{v\d+}}, [[INDEX]])
// CHECK: BoxInt32
+
+// An inlined method with a for-of loop over an array starts the loop without
+// a call, every time.
+
+class Totals {
+ constructor() {
+ this.total = 0;
+ }
+ add(values) {
+ for (const value of values) this.total += value;
+ }
+}
+function addTwice(totals, values) {
+ totals.add(values);
+ totals.add(values);
+ return totals.total;
+}
+jit.prepare(Totals.prototype.add);
+jit.prepare(addTwice);
+for (let i = 0; i < 10; ++i) addTwice(new Totals(), [1, 2, 3]);
+jit.compile(addTwice);
+if (addTwice(new Totals(), [4, 5]) !== 18) throw new Error("wrong total");
+
+// CHECK-FUNCTION: addTwice
+// CHECK-PASS: frame initialization
+// CHECK-NOT: CallDirect
+// CHECK-COUNT-2: BranchArrayWithRealmArrayPrototypeAndNoNamedProperties
diff --git a/Tests/LibJS/Runtime/jit/array-iteration-dependencies.js b/Tests/LibJS/Runtime/jit/array-iteration-dependencies.js
new file mode 100644
index 00000000000..11536cd74d6
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/array-iteration-dependencies.js
@@ -0,0 +1,130 @@
+// Compiled code starts for-of loops over arrays without asking the runtime while the realm's arrays are iterated with
+// the realm's array iterators, whose next method is the builtin one, which it reads from the realm at every loop start.
+// Changing either method, also while the code runs, makes the next loop start use the new method.
+//
+// NB: Every change of an iterator method makes the realm's arrays observably iterated for good, so the test that makes
+// one comes last, and array-iterator-next-dependency.js changes the other method in a realm of its own. The
+// functions come from the Function constructor, so that each run of a test (see LIBJS_TEST_REPEAT) compiles new
+// ones.
+
+function compiled(parameters, body, ...warmUpArguments) {
+ const f = new Function(...parameters, body);
+ jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f(...warmUpArguments);
+ expect(jit.compile(f)).toBe(jit.enabled);
+ return f;
+}
+
+const collectBody = "const values = []; for (const value of iterable) values.push(value); return values;";
+
+describe("for-of loops over arrays in compiled code", () => {
+ test("iterables other than plain arrays of the realm take the slow path", () => {
+ const collect = compiled(["iterable"], collectBody, [1, 2, 3]);
+ expect(collect([4, 5])).toEqual([4, 5]);
+ expect(collect([])).toEqual([]);
+ expect(collect([1, , 3])).toEqual([1, undefined, 3]);
+ const named = [1, 2];
+ named.label = "named";
+ expect(collect(named)).toEqual([1, 2]);
+ const own = [1, 2];
+ own[Symbol.iterator] = function* () {
+ yield "own";
+ };
+ expect(collect(own)).toEqual(["own"]);
+ class Subclass extends Array {}
+ expect(collect(Subclass.of(3, 4))).toEqual([3, 4]);
+ const otherPrototype = Object.setPrototypeOf([7, 8], {
+ *[Symbol.iterator]() {
+ yield "other";
+ },
+ });
+ expect(collect(otherPrototype)).toEqual(["other"]);
+ expect(() => collect(Object.setPrototypeOf([9], null))).toThrow(TypeError);
+ expect(collect(new Map([[1, 2]]))).toEqual([[1, 2]]);
+ expect(collect(new Set([9]))).toEqual([9]);
+ expect(collect("hi")).toEqual(["h", "i"]);
+ expect(collect(new Int8Array([1, 2]))).toEqual([1, 2]);
+ expect(collect({ length: 2, 0: "a", 1: "b", [Symbol.iterator]: Array.prototype.values })).toEqual(["a", "b"]);
+ expect(
+ collect(
+ (function* () {
+ yield 1;
+ })()
+ )
+ ).toEqual([1]);
+ expect(() => collect({})).toThrow(TypeError);
+ expect(() => collect(undefined)).toThrow(TypeError);
+ expect(collect([6, 7])).toEqual([6, 7]);
+ });
+
+ test("arrays that change while their loop runs", () => {
+ const visit = compiled(
+ ["array", "change"],
+ "const values = []; for (const value of array) { values.push(value); change(array, values.length); } return values;",
+ [1, 2, 3],
+ () => {}
+ );
+ const grow = (array, count) => {
+ if (count === 1) array.push(4);
+ };
+ const shrink = array => {
+ array.length = 1;
+ };
+ const name = (array, count) => {
+ if (count === 1) array.label = "named";
+ };
+ const ownIteratorMethod = (array, count) => {
+ if (count === 1)
+ array[Symbol.iterator] = function* () {
+ yield "own";
+ };
+ };
+ expect(visit([1, 2, 3], grow)).toEqual([1, 2, 3, 4]);
+ expect(visit([1, 2, 3], shrink)).toEqual([1]);
+ expect(visit([1, 2, 3], name)).toEqual([1, 2, 3]);
+ const array = [1, 2, 3];
+ expect(visit(array, ownIteratorMethod)).toEqual([1, 2, 3]);
+ expect(visit(array, () => {})).toEqual(["own"]);
+ });
+
+ test("loops in inlined callees", () => {
+ const sum = new Function("values", "let total = 0; for (const value of values) total += value; return total;");
+ jit.prepare(sum);
+ const sumBoth = compiled(["sum", "a", "b"], "return sum(a) + sum(b);", sum, [1, 2], [3]);
+ expect(sumBoth(sum, [1, 2, 3], [4])).toBe(10);
+ const named = [5];
+ named.label = "named";
+ expect(sumBoth(sum, named, new Set([6]))).toBe(11);
+ expect(sumBoth(sum, [], [1, , 2])).toBeNaN();
+ });
+});
+
+describe("a changed iterator method", () => {
+ // NB: The code calls the same function between its loops every time, so that it goes on in compiled code after it.
+ let action = () => {};
+ const between = () => action();
+
+ test("an iterator method of arrays replaced while compiled code runs is called from the next loop on", () => {
+ const originalIteratorMethod = Array.prototype[Symbol.iterator];
+ const twoLoops = compiled(
+ ["array", "between"],
+ "let first = ''; for (const value of array) { first += value; between(); } let second = ''; for (const value of array) second += value; return [first, second];",
+ [1, 2],
+ between
+ );
+ action = () => {
+ Array.prototype[Symbol.iterator] = function* () {
+ yield "replaced";
+ };
+ };
+ try {
+ expect(twoLoops([1, 2], between)).toEqual(["12", "replaced"]);
+ action = () => {};
+ expect(twoLoops([1, 2], between)).toEqual(["replaced", "replaced"]);
+ } finally {
+ action = () => {};
+ Array.prototype[Symbol.iterator] = originalIteratorMethod;
+ }
+ expect(twoLoops([1, 2], between)).toEqual(["12", "12"]);
+ });
+});
diff --git a/Tests/LibJS/Runtime/jit/array-iterator-next-dependency.js b/Tests/LibJS/Runtime/jit/array-iterator-next-dependency.js
new file mode 100644
index 00000000000..f9966d339a4
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/array-iterator-next-dependency.js
@@ -0,0 +1,45 @@
+// Compiled code starts for-of loops over arrays without asking the runtime while the realm's array iterators have
+// their builtin next method. Replacing it, also while the code runs, makes the next loop start call the new method
+// (see array-iteration-dependencies.js).
+
+function compiled(parameters, body, ...warmUpArguments) {
+ const f = new Function(...parameters, body);
+ jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f(...warmUpArguments);
+ expect(jit.compile(f)).toBe(jit.enabled);
+ return f;
+}
+
+// NB: The code calls the same function between its loops every time, so that it goes on in compiled code after it.
+let action = () => {};
+const between = () => action();
+
+test("a next method of array iterators replaced while compiled code runs is called from the next loop on", () => {
+ const iteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+ const originalNext = iteratorPrototype.next;
+ let calls = 0;
+ const twoLoops = compiled(
+ ["array", "between"],
+ "let first = 0; for (const value of array) { first += value; between(); } let second = 0; for (const value of array) second += value; return [first, second];",
+ [1, 2],
+ between
+ );
+ action = () => {
+ iteratorPrototype.next = function () {
+ ++calls;
+ return originalNext.call(this);
+ };
+ };
+ try {
+ expect(twoLoops([1, 2], between)).toEqual([3, 3]);
+ expect(calls).toBe(3);
+ action = () => {};
+ expect(twoLoops([1, 2], between)).toEqual([3, 3]);
+ expect(calls).toBe(9);
+ } finally {
+ action = () => {};
+ iteratorPrototype.next = originalNext;
+ }
+ expect(twoLoops([1, 2], between)).toEqual([3, 3]);
+ expect(calls).toBe(9);
+});