Skip to content

Truly independent web browser

LibJS/JIT: Optimize Array.prototype.splice for packed arrays

Andreas Kling75ef363e2f31
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 8d5fe3a2426..a3e5b6c946b 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -150,6 +150,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| CallFloat64Function | `Math.exp`, `log`, `sin`, `cos`, `tan` and `pow` of float64 values, through the runtime's function of doubles for each, which only computes. | | | | call, cse |
| PrimitiveToString, ToObject | ToString of a primitive, and ToObject of a primitive (but undefined and null) as a builtin of the running realm makes it (else the empty value), through the runtime. | | | | call, allocates |
| CallIntrinsic | A builtin of a `this` value and arguments of the kinds its `HelperCall` lists (like a string and an int32 position for `String.prototype.indexOf`), through its runtime helper, without a native frame; the helper runs in the realm of the calling code. Helpers that return any value return the empty value where they decline, having done nothing observable. | | Per `HelperCall` | Per `HelperCall` | call, allocates |
+| CallArraySplice | `Array.prototype.splice` of a plain packed array with int32 start and delete count and up to three inserted values, through the runtime without a native frame. The inserted values are passed on the native stack, where GC can see them. The helper checks the receiver, prototype chain and default species before allocating the removed-elements array and moving the suffix in bulk; it returns the empty value without observable effects for other cases, which take the call's slow path. | | Named, Elements | Elements | call, allocates |
| ArrayCreate | `new Array(length)` as the running realm's `Array` constructor makes it, through the runtime. | | | | call, allocates |
| **Checks** | | | | | |
| CheckObject, CheckValue, CheckClosure, CheckIdentityComparable | Exit unless input 0 is an object, a given value, a closure of a given function, or identity comparable. The value is input 0, refined (section 3.2). | E | | | cse |
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
index 3cffb9d915c..68e894e90f7 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
@@ -41,10 +41,72 @@ pub enum StringCharacter {
/// How many values `try_build_array_push()` appends inline at most.
const MAX_INLINE_PUSHED_VALUES: usize = 8;
+/// Keep the receiver, start, delete count and inserted values within the
+/// input limit of direct calls on every target.
+const MAX_INLINE_SPLICED_VALUES: usize = crate::codegen::DIRECT_CALL_MAX_INPUTS - 3;
+
/// How many arguments `try_build_math_min_max()` compares inline at most.
const MAX_MIN_MAX_ARGUMENTS: usize = 8;
impl GraphBuilder<'_> {
+ /// Calls the packed-array splice helper without a native frame. It
+ /// declines before doing anything observable for receivers or species
+ /// constructors that require the ordinary call.
+ pub(super) fn try_build_array_splice(&mut self, instruction: &Instruction) -> Result<Option<Flow>, CompileFailure> {
+ let Instruction::Call {
+ call_feedback,
+ dst,
+ callee,
+ this_value,
+ arguments,
+ ..
+ } = instruction
+ else {
+ return Ok(None);
+ };
+ if arguments.len() < 2
+ || arguments.len() > 2 + MAX_INLINE_SPLICED_VALUES
+ || self.runtime.array_splice == 0
+ || self.peek_intrinsic_callee(*call_feedback) != Some(Intrinsic::ArrayPrototypeSplice)
+ || self.holds_virtual_arguments(*this_value)
+ || arguments.iter().any(|argument| self.holds_virtual_arguments(*argument))
+ {
+ return Ok(None);
+ }
+ let realm = self
+ .function
+ .executable
+ .function
+ .map_or(self.runtime.realm, |function| function.realm);
+ if self
+ .call_feedback(*call_feedback)
+ .and_then(|feedback| feedback.native_call)
+ .map(|native| native.realm)
+ != Some(realm)
+ || self.checked_intrinsic_callee(*call_feedback, *callee)?.is_none()
+ {
+ return Ok(None);
+ }
+ let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;
+ let receiver = self.read(*this_value)?;
+ let mut inputs = vec![receiver];
+ for (index, argument) in arguments.iter().enumerate() {
+ let value = self.read(*argument)?;
+ inputs.push(if index < 2 {
+ self.int32_or_slow_path(&mut slow_paths, value)
+ } else {
+ value
+ });
+ }
+ let result = self.emit(Op::CallArraySplice, inputs, Some(Repr::Tagged));
+ let result = self.branch_if_empty(&mut slow_paths, result);
+ let result = self
+ .join_slow_paths(slow_paths, Some(result))
+ .expect("calls have a value");
+ self.write(*dst, result)?;
+ Ok(Some(Flow::Continue))
+ }
+
/// Builds a `Call` whose feedback saw a builtin that compiled code runs
/// inline: a function of `Math` that computes with numbers,
/// `String.prototype.charAt` and `charCodeAt`, or `String.fromCharCode`.
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index ddd24efbb0f..54f8fa777aa 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -1661,6 +1661,9 @@ impl<'a> GraphBuilder<'a> {
if let Some(flow) = self.try_build_array_push(instruction)? {
return Ok(Some(flow));
}
+ if let Some(flow) = self.try_build_array_splice(instruction)? {
+ return Ok(Some(flow));
+ }
if let Some(flow) = self.try_build_math_min_max(instruction)? {
return Ok(Some(flow));
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
index 60ec8c73c7a..527e7c3265f 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
@@ -7,8 +7,8 @@
//! Lowering of the array ops that `Array.prototype.push` of one value is
//! built from, the way its own fast path for packed arrays appends.
-use super::Codegen;
use super::slow_path_calls::slow_path_saved_registers;
+use super::{Codegen, InputValue};
use crate::asm::Address;
use crate::asm::Condition;
use crate::asm::Gpr;
@@ -18,6 +18,31 @@ use crate::asm::Scale;
use crate::ir::NodeId;
impl<M: PortableMacroAssembler> Codegen<'_, M> {
+ /// Calls the splice helper with the inserted values on the native
+ /// stack. The receiver, start and delete count are in argument registers;
+ /// store the other inputs before setting up the remaining arguments.
+ pub(in crate::codegen) fn emit_call_array_splice(&mut self, node: NodeId) {
+ let count = self.graph.node(node).inputs.len() - 3;
+ let bytes = ((count * 8 + 15) & !15) as i64;
+ if bytes != 0 {
+ self.masm.sub64_imm(M::STACK_POINTER, M::STACK_POINTER, bytes);
+ }
+ for index in 0..count {
+ let address = Address::new(M::STACK_POINTER, (index * 8) as i32);
+ match self.input_value(node, index + 3) {
+ InputValue::Register(value) => self.masm.store64(&address, value),
+ InputValue::Constant(value) => self.masm.store_imm64(&address, value),
+ }
+ }
+ self.masm.move64(M::ARGUMENT_GPRS[0], self.pinned.vm);
+ self.masm.move64(M::ARGUMENT_GPRS[4], M::STACK_POINTER);
+ self.masm.move_imm32(M::ARGUMENT_GPRS[5], count as u32);
+ self.masm.call_absolute(self.runtime.array_splice);
+ if bytes != 0 {
+ self.masm.add64_imm(M::STACK_POINTER, M::STACK_POINTER, bytes);
+ }
+ }
+
/// `CheckAppendableArray`: exits unless the input is an array that
/// `Array.prototype.push` appends to without any observable step.
pub(in crate::codegen) fn emit_check_appendable_array(&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 3fd0e7f4f43..7167dc878d9 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -1755,6 +1755,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::LoadElementsCapacity => self.emit_load_elements_capacity(node_id),
Op::AppendElement => self.emit_append_element_node(node_id),
Op::CallArrayPush => self.emit_call_array_push(node_id),
+ Op::CallArraySplice => self.emit_call_array_splice(node_id),
Op::CallStoreHoleyElement => self.emit_call_store_holey_element(node_id),
Op::OpenArrayIteration => self.emit_open_array_iteration(node_id),
Op::LoadArrayIteratorArray => self.emit_load_array_iterator_array(node_id),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index f4463ea0274..f4c04e9f7aa 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -323,6 +323,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
| Op::LoadElementsCapacity
| Op::AppendElement
| Op::CallArrayPush
+ | Op::CallArraySplice
| Op::CallStoreHoleyElement
| Op::OpenArrayIteration
| Op::LoadArrayIteratorArray
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index c9f19762fbd..9cab76ee60f 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -515,6 +515,10 @@ pub enum Op {
CallIntrinsic {
intrinsic: Intrinsic,
},
+ /// Splices a plain packed array through the runtime, or returns the
+ /// empty value without observable effects. Inputs: the tagged receiver,
+ /// int32 start and delete count, and the tagged values to insert.
+ CallArraySplice,
/// ToObject of input 0, a primitive other than undefined and null, as
/// the builtin function input 1 makes it (in its realm), through the
/// runtime, or the empty value where that is not the running realm.
@@ -1389,6 +1393,13 @@ impl Op {
allocates: true,
..P::PURE
},
+ Op::CallArraySplice => P {
+ is_call: true,
+ allocates: true,
+ reads: Locations::NAMED.union(Locations::ELEMENTS_AND_COUNTS),
+ writes: Locations::ELEMENTS_AND_COUNTS,
+ ..P::PURE
+ },
Op::CheckInt32
| Op::CheckFloat64Int32
| Op::CheckNumber
@@ -1680,6 +1691,7 @@ impl Op {
Op::ToBoolean => "ToBoolean",
Op::PrimitiveToString => "PrimitiveToString",
Op::CallIntrinsic { .. } => "CallIntrinsic",
+ Op::CallArraySplice => "CallArraySplice",
Op::ToObject => "ToObject",
Op::ArrayCreate => "ArrayCreate",
Op::Generic { .. } => "Generic",
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 6a4adb891e9..36a4100fd32 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -530,6 +530,15 @@ fn expected_input_reprs(graph: &Graph, node: NodeId) -> Option<Vec<Repr>> {
.collect()
}),
Op::ArrayCreate => Some(vec![Repr::Int32, Repr::Tagged]),
+ Op::CallArraySplice => {
+ let mut inputs = tagged(node.inputs.len());
+ if inputs.len() < 3 {
+ return Some(vec![Repr::Tagged, Repr::Int32, Repr::Int32]);
+ }
+ inputs[1] = Repr::Int32;
+ inputs[2] = Repr::Int32;
+ Some(inputs)
+ }
Op::LoadStringCodeUnit => Some(vec![Repr::Pointer, Repr::Int32]),
Op::SingleCharacterString | Op::Int32Abs | Op::Int32ToFloat64 => Some(vec![Repr::Int32]),
Op::AppendElement | Op::CallStoreHoleyElement => Some(vec![Repr::Pointer, Repr::Int32, Repr::Tagged]),
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index 4dcf19cf930..e601b567c64 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -338,6 +338,18 @@ fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {
.collect();
constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
}
+ Op::CallArraySplice => {
+ constraints.inputs = (0..node.inputs.len())
+ .map(|index| {
+ if index < 3 {
+ InputConstraint::FixedRegister(registers.argument_gprs[index + 1])
+ } else {
+ InputConstraint::RegisterOrConstant
+ }
+ })
+ .collect();
+ constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
+ }
Op::Generic { .. } => {
if node.repr.is_some() {
constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 7f707920356..b8f2827fe4b 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -749,6 +749,8 @@ pub enum Intrinsic {
ArrayPrototypePush,
/// `Array.prototype.slice`.
ArrayPrototypeSlice,
+ /// `Array.prototype.splice`.
+ ArrayPrototypeSplice,
/// `Object.prototype.hasOwnProperty`.
ObjectPrototypeHasOwnProperty,
/// `String.fromCharCode`.
@@ -1067,6 +1069,10 @@ pub struct RuntimeInfo {
/// observable step, growing its packed elements, and returns the new
/// length as a value.
pub array_push: u64,
+ /// `u64 (VM*, u64 receiver, i32 start, i32 delete_count, Value* items,
+ /// u32 item_count)`: splices a plain packed array without running code,
+ /// or returns the empty value without observable effects.
+ pub array_splice: u64,
/// `void libjs_jit_store_holey_element(Object*, u32 index, u64 value)`:
/// stores `value` at `index`, below the length of the holey elements of
/// an array whose prototype chain has no indexed properties, growing the
diff --git a/Libraries/LibJS/Rust/src/jit/helper_calls.rs b/Libraries/LibJS/Rust/src/jit/helper_calls.rs
index 11531e83b0a..26584439206 100644
--- a/Libraries/LibJS/Rust/src/jit/helper_calls.rs
+++ b/Libraries/LibJS/Rust/src/jit/helper_calls.rs
@@ -42,6 +42,7 @@ pub fn address(intrinsic: Intrinsic) -> u64 {
| Intrinsic::FunctionPrototypeCall
| Intrinsic::ArrayPrototypePush
| Intrinsic::ArrayPrototypeSlice
+ | Intrinsic::ArrayPrototypeSplice
| Intrinsic::ObjectPrototypeHasOwnProperty
| Intrinsic::StringFromCharCode
| Intrinsic::StringConstructor
diff --git a/Libraries/LibJS/Rust/src/jit/intrinsics.rs b/Libraries/LibJS/Rust/src/jit/intrinsics.rs
index 429b5696d42..cfb81664742 100644
--- a/Libraries/LibJS/Rust/src/jit/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/jit/intrinsics.rs
@@ -17,6 +17,7 @@ use crate::layout::cell::Gc;
use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::runtime::array::Array;
+use crate::runtime::completion::Must;
use crate::runtime::module_namespace_object::ModuleNamespaceObject;
use crate::runtime::property_key::{PropertyKey, StringMayBeNumber};
use crate::runtime::proxy_object::ProxyObject;
@@ -25,6 +26,65 @@ use crate::runtime::string_object::StringObject;
use crate::runtime::typed_array::{ContentType, TypedArrayBase};
use crate::utf16::{has_fly_string_storage, to_utf16_fly_string};
+/// The packed-array path of Array.prototype.splice, without coercions or
+/// calls of species constructors. All checks precede its observable work.
+///
+/// # Safety
+///
+/// `items` points to `item_count` live, aligned values on the caller's native
+/// stack, outside any object's element storage, for the duration of the call.
+pub unsafe extern "C" fn libjs_jit_array_splice(
+ vm: &Vm,
+ receiver: u64,
+ start: i32,
+ delete_count: i32,
+ items: *const Value,
+ item_count: u32,
+) -> u64 {
+ let receiver = Value::from_bits(receiver);
+ if !receiver.is_object() {
+ return Value::EMPTY.0;
+ }
+ let Some(array) = receiver.as_object().downcast::<Array>() else {
+ return Value::EMPTY.0;
+ };
+ let realm = vm.current_realm().expect("JIT code runs in a realm");
+ if array.realm() != realm
+ || !array.is_simple_packed_array()
+ || !array.extensible()
+ || !array.length_is_writable()
+ || array.shape().property_count() != 0
+ || !array.default_prototype_chain_intact()
+ || !realm_watchpoints::array_species_is_unchanged(vm, realm)
+ {
+ return Value::EMPTY.0;
+ }
+ let length = array.indexed_array_like_size();
+ let start = if start < 0 {
+ (i64::from(length) + i64::from(start)).max(0) as u32
+ } else {
+ (start as u32).min(length)
+ };
+ let delete_count = (delete_count.max(0) as u32).min(length - start);
+ if u64::from(length - delete_count) + u64::from(item_count) > u64::from(u32::MAX) {
+ return Value::EMPTY.0;
+ }
+ let removed = Array::create(vm, realm, 0, None).must();
+ removed.set_indexed_property_elements_to_undefined(delete_count);
+ for index in 0..delete_count {
+ let value = array
+ .indexed_get(start + index)
+ .expect("packed arrays have every element")
+ .value;
+ removed.set_packed_indexed_element(index, value);
+ }
+ // SAFETY: The caller keeps these values on its native stack, which GC
+ // scans while allocating the result. Element storage growth does not collect.
+ let items = unsafe { ak::slice_from_raw_parts(items, item_count as usize) };
+ array.splice_packed_indexed_elements(start, delete_count, items);
+ Value::from_object(removed).0
+}
+
/// The property key of a string or symbol, which converting runs no code for.
fn string_or_symbol_key(vm: &Vm, key: Value) -> Option<PropertyKey> {
if !key.is_string() && !key.is_symbol() {
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 4c9c4d292ee..c2bb42d2b0b 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -499,6 +499,7 @@ pub fn runtime_info(
0
},
array_push: super::calls::libjs_jit_array_push as *const () as u64,
+ array_splice: super::intrinsics::libjs_jit_array_splice as *const () as u64,
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,
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 73b85e40ea8..c0f74f3e6ed 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -181,11 +181,12 @@ fn intrinsic_of(vm: &Vm, cell: Option<Gc<CellHeader>>) -> Option<Intrinsic> {
}
/// The intrinsics the compiler knows by their native functions (of any realm).
-static NATIVE_INTRINSICS: [(&RawNativeFunctionPointer, Intrinsic); 23] = [
+static NATIVE_INTRINSICS: [(&RawNativeFunctionPointer, Intrinsic); 24] = [
(&function_prototype::APPLY_FUNCTION, Intrinsic::FunctionPrototypeApply),
(&function_prototype::CALL_FUNCTION, Intrinsic::FunctionPrototypeCall),
(&array_prototype::PUSH_FUNCTION, Intrinsic::ArrayPrototypePush),
(&array_prototype::SLICE_FUNCTION, Intrinsic::ArrayPrototypeSlice),
+ (&array_prototype::SPLICE_FUNCTION, Intrinsic::ArrayPrototypeSplice),
(
&object_prototype::HAS_OWN_PROPERTY_FUNCTION,
Intrinsic::ObjectPrototypeHasOwnProperty,
diff --git a/Libraries/LibJS/Rust/src/runtime/array_prototype.rs b/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
index 07146330671..cd75b2acd1a 100644
--- a/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
@@ -120,9 +120,10 @@ fn clamp(value: f64, min: f64, max: f64) -> f64 {
value
}
-/// The native functions of Array.prototype.push and slice, which JIT code knows.
+/// The native functions of Array.prototype.push, slice and splice, which JIT code knows.
pub(crate) static PUSH_FUNCTION: RawNativeFunctionPointer = raw_native!(ArrayPrototype::push);
pub(crate) static SLICE_FUNCTION: RawNativeFunctionPointer = raw_native!(ArrayPrototype::slice);
+pub(crate) static SPLICE_FUNCTION: RawNativeFunctionPointer = raw_native!(ArrayPrototype::splice);
impl ArrayPrototype {
pub fn create(vm: &Vm, realm: Gc<Realm>) -> Gc<ArrayPrototype> {
@@ -178,7 +179,7 @@ impl ArrayPrototype {
define_native_function(&names.slice, SLICE_FUNCTION, 2);
define_native_javascript_backed_function(&names.some, intrinsics.some_array_prototype_function(vm));
define_native_function(&names.sort, raw_native!(ArrayPrototype::sort), 1);
- define_native_function(&names.splice, raw_native!(ArrayPrototype::splice), 2);
+ define_native_function(&names.splice, SPLICE_FUNCTION, 2);
define_native_function(&names.toLocaleString, raw_native!(ArrayPrototype::to_locale_string), 0);
define_native_function(&names.toReversed, raw_native!(ArrayPrototype::to_reversed), 0);
define_native_function(&names.toSorted, raw_native!(ArrayPrototype::to_sorted), 1);
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 547fba3c966..ec19c48ed91 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -4483,6 +4483,35 @@ impl Object {
assert!(index < self.indexed_packed_element_count());
self.set_indexed_element(index, value);
}
+
+ /// Splices packed storage whose ordinary property operations the caller
+ /// has established have no observable effects. Storage growth never
+ /// collects, and `items` must come from outside this object's storage.
+ #[cfg(feature = "jit")]
+ pub(crate) fn splice_packed_indexed_elements(&self, start: u32, delete_count: u32, items: &[Value]) {
+ assert_eq!(self.indexed_storage_kind(), IndexedStorageKind::Packed);
+ let old_size = self.indexed_array_like_size();
+ assert!(start <= old_size && delete_count <= old_size - start);
+ let new_size = u32::try_from(u64::from(old_size - delete_count) + items.len() as u64)
+ .expect("the caller checked the new array length");
+ self.ensure_indexed_elements(new_size);
+ let elements = self.indexed_elements.get();
+ // SAFETY: Packed storage holds all old_size elements, and growing it
+ // above made room for new_size. Both ranges are in that storage and
+ // may overlap. The inserted values do not alias the storage.
+ unsafe {
+ core::ptr::copy(
+ elements.add((start + delete_count) as usize),
+ elements.add(start as usize + items.len()),
+ (old_size - start - delete_count) as usize,
+ );
+ core::ptr::copy_nonoverlapping(items.as_ptr(), elements.add(start as usize), items.len());
+ for index in new_size..old_size {
+ elements.add(index as usize).write(Value::EMPTY);
+ }
+ }
+ self.indexed_array_like_size.set(new_size);
+ }
}
fn create_data_property_for_set(
diff --git a/Tests/LibJS/JIT/ir/array-splice.js b/Tests/LibJS/JIT/ir/array-splice.js
new file mode 100644
index 00000000000..eea626a4e1c
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/array-splice.js
@@ -0,0 +1,25 @@
+function spliceThree(array, start, count, x, y, z) {
+ return array.splice(start, count, x, y, z);
+}
+jit.prepare(spliceThree);
+for (let i = 0; i < 10; ++i) spliceThree([1, 2, 3, 4], 1, 1, 5, 6, 7);
+jit.compile(spliceThree);
+
+// CHECK-FUNCTION: spliceThree
+// CHECK-PASS: graph building
+// CHECK: CallArraySplice
+// CHECK-NOT: CallNative
+// CHECK: CallSlowPath Call
+
+function deleteOnly(array, start, count) {
+ return array.splice(start, count);
+}
+jit.prepare(deleteOnly);
+for (let i = 0; i < 10; ++i) deleteOnly([1, 2, 3, 4], 1, 2);
+jit.compile(deleteOnly);
+
+// CHECK-FUNCTION: deleteOnly
+// CHECK-PASS: graph building
+// CHECK: CallArraySplice
+// CHECK-NOT: CallNative
+// CHECK: CallSlowPath Call
diff --git a/Tests/LibJS/Runtime/jit/array-splice.js b/Tests/LibJS/Runtime/jit/array-splice.js
new file mode 100644
index 00000000000..0ac5feaa147
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/array-splice.js
@@ -0,0 +1,161 @@
+function compiledSplice(itemCount) {
+ const parameters = ["array", "start", "count", "x", "y", "z"].slice(0, itemCount + 3);
+ const call = parameters.slice(1).join(", ");
+ const splice = new Function(...parameters, `return array.splice(${call});`);
+ jit.prepare(splice);
+ for (let i = 0; i < 10; ++i) splice([1, 2, 3, 4], 1, 1, 5, 6, 7);
+ expect(jit.compile(splice)).toBe(jit.enabled);
+ return splice;
+}
+
+test("packed splices move both overlapping directions and return removed elements", () => {
+ for (let itemCount = 0; itemCount <= 3; ++itemCount) {
+ const splice = compiledSplice(itemCount);
+ const reference = new Function("a", "start", "count", "items", "return a.splice(start, count, ...items);");
+ jit.neverCompile(reference);
+ const items = [{ name: "one" }, "two", 3.5].slice(0, itemCount);
+ for (const length of [1, 2, 4, 7, 64, 1025]) {
+ const values = Array.from({ length }, (_, i) => i);
+ for (const start of [-0x80000000, -length - 1, -1, 0, 1, length - 1, length, 0x7fffffff]) {
+ for (const count of [-0x80000000, -1, 0, 1, 2, length, 0x7fffffff]) {
+ const actual = values.slice();
+ const expected = values.slice();
+ expect(splice(actual, start, count, ...items)).toEqual(reference(expected, start, count, items));
+ expect(actual).toEqual(expected);
+ }
+ }
+ }
+ }
+});
+
+test("empty and holey arrays keep their ordinary splice behavior", () => {
+ const splice = compiledSplice(2);
+ const empty = [];
+ expect(splice(empty, 0, 10, "a", "b")).toEqual([]);
+ expect(empty).toEqual(["a", "b"]);
+ const holey = [1, , 3, , 5];
+ const removed = splice(holey, 1, 3, "a", "b");
+ expect(removed.length).toBe(3);
+ expect(0 in removed).toBeFalse();
+ expect(removed[1]).toBe(3);
+ expect(2 in removed).toBeFalse();
+ expect(holey).toEqual([1, "a", "b", 5]);
+});
+
+test("argument coercions and changed methods run once", () => {
+ const splice = compiledSplice(1);
+ let calls = 0;
+ const array = [1, 2, 3];
+ const start = {
+ valueOf() {
+ ++calls;
+ return 1;
+ },
+ };
+ expect(splice(array, start, 1, "x")).toEqual([2]);
+ expect(calls).toBe(1);
+ expect(array).toEqual([1, "x", 3]);
+ array.splice = function (...args) {
+ ++calls;
+ return args;
+ };
+ expect(splice(array, 0, 2, "y")).toEqual([0, 2, "y"]);
+ expect(calls).toBe(2);
+});
+
+test("custom species is observed before changing the source array", () => {
+ const splice = compiledSplice(3);
+ const array = [1, 2, 3];
+ let calls = 0;
+ array.constructor = {
+ [Symbol.species]: function (length) {
+ ++calls;
+ expect(length).toBe(1);
+ expect(array).toEqual([1, 2, 3]);
+ return { created: true };
+ },
+ };
+ expect(splice(array, 1, 1, "a", "b", "c")).toEqual({ 0: 2, length: 1, created: true });
+ expect(calls).toBe(1);
+ expect([...array]).toEqual([1, "a", "b", "c", 3]);
+});
+
+test("non-writable arrays throw through the ordinary call", () => {
+ const splice = compiledSplice(1);
+ expect(() => splice(Object.freeze([1, 2, 3]), 1, 1, 4)).toThrow(TypeError);
+ const array = [1, 2, 3];
+ Object.defineProperty(array, "length", { writable: false });
+ expect(() => splice(array, 1, 1, 4)).toThrow(TypeError);
+ expect(array).toEqual([1, 4, 3]);
+});
+
+test("objects inserted through stack arguments survive allocation and collection", () => {
+ const splice = new Function("array", "i", "return array.splice(0, array.length, { i }, [i + 1], { next: i + 2 });");
+ jit.prepare(splice);
+ for (let i = 0; i < 10; ++i) splice([null], i);
+ expect(jit.compile(splice)).toBe(jit.enabled);
+ const array = [null];
+ for (let i = 0; i < 5000; ++i) {
+ splice(array, i);
+ expect(array).toEqual([{ i }, [i + 1], { next: i + 2 }]);
+ }
+});
+
+test("values live across a splice keep their registers and spill slots", () => {
+ const compute = new Function(
+ "array",
+ "start",
+ "count",
+ "x",
+ "y",
+ "z",
+ `const before = start * 11 + count * 7 + x * 5 + y * 3 + z;
+ const removed = array.splice(start, count, x, y, z);
+ return [before, start, count, x, y, z, removed, array];`
+ );
+ jit.prepare(compute);
+ for (let i = 0; i < 10; ++i) compute([1, 2, 3, 4], 1, 2, 5, 6, 7);
+ expect(jit.compile(compute)).toBe(jit.enabled);
+ expect(compute([1, 2, 3, 4], 1, 2, 5, 6, 7)).toEqual([75, 1, 2, 5, 6, 7, [2, 3], [1, 5, 6, 7, 4]]);
+});
+
+test("inherited setters see inserted indices", () => {
+ const splice = compiledSplice(1);
+ const seen = [];
+ const prototype = Object.create(Array.prototype);
+ Object.defineProperty(prototype, "3", {
+ set(value) {
+ seen.push(value);
+ },
+ });
+ const array = [1, 2, 3];
+ Object.setPrototypeOf(array, prototype);
+ expect(splice(array, 3, 0, "x")).toEqual([]);
+ expect(seen).toEqual(["x"]);
+ expect(Object.hasOwn(array, "3")).toBeFalse();
+ expect(array.length).toBe(4);
+});
+
+test("changes to the default species are observed by compiled calls", () => {
+ const splice = compiledSplice(1);
+ class Removed extends Array {}
+ const descriptor = Object.getOwnPropertyDescriptor(Array, Symbol.species);
+ let calls = 0;
+ Object.defineProperty(Array, Symbol.species, {
+ configurable: true,
+ get() {
+ ++calls;
+ return Removed;
+ },
+ });
+ try {
+ const array = [1, 2, 3];
+ const removed = splice(array, 1, 1, "x");
+ expect(removed).toBeInstanceOf(Removed);
+ expect(removed).toEqual([2]);
+ expect(calls).toBe(1);
+ expect(array).toEqual([1, "x", 3]);
+ } finally {
+ Object.defineProperty(Array, Symbol.species, descriptor);
+ }
+});