Skip to content

Truly independent web browser

LibJS: Inline callees that use their arguments object

Andreas Kling0beca192a02a
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
index 773fd86db6b..723dca812b3 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
@@ -25,6 +25,16 @@
//! graph cannot do without the object, and the builder starts over without
//! virtual arguments objects.
//!
+//! Inlined callees keep their arguments objects virtual the same way, with
+//! the values their call passed: `arguments.length` is the passed argument
+//! count, `arguments[i]` the passed value for a constant `i`, and
+//! `f.apply(this_arg, arguments)` an inlined call with those values. Their
+//! frame states list every passed argument, so that exits create the object
+//! from the frames they materialize. Anything else that needs the object
+//! (including returning it, or a use that fails the build) has the graph
+//! built again without virtual arguments objects in inlined callees, which
+//! then are not inlined.
+//!
//! On-stack replacement entries load every slot from the frame, where the
//! interpreter's arguments object is, so the stand-in meets that object at
//! loop headers. A graph that only uses the object there is built again
@@ -32,6 +42,7 @@
//! and every later call runs without an arguments object.
use super::GraphBuilder;
+use super::inlining::InlineValue;
use crate::CompileFailure;
use crate::bytecode::Instruction;
use crate::bytecode::MAPPED_ARGUMENTS;
@@ -70,6 +81,27 @@ pub(super) fn may_write_parameter_bindings(opcode: OpCode) -> bool {
)
}
+/// Whether `instruction` of `function` is a `CreateArguments` that can build a
+/// virtual arguments object, as far as the function itself can tell.
+pub(super) fn can_create_virtual_arguments(function: &super::Function<'_>, instruction: &Instruction) -> bool {
+ let Instruction::CreateArguments {
+ dst,
+ kind,
+ creates_parameter_bindings,
+ ..
+ } = *instruction
+ else {
+ return false;
+ };
+ // NB: Creating the parameter bindings is a side effect that a virtual arguments object would skip.
+ dst.is_some()
+ && !creates_parameter_bindings
+ && !function.writes_arguments
+ && !(kind == MAPPED_ARGUMENTS
+ && function.executable.mapped_arguments_alias_parameters
+ && function.may_write_parameter_bindings)
+}
+
/// Whether a node of `graph` takes a virtual arguments object as an input,
/// which only a real object can be.
pub(super) fn uses_virtual_arguments(graph: &Graph) -> bool {
@@ -103,25 +135,24 @@ impl GraphBuilder<'_> {
/// Builds `CreateArguments` as a virtual arguments object, if it can be
/// one. Returns false, having built nothing, otherwise.
- pub(super) fn try_build_virtual_arguments(
- &mut self,
- dst: Option<Operand>,
- kind: u32,
- ) -> Result<bool, CompileFailure> {
- let Some(dst) = dst else {
+ pub(super) fn try_build_virtual_arguments(&mut self, instruction: &Instruction) -> Result<bool, CompileFailure> {
+ let Instruction::CreateArguments {
+ dst: Some(dst), kind, ..
+ } = *instruction
+ else {
return Ok(false);
};
- let mapped = kind == MAPPED_ARGUMENTS;
- let can_virtualize = self.virtualize_arguments
- && !self.function.is_virtual()
- && !self.function.writes_arguments
- && !(mapped
- && self.function.executable.mapped_arguments_alias_parameters
- && self.function.may_write_parameter_bindings);
+ let virtualization = self.virtualize_arguments;
+ let can_virtualize = virtualization.compiled_function
+ && (!self.function.is_virtual() || virtualization.inlined_callees)
+ && can_create_virtual_arguments(&self.function, instruction);
if !can_virtualize {
return Ok(false);
}
- let bits = if mapped {
+ if self.function.is_virtual() {
+ virtualization.inlined_callees_virtualized.set(true);
+ }
+ let bits = if kind == MAPPED_ARGUMENTS {
value::VIRTUAL_MAPPED_ARGUMENTS
} else {
value::VIRTUAL_UNMAPPED_ARGUMENTS
@@ -131,12 +162,65 @@ impl GraphBuilder<'_> {
Ok(true)
}
+ /// The value the call of the inlined callee being built passed it as
+ /// argument `argument`, if it passed one, or `None` outside inlined
+ /// callees.
+ fn inlined_call_argument(&self, argument: u32) -> Option<NodeId> {
+ let call = self.function.inline.as_ref()?;
+ if argument >= call.passed_argument_count {
+ return None;
+ }
+ let layout = self.function.layout;
+ if argument >= layout.number_of_arguments {
+ return Some(call.untracked_arguments[(argument - layout.number_of_arguments) as usize]);
+ }
+ let slot = layout
+ .tracked_index(Operand::from_raw(layout.arguments_base() + argument))
+ .expect("arguments are tracked");
+ match self.frame.slots[slot] {
+ super::SlotState::Value { node, .. } => Some(node),
+ super::SlotState::InMemory => unreachable!("inlined callees hold their slots as values"),
+ }
+ }
+
+ /// The values the call of the inlined callee being built passed it, all
+ /// of them, as arguments of a call it inlines, and their count; `None`
+ /// outside inlined callees.
+ pub(super) fn inlined_call_arguments(&self) -> Option<(Vec<InlineValue>, u32)> {
+ let count = self.function.inline.as_ref()?.passed_argument_count;
+ let values = (0..count)
+ .map(|argument| {
+ let node = self.inlined_call_argument(argument).expect("the call passed it");
+ InlineValue::Node(node)
+ })
+ .collect();
+ Some((values, count))
+ }
+
+ /// Fails the build where an inlined callee returns its virtual arguments
+ /// object, which would leave it to its caller's frame.
+ pub(super) fn check_not_returning_virtual_arguments(&self, value: NodeId) -> Result<(), CompileFailure> {
+ if self.function.is_virtual() && self.is_virtual_arguments(value) {
+ return Err(CompileFailure::UnsupportedInstruction {
+ pc: self.function.pc,
+ opcode: OpCode::Return,
+ reason: "returns the arguments object of an inlined callee",
+ });
+ }
+ Ok(())
+ }
+
/// Builds `dst = base.length` for a virtual arguments object. Returns
/// false, having built nothing, for other bases.
pub(super) fn try_build_arguments_length(&mut self, dst: Operand, base: Operand) -> Result<bool, CompileFailure> {
if !self.holds_virtual_arguments(base) {
return Ok(false);
}
+ if let Some(call) = &self.function.inline {
+ let count = self.constant(value::int32(call.passed_argument_count.cast_signed()));
+ self.write(dst, count)?;
+ return Ok(true);
+ }
let count = self.emit(Op::ArgumentCount, Vec::new(), Some(Repr::Tagged));
self.write(dst, count)?;
Ok(true)
@@ -151,7 +235,25 @@ impl GraphBuilder<'_> {
base: Operand,
property: Operand,
) -> Result<bool, CompileFailure> {
- if !self.holds_virtual_arguments(base) || !self.may_speculate(ExitKind::ArgumentsIndex) {
+ if !self.holds_virtual_arguments(base) {
+ return Ok(false);
+ }
+ // NB: Inlined callees read constant indices of what their call passed.
+ if self.function.is_virtual() {
+ let index = self.read(property)?;
+ let Some(value) = self
+ .graph
+ .constant_value(index)
+ .and_then(value::as_int32)
+ .and_then(|index| u32::try_from(index).ok())
+ .and_then(|index| self.inlined_call_argument(index))
+ else {
+ return Ok(false);
+ };
+ self.write(dst, value)?;
+ return Ok(true);
+ }
+ if !self.may_speculate(ExitKind::ArgumentsIndex) {
return Ok(false);
}
let index = self.read(property)?;
@@ -185,7 +287,10 @@ impl GraphBuilder<'_> {
[forwarded, start] => (*forwarded, Some(*start)),
_ => return Ok(None),
};
- if !self.holds_virtual_arguments(forwarded) || !self.may_speculate(ExitKind::ArgumentsIndex) {
+ if !self.holds_virtual_arguments(forwarded)
+ || self.function.is_virtual()
+ || !self.may_speculate(ExitKind::ArgumentsIndex)
+ {
return Ok(None);
}
if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeCall) {
@@ -229,7 +334,9 @@ impl GraphBuilder<'_> {
let [_, forwarded] = arguments.as_slice() else {
return None;
};
- if !self.holds_virtual_arguments(*forwarded) {
+ // NB: CallForwardingArguments reads the running frame, which is not an
+ // inlined callee's.
+ if !self.holds_virtual_arguments(*forwarded) || self.function.is_virtual() {
return None;
}
(self.constant_intrinsic(*callee) == Some(Intrinsic::FunctionPrototypeApply)).then_some(*forwarded)
@@ -276,6 +383,7 @@ impl GraphBuilder<'_> {
.tracked_index(array)
.is_some_and(|slot| !self.function.liveness.live_out(index + 2).contains(slot));
if dst != array
+ || self.function.is_virtual()
|| arguments != array
|| !in_one_block
|| !array_dies
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index a728f300657..a26b3d0d939 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -31,6 +31,7 @@ use super::Flow;
use super::Function;
use super::GraphBuilder;
use super::SlotState;
+use super::arguments;
use crate::CompileFailure;
use crate::bitset::BitSet;
use crate::builder::Handling;
@@ -110,12 +111,16 @@ pub(super) struct CallbackTarget {
/// needed in memory outside generic nodes, its environments must stay those
/// of its function object, it must be fully compilable, and it must not step
/// for-in loops.
-fn can_inline(callee: &Function<'_>) -> bool {
+fn can_inline(callee: &Function<'_>, virtual_arguments: bool) -> bool {
if !callee.written_constants.is_empty() {
return false;
}
callee.instructions.iter().all(|instruction| {
let opcode = instruction.instruction.opcode();
+ // NB: An arguments object the callee never creates reads no frame (see `arguments`).
+ if virtual_arguments && arguments::can_create_virtual_arguments(callee, &instruction.instruction) {
+ return true;
+ }
let reads_frame_fields = matches!(
opcode,
OpCode::GetLexicalEnvironment
@@ -161,12 +166,14 @@ fn returns_no_object(callee: &Function<'_>) -> bool {
/// Where the `this` value or an argument of an inlined call comes from.
#[derive(Debug, Clone, Copy)]
-enum InlineValue {
+pub(super) enum InlineValue {
Operand(Operand),
Constant(u64),
/// The running frame's argument at this index, whose arguments object
/// the code never created.
FrameArgument(u32),
+ /// A value the code has, like an argument of an inlined callee.
+ Node(NodeId),
}
/// A call to inline.
@@ -196,6 +203,32 @@ struct InlinedCallSite {
}
impl InlinedCallSite {
+ /// A call of snapshot executable `index` through
+ /// `Function.prototype.call` with `arguments`, whose first is `this`.
+ fn through_call(index: u32, arguments: &[Operand], argument_count: u32, dst: Operand) -> Self {
+ let this = arguments
+ .first()
+ .map_or(InlineValue::Constant(value::UNDEFINED), |this| {
+ InlineValue::Operand(*this)
+ });
+ Self::forwarded(
+ index,
+ this,
+ arguments.iter().skip(1).copied().map(InlineValue::Operand).collect(),
+ argument_count.saturating_sub(1),
+ dst,
+ )
+ }
+
+ /// A call of snapshot executable `index` that gets other arguments than
+ /// the `Call` instruction's.
+ fn forwarded(index: u32, this: InlineValue, arguments: Vec<InlineValue>, count: u32, dst: Operand) -> Self {
+ Self {
+ forwarded: true,
+ ..Self::new(index, this, arguments, count, dst)
+ }
+ }
+
/// A call of snapshot executable `index` with `this` and `arguments`,
/// into `dst`, which checks no callee and forwards nothing.
fn new(
@@ -655,18 +688,7 @@ impl GraphBuilder<'_> {
}
InlinedCallSite {
callee: Some(*this_value),
- forwarded: true,
- ..InlinedCallSite::new(
- index,
- arguments
- .first()
- .map_or(InlineValue::Constant(value::UNDEFINED), |this| {
- InlineValue::Operand(*this)
- }),
- arguments.iter().skip(1).copied().map(InlineValue::Operand).collect(),
- argument_count.saturating_sub(1),
- *dst,
- )
+ ..InlinedCallSite::through_call(index, arguments, *argument_count, *dst)
}
}
Forwarding::Apply => {
@@ -675,20 +697,20 @@ impl GraphBuilder<'_> {
};
if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeApply)
|| !self.holds_virtual_arguments(*forwarded_arguments)
- || !self.may_speculate(ExitKind::UnexpectedValue)
{
return Ok(None);
}
- InlinedCallSite {
- callee: Some(*this_value),
- forwarded: true,
- ..InlinedCallSite::new(
- index,
- InlineValue::Operand(*this),
+ let (arguments, count) = match self.inlined_call_arguments() {
+ Some(arguments) => arguments,
+ None if self.may_speculate(ExitKind::UnexpectedValue) => (
(0..forwarded.argument_count).map(InlineValue::FrameArgument).collect(),
forwarded.argument_count,
- *dst,
- )
+ ),
+ None => return Ok(None),
+ };
+ InlinedCallSite {
+ callee: Some(*this_value),
+ ..InlinedCallSite::forwarded(index, InlineValue::Operand(*this), arguments, count, *dst)
}
}
Forwarding::Bound => {
@@ -719,8 +741,10 @@ impl GraphBuilder<'_> {
}
/// Inlines a `Call` of a function the code holds as a constant, which
- /// needs no feedback: called itself (`f(...)`), or through
- /// `Function.prototype.call` (`f.call(this_arg, ...)`). Sites that call
+ /// needs no feedback: called itself (`f(...)`), through
+ /// `Function.prototype.call` (`f.call(this_arg, ...)`), or in an inlined
+ /// callee, through `Function.prototype.apply` with its virtual arguments
+ /// object (`f.apply(this_arg, arguments)`). Sites that call
/// several functions, like a method of a constructor every class shares,
/// call one of them where the code knows which. Returns `None`, having
/// built nothing that matters, if it does not.
@@ -749,24 +773,19 @@ impl GraphBuilder<'_> {
let Some(index) = self.constant_inlinable_function(*this_value) else {
return Ok(None);
};
+ // NB: An inlined callee forwards what its call passed it.
+ if self.constant_intrinsic(*callee) == Some(Intrinsic::FunctionPrototypeApply)
+ && let [this, forwarded_arguments] = arguments.as_slice()
+ && self.holds_virtual_arguments(*forwarded_arguments)
+ && let Some((arguments, count)) = self.inlined_call_arguments()
+ {
+ let call = InlinedCallSite::forwarded(index, InlineValue::Operand(*this), arguments, count, *dst);
+ return self.inline_call(call);
+ }
if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeCall) {
return Ok(None);
}
- let call = InlinedCallSite {
- forwarded: true,
- ..InlinedCallSite::new(
- index,
- arguments
- .first()
- .map_or(InlineValue::Constant(value::UNDEFINED), |this| {
- InlineValue::Operand(*this)
- }),
- arguments.iter().skip(1).copied().map(InlineValue::Operand).collect(),
- argument_count.saturating_sub(1),
- *dst,
- )
- };
- self.inline_call(call)
+ self.inline_call(InlinedCallSite::through_call(index, arguments, *argument_count, *dst))
}
/// Inlines the call of the getter whose executable is snapshot executable
@@ -931,6 +950,7 @@ impl GraphBuilder<'_> {
match value {
InlineValue::Operand(operand) => self.read(operand),
InlineValue::Constant(bits) => Ok(self.constant(bits)),
+ InlineValue::Node(node) => Ok(node),
InlineValue::FrameArgument(index) => {
let index = self.constant(value::int32(index.cast_signed()));
let arguments_base = self.function.layout.arguments_base();
@@ -996,13 +1016,22 @@ impl GraphBuilder<'_> {
return Ok(None);
}
// NB: CheckClosure checks shared data, not legacy-property eligibility.
- // Keep non-strict closure calls conservative.
+ // Keep non-strict closure calls conservative. Frames with a virtual
+ // arguments object keep every passed argument too, which exits
+ // create the object from.
+ let virtual_arguments =
+ self.virtualize_arguments.compiled_function && self.virtualize_arguments.inlined_callees;
+ let creates_arguments = decoded
+ .instructions
+ .iter()
+ .any(|instruction| instruction.instruction.opcode() == OpCode::CreateArguments);
let has_legacy_arguments = callee_executable.supports_legacy_arguments
- || (closure.is_some() && callee_executable.is_non_strict_function());
+ || (closure.is_some() && callee_executable.is_non_strict_function())
+ || (virtual_arguments && creates_arguments);
let Ok(mut callee_function) = Function::new(index, callee_executable, decoded, has_legacy_arguments) else {
return Ok(None);
};
- if !can_inline(&callee_function) {
+ if !can_inline(&callee_function, virtual_arguments) {
return Ok(None);
}
if construct.is_some() && !returns_no_object(&callee_function) {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 9db8a510efb..2905b44ff51 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -101,6 +101,7 @@ use crate::snapshot::RuntimeInfo;
use crate::snapshot::Snapshot;
pub(crate) use slow_paths::is_ssa_slow_path_output;
pub(crate) use slow_paths::js_call_operands;
+use std::cell::Cell;
use std::cell::OnceCell;
/// Builds the IR for `snapshot.executables[0]`.
@@ -147,18 +148,50 @@ pub fn build_graph_with_feedback(snapshot: &Snapshot, has_run: &dyn Fn(u32) -> b
let decoded = (0..snapshot.executables.len())
.map(|_| OnceCell::new())
.collect::<Vec<_>>();
- let graph = GraphBuilder::new(snapshot, has_run, &decoded, true, true)?.build()?;
+ let virtualized_inlined_arguments = Cell::new(false);
+ let build = |virtualize_arguments, virtualize_inlined_arguments, build_osr_entries| {
+ GraphBuilder::new(
+ snapshot,
+ has_run,
+ &decoded,
+ ArgumentsVirtualization {
+ compiled_function: virtualize_arguments,
+ inlined_callees: virtualize_inlined_arguments,
+ inlined_callees_virtualized: &virtualized_inlined_arguments,
+ },
+ build_osr_entries,
+ )?
+ .build()
+ };
+ // NB: Where an inlined callee had a virtual arguments object, a graph
+ // that needs it, or a build that failed, is built again without
+ // those (see `arguments`), which then are not inlined.
+ let graph = match build(true, true, true) {
+ Ok(graph) if !arguments::uses_virtual_arguments(&graph) => return Ok(graph),
+ _ if virtualized_inlined_arguments.get() => build(true, false, true)?,
+ result => result?,
+ };
if !arguments::uses_virtual_arguments(&graph) {
return Ok(graph);
}
if !graph.osr_entries.is_empty() {
- let graph = GraphBuilder::new(snapshot, has_run, &decoded, true, false)?.build()?;
+ let graph = build(true, false, false)?;
if !arguments::uses_virtual_arguments(&graph) {
return Ok(graph);
}
}
// Something needs the arguments object itself.
- GraphBuilder::new(snapshot, has_run, &decoded, false, true)?.build()
+ build(false, false, true)
+}
+
+/// Where the graph builder may build virtual arguments objects (see
+/// `arguments`).
+#[derive(Clone, Copy)]
+struct ArgumentsVirtualization<'a> {
+ compiled_function: bool,
+ inlined_callees: bool,
+ /// Set once an inlined callee got a virtual arguments object.
+ inlined_callees_virtualized: &'a Cell<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -509,8 +542,8 @@ struct GraphBuilder<'a> {
callers: Vec<Function<'a>>,
/// Bytecode instructions inlined so far, for the inlining budget.
inlined_instructions: usize,
- /// Whether `CreateArguments` may build a virtual arguments object.
- virtualize_arguments: bool,
+ /// Where `CreateArguments` may build a virtual arguments object.
+ virtualize_arguments: ArgumentsVirtualization<'a>,
/// Whether to build on-stack replacement entries (see `arguments`).
build_osr_entries: bool,
/// The intrinsics among the constants, by value.
@@ -529,7 +562,7 @@ impl<'a> GraphBuilder<'a> {
snapshot: &'a Snapshot,
has_run: &'a dyn Fn(u32) -> bool,
decoded: &'a [OnceCell<Result<DecodedFunction, CompileFailure>>],
- virtualize_arguments: bool,
+ virtualize_arguments: ArgumentsVirtualization<'a>,
build_osr_entries: bool,
) -> Result<Self, CompileFailure> {
let executable = snapshot.executables.first().ok_or(CompileFailure::InvalidBytecode {
@@ -1443,6 +1476,7 @@ impl<'a> GraphBuilder<'a> {
Instruction::ToBoolean { dst, value } => self.build_truthiness_value(dst, value, false)?,
Instruction::Return { value } => {
let value = self.read(value)?;
+ self.check_not_returning_virtual_arguments(value)?;
if self.function.is_virtual() {
return Ok(Some(self.build_inline_return(value, true)));
}
@@ -1460,6 +1494,7 @@ impl<'a> GraphBuilder<'a> {
}
Instruction::End { value } => {
let value = self.read(value)?;
+ self.check_not_returning_virtual_arguments(value)?;
// NB: In an inlined callee, End returns its value (never
// empty) to the caller like Return does.
if self.function.is_virtual() {
@@ -1494,14 +1529,8 @@ impl<'a> GraphBuilder<'a> {
};
self.write(dst, count)?;
}
- Instruction::CreateArguments {
- dst,
- kind,
- creates_parameter_bindings,
- ..
- } => {
- // NB: Creating the parameter bindings is a side effect that a virtual arguments object would skip.
- if creates_parameter_bindings || !self.try_build_virtual_arguments(dst, kind)? {
+ Instruction::CreateArguments { .. } => {
+ if !self.try_build_virtual_arguments(instruction)? {
return Ok(None);
}
}
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 92846812c00..1e3f7beae58 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -397,19 +397,25 @@ fn write_frame_state(
slots[index].set(Value::EMPTY);
}
}
- // NB: Every slot holding the arguments object the code never created holds the same object.
- let mut arguments_object = None;
+ // NB: Every slot holding the arguments object the code never created holds the same object, which is created from
+ // the frame's arguments once they are written: frames of inlined calls get theirs from the frame state too.
+ let mut arguments_object_slots = Vec::new();
for (slot, location) in &frame_state.values {
// NB: The function object of a frame of an inlined closure is in no slot.
if *slot == CALLEE_SLOT || Some(*slot) == kept {
continue;
}
- let value = if let ValueLocation::ArgumentsObject { mapped } = location {
- *arguments_object.get_or_insert_with(|| create_arguments_object(vm, frame, *mapped))
- } else {
- values.value(*location)
- };
- slots[*slot as usize].set(value);
+ if let ValueLocation::ArgumentsObject { mapped } = location {
+ arguments_object_slots.push((*slot, *mapped));
+ continue;
+ }
+ slots[*slot as usize].set(values.value(*location));
+ }
+ if let Some((_, mapped)) = arguments_object_slots.first() {
+ let arguments_object = create_arguments_object(vm, frame, *mapped);
+ for (slot, _) in &arguments_object_slots {
+ slots[*slot as usize].set(arguments_object);
+ }
}
}
diff --git a/Tests/LibJS/JIT/ir/inlined-arguments-objects.js b/Tests/LibJS/JIT/ir/inlined-arguments-objects.js
new file mode 100644
index 00000000000..94d4c449812
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/inlined-arguments-objects.js
@@ -0,0 +1,45 @@
+// REQUIRES: inline-allocation
+// Inlined callees keep their arguments objects virtual: forwarding them with apply inlines the call with the values
+// the inlined call passed, and their length and constant indices are those values.
+
+const Class = {
+ create() {
+ return function () {
+ this.initialize.apply(this, arguments);
+ };
+ },
+};
+const Point = Class.create();
+Point.prototype = {
+ initialize(x, y) {
+ this.x = x;
+ this.y = y;
+ },
+};
+const Color = Class.create();
+Color.prototype = {
+ initialize(r, g, b) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ },
+};
+function second() {
+ return arguments.length + arguments[1];
+}
+function make(i) {
+ return new Point(i, 2).x + second(i, 3);
+}
+jit.prepare(make);
+for (let i = 0; i < 10; ++i) {
+ new Color(1, 2, 3);
+ make(i);
+}
+jit.compile(make);
+
+// CHECK-FUNCTION: make
+// CHECK-PASS: graph building
+// CHECK-NOT: CreateArguments
+// CHECK-NOT: CallSlowPath
+// CHECK-NOT: CallForwardingArguments
+// CHECK: Return
diff --git a/Tests/LibJS/Runtime/jit/inlined-arguments-objects.js b/Tests/LibJS/Runtime/jit/inlined-arguments-objects.js
new file mode 100644
index 00000000000..3954f7f64fe
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/inlined-arguments-objects.js
@@ -0,0 +1,166 @@
+// JIT code inlines functions that use their arguments object, which they
+// never create, and calls of methods it knows from the shape of an object it
+// created. These tests run every function many times, so that with a low JIT
+// threshold they are compiled.
+
+const iterations = 100;
+
+describe("arguments objects of inlined callees", () => {
+ test("constructors forwarding their arguments with apply", () => {
+ const Class = {
+ create() {
+ return function () {
+ this.initialize.apply(this, arguments);
+ };
+ },
+ };
+ const Point = Class.create();
+ Point.prototype = {
+ initialize(x, y) {
+ this.x = x;
+ this.y = y;
+ },
+ };
+ const Color = Class.create();
+ Color.prototype = {
+ initialize(r, g, b) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ },
+ };
+ const Pair = Class.create();
+ Pair.prototype = {
+ initialize() {
+ this.count = arguments.length;
+ this.first = arguments[0];
+ },
+ };
+ function make(i) {
+ const point = new Point(i, 2);
+ const color = new Color(1, i, 3);
+ const pair = new Pair(i, i);
+ return point.x + point.y + color.g + pair.count + pair.first;
+ }
+ for (let i = 0; i < iterations; ++i) expect(make(i)).toBe(3 * i + 4);
+ // Another type of value.
+ expect(make("a")).toBe("a2a2a");
+ // A method that changes after compilation.
+ Point.prototype.initialize = function (x, y) {
+ this.x = x * 10;
+ this.y = y;
+ };
+ expect(make(1)).toBe(16);
+ });
+
+ test("length and indices", () => {
+ function count() {
+ return arguments.length;
+ }
+ function second() {
+ return arguments[1];
+ }
+ function outOfRange() {
+ return arguments[3];
+ }
+ function caller(i) {
+ return count(i, i, i) + second(1, i) + (outOfRange(i) === undefined ? 1 : 0);
+ }
+ for (let i = 0; i < iterations; ++i) expect(caller(i)).toBe(i + 4);
+ });
+
+ test("exits that create the arguments object of an inlined callee", () => {
+ function sum() {
+ let total = 0;
+ for (let i = 0; i < arguments.length; ++i) total += arguments[i];
+ return total;
+ }
+ function inner(a, b) {
+ const value = a + b;
+ // A string makes this exit after the arguments were used.
+ return value + Array.prototype.slice.call(arguments).length;
+ }
+ function caller(i) {
+ return sum(i, 1, 2) + inner(i, 1, 2);
+ }
+ for (let i = 0; i < iterations; ++i) expect(caller(i)).toBe(2 * i + 7);
+ expect(inner("a", "b", "c")).toBe("ab3");
+ expect(caller("x")).toBe("0x12x13");
+ });
+
+ test("returned arguments objects", () => {
+ function args() {
+ return arguments;
+ }
+ function caller(i) {
+ const object = args(i, i + 1);
+ return object.length + object[1] + (object !== arguments ? 1 : 0);
+ }
+ for (let i = 0; i < iterations; ++i) expect(caller(i)).toBe(i + 4);
+ });
+
+ test("arguments that escape", () => {
+ let kept;
+ function keep() {
+ kept = arguments;
+ return arguments.length;
+ }
+ function caller(i) {
+ return keep(i, i);
+ }
+ for (let i = 0; i < iterations; ++i) {
+ expect(caller(i)).toBe(2);
+ expect(kept[0]).toBe(i);
+ }
+ });
+});
+
+describe("methods of objects of known shapes", () => {
+ test("a method of a constructor many classes share", () => {
+ function makeClass(scale) {
+ const constructor = function (value) {
+ this.initialize(value);
+ };
+ constructor.prototype = {
+ initialize(value) {
+ this.value = value * scale;
+ },
+ };
+ return constructor;
+ }
+ const classes = [];
+ for (let scale = 1; scale <= 8; ++scale) classes.push(makeClass(scale));
+ const [First, Second] = classes;
+ function make(i) {
+ return new First(i).value + new Second(i).value;
+ }
+ for (let i = 0; i < iterations; ++i) {
+ for (const Class of classes) expect(new Class(i).value).toBeGreaterThanOrEqual(i);
+ expect(make(i)).toBe(3 * i);
+ }
+ First.prototype.initialize = function (value) {
+ this.value = -value;
+ };
+ expect(make(2)).toBe(2);
+ });
+
+ test("properties added before a read", () => {
+ function Box(value) {
+ this.value = value;
+ this.double = this.twice();
+ }
+ Box.prototype.twice = function () {
+ return this.value * 2;
+ };
+ function make(i) {
+ const box = new Box(i);
+ box.extra = 1;
+ return box.double + box.extra;
+ }
+ for (let i = 0; i < iterations; ++i) expect(make(i)).toBe(2 * i + 1);
+ Box.prototype.twice = function () {
+ return 0;
+ };
+ expect(make(5)).toBe(1);
+ });
+});