Truly independent web browser
LibJS: Inline constructs of derived classes and their super() parent
Andreas Klingd2822e5f9ebe
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex cd218871251..726c3c914c7 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -60,6 +60,7 @@ use crate::snapshot::CellId;use crate::snapshot::ConstructTarget;use crate::snapshot::Forwarding;use crate::snapshot::Intrinsic;+use crate::snapshot::SuperConstructTarget;use crate::snapshot::call_feedback_flags;/// How an inlined callee was called.@@ -99,6 +100,11 @@ pub(super) struct InlineCall {pub frame_bytes: u64,/// Whether the call is a construct, whose result is `this`.pub construct: bool,+ /// The new target of a construct.+ pub new_target: Option<CellId>,+ /// For a construct of a derived constructor: what it does (see+ /// `ConstructTarget`). Its `this` starts empty, and super() binds it.+ pub derived_construct: Option<ConstructTarget>,}/// The callbacks a call site passed to the builtin it called, which it calls@@ -118,7 +124,7 @@ const MAX_CALLEE_CASES: usize = 4;/// needed in memory outside generic nodes, its environments must stay those/// of its function object, it must be fully compilable, and its exception/// handlers must never have caught anything.-fn can_inline(callee: &Function<'_>, virtual_arguments: bool) -> bool {+fn can_inline(callee: &Function<'_>, virtual_arguments: bool, derived_construct: bool) -> bool {if !callee.written_constants.is_empty() {return false;}@@ -150,12 +156,15 @@ fn can_inline(callee: &Function<'_>, virtual_arguments: bool) -> bool {// NB: These read the function, the this value or the new target of the running frame, which is the// caller's while an inlined callee runs (see `function_with_frame_as_this_environment()` in the// runtime).- | OpCode::GetSuperConstructor| OpCode::SuperCallWithArgumentArray- | OpCode::SuperCall- | OpCode::SuperCallWithForwardedArguments- | OpCode::BindThisFromSuperCall- );+ ) || (!derived_construct+ && matches!(+ opcode,+ OpCode::GetSuperConstructor+ | OpCode::SuperCall+ | OpCode::SuperCallWithForwardedArguments+ | OpCode::BindThisFromSuperCall+ ));// NB: The new target of a callee with its own new.target is known (see `try_build_new_target()`).let unknown_new_target = opcode == OpCode::GetNewTarget&& !callee@@ -198,6 +207,93 @@ fn returns_no_object(callee: &Function<'_>) -> bool {})}+/// Whether every path through the derived constructor `callee` calls+/// super() exactly once before anything else reads `this` or the frame+/// returns, and every return returns undefined (or, right after super(),+/// what super() returned, like default derived constructors): then the+/// super() of an inlined construct of it (see+/// `GraphBuilder::try_inline_super_call()`) always binds `this` while it is+/// empty, and the result of the construct is always `this`. Its frames+/// materialized before super() run it in the interpreter, and those+/// materialized after super() return their this value (see+/// `ExecutionContext::caller_is_construct` in the runtime).+///+/// A constructor with exception handlers never qualifies: a handler that+/// catches what super() or its arguments throw runs in the materialized+/// frame and can return while `this` is still empty, and nothing checks the+/// value such a frame returns.+fn calls_super_once_before_returning(callee: &Function<'_>) -> bool {+ let mut jump_targets = Vec::new();+ for instruction in callee.instructions {+ instruction+ .instruction+ .for_each_jump_target(|target| jump_targets.push(target.0));+ }+ let mut super_call_result = None;+ let mut bound_this_at = None;+ let mut previous_opcode = None;+ for instruction in callee.instructions {+ let opcode = instruction.instruction.opcode();+ // NB: Then nothing changed what super() returned.+ let follows_bind_this =+ previous_opcode == Some(OpCode::BindThisFromSuperCall) && !jump_targets.contains(&instruction.pc);+ previous_opcode = Some(opcode);+ let called_super = super_call_result.is_some();+ if bound_this_at.is_none() {+ // NB: The instructions up to the BindThisFromSuperCall run once, one after the other.+ match instruction.instruction {+ Instruction::SuperCall { dst, .. } | Instruction::SuperCallWithForwardedArguments { dst, .. }+ if !called_super =>+ {+ super_call_result = Some(dst);+ continue;+ }+ _ => {}+ }+ match instruction.instruction {+ Instruction::BindThisFromSuperCall { result } if Some(result) == super_call_result => {+ bound_this_at = Some(instruction.pc);+ continue;+ }+ _ => {}+ }+ match opcode {+ OpCode::GetSuperConstructor => {}+ OpCode::SuperCall+ | OpCode::SuperCallWithForwardedArguments+ | OpCode::BindThisFromSuperCall+ | OpCode::ResolveThisBinding+ | OpCode::CreateArguments => return false,+ _ if instruction.instruction.is_terminator() => return false,+ _ => {}+ }+ continue;+ }+ // NB: What super() returned is `this`.+ let returns_undefined_or_this = |value: Operand| match callee.layout.slot_kind(value) {+ SlotKind::Constant(index) => callee.executable.constants.get(index as usize) == Some(&value::UNDEFINED),+ _ => follows_bind_this && Some(value) == super_call_result,+ };+ match instruction.instruction {+ Instruction::Return { value } | Instruction::End { value } if !returns_undefined_or_this(value) => {+ return false;+ }+ _ => {}+ }+ if matches!(+ opcode,+ OpCode::GetSuperConstructor+ | OpCode::SuperCall+ | OpCode::SuperCallWithForwardedArguments+ | OpCode::BindThisFromSuperCall+ | OpCode::CreateArguments+ ) {+ return false;+ }+ }+ bound_this_at.is_some_and(|bound_this_at| jump_targets.iter().all(|target| *target > bound_this_at))+}+/// Where the `this` value or an argument of an inlined call comes from.#[derive(Debug, Clone, Copy)]pub(super) enum InlineValue {@@ -227,6 +323,9 @@ struct InlinedCallSite {dst: Operand,/// For a `CallConstruct`: what its construct does.construct: Option<ConstructTarget>,+ /// The new target of a construct, if it is not the callee: the derived+ /// constructor whose super() constructs with the callee.+ new_target: Option<CellId>,/// The closure called, if the callee is a closure of the inlined/// executable's function rather than that function itself...closure: Option<NodeId>,@@ -282,6 +381,7 @@ impl InlinedCallSite {forwarded: false,dst,construct: None,+ new_target: None,closure: None,check_closure: false,callback: None,@@ -1355,6 +1455,11 @@ impl GraphBuilder<'_> {if !self.may_speculate(ExitKind::BadShape) || !self.may_speculate(ExitKind::UnexpectedValue) {return Ok(None);}+ if let Some(super_constructor) = construct.super_constructor+ && !self.may_inline_super_constructor(super_constructor)+ {+ return Ok(None);+ }let call = InlinedCallSite {callee: Some(*callee),construct: Some(construct),@@ -1369,6 +1474,218 @@ impl GraphBuilder<'_> {self.inline_call(call)}+ /// Whether the super() of an inlined construct of a derived constructor+ /// here can inline the construct of `target` (see+ /// `try_inline_super_call()`), one inlined call deeper.+ fn may_inline_super_constructor(&self, target: SuperConstructTarget) -> bool {+ let Some(executable) = self.snapshot.executables.get(target.executable as usize) else {+ return false;+ };+ if executable.function.is_none()+ || !self.may_inline_calls_of(executable)+ || self.callers.len() + 1 >= self.snapshot.options.inlining.max_depth as usize+ {+ return false;+ }+ let Ok(decoded) = super::decoded_function(executable, &self.decoded[target.executable as usize]) else {+ return false;+ };+ if decoded.instructions.len() > self.snapshot.options.inlining.max_construct_instructions as usize {+ return false;+ }+ let Ok(function) = Function::new(+ target.executable,+ executable,+ decoded,+ executable.supports_legacy_arguments,+ ) else {+ return false;+ };+ let virtual_arguments =+ self.virtualize_arguments.compiled_function && self.virtualize_arguments.inlined_callees;+ can_inline(&function, virtual_arguments, false) && returns_no_object(&function)+ }++ /// `GetSuperConstructor` in an inlined construct of a derived+ /// constructor: its [[Prototype]], which stays the same while its shape+ /// does.+ pub(super) fn try_build_super_constructor(&mut self, dst: Operand) -> Result<bool, CompileFailure> {+ let Some(construct) = self.function.inline.as_ref().and_then(|call| call.derived_construct) else {+ return Ok(false);+ };+ let (function, target) = self.derived_construct_function(&construct)?;+ // 13.3.7.2 GetSuperConstructor ( ), https://tc39.es/ecma262/#sec-getsuperconstructor+ // 1. Let envRec be GetThisEnvironment().+ // 2. Assert: envRec is a Function Environment Record.+ // 3. Let activeFunction be envRec.[[FunctionObject]].+ // 4. Assert: activeFunction is an ECMAScript function object.+ // 5. Let superConstructor be ! activeFunction.[[GetPrototypeOf]]().+ let function = self.boxed_object(function);+ let function = self.constant(function);+ self.check_shapes(+ function,+ &[ShapeCheck {+ shape: construct.function_shape,+ dictionary_generation: None,+ }],+ );+ // 6. Return superConstructor.+ self.embed(target.function);+ let super_constructor = self.boxed_object(target.function);+ let super_constructor = self.constant(super_constructor);+ self.write(dst, super_constructor)?;+ Ok(true)+ }++ /// The derived constructor of an inlined construct, and the base+ /// constructor its super() constructs with.+ fn derived_construct_function(+ &self,+ construct: &ConstructTarget,+ ) -> Result<(CellId, SuperConstructTarget), CompileFailure> {+ let invalid = |reason| CompileFailure::InvalidBytecode {+ pc: self.function.pc,+ reason,+ };+ let function = self+ .function+ .executable+ .function+ .ok_or(invalid("inlined construct without a known function"))?;+ let target = construct+ .super_constructor+ .ok_or(invalid("derived construct without a super constructor"))?;+ Ok((function.function, target))+ }++ /// `SuperCall` in an inlined construct of a derived constructor: inlines+ /// the construct of its super constructor, with the derived constructor+ /// as the new target. Its result is `this`, which `BindThisFromSuperCall`+ /// binds (see `try_build_bind_this_from_super_call()`).+ pub(super) fn try_inline_super_call(&mut self, instruction: &Instruction) -> Result<Option<Flow>, CompileFailure> {+ let Some(construct) = self.function.inline.as_ref().and_then(|call| call.derived_construct) else {+ return Ok(None);+ };+ let (dst, super_constructor, arguments, argument_count, forwarded) = match instruction {+ Instruction::SuperCall {+ dst,+ super_constructor,+ argument_count,+ arguments,+ ..+ } => (+ dst,+ super_constructor,+ arguments.iter().copied().map(InlineValue::Operand).collect::<Vec<_>>(),+ *argument_count,+ false,+ ),+ // NB: The passed arguments of the derived constructor are all known, as it keeps them like legacy+ // `arguments` (see `inline_call()`).+ Instruction::SuperCallWithForwardedArguments {+ dst, super_constructor, ..+ } => {+ let call = self+ .function+ .inline+ .as_ref()+ .expect("derived constructs are inlined calls");+ let count = call.passed_argument_count;+ let arguments = self+ .legacy_argument_values()+ .into_iter()+ .take(count as usize)+ .map(|(_, node)| InlineValue::Node(node))+ .collect::<Vec<_>>();+ if arguments.len() != count as usize {+ return Err(CompileFailure::InvalidBytecode {+ pc: self.function.pc,+ reason: "forwarded arguments of an inlined derived construct are not known",+ });+ }+ (dst, super_constructor, arguments, count, true)+ }+ _ => return Ok(None),+ };+ let (function, target) = self.derived_construct_function(&construct)?;+ // NB: GetSuperConstructor put the super constructor there.+ let super_constructor_value = self.read(*super_constructor)?;+ let expected = self.boxed_object(target.function);+ if self.graph.constant_value(super_constructor_value) != Some(expected) {+ self.emit_checked(+ Op::CheckValue {+ expected,+ kind: ExitKind::UnexpectedValue,+ },+ vec![super_constructor_value],+ None,+ );+ }+ // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation+ // 6. Let result be ? Construct(superCtor, argList, newTarget).+ // NB: OrdinaryCreateFromConstructor of the construct reads "prototype" of the new target, the derived+ // constructor.+ let call = InlinedCallSite {+ construct: Some(ConstructTarget {+ executable: target.executable,+ super_constructor: None,+ ..construct+ }),+ new_target: Some(function),+ forwarded,+ ..InlinedCallSite::new(+ target.executable,+ InlineValue::Constant(value::UNDEFINED),+ arguments,+ argument_count,+ *dst,+ )+ };+ match self.inline_call(call)? {+ Some(flow) => Ok(Some(flow)),+ None => Err(CompileFailure::InvalidBytecode {+ pc: self.function.pc,+ reason: "super() of an inlined derived construct could not be inlined",+ }),+ }+ }++ /// `BindThisFromSuperCall` in an inlined construct of a derived+ /// constructor, whose `this` is still empty there (see+ /// `calls_super_once_before_returning()`) and which has no fields.+ pub(super) fn try_build_bind_this_from_super_call(&mut self, result: Operand) -> Result<bool, CompileFailure> {+ if self+ .function+ .inline+ .as_ref()+ .and_then(|call| call.derived_construct)+ .is_none()+ {+ return Ok(false);+ }+ let this_register = Operand::from_raw(THIS_VALUE_REGISTER);+ let this_value = self.read(this_register)?;+ if self.graph.constant_value(this_value) != Some(value::EMPTY) {+ return Err(CompileFailure::InvalidBytecode {+ pc: self.function.pc,+ reason: "super() of an inlined derived construct with this bound",+ });+ }+ // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation+ // 7. Let thisER be GetThisEnvironment().+ // 8. Assert: thisER is a Function Environment Record.+ // 9. Perform ? BindThisValue(thisER, result).+ // NB: The result of the inlined construct is its `this`, an object.+ let result = self.read(result)?;+ self.write(this_register, result)?;+ // 10. Let funcObj be thisER.[[FunctionObject]].+ // 11. Assert: funcObj is an ECMAScript function object.+ // 12. Perform ? InitializeInstanceElements(result, funcObj).+ // NB: The derived constructor has no fields or private methods.+ // 13. Return result.+ Ok(true)+ }+/// `ResolveSuperBase` in an inlined callee, whose home object is known: its prototype, which stays the same while/// its shape does. The interpreter's slow path reads the running function, which is the caller's here.pub(super) fn try_build_resolve_super_base(&mut self, dst: Operand) -> Result<bool, CompileFailure> {@@ -1413,17 +1730,9 @@ impl GraphBuilder<'_> {let Some(call) = self.function.inline.as_ref() else {return Ok(false);};- let value = if call.construct {- let function = self- .function- .executable- .function- .ok_or(CompileFailure::InvalidBytecode {- pc: self.function.pc,- reason: "inlined construct without a known function",- })?;- self.embed(function.function);- self.boxed_object(function.function)+ let value = if let Some(new_target) = call.new_target {+ self.embed(new_target);+ self.boxed_object(new_target)} else {value::UNDEFINED};@@ -1524,10 +1833,12 @@ impl GraphBuilder<'_> {forwarded,dst,construct,+ new_target,closure,check_closure,callback,} = call;+ let derived_construct = construct.filter(|construct| construct.super_constructor.is_some());// NB: The callee's frame cannot hold the virtual arguments object:// the callee's generic instructions could not read it.if std::iter::once(&this)@@ -1570,13 +1881,20 @@ impl GraphBuilder<'_> {.instructions.iter().any(|instruction| instruction.instruction.opcode() == OpCode::CreateArguments);+ // NB: A derived constructor that passes its arguments on to super() keeps them all, like legacy `arguments`.+ let forwards_arguments_to_super = derived_construct.is_some()+ && decoded+ .instructions+ .iter()+ .any(|instruction| instruction.instruction.opcode() == OpCode::SuperCallWithForwardedArguments);let has_legacy_arguments = callee_executable.supports_legacy_arguments|| (closure.is_some() && callee_executable.is_non_strict_function())- || (virtual_arguments && creates_arguments);+ || (virtual_arguments && creates_arguments)+ || forwards_arguments_to_super;let Ok(mut callee_function) = Function::new(index, callee_executable, decoded, has_legacy_arguments) else {return Ok(None);};- if !can_inline(&callee_function, virtual_arguments) {+ if !can_inline(&callee_function, virtual_arguments, derived_construct.is_some()) {return Ok(None);}// NB: Closures of a function share its code but may have other home objects, and the base of `super` property@@ -1588,7 +1906,11 @@ impl GraphBuilder<'_> {if resolves_super_base && (closure.is_some() || !self.may_speculate(ExitKind::BadShape)) {return Ok(None);}- if construct.is_some() && !returns_no_object(&callee_function) {+ if derived_construct.is_some() {+ if !calls_super_once_before_returning(&callee_function) {+ return Ok(None);+ }+ } else if construct.is_some() && !returns_no_object(&callee_function) {return Ok(None);}@@ -1640,9 +1962,12 @@ impl GraphBuilder<'_> {if let Some(callee) = callee {self.check_callee(callee, expected_callee)?;}+ // NB: super() creates `this` of a derived constructor.let receiver = match &construct {- Some(construct) => self.construct_this(function.function, construct),- None => receiver,+ Some(construct) if derived_construct.is_none() => {+ self.construct_this(new_target.unwrap_or(function.function), construct)+ }+ _ => receiver,};// NB: Arguments forwarded from the frame are as many as when the// forwarding was seen.@@ -1729,6 +2054,8 @@ impl GraphBuilder<'_> {return_fresh_shapes: None,frame_bytes,construct: construct.is_some(),+ new_target: construct.map(|_| new_target.unwrap_or(function.function)),+ derived_construct,});// NB: Walk the callee's bytecode, then continue in the caller.@@ -1764,12 +2091,19 @@ impl GraphBuilder<'_> {/// Ends the current block of an inlined callee with a return of `value`/// to the continuation in the caller.- pub(super) fn build_inline_return(&mut self, value: NodeId, empty_is_undefined: bool) -> Flow {- let construct_this = self- .function- .inline- .as_ref()- .and_then(|call| call.construct.then_some(call.this));+ pub(super) fn build_inline_return(+ &mut self,+ value: NodeId,+ empty_is_undefined: bool,+ ) -> Result<Flow, CompileFailure> {+ let call = self.function.inline.as_ref().expect("returns from inlined callees");+ let construct_this = if call.derived_construct.is_some() {+ // NB: The callee returns undefined only, once super() bound `this` (see+ // `calls_super_once_before_returning()`), so the result is always `this`.+ Some(self.read(Operand::from_raw(THIS_VALUE_REGISTER))?)+ } else {+ call.construct.then_some(call.this)+ };let value = if let Some(this) = construct_this {// 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget// NB: The callee returns no objects but `this` (see@@ -1805,6 +2139,6 @@ impl GraphBuilder<'_> {}self.set_control(Op::Jump { target: continuation }, Vec::new());self.graph.blocks[continuation.index()].predecessors.push(self.block);- Flow::Ended+ Ok(Flow::Ended)}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 7e04b5ce84b..9b381a653a8 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -1500,7 +1500,7 @@ impl<'a> GraphBuilder<'a> {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)));+ return Ok(Some(self.build_inline_return(value, true)?));}// NB: An empty value returns `undefined`, but a value that is// never empty needs no check for it.@@ -1520,7 +1520,7 @@ impl<'a> GraphBuilder<'a> {// NB: In an inlined callee, End returns its value (never// empty) to the caller like Return does.if self.function.is_virtual() {- return Ok(Some(self.build_inline_return(value, false)));+ return Ok(Some(self.build_inline_return(value, false)?));}self.set_control(Op::Return, vec![value]);return Ok(Some(Flow::Ended));@@ -1652,6 +1652,19 @@ impl<'a> GraphBuilder<'a> {return Ok(None);}}+ Instruction::GetSuperConstructor { dst } => {+ if !self.try_build_super_constructor(dst)? {+ return Ok(None);+ }+ }+ Instruction::BindThisFromSuperCall { result } => {+ if !self.try_build_bind_this_from_super_call(result)? {+ return Ok(None);+ }+ }+ Instruction::SuperCall { .. } | Instruction::SuperCallWithForwardedArguments { .. } => {+ return self.try_inline_super_call(instruction);+ }Instruction::CacheObjectShape { object, cache } => {if !self.try_build_cache_object_shape(object, cache)? {return Ok(None);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex bfa77fe5f59..9aba9ecf09a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -1696,7 +1696,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {return_pc: u32,dst: u32,passed_argument_count: u32,- construct: bool,+ construct_new_target: Option<CellId>,this: Gpr,closure: Option<Gpr>,temps: [Gpr; 3],@@ -1740,10 +1740,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}None => self.emit_frame_header(executable, new_frame, function_register, temp, &header),};- if construct {+ if let Some(new_target) = construct_new_target {+ let new_target = self.boxed_object(new_target);for field in &mut constants {if field.0 == offsets.execution_context_caller_is_construct {field.2 = 1;+ } else if field.0 == offsets.execution_context_new_target {+ field.2 = new_target;}}}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex 832153e796b..ff7f3410d78 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -310,18 +310,44 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {frames.push((frame, values));}let mut clobbered = false;+ // NB: The new target of the frame of the level above.+ let mut new_target = None;for level in (0..frames.len()).rev() {if level + 1 < frames.len() {let (caller, _) = &frames[level + 1];let (callee, values) = &frames[level];let call = self.decoded(caller.executable, caller.pc)?;+ let callee_function = self.executables[callee.executable as usize]+ .function+ .map(|function| function.function);let (argument_count, construct) = match call.instruction {- crate::bytecode::Instruction::Call { argument_count, .. } => (argument_count, false),- crate::bytecode::Instruction::CallConstruct { argument_count, .. } => (argument_count, true),+ crate::bytecode::Instruction::Call { argument_count, .. } => {+ new_target = None;+ (argument_count, false)+ }+ crate::bytecode::Instruction::CallConstruct { argument_count, .. } => {+ new_target = callee_function;+ (argument_count, true)+ }+ // NB: The super() of a derived constructor constructs+ // with the derived constructor's new target.+ crate::bytecode::Instruction::SuperCall { argument_count, .. } if new_target.is_some() => {+ (argument_count, true)+ }+ // NB: Frame states at it list how many arguments it passes+ // on.+ crate::bytecode::Instruction::SuperCallWithForwardedArguments { .. } if new_target.is_some() => {+ (0, true)+ }// NB: Property gets and sets call inlined getters and// setters.- crate::bytecode::Instruction::GetById { .. } => (0, false),- crate::bytecode::Instruction::PutById { .. } => (1, false),+ crate::bytecode::Instruction::GetById { .. } | crate::bytecode::Instruction::PutById { .. } => {+ new_target = None;+ (+ u32::from(matches!(call.instruction, crate::bytecode::Instruction::PutById { .. })),+ false,+ )+ }_ => {return Err(CompileFailure::InvalidBytecode {pc: caller.pc,@@ -360,7 +386,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {call.next_pc(),dst,caller.passed_argument_count.unwrap_or(argument_count),- construct,+ construct.then_some(new_target).flatten(),this,closure,[saved[0], saved[1], saved[2]],diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 08c9ce917c7..c10bc811df4 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -463,6 +463,12 @@ pub struct CallFeedbackSnapshot {/// creates `this` as an empty plain object of `this_shape`, whose prototype/// that is, and runs the body of the snapshot executable `executable`/// (with no function environment).+///+/// Or a derived constructor without fields whose super() constructs with+/// `super_constructor`, its [[Prototype]] while it has `function_shape`.+/// Its construct runs its body, and super() creates `this` like the+/// construct of a base constructor does, with the derived constructor as+/// the new target.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ConstructTarget {pub executable: u32,@@ -471,8 +477,19 @@ pub struct ConstructTarget {pub prototype: CellId,pub this_shape: CellId,/// How many properties the new object gets room for (see- /// `SharedFunctionInstanceData::construct_reserve()`).+ /// `SharedFunctionInstanceData::construct_reserve()`): those of the+ /// super constructor for a derived constructor.pub reserve: u32,+ pub super_constructor: Option<SuperConstructTarget>,+}++/// The base constructor without fields that super() in a derived+/// constructor JIT code can inline constructs with: `function`, whose body+/// is the snapshot executable `executable`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SuperConstructTarget {+ pub executable: u32,+ pub function: CellId,}/// How a callee forwards calls to another function.diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 3954d4e86cc..e9d7e733973 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -20,7 +20,7 @@ use libjs_jit::snapshot::{InlinedFunctionSnapshot, InliningLimits, Intrinsic, KeyedFeedbackSnapshot, LexicalEnvironmentTemplateSnapshot,NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot, PropertyCacheEntrySnapshot,PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, ShapeSnapshot, Snapshot, StressOptions,- SuperBaseSnapshot, TypedArraySnapshot,+ SuperBaseSnapshot, SuperConstructTarget, TypedArraySnapshot,};use super::allocation::{@@ -812,12 +812,12 @@ impl SnapshotBuilder<'_> {}/// Describes the single constructor of a construct site if JIT code can inline its construct: a base constructor- /// without fields (whose construct only creates `this` before running its body), with a function object of a shape- /// that has its "prototype" as a data property holding an object.+ /// without fields (whose construct only creates `this` before running its body), or a derived constructor without+ /// fields whose [[Prototype]] is such a base constructor, with a function object of a shape that has its+ /// "prototype" as a data property holding an object.fn construct_target(&mut self, target: Option<Gc<CellHeader>>, caller: &Entry) -> Option<ConstructTarget> {let function = ecmascript_function(target)?;if !function.has_constructor()- || function.constructor_kind() != ConstructorKind::Base|| function.has_class_data()|| function.allocates_function_environment()|| function.contains_direct_call_to_eval()@@ -825,12 +825,34 @@ impl SnapshotBuilder<'_> {{return None;}+ let super_constructor = match function.constructor_kind() {+ ConstructorKind::Base => None,+ ConstructorKind::Derived => {+ // NB: The frame of the derived constructor holds its this value (see+ // `function_with_frame_as_this_environment()`).+ if function.shared_data().function_environment_has_this_binding() {+ return None;+ }+ let parent = ecmascript_function(function.prototype().map(|parent| parent.upcast::<CellHeader>()))?;+ if !parent.has_constructor()+ || parent.constructor_kind() != ConstructorKind::Base+ || parent.has_class_data()+ || parent.allocates_function_environment()+ || parent.contains_direct_call_to_eval()+ || parent.realm() != Some(caller.realm)+ {+ return None;+ }+ Some(parent)+ }+ };// NB: Class constructors cannot be called, only constructed, so their executable is no inline call executable,// but it runs in an inline frame for a construct all the same.- let executable = function.bytecode_executable()?;let limit = MAX_INLINED_CONSTRUCT_INSTRUCTION_COUNT;- if instruction_count(&executable, limit) > limit {- return None;+ for constructor in core::iter::once(function).chain(super_constructor) {+ if instruction_count(&*constructor.bytecode_executable()?, limit) > limit {+ return None;+ }}let function_shape = function.shape();if function_shape.is_dictionary() {@@ -852,14 +874,31 @@ impl SnapshotBuilder<'_> {empty_shape.create_prototype_transition(self.vm, Some(prototype))};let index = self.inlined_function_index(function, caller)?;- self.construct_this_shapes.insert(index, this_shape);+ let (super_constructor, reserve) = match super_constructor {+ None => {+ self.construct_this_shapes.insert(index, this_shape);+ (None, function.shared_data().current_construct_reserve())+ }+ Some(parent) => {+ let entry = self.entries[index as usize];+ let parent_index = self.inlined_function_index(parent, &entry)?;+ (+ Some(SuperConstructTarget {+ executable: parent_index,+ function: self.cell(parent),+ }),+ parent.shared_data().current_construct_reserve(),+ )+ }+ };Some(ConstructTarget {executable: index,function_shape: self.cell(function_shape),prototype_offset: metadata.offset,prototype: self.cell(prototype),this_shape: self.cell(this_shape),- reserve: function.shared_data().current_construct_reserve(),+ reserve,+ super_constructor,})}diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex ac8e9bb601e..c6f881d1d65 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -289,26 +289,44 @@ struct CallLinkage {return_pc: u32,dst: u32,is_construct: bool,+ /// Whether the call is the super() of a derived constructor, whose new target is the caller's.+ is_super_call: bool,}-/// The argument count, length and kind of the Call or CallConstruct instruction at the start of `bytes`, or of the call-/// of a getter a GetById instruction or of a setter a PutById instruction makes.-fn call_instruction_shape(executable: &Executable, pc: u32) -> (u32, u32, bool) {+/// The kind of call an instruction that an inlined call is made for makes.+#[derive(Clone, Copy, PartialEq, Eq)]+enum CallKind {+ Call,+ Construct,+ SuperCall,+}++/// The argument count, length and kind of the Call, CallConstruct or SuperCall* instruction at `pc`, or of the call of+/// a getter a GetById instruction or of a setter a PutById instruction makes.+fn call_instruction_shape(executable: &Executable, pc: u32) -> (u32, u32, CallKind) {let opcode = executable.bytecode()[pc as usize];if opcode == OpCode::GetById as u8 {let get = instruction_at::<op::GetById>(executable, pc);- return (0, get.length(), false);+ return (0, get.length(), CallKind::Call);}if opcode == OpCode::PutById as u8 {let put = instruction_at::<op::PutById>(executable, pc);- return (1, put.length(), false);+ return (1, put.length(), CallKind::Call);}if opcode == OpCode::CallConstruct as u8 {let call = instruction_at::<op::CallConstruct>(executable, pc);- return (u32::from(call.argument_count), call.length(), true);+ return (u32::from(call.argument_count), call.length(), CallKind::Construct);+ }+ if opcode == OpCode::SuperCall as u8 {+ let call = instruction_at::<op::SuperCall>(executable, pc);+ return (u32::from(call.argument_count), call.length(), CallKind::SuperCall);+ }+ // NB: Frame states at it list how many arguments it passes on.+ if opcode == OpCode::SuperCallWithForwardedArguments as u8 {+ return (0, op::SuperCallWithForwardedArguments::LENGTH, CallKind::SuperCall);}let call = instruction_at::<op::Call>(executable, pc);- (u32::from(call.argument_count), call.length(), false)+ (u32::from(call.argument_count), call.length(), CallKind::Call)}/// The linkage of the frame of `executable` at the call of `frame_state`: its frame continues after the call (or@@ -319,12 +337,13 @@ fn call_linkage(executable: &Executable, frame_state: &FrameState) -> CallLinkagunreachable!("frames at calls resume after them");};let pc = frame_state.pc;- let (argument_count, length, is_construct) = call_instruction_shape(executable, pc);+ let (argument_count, length, kind) = call_instruction_shape(executable, pc);CallLinkage {passed_argument_count: frame_state.passed_argument_count.unwrap_or(argument_count),return_pc: pc + length,dst,- is_construct,+ is_construct: kind != CallKind::Call,+ is_super_call: kind == CallKind::SuperCall,}}@@ -360,8 +379,14 @@ enum FrameSlots {Uninitialized,}-/// Pushes the frame of an inlined call, linked to the running frame like an interpreter inline call.-fn push_frame(vm: &Vm, callee: InlinedFunction, linkage: CallLinkage, slots: FrameSlots) -> NonNull<ExecutionContext> {+/// Pushes the frame of an inlined call, linked to the running frame, `caller`, like an interpreter inline call.+fn push_frame(+ vm: &Vm,+ caller: &ExecutionContext,+ callee: InlinedFunction,+ linkage: CallLinkage,+ slots: FrameSlots,+) -> NonNull<ExecutionContext> {// NB: JIT code checks at entry that the interpreter stack has room for every frame it may materialize.let frame = match callee {InlinedFunction::Ecmascript(callee) => {@@ -375,7 +400,13 @@ fn push_frame(vm: &Vm, callee: InlinedFunction, linkage: CallLinkage, slots: Fra} else {callee.inline_call_executable()};- let new_target = linkage.is_construct.then(|| callee.upcast());+ // NB: The super() of a derived constructor constructs with the derived constructor's new target, like+ // the interpreter's SuperCall does.+ let new_target = if linkage.is_super_call {+ Some(caller.new_target.get().as_object())+ } else {+ linkage.is_construct.then(|| callee.upcast())+ };vm.push_inline_frame_without_this(callee,executable,@@ -556,6 +587,7 @@ fn push_site_frames(let function = values.function(code, frame_state);frame = push_frame(vm,+ frame_of(frame),function,linkage.expect("callers of inlined calls link them"),FrameSlots::Initialize,@@ -778,9 +810,11 @@ pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode,let root_frame_state = frame_states.last().expect("a frame state");frame_of(root).program_counter.set(root_frame_state.pc);let mut linkage = call_linkage(&executable_of(frame_of(root)), root_frame_state);+ let mut caller = root;for (index, frame_state) in frame_states.iter().enumerate().rev().skip(1) {let function = values.function(code, frame_state);- let frame = push_frame(vm, function, linkage, FrameSlots::Uninitialized);+ let frame = push_frame(vm, frame_of(caller), function, linkage, FrameSlots::Uninitialized);+ caller = frame;let frame_ref = frame_of(frame);let executable = executable_of(frame_ref);let arguments_base = arguments_base_of(&executable);diff --git a/Tests/LibJS/JIT/ir/inlining-derived-constructs.js b/Tests/LibJS/JIT/ir/inlining-derived-constructs.jsnew file mode 100644index 00000000000..e5b7fd8681d--- /dev/null+++ b/Tests/LibJS/JIT/ir/inlining-derived-constructs.js@@ -0,0 +1,49 @@+// REQUIRES: inline-allocation+// A construct of a derived constructor without fields inlines the derived constructor and the construct of its base+// parent at super(), which creates `this` from the "prototype" of the derived constructor. Default derived+// constructors pass their arguments on the same way.++class A {+ constructor(x) {+ this.x = x;+ }+}+class B extends A {+ constructor(x) {+ super(x);+ this.y = 1;+ }+}+class C extends A {}+function make(i) {+ return new B(i).x;+}+function makeDefault(i) {+ return new C(i).x;+}+jit.prepare(make);+jit.prepare(makeDefault);+for (let i = 0; i < 10; ++i) {+ make(i);+ makeDefault(i);+}+jit.compile(make);+jit.compile(makeDefault);++// CHECK-FUNCTION: make+// CHECK-PASS: graph building+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK: AllocateObject+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK-NOT: BindThisFromSuperCall++// CHECK-FUNCTION: makeDefault+// CHECK-PASS: graph building+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK: AllocateObject+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK-NOT: BindThisFromSuperCalldiff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.jsindex dfec98121a1..51029178026 100644--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js@@ -650,3 +650,318 @@ describe("super property loads and new.target in hot code", () => {});});});++describe("derived constructs in hot callers", () => {+ test("this, new.target and prototypes", () => {+ class A {+ constructor(x) {+ this.x = x;+ this.parentTarget = new.target;+ }+ }+ class B extends A {+ constructor(x, y) {+ super(x);+ this.y = y;+ this.ownTarget = new.target;+ }+ }+ function make(i) {+ return new B(i, i + 1);+ }+ repeat(i => {+ const b = make(i);+ expect(b.x).toBe(i);+ expect(b.y).toBe(i + 1);+ expect(b.parentTarget).toBe(B);+ expect(b.ownTarget).toBe(B);+ expect(Object.getPrototypeOf(b)).toBe(B.prototype);+ expect(Object.keys(b)).toEqual(["x", "parentTarget", "y", "ownTarget"]);+ });+ });++ test("argument counts above and below the parameter counts", () => {+ class A {+ constructor(a, b, c) {+ this.values = [a, b, c, arguments.length];+ }+ }+ class B extends A {+ constructor(a, b) {+ super(a);+ this.b = b;+ }+ }+ class C extends A {+ constructor(a) {+ super(a, a, a, a);+ }+ }+ repeat(i => {+ expect(new B().values).toEqual([undefined, undefined, undefined, 1]);+ expect(new B(i, 2, 3).values).toEqual([i, undefined, undefined, 1]);+ expect(new B(i, 2, 3).b).toBe(2);+ expect(new C(i).values).toEqual([i, i, i, 4]);+ });+ });++ test("values of other types before, in and after super()", () => {+ class A {+ constructor(x) {+ this.x = x.value + 1;+ }+ }+ class B extends A {+ constructor(x, y) {+ super(x.inner);+ this.y = y.value * 2;+ }+ }+ function make(i, kind) {+ const inner = kind === 1 ? { value: "s" } : { value: i };+ const x = kind === 0 ? { inner } : { other: 1, inner };+ const y = kind === 2 ? { value: "2" } : { value: i };+ return new B(x, y);+ }+ for (let kind = 0; kind < 3; kind++) {+ repeat(i => {+ const b = make(i, i < ITERATIONS / 2 ? 0 : kind);+ const changed = i >= ITERATIONS / 2 ? kind : 0;+ expect(b.x).toBe(changed === 1 ? "s1" : i + 1);+ expect(b.y).toBe(changed === 2 ? 4 : i * 2);+ expect(b).toBeInstanceOf(B);+ });+ }+ });++ test("exceptions from the parent and after super()", () => {+ class A {+ constructor(fail) {+ if (fail === 1) throw new Error("parent");+ this.ok = true;+ }+ }+ class B extends A {+ constructor(fail) {+ super(fail);+ if (fail === 2) throw new Error("derived");+ this.done = true;+ }+ }+ function make(fail) {+ return new B(fail);+ }+ repeat(i => {+ const fail = i % 50 === 0 ? 1 + ((i / 50) % 2) : 0;+ if (fail === 0) {+ const b = make(0);+ expect(b.ok).toBeTrue();+ expect(b.done).toBeTrue();+ } else {+ let caught;+ try {+ make(fail);+ } catch (e) {+ caught = e;+ }+ expect(caught.message).toBe(fail === 1 ? "parent" : "derived");+ const frames = caught.stack.split("\n").map(line => line.trim().split(" ")[1]);+ expect(frames.slice(1, fail === 1 ? 4 : 3)).toEqual(fail === 1 ? ["A", "B", "make"] : ["B", "make"]);+ }+ });+ });++ test("a parent changed with Object.setPrototypeOf while the caller is hot", () => {+ class A {+ constructor(x) {+ this.from = "A";+ this.x = x;+ }+ }+ class C {+ constructor(x) {+ this.from = "C";+ this.x = x;+ }+ }+ class B extends A {+ constructor(x) {+ super(x);+ this.y = 1;+ }+ }+ function make(i) {+ return new B(i);+ }+ repeat(i => {+ if (i === ITERATIONS / 2) Object.setPrototypeOf(B, C);+ const b = make(i);+ expect(b.from).toBe(i < ITERATIONS / 2 ? "A" : "C");+ expect(b.x).toBe(i);+ expect(b.y).toBe(1);+ expect(b).toBeInstanceOf(B);+ });+ });++ test("Reflect.construct with another new.target while new is hot", () => {+ class A {+ constructor() {+ this.target = new.target;+ }+ }+ class B extends A {+ constructor() {+ super();+ this.ownTarget = new.target;+ }+ }+ function Other() {}+ function make() {+ return new B();+ }+ repeat(i => {+ expect(make().target).toBe(B);+ if (i % 100 === 0) {+ const other = Reflect.construct(B, [], Other);+ expect(other.target).toBe(Other);+ expect(other.ownTarget).toBe(Other);+ expect(Object.getPrototypeOf(other)).toBe(Other.prototype);+ }+ });+ });++ test("three levels of inheritance", () => {+ class A {+ constructor(x) {+ this.a = x;+ }+ }+ class B extends A {+ constructor(x) {+ super(x);+ this.b = x + 1;+ }+ }+ class C extends B {+ constructor(x) {+ super(x);+ this.c = x + 2;+ }+ }+ function make(i) {+ return new C(i);+ }+ repeat(i => {+ const c = make(i);+ expect([c.a, c.b, c.c]).toEqual([i, i + 1, i + 2]);+ expect(c).toBeInstanceOf(C);+ expect(new B(i).b).toBe(i + 1);+ });+ });++ test("default derived constructors", () => {+ class A {+ constructor(a, b) {+ this.a = a;+ this.b = b;+ this.target = new.target;+ }+ }+ class B extends A {}+ function make(i) {+ if (i % 3 === 0) return new B();+ if (i % 3 === 1) return new B(i);+ return new B(i, i + 1, i + 2);+ }+ repeat(i => {+ const b = make(i);+ const count = i % 3 === 0 ? 0 : i % 3 === 1 ? 1 : 3;+ expect(b.a).toBe(count > 0 ? i : undefined);+ expect(b.b).toBe(count > 1 ? i + 1 : undefined);+ expect(b.target).toBe(B);+ expect(b).toBeInstanceOf(B);+ });+ });++ test("default derived constructors whose parent changes while the caller is hot", () => {+ class A {+ constructor(x) {+ this.from = "A";+ this.x = x;+ }+ }+ class C {+ constructor(x) {+ this.from = "C";+ this.x = x;+ }+ }+ class B extends A {}+ function make(i) {+ return new B(i);+ }+ repeat(i => {+ if (i === ITERATIONS / 2) Object.setPrototypeOf(B, C);+ const b = make(i);+ expect(b.from).toBe(i < ITERATIONS / 2 ? "A" : "C");+ expect(b.x).toBe(i);+ });+ });++ test("classes with fields and private methods", () => {+ class A {+ constructor(x) {+ this.x = x;+ }+ }+ class B extends A {+ field = 1;+ #secret() {+ return this.x;+ }+ constructor(x) {+ super(x);+ this.y = this.#secret() + this.field;+ }+ }+ function make(i) {+ return new B(i);+ }+ repeat(i => {+ const b = make(i);+ expect(b.y).toBe(i + 1);+ expect(Object.keys(b)).toEqual(["x", "field", "y"]);+ });+ });++ test("a handler that catches what super() throws", () => {+ class A {+ constructor(fail) {+ if (fail) throw new Error("failed");+ this.x = 1;+ }+ }+ class B extends A {+ constructor(fail) {+ try {+ super(fail);+ } catch {}+ }+ }+ function make(fail) {+ return new B(fail);+ }+ repeat(() => {+ expect(make(false).x).toBe(1);+ });+ // NB: The handler runs for the first time here, and the constructor returns without a this value.+ expect(() => make(true)).toThrowWithMessage(ReferenceError, "|this| has not been initialized");+ repeat(i => {+ if (i % 100 === 0) {+ expect(() => make(true)).toThrowWithMessage(ReferenceError, "|this| has not been initialized");+ } else {+ expect(make(false).x).toBe(1);+ }+ });+ });+});