Truly independent web browser
LibJS: Construct through a stub that builds the frame in JIT code
Andreas Klinga7880d018ae4
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex 9aba9ecf09a..8387e167e7b 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -73,6 +73,7 @@ enum CallOperand {/// A register: an input of the call's node, or a value loaded already.Register(Gpr),Undefined,+ Empty,}/// What `emit_js_call()` worked out about a `Call` instruction before@@ -261,6 +262,61 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_js_call(executable, pc, None, call_function)}+ /// A generic `CallConstruct`, `SuperCall` or `SuperCallWithForwardedArguments`:+ /// through the construct stub (see `RuntimeInfo::construct_stub`), with+ /// the constructor as its own new target for `CallConstruct` and the+ /// running frame's for super calls. `SuperCallWithForwardedArguments`+ /// passes no callee, which has the runtime prepare the construct.+ pub(super) fn emit_generic_construct(&mut self, executable: u32, pc: u32) -> Result<(), CompileFailure> {+ let decoded = self.decoded(executable, pc)?;+ let next_pc = decoded.next_pc();+ let (dst, callee, new_target, arguments) = match decoded.instruction {+ Instruction::CallConstruct {+ dst,+ callee,+ ref arguments,+ ..+ } => (+ dst,+ CallOperand::Slot(callee),+ CallOperand::Slot(callee),+ arguments.clone(),+ ),+ Instruction::SuperCall {+ dst,+ super_constructor,+ ref arguments,+ ..+ } => (+ dst,+ CallOperand::Slot(super_constructor),+ CallOperand::Empty,+ arguments.clone(),+ ),+ Instruction::SuperCallWithForwardedArguments { dst, .. } => {+ (dst, CallOperand::Undefined, CallOperand::Empty, Vec::new())+ }+ _ => {+ return Err(CompileFailure::InvalidBytecode {+ pc,+ reason: "generic construct of a non-construct instruction",+ });+ }+ };+ let arguments = arguments.into_iter().map(CallOperand::Slot).collect::<Vec<_>>();+ self.emit_call_stub_call(+ callee,+ new_target,+ &arguments,+ pc,+ next_pc,+ dst.raw(),+ self.runtime.construct_stub,+ )?;+ self.emit_continuation_check(next_pc, &[]);+ Ok(())+ }+/// Whether generic `Call` nodes try to call ECMAScript functions directly/// before taking the generic path.pub(super) fn makes_dynamic_calls(&self) -> bool {@@ -815,7 +871,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_push_inlined_call_frames(site, &inputs);}store_operands(self)?;- self.emit_call_stub_call(callee_operand, this_operand, argument_operands, pc, next_pc, dst.raw())?;+ self.emit_call_stub_call(+ callee_operand,+ this_operand,+ argument_operands,+ pc,+ next_pc,+ dst.raw(),+ call_stub,+ )?;self.masm.jump(check);}@@ -992,6 +1056,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}CallOperand::Register(register) => self.masm.move64(dst, register),CallOperand::Undefined => self.masm.move_imm64(dst, value::UNDEFINED),+ CallOperand::Empty => self.masm.move_imm64(dst, value::EMPTY),}Ok(())}@@ -1015,6 +1080,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// `callee`, with `this` and `arguments`, which it stores on the machine/// stack for the stub. Leaves the stub's control word in the first/// return register.+ #[allow(clippy::too_many_arguments)]fn emit_call_stub_call(&mut self,callee: CallOperand,@@ -1023,6 +1089,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {pc: u32,next_pc: u32,dst: u32,+ stub: u64,) -> Result<(), CompileFailure> {let registers = M::ARGUMENT_GPRS;let scratch = self.pinned.scratch;@@ -1047,7 +1114,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.move_imm64(registers[3], u64::from(pc) | (u64::from(next_pc) << 32));self.masm.move_imm32(registers[4], dst);- self.masm.call_absolute(self.runtime.dynamic_calls.call_stub);+ self.masm.call_absolute(stub);if argument_bytes != 0 {self.masm.add64_imm(M::STACK_POINTER, M::STACK_POINTER, argument_bytes);}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 921f5fdbe00..0cde1181bbb 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -62,7 +62,9 @@ mod local {pub const PREPARED_THIS: u32 = 48;/// The callee's executable while its frame is built, then the frame.pub const EXECUTABLE: u32 = 56;- pub const SIZE: u32 = 64;+ /// The new target of a construct.+ pub const NEW_TARGET: u32 = 64;+ pub const SIZE: u32 = 80;}/// Generates the call stub, or nothing if the runtime lacks a helper it@@ -72,6 +74,32 @@ pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> Rif layout.object_flag_is_ecmascript_function == 0 || runtime.jit_call == 0 || runtime.finish_direct_call == 0 {return Ok(None);}+ generate_stub::<M>(runtime, false).map(Some)+}++/// Generates the construct stub (see `Codegen::emit_call_stub()`), or+/// nothing if the runtime lacks a helper it needs (then JIT code makes+/// constructs through `RuntimeInfo::jit_call`).+pub fn generate_construct_stub<M: PortableMacroAssembler>(+ runtime: &RuntimeInfo,+) -> Result<Option<Vec<u8>>, CompileFailure> {+ let layout = runtime.dynamic_calls;+ if layout.object_flag_is_ecmascript_function == 0+ || layout.jit_entry_table == 0+ || runtime.construct_this == 0+ || runtime.throw_call_stack_size_exceeded == 0+ || runtime.prepare_construct == 0+ || runtime.construct_result_error == 0+ || runtime.finish_direct_construct == 0+ {+ return Ok(None);+ }+ generate_stub::<M>(runtime, true).map(Some)+}++/// Generates the code of the call stub, or with `construct` of the construct+/// stub (see `Codegen::emit_call_stub()`).+fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bool) -> Result<Vec<u8>, CompileFailure> {let graph = Graph::default();let allocation = Allocation::default();let (_, pinned) = target_registers::<M>();@@ -116,12 +144,12 @@ pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> Rabsorbed_initializations: Vec::new(),inline_initializations: Default::default(),};- codegen.emit_call_stub()?;+ codegen.emit_call_stub(construct)?;let (code, _) = codegen.masm.finish_with_data_offset().map_err(|_| CompileFailure::CodeGeneration)?;- Ok(Some(code))+ Ok(code)}/// The registers `emit_stub_call_environment()` works with: the callee's@@ -295,7 +323,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}- fn emit_call_stub(&mut self) -> Result<(), CompileFailure> {+ /// The call stub, or with `construct` the construct stub: called like+ /// the call stub for a `CallConstruct` or `SuperCall` instruction, with+ /// the new target in place of the `this` value (or the empty value for+ /// the running frame's new.target), it makes constructs of ECMAScript+ /// constructors the runtime allows (see `RuntimeInfo::construct_this`)+ /// the same way, and lets the runtime push the constructor's frame for+ /// the stub to enter (see `RuntimeInfo::prepare_construct`) or make the+ /// construct otherwise.+ fn emit_call_stub(&mut self, construct: bool) -> Result<(), CompileFailure> {let runtime = self.runtime;let offsets = runtime.offsets;let layout = runtime.dynamic_calls;@@ -351,7 +387,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {u32::from(layout.object_flag_is_ecmascript_function),ecmascript_function,);- if layout.object_flag_is_raw_native_function != 0 && runtime.raw_native_exception != 0 {+ if !construct && layout.object_flag_is_raw_native_function != 0 && runtime.raw_native_exception != 0 {self.masm.branch_test32(Condition::Zero,temp,@@ -384,50 +420,46 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {);};load_function_data(self);- self.masm- .branch_test64(Condition::Zero, receiver, layout.metadata_can_inline_call, slow);+ if !construct {+ self.masm+ .branch_test64(Condition::Zero, receiver, layout.metadata_can_inline_call, slow);+ }self.masm.branch_test32(Condition::Zero, executable_register, u32::MAX, slow);self.emit_decompress_cell(executable_register);let environment_local = self.stub_local(local::ENVIRONMENT);- self.masm.store_imm64(&environment_local, 0);- // Callees that need a function environment or the resolution of- // their `this` value get both from the runtime before their frame is- // built.- let resume = self.masm.new_label();- if layout.prepare_call_environment != 0 {+ // A construct gets its this value and new target from the runtime.+ // NB: From here on, the construct cannot take the slow path anymore.+ let stack_overflow = self.masm.new_label();+ let failed_after_this = if construct { stack_overflow } else { slow };+ if construct {+ self.emit_native_stack_check(slow);self.masm.branch_test64(- Condition::Zero,+ Condition::NonZero,receiver,layout.metadata_needs_environment_or_this_value_resolution,- resume,+ slow,);- if layout.shared_data_call_environment_template != 0 && runtime.object_allocation.heap != 0 {- let from_runtime = self.masm.new_label();- self.emit_stub_call_environment(- StubCallEnvironmentRegisters {- shared_data: other,- function: function_register,- metadata: receiver,- template: callee_frame,- cell: temp,- },- from_runtime,- );- self.masm.jump(resume);- self.masm.bind(from_runtime);- }let this_local = self.stub_local(local::THIS);+ let pcs_local = self.stub_local(local::PCS);self.masm.load64(registers[2], &this_local);self.masm.move64(registers[1], function_register);+ self.masm.load32(registers[3], &pcs_local);self.masm.move64(registers[0], vm);- self.masm.call_absolute(layout.prepare_call_environment);- let [environment, this] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];- self.masm.branch64_imm(Condition::Equal, environment, 0, slow);- self.masm.store64(&environment_local, environment);+ self.masm.call_absolute(runtime.construct_this);+ let [this, new_target] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];+ self.masm.branch64_imm(Condition::Equal, this, 0, slow);+ let constructed = self.masm.new_label();+ self.masm.branch64_imm(Condition::NotEqual, this, 1, constructed);+ // NB: The runtime threw, and the second register has the control word.+ self.masm.move64(M::RETURN_GPRS[0], new_target);+ self.masm.jump(leave);+ self.masm.bind(constructed);let prepared_this = self.stub_local(local::PREPARED_THIS);self.masm.store64(&prepared_this, this);+ let new_target_local = self.stub_local(local::NEW_TARGET);+ self.masm.store64(&new_target_local, new_target);// The runtime may have collected garbage: load the function and// what comes from it again.let callee_local = self.stub_local(local::CALLEE);@@ -436,14 +468,60 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {load_function_data(self);self.emit_decompress_cell(executable_register);} else {- self.masm.branch_test64(- Condition::NonZero,- receiver,- layout.metadata_needs_environment_or_this_value_resolution,- slow,- );+ // Callees that need a function environment or the resolution of+ // their `this` value get both from the runtime before their frame+ // is built.+ self.masm.store_imm64(&environment_local, 0);+ let resume = self.masm.new_label();+ if layout.prepare_call_environment != 0 {+ self.masm.branch_test64(+ Condition::Zero,+ receiver,+ layout.metadata_needs_environment_or_this_value_resolution,+ resume,+ );+ if layout.shared_data_call_environment_template != 0 && runtime.object_allocation.heap != 0 {+ let from_runtime = self.masm.new_label();+ self.emit_stub_call_environment(+ StubCallEnvironmentRegisters {+ shared_data: other,+ function: function_register,+ metadata: receiver,+ template: callee_frame,+ cell: temp,+ },+ from_runtime,+ );+ self.masm.jump(resume);+ self.masm.bind(from_runtime);+ }+ let this_local = self.stub_local(local::THIS);+ self.masm.load64(registers[2], &this_local);+ self.masm.move64(registers[1], function_register);+ self.masm.move64(registers[0], vm);+ self.masm.call_absolute(layout.prepare_call_environment);+ let [environment, this] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];+ self.masm.branch64_imm(Condition::Equal, environment, 0, slow);+ self.masm.store64(&environment_local, environment);+ let prepared_this = self.stub_local(local::PREPARED_THIS);+ self.masm.store64(&prepared_this, this);+ // The runtime may have collected garbage: load the function and+ // what comes from it again.+ let callee_local = self.stub_local(local::CALLEE);+ self.masm.load64(temp, &callee_local);+ self.emit_unbox_cell(function_register, temp);+ load_function_data(self);+ self.emit_decompress_cell(executable_register);+ } else {+ self.masm.branch_test64(+ Condition::NonZero,+ receiver,+ layout.metadata_needs_environment_or_this_value_resolution,+ slow,+ );+ }+ self.masm.bind(resume);}- self.masm.bind(resume);// The number of argument slots: the formal parameter count (in the// low bits of the metadata), or more if more were passed.@@ -456,36 +534,40 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.move32(formal_count, temp);self.masm.bind(enough);- // Bind `this` like the interpreter's call fast path: as is for strict+ // A construct binds the `this` value the runtime made. A call binds+ // `this` like the interpreter's call fast path: as is for strict// callees, objects only for sloppy ones (the generic call boxes// primitives and resolves null and undefined), and as the runtime// prepared it for callees with an environment.- let have_receiver = self.masm.new_label();- let own_environment = self.masm.new_label();- self.masm- .branch64_memory_imm(Condition::Equal, &environment_local, 0, own_environment);let prepared_this = self.stub_local(local::PREPARED_THIS);- self.masm.load64(receiver, &prepared_this);- self.masm.jump(have_receiver);- self.masm.bind(own_environment);- let uses_this = self.masm.new_label();- self.masm- .branch_test64(Condition::NonZero, receiver, layout.metadata_uses_this, uses_this);- self.masm.move_imm64(receiver, value::EMPTY);- self.masm.jump(have_receiver);- self.masm.bind(uses_this);- let strict = self.masm.new_label();- self.masm- .branch_test64(Condition::NonZero, receiver, layout.metadata_strict, strict);- let this_local = self.stub_local(local::THIS);- self.masm.load64(receiver, &this_local);- self.branch_on_tag(Condition::NotEqual, receiver, value::OBJECT_TAG, temp, slow);- self.masm.jump(have_receiver);- self.masm.bind(strict);- self.masm.load64(receiver, &this_local);- self.masm.bind(have_receiver);-- self.emit_native_stack_check(slow);+ if construct {+ self.masm.load64(receiver, &prepared_this);+ } else {+ let have_receiver = self.masm.new_label();+ let own_environment = self.masm.new_label();+ self.masm+ .branch64_memory_imm(Condition::Equal, &environment_local, 0, own_environment);+ self.masm.load64(receiver, &prepared_this);+ self.masm.jump(have_receiver);+ self.masm.bind(own_environment);+ let uses_this = self.masm.new_label();+ self.masm+ .branch_test64(Condition::NonZero, receiver, layout.metadata_uses_this, uses_this);+ self.masm.move_imm64(receiver, value::EMPTY);+ self.masm.jump(have_receiver);+ self.masm.bind(uses_this);+ let strict = self.masm.new_label();+ self.masm+ .branch_test64(Condition::NonZero, receiver, layout.metadata_strict, strict);+ let this_local = self.stub_local(local::THIS);+ self.masm.load64(receiver, &this_local);+ self.branch_on_tag(Condition::NotEqual, receiver, value::OBJECT_TAG, temp, slow);+ self.masm.jump(have_receiver);+ self.masm.bind(strict);+ self.masm.load64(receiver, &this_local);+ self.masm.bind(have_receiver);+ self.emit_native_stack_check(slow);+ }// The frame's slot count, and its allocation on the interpreter stack.self.masm.load32(@@ -495,7 +577,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {layout.executable_registers_and_locals_and_constants_count as i32,),);- self.masm.branch_add32_overflow(temp, temp, formal_count, slow);+ self.masm+ .branch_add32_overflow(temp, temp, formal_count, failed_after_this);self.masm.load64(callee_frame, &vm_field(offsets.vm_interpreter_stack_top));self.masm.load_effective_address(@@ -510,22 +593,24 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Condition::Below,&vm_field(offsets.vm_interpreter_stack_limit),scratch,- slow,+ failed_after_this,);self.masm.store64(&vm_field(offsets.vm_interpreter_stack_top), scratch);// Fill in the frame like the interpreter's call fast path.let field = |offset: u32| Address::new(callee_frame, offset as i32);self.emit_function_fields(callee_frame, function_register, scratch);- let prepared_environment = self.masm.new_label();- self.masm.load64(scratch, &environment_local);- self.masm- .branch64_imm(Condition::Equal, scratch, 0, prepared_environment);- self.masm- .store64(&field(offsets.execution_context_lexical_environment), scratch);- self.masm- .store64(&field(offsets.execution_context_variable_environment), scratch);- self.masm.bind(prepared_environment);+ if !construct {+ let prepared_environment = self.masm.new_label();+ self.masm.load64(scratch, &environment_local);+ self.masm+ .branch64_imm(Condition::Equal, scratch, 0, prepared_environment);+ self.masm+ .store64(&field(offsets.execution_context_lexical_environment), scratch);+ self.masm+ .store64(&field(offsets.execution_context_variable_environment), scratch);+ self.masm.bind(prepared_environment);+ }self.emit_load_compressed_cell(scratch, &Address::new(function_register, offsets.object_shape as i32));self.emit_load_compressed_cell(scratch, &Address::new(scratch, layout.shape_realm as i32));self.masm.store64(&field(offsets.execution_context_realm), scratch);@@ -542,6 +627,22 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {constants.push((slot(register), 8, value::EMPTY));}self.emit_constant_fields_with_vector(callee_frame, scratch, &mut constants, Some(M::ARGUMENT_FPRS[0]), &[])?;+ if construct {+ // The frame of a constructor has its new target, and that of a+ // derived constructor its this value, empty until super() binds+ // it (see `ExecutionContext::caller_is_derived_construct`).+ let new_target_local = self.stub_local(local::NEW_TARGET);+ self.masm.load64(scratch, &new_target_local);+ self.masm.store64(&field(offsets.execution_context_new_target), scratch);+ let base = self.masm.new_label();+ self.masm+ .branch64_imm(Condition::NotEqual, receiver, value::EMPTY as i64, base);+ self.masm+ .store_imm8(&field(offsets.execution_context_caller_is_construct), 1);+ self.masm+ .store_imm8(&field(offsets.execution_context_caller_is_derived_construct), 1);+ self.masm.bind(base);+ }// The arguments start after the registers, locals and constants: slot// count minus formal count. Copy the passed ones and fill the formal@@ -589,10 +690,62 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// does not belong to the executable enters through slot 0, which has// the interpreter run the frame.self.masm.store64(&executable_local, callee_frame);- let (entry_slot, table) = (temp, registers[0]);+ if construct {+ self.emit_construct_stub_tail(slow, stack_overflow, leave);+ return Ok(());+ }+ self.emit_stub_enter_frame(other);++ // The callee returned: pop its frame like the interpreter's Return.+ let [value_register, status] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];+ let not_returned = self.masm.new_label();+ self.masm+ .branch64_imm(Condition::NotEqual, status, JitStatus::Returned as i64, not_returned);+ // NB: JIT code never returns the empty value.+ self.emit_stub_store_result(value_register, temp);+ self.masm.load64(temp, &executable_local);+ self.masm.store64(&vm_field(offsets.vm_interpreter_stack_top), temp);+ self.masm+ .store64(&vm_field(offsets.vm_running_execution_context), frame);+ self.masm+ .add32_to_memory_imm(&vm_field(offsets.vm_execution_generation), 1);+ self.emit_stub_continuation();+ self.masm.jump(leave);++ // The callee's frame still runs: let the runtime finish the call.+ self.masm.bind(not_returned);+ self.masm.move64(registers[3], status);+ self.masm.move64(registers[0], vm);+ self.masm.move64(registers[1], frame);+ let pcs_local = self.stub_local(local::PCS);+ self.masm.load32(registers[2], &pcs_local);+ self.masm.call_absolute(runtime.finish_direct_call);+ self.masm.jump(leave);++ // Everything else takes the generic path.+ self.masm.bind(slow);+ self.masm.move64(registers[0], vm);+ self.masm.move64(registers[1], frame);+ self.masm.load32(registers[2], &pcs_local);+ self.masm.call_absolute(runtime.jit_call);++ self.masm.bind(leave);+ self.masm.emit_epilogue(&machine_frame);+ self.masm.ret();+ Ok(())+ }++ /// Enters the frame in the second argument register, which runs the+ /// executable in `executable`, through the executable's entry in the JIT+ /// entry table (see `emit_call_stub()`). Clobbers the argument registers+ /// other than the second.+ fn emit_stub_enter_frame(&mut self, executable: Gpr) {+ let layout = self.runtime.dynamic_calls;+ let registers = M::ARGUMENT_GPRS;+ let (entry_slot, table, entry) = (registers[2], registers[0], registers[5]);self.masm.load32(entry_slot,- &Address::new(other, layout.executable_jit_entry_slot as i32),+ &Address::new(executable, layout.executable_jit_entry_slot as i32),);self.masm.and32_imm(entry_slot, entry_slot, layout.jit_entry_slot_mask);self.masm.move_imm64(table, layout.jit_entry_table);@@ -604,12 +757,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {index: Some((entry_slot, Scale::Eight)),displacement: layout.jit_entry_table_owners as i32,},- other,+ executable,owned,);self.masm.move_imm32(entry_slot, 0);self.masm.bind(owned);- let entry = receiver;self.masm.load64(entry,&Address {@@ -618,46 +770,125 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {displacement: 0,},);- self.masm.move64(registers[0], vm);+ self.masm.move64(registers[0], self.pinned.vm);self.masm.call_register(entry);+ }- // The callee returned: pop its frame like the interpreter's Return.- let [value_register, status] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];+ /// The rest of the construct stub (see `emit_call_stub()`) once it built+ /// the constructor's frame, which is in the second argument register+ /// (and the frame local), with the constructor's executable in the+ /// fourth: enters the frame, pops it and finishes the construct. Also+ /// emits the paths of `slow` constructs, which the runtime prepares,+ /// and of constructs that ran out of stack after the runtime made their+ /// this value.+ fn emit_construct_stub_tail(&mut self, slow: Label, stack_overflow: Label, leave: Label) {+ let runtime = self.runtime;+ let offsets = runtime.offsets;+ let registers = M::ARGUMENT_GPRS;+ let (vm, frame, scratch) = (self.pinned.vm, self.pinned.frame, self.pinned.scratch);+ let vm_field = |offset: u32| Address::new(vm, offset as i32);+ let [result, status] = [M::RETURN_GPRS[0], M::RETURN_GPRS[1]];+ let (temp, other) = (registers[3], registers[4]);+ let pcs_local = self.stub_local(local::PCS);+ let frame_local = self.stub_local(local::EXECUTABLE);+ let value_local = self.stub_local(local::PREPARED_THIS);+ let enter = self.masm.new_label();++ self.masm.bind(enter);+ self.emit_stub_enter_frame(registers[3]);++ // The constructor returned: pop its frame like the interpreter's+ // Return.let not_returned = self.masm.new_label();self.masm.branch64_imm(Condition::NotEqual, status, JitStatus::Returned as i64, not_returned);- // NB: JIT code never returns the empty value.- self.emit_stub_store_result(value_register, temp);- self.masm.load64(temp, &executable_local);+ self.masm.load64(temp, &frame_local);+ // NB: The frame of a derived constructor returns its this value for+ // undefined (see `ExecutionContext::caller_is_derived_construct`).+ let returned_value = self.masm.new_label();+ self.masm+ .branch64_imm(Condition::NotEqual, result, value::UNDEFINED as i64, returned_value);+ self.masm.load64(other, &value_local);+ self.branch_on_tag(Condition::Equal, other, value::OBJECT_TAG, scratch, returned_value);+ self.masm+ .load64(result, &Address::new(temp, offsets.execution_context_this_value as i32));+ self.masm.bind(returned_value);self.masm.store64(&vm_field(offsets.vm_interpreter_stack_top), temp);self.masm.store64(&vm_field(offsets.vm_running_execution_context), frame);self.masm.add32_to_memory_imm(&vm_field(offsets.vm_execution_generation), 1);++ // 12. If Type(result.[[Value]]) is Object, return result.[[Value]].+ // 13. If kind is base, return thisArgument.+ // NB: The value from the runtime is thisArgument for a base constructor, and the empty value for a derived one.+ let have_result = self.masm.new_label();+ self.branch_on_tag(Condition::Equal, result, value::OBJECT_TAG, scratch, have_result);+ self.masm.load64(temp, &value_local);+ let error = self.masm.new_label();+ self.branch_on_tag(Condition::NotEqual, temp, value::OBJECT_TAG, scratch, error);+ self.masm.move64(result, temp);+ self.masm.bind(have_result);+ self.emit_stub_store_result(result, temp);self.emit_stub_continuation();self.masm.jump(leave);- // The callee's frame still runs: let the runtime finish the call.+ // A derived constructor returned something other than an object.+ self.masm.bind(error);+ self.masm.move64(registers[3], result);+ self.masm.move64(registers[0], vm);+ self.masm.move64(registers[1], frame);+ self.masm.load32(registers[2], &pcs_local);+ self.masm.call_absolute(runtime.construct_result_error);+ self.masm.jump(leave);++ // The constructor's frame still runs: let the runtime finish the+ // construct.self.masm.bind(not_returned);self.masm.move64(registers[3], status);+ self.masm.load64(registers[4], &value_local);self.masm.move64(registers[0], vm);self.masm.move64(registers[1], frame);- let pcs_local = self.stub_local(local::PCS);self.masm.load32(registers[2], &pcs_local);- self.masm.call_absolute(runtime.finish_direct_call);+ self.masm.call_absolute(runtime.finish_direct_construct);self.masm.jump(leave);- // Everything else takes the generic path.+ // The runtime made the this value, but the stacks are too full.+ self.masm.bind(stack_overflow);+ self.masm.move64(registers[0], vm);+ self.masm.move64(registers[1], frame);+ self.masm.load32(registers[2], &pcs_local);+ self.masm.call_absolute(runtime.throw_call_stack_size_exceeded);+ self.masm.jump(leave);++ // Everything else: the runtime pushes the constructor's frame, or+ // makes the construct.self.masm.bind(slow);self.masm.move64(registers[0], vm);self.masm.move64(registers[1], frame);self.masm.load32(registers[2], &pcs_local);- self.masm.call_absolute(runtime.jit_call);+ self.masm.call_absolute(runtime.prepare_construct);+ let pushed = self.masm.new_label();+ self.masm.branch64_imm(Condition::NotEqual, result, 0, pushed);+ self.masm.move64(result, status);+ self.masm.jump(leave);+ self.masm.bind(pushed);+ self.masm.store64(&frame_local, result);+ self.masm.store64(&value_local, status);+ self.masm.load64(registers[1], &frame_local);+ self.masm.load64(+ registers[3],+ &Address::new(registers[1], offsets.execution_context_executable as i32),+ );+ self.masm.jump(enter);self.masm.bind(leave);+ // NB: The this value must not outlive the construct on the stack, which the garbage collector scans+ // conservatively.+ self.masm.store_imm64(&value_local, value::UNDEFINED);+ let machine_frame = self.frame;self.masm.emit_epilogue(&machine_frame);self.masm.ret();- Ok(())}/// Stores the fields of a new frame at `new_frame` that describe the calldiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex b197c0f1058..7f7072a052c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -38,6 +38,7 @@ enum InputValue {Constant(u64),}pub use call_stub::generate_call_stub;+pub use call_stub::generate_construct_stub;pub use entry::generate_entry_trampoline;mod array_iterators;mod arrays;@@ -2604,6 +2605,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_generic_js_call(executable, pc)?;return Ok(Vec::new());}+ if matches!(+ opcode,+ crate::bytecode::OpCode::CallConstruct+ | crate::bytecode::OpCode::SuperCall+ | crate::bytecode::OpCode::SuperCallWithForwardedArguments+ ) && self.runtime.construct_stub != 0+ {+ self.emit_generic_construct(executable, pc)?;+ return Ok(Vec::new());+ }let decoded = self.decoded(executable, pc)?;let next_pc = decoded.next_pc();let call = slow_path_call(opcode).expect("generic nodes have a slow path");diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 01af9a31eb4..591dddb10c2 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -1116,6 +1116,41 @@ pub struct RuntimeInfo {/// interpreter as needed, and returns a slow path control word for the/// call, whose result is in its destination slot.pub finish_direct_call: u64,+ /// `PreparedConstruct libjs_jit_prepare_construct(VM*, ExecutionContext*+ /// frame, u32 pc)`: starts the `CallConstruct`, `SuperCall` or+ /// `SuperCallWithForwardedArguments` instruction at `pc` of `frame`. In+ /// two registers: the frame of an ECMAScript constructor the runtime+ /// pushed for the construct stub to enter, and the value of the construct+ /// if that frame returns something other than an object (an object, or+ /// the empty value for a derived constructor); or 0 and a slow path+ /// control word if the runtime ran the instruction to completion.+ pub prepare_construct: u64,+ /// `ConstructThis libjs_jit_construct_this(VM*, ECMAScriptFunctionObject*,+ /// u64 new_target, u32 pc)`: for a construct with the function (with+ /// `new_target`, or the empty value for the frame's new.target) whose+ /// frame the construct stub may build like a call's: in two registers+ /// its this value (an object, or the empty value for a derived+ /// constructor) and its new target. Or 0 if the stub must not build the+ /// frame, before anything observable happened, or 1 and a slow path+ /// control word if making the this value threw.+ pub construct_this: u64,+ /// `i64 libjs_jit_throw_call_stack_size_exceeded(VM*, ExecutionContext*+ /// frame, u32 pc)`: throws the error of a call with too little stack+ /// left at `pc` of `frame`.+ pub throw_call_stack_size_exceeded: u64,+ /// `i64 libjs_jit_construct_result_error(VM*, ExecutionContext* frame,+ /// u32 pc, u64 result)`: throws the error of a construct whose derived+ /// constructor's frame returned `result`, which is not an object.+ pub construct_result_error: u64,+ /// `i64 libjs_jit_finish_direct_construct(VM*, ExecutionContext* frame,+ /// u32 pc, u64 status, u64 value)`: like `finish_direct_call` for a+ /// construct whose frame did not return to the construct stub, with the+ /// value from `prepare_construct`.+ pub finish_direct_construct: u64,+ /// The address of the construct stub (see+ /// `codegen::generate_construct_stub()`), or 0 if JIT code makes+ /// constructs through `jit_call`.+ pub construct_stub: u64,/// `i64 asm_helper_handle_raw_native_exception(VM*, u64 exception)`: unwinds/// the frame of a raw native function that threw, and returns a slow/// path control word for the exception.diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex dd13add9a69..8f003601b30 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -182,18 +182,34 @@ fn call_builtin_from_jit(Some(run_callee_frame_from_jit(vm, site, callee_frame))}+/// Whether constructs from JIT code with `function` as the constructor run its bytecode in an inline frame.+fn constructs_in_inline_frame(function: Gc<EcmascriptFunctionObject>) -> bool {+ function.kind() == FunctionKind::Normal && function.has_constructor() && function.bytecode_executable().is_some()+}++/// The frame of a construct from JIT code, pushed by push_construct_frame() and running next.+struct PushedConstruct {+ callee_frame: NonNull<ExecutionContext>,+ /// The this value of a base constructor.+ this_argument: Option<Gc<Object>>,+ /// Whether the this value of a derived constructor is in its frame (see+ /// ExecutionContext::caller_is_derived_construct).+ this_is_in_frame: bool,+ constructor_environment: Gc<crate::layout::environment::Environment>,+}+// 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget-/// Constructs with an ECMAScript function as the new target, in an inline frame linked to the call site's frame like a-/// call.-fn construct_ecmascript_function_from_jit(+/// Steps 2 to 7 of a construct with an ECMAScript function from JIT code: pushes its frame, an inline frame linked to+/// the call site's frame like a call, which runs next.+fn push_construct_frame(vm: &Vm,site: &JitCallSite,function: Gc<EcmascriptFunctionObject>,new_target: Gc<FunctionObject>,arguments: &[Value],-) -> SlowPathControl {+) -> Result<PushedConstruct, SlowPathControl> {if vm.did_reach_stack_space_limit() {- return throw_call_stack_size_exceeded(vm, site.pc);+ return Err(throw_call_stack_size_exceeded(vm, site.pc));}// 2. Let kind be F.[[ConstructorKind]].@@ -206,18 +222,18 @@ fn construct_ecmascript_function_from_jit(// NB: With room for the properties the constructor is known to add.match Object::create_from_constructor_for_construct(vm, new_target, function.shared_data()) {Ok(object) => this_argument = Some(object),- Err(throw) => return handle_asm_exception(vm, site.pc, throw.value()),+ Err(throw) => return Err(handle_asm_exception(vm, site.pc, throw.value())),}}// 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).- // NB: The frame does not use the construct return rule of Return, which knows nothing of derived constructors;- // steps 10 to 17 are below.+ // NB: The frame of a base constructor does not use the construct return rule of Return; steps 10 to 17 are in+ // finish_construct().// NB: The prototype lookup above may have run code and collected garbage, which may have flushed the// constructor's code (see `bytecode::flushing`).let executable = match function.compiled_executable(vm) {Ok(executable) => executable,- Err(throw) => return handle_asm_exception(vm, site.pc, throw.value()),+ Err(throw) => return Err(handle_asm_exception(vm, site.pc, throw.value())),};let argument_count = u32::try_from(arguments.len()).expect("the argument count fits in u32");let Some(callee_frame) = vm.push_inline_frame_without_this(@@ -230,10 +246,10 @@ fn construct_ecmascript_function_from_jit(Some(function_object_as_object(new_target)),false,) else {- return throw_call_stack_size_exceeded(vm, site.pc);+ return Err(throw_call_stack_size_exceeded(vm, site.pc));};let callee_frame_ref = frame_of(callee_frame);- // NB: The frame of a derived constructor without an environment for `this` has the this value, which step 15 below+ // NB: The frame of a derived constructor without an environment for `this` has the this value, which step 15// needs after the frame is gone. Returning undefined from the frame returns it instead (see// ExecutionContext::caller_is_derived_construct).let this_is_in_frame =@@ -255,7 +271,7 @@ fn construct_ecmascript_function_from_jit(vm.unwind_inline_frame_for_exception();// ii. Return ? initializeResult.- return handle_asm_exception(vm, site.pc, throw.value());+ return Err(handle_asm_exception(vm, site.pc, throw.value()));}}@@ -265,15 +281,24 @@ fn construct_ecmascript_function_from_jit(.get().expect("a constructor runs in an environment");- // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).- // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.- // 10. If result is a throw completion, then- // a. Return ? result.- let control = run_callee_frame_from_jit(vm, site, callee_frame);- if !control.continues_in_frame() {- return control;- }+ Ok(PushedConstruct {+ callee_frame,+ this_argument,+ this_is_in_frame,+ constructor_environment,+ })+}+/// Steps 11 to 17 of a construct from JIT code (see push_construct_frame()), once its frame returned the value now in+/// the call site's destination slot.+fn finish_construct(+ vm: &Vm,+ site: &JitCallSite,+ this_argument: Option<Gc<Object>>,+ this_is_in_frame: bool,+ constructor_environment: Option<Gc<crate::layout::environment::Environment>>,+ control: SlowPathControl,+) -> SlowPathControl {// 11. Assert: result is a return completion.let result_slot = &frame_of(site.frame).slots()[site.dst as usize];let result = result_slot.get();@@ -313,6 +338,8 @@ fn construct_ecmascript_function_from_jit(}// 15. Let thisBinding be ? constructorEnv.GetThisBinding().+ let constructor_environment =+ constructor_environment.expect("a frame without the this value has an environment for it");let this_binding = match constructor_environment.get_this_binding(vm) {Ok(this_binding) => this_binding,Err(throw) => return handle_asm_exception(vm, site.pc, throw.value()),@@ -326,6 +353,39 @@ fn construct_ecmascript_function_from_jit(control}+// 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget+/// Constructs with an ECMAScript function as the new target, in an inline frame linked to the call site's frame like a+/// call.+fn construct_ecmascript_function_from_jit(+ vm: &Vm,+ site: &JitCallSite,+ function: Gc<EcmascriptFunctionObject>,+ new_target: Gc<FunctionObject>,+ arguments: &[Value],+) -> SlowPathControl {+ let pushed = match push_construct_frame(vm, site, function, new_target, arguments) {+ Ok(pushed) => pushed,+ Err(control) => return control,+ };++ // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).+ // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.+ // 10. If result is a throw completion, then+ // a. Return ? result.+ let control = run_callee_frame_from_jit(vm, site, pushed.callee_frame);+ if !control.continues_in_frame() {+ return control;+ }+ finish_construct(+ vm,+ site,+ pushed.this_argument,+ pushed.this_is_in_frame,+ Some(pushed.constructor_environment),+ control,+ )+}+/// Calls `callee` from JIT code. Calls of ECMAScript functions avoid the generic call machinery, and calls through/// bound functions and Function.prototype.call/apply call their target directly. Returns nothing if the caller should/// make the call through the generic call machinery instead, which only happens before anything observable was done.@@ -623,9 +683,7 @@ pub unsafe extern "C" fn libjs_jit_call(vm: *const Vm, frame: *mut ExecutionContlet arguments = storage.values();let callee = load(call.callee);if let Some(function) = value_as_ecmascript_function_object(callee)- && function.kind() == FunctionKind::Normal- && function.has_constructor()- && function.bytecode_executable().is_some()+ && constructs_in_inline_frame(function){return construct_ecmascript_function_from_jit(vm,@@ -759,9 +817,7 @@ fn super_call_from_jit(arguments: &[Value],) -> Option<SlowPathControl> {if let Some(function) = value_as_ecmascript_function_object(super_constructor)- && function.kind() == FunctionKind::Normal- && function.has_constructor()- && function.bytecode_executable().is_some()+ && constructs_in_inline_frame(function){let new_target = vm.get_new_target();assert!(new_target.is_object());@@ -910,7 +966,23 @@ pub unsafe extern "C" fn libjs_jit_finish_direct_call(let frame_ref = frame_of(frame);let executable = Executable::from_head(frame_ref.executable.get().expect("the frame runs an executable"));let call = instruction_at::<op::Call>(&executable, pc);+ let site = JitCallSite {+ frame,+ pc,+ return_pc: pc + call.length(),+ dst: call.dst.0.into(),+ };+ finish_direct_call_frames(vm, frame, &site, status).0+}+/// Runs the callee frame of a direct call or construct from JIT code that did not return to it to completion (see+/// `libjs_jit_finish_direct_call()`), and finishes the call.+fn finish_direct_call_frames(+ vm: &Vm,+ frame: NonNull<ExecutionContext>,+ site: &JitCallSite,+ status: u64,+) -> SlowPathControl {// NB: The callee's frame, and the frames of the calls it inlined that its exit materialized, run in the// interpreter from now on.for callee_frame in frames_above(vm, frame).expect("the calling frame is on the running frame's chain") {@@ -923,7 +995,297 @@ pub unsafe extern "C" fn libjs_jit_finish_direct_call(}vm.run_running_frame_in_interpreter();}- finish_call_from_jit(vm, frame, pc, pc + call.length()).0+ finish_call_from_jit(vm, frame, site.pc, site.return_pc)+}++/// The call site of the CallConstruct, SuperCall or SuperCallWithForwardedArguments instruction at `pc` of `frame`.+fn construct_site(frame: NonNull<ExecutionContext>, pc: u32) -> JitCallSite {+ let executable = super::executable_of(frame_of(frame));+ let opcode = executable.bytecode()[pc as usize];+ let (dst, length) = if opcode == OpCode::CallConstruct as u8 {+ let call = instruction_at::<op::CallConstruct>(&executable, pc);+ (call.dst, call.length())+ } else if opcode == OpCode::SuperCall as u8 {+ let call = instruction_at::<op::SuperCall>(&executable, pc);+ (call.dst, call.length())+ } else {+ assert_eq!(opcode, OpCode::SuperCallWithForwardedArguments as u8);+ let call = instruction_at::<op::SuperCallWithForwardedArguments>(&executable, pc);+ (call.dst, op::SuperCallWithForwardedArguments::LENGTH)+ };+ JitCallSite {+ frame,+ pc,+ return_pc: pc + length,+ dst: dst.0.into(),+ }+}++/// What `libjs_jit_prepare_construct()` returns, in two registers.+#[repr(C)]+pub struct PreparedConstruct {+ /// The frame of the construct, or null if the construct is done.+ pub callee_frame: u64,+ /// With a frame, the value of the construct if the frame returns something other than an object: the this value+ /// of a base constructor, or the empty value. Without one, the slow path control word of the construct.+ pub value: u64,+}++/// `PreparedConstruct libjs_jit_prepare_construct(VM*, ExecutionContext* frame, u32 pc)`: starts the CallConstruct,+/// SuperCall or SuperCallWithForwardedArguments instruction at `pc` of the frame, the running execution context. A+/// construct with an ECMAScript function whose this value is not in an environment gets its frame pushed, linked to+/// the frame and running next, which JIT code enters and pops, and whose result it finishes with the value returned+/// here (see `finish_construct()`) or `libjs_jit_construct_result_error()`. Every other construct runs to completion+/// like `libjs_jit_call()`.+///+/// # Safety+///+/// JIT code calls this with its VM, its frame and the pc of such an instruction.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_prepare_construct(+ vm: *const Vm,+ frame: *mut ExecutionContext,+ pc: u32,+) -> PreparedConstruct {+ // SAFETY: JIT code passes live pointers.+ let vm_ref = unsafe { &*vm };+ let frame_pointer = NonNull::new(frame).expect("JIT code passes its frame");+ assert_eq!(vm_ref.running_execution_context(), Some(frame_pointer));+ let frame_ref = frame_of(frame_pointer);+ frame_ref.program_counter.set(pc);+ let executable = super::executable_of(frame_ref);+ let slots = frame_ref.slots();+ let load = |operand: Operand| slots[operand.0 as usize].get();+ let opcode = executable.bytecode()[pc as usize];+ let site = construct_site(frame_pointer, pc);+ let takes_frame = |function: Gc<EcmascriptFunctionObject>| {+ constructs_in_inline_frame(function)+ && (function.constructor_kind() == ConstructorKind::Base+ || !function.shared_data().function_environment_has_this_binding())+ };++ let mut storage = ArgumentStorage::empty();+ let construct = if opcode == OpCode::CallConstruct as u8 {+ let call = instruction_at::<op::CallConstruct>(&executable, pc);+ match value_as_ecmascript_function_object(load(call.callee)) {+ Some(function) if takes_frame(function) => {+ storage.fill_from(vm_ref, call.arguments().iter().map(|operand| load(*operand)));+ Some((function, function.as_function_object_gc()))+ }+ _ => None,+ }+ } else {+ // NB: The arguments of a SuperCallWithForwardedArguments are the passed arguments of the frame.+ let (super_constructor, call_feedback, argument_operands) = if opcode == OpCode::SuperCall as u8 {+ let call = instruction_at::<op::SuperCall>(&executable, pc);+ (load(call.super_constructor), call.call_feedback, Some(call.arguments()))+ } else {+ let call = instruction_at::<op::SuperCallWithForwardedArguments>(&executable, pc);+ (load(call.super_constructor), call.call_feedback, None)+ };+ match value_as_ecmascript_function_object(super_constructor) {+ Some(function) if takes_frame(function) => {+ match argument_operands {+ Some(operands) => storage.fill_from(vm_ref, operands.iter().map(|operand| load(*operand))),+ None => storage.fill_from_passed_arguments(vm_ref, frame_ref),+ }+ let new_target = vm_ref.get_new_target();+ assert!(new_target.is_object());+ slow_paths::feedback::record_call(+ vm_ref,+ call_feedback,+ super_constructor,+ crate::bytecode::feedback::call_feedback_flags::SAW_CONSTRUCT,+ );+ Some((function, new_target.as_function()))+ }+ _ => None,+ }+ };+ let done = |control: SlowPathControl| PreparedConstruct {+ callee_frame: 0,+ value: control.0 as u64,+ };+ let Some((function, new_target)) = construct else {+ // SAFETY: The caller's pointers are live.+ return done(SlowPathControl(unsafe { libjs_jit_call(vm, frame, pc) }));+ };+ match push_construct_frame(vm_ref, &site, function, new_target, &storage.values()) {+ Ok(pushed) => {+ frame_of(pushed.callee_frame).returns_to_native_caller.set(true);+ PreparedConstruct {+ callee_frame: pushed.callee_frame.as_ptr() as u64,+ value: pushed.this_argument.map_or(Value::EMPTY, Value::from_object).0,+ }+ }+ Err(control) => done(control),+ }+}++/// What `libjs_jit_construct_this()` returns, in two registers.+#[repr(C)]+pub struct ConstructThis {+ pub this_value: u64,+ pub new_target: u64,+}++// 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget+/// `ConstructThis libjs_jit_construct_this(VM*, ECMAScriptFunctionObject*, u64 new_target, u32 pc)`: step 3 of a+/// construct from JIT code with the function as the constructor and `new_target` (or the empty value for the+/// new.target of the running execution context, JIT code's frame), whose frame the construct stub builds like the+/// frame of a call: the this value (the empty value for a derived constructor) and the new target. Returns 0 for+/// constructs whose frame the stub must not build, before doing anything observable, or 1 and the slow path control+/// word of the exception if step 3 threw.+///+/// # Safety+///+/// JIT code calls this with its VM, an ECMAScript function and the pc of the construct instruction in its frame.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_construct_this(+ vm: *const Vm,+ function: *const EcmascriptFunctionObject,+ new_target: u64,+ pc: u32,+) -> ConstructThis {+ // SAFETY: JIT code passes live pointers.+ let (vm, function) = unsafe {+ (+ &*vm,+ Gc::from_non_null(NonNull::new(function.cast_mut()).expect("a function")),+ )+ };+ let declined = ConstructThis {+ this_value: 0,+ new_target: 0,+ };+ if !constructs_in_inline_frame(function) || vm.did_reach_stack_space_limit() {+ return declined;+ }+ let shared_data = function.shared_data();+ let new_target = match Value::from_bits(new_target) {+ new_target if new_target.is_empty() => {+ let new_target = vm.get_new_target();+ assert!(new_target.is_object());+ new_target+ }+ new_target => new_target,+ };++ // 2. Let kind be F.[[ConstructorKind]].+ // 3. If kind is base, then+ if function.constructor_kind() == ConstructorKind::Base {+ // NB: InitializeInstanceElements runs in the constructor's frame, which the runtime pushes.+ if function.has_class_data() && (function.private_methods_count() != 0 || function.fields_count() != 0) {+ return declined;+ }+ // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").+ // NB: With room for the properties the constructor is known to add.+ let this_argument =+ match Object::create_from_constructor_for_construct(vm, new_target.as_function(), shared_data) {+ Ok(object) => object,+ Err(throw) => {+ return ConstructThis {+ this_value: 1,+ new_target: handle_asm_exception(vm, pc, throw.value()).0 as u64,+ };+ }+ };+ // NB: The prototype lookup above may have run code and collected garbage, which may have flushed the+ // constructor's code (see `bytecode::flushing`).+ if let Err(throw) = function.compiled_executable(vm) {+ return ConstructThis {+ this_value: 1,+ new_target: handle_asm_exception(vm, pc, throw.value()).0 as u64,+ };+ }+ return ConstructThis {+ this_value: Value::from_object(this_argument).0,+ new_target: new_target.0,+ };+ }+ if shared_data.function_environment_has_this_binding() {+ return declined;+ }+ ConstructThis {+ this_value: Value::EMPTY.0,+ new_target: new_target.0,+ }+}++/// `i64 libjs_jit_throw_call_stack_size_exceeded(VM*, ExecutionContext* frame, u32 pc)`: throws the error of a call+/// at `pc` of the frame, the running execution context, with too little stack left.+///+/// # Safety+///+/// JIT code calls this with its VM, its frame and the pc of the call instruction.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_throw_call_stack_size_exceeded(+ vm: *const Vm,+ frame: *mut ExecutionContext,+ pc: u32,+) -> i64 {+ // SAFETY: JIT code passes live pointers.+ let vm = unsafe { &*vm };+ assert_eq!(vm.running_execution_context(), NonNull::new(frame));+ throw_call_stack_size_exceeded(vm, pc).0+}++/// `i64 libjs_jit_construct_result_error(VM*, ExecutionContext* frame, u32 pc, u64 result)`: throws the error of a+/// construct prepared by `libjs_jit_prepare_construct()` (for the instruction at `pc` of the frame, which runs again)+/// whose derived constructor's frame returned `result`, which is not an object, and returns its slow path control word.+///+/// # Safety+///+/// JIT code calls this with its VM, its frame and the pc of the construct instruction.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_construct_result_error(+ vm: *const Vm,+ frame: *mut ExecutionContext,+ pc: u32,+ result: u64,+) -> i64 {+ // SAFETY: JIT code passes live pointers.+ let vm = unsafe { &*vm };+ let frame = NonNull::new(frame).expect("JIT code passes its frame");+ let site = construct_site(frame, pc);+ frame_of(frame).slots()[site.dst as usize].set(Value::from_bits(result));+ finish_construct(+ vm,+ &site,+ None,+ true,+ None,+ SlowPathControl::continue_at(site.return_pc),+ )+ .0+}++/// `i64 libjs_jit_finish_direct_construct(VM*, ExecutionContext* frame, u32 pc, u64 status, u64 value)`: like+/// `libjs_jit_finish_direct_call()` for a construct prepared by `libjs_jit_prepare_construct()` whose frame did not+/// return to JIT code, which finishes the construct with the `value` that returned.+///+/// # Safety+///+/// JIT code calls this with its VM and frame, the pc of the construct instruction, the callee's status and the value.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_finish_direct_construct(+ vm: *const Vm,+ frame: *mut ExecutionContext,+ pc: u32,+ status: u64,+ value: u64,+) -> i64 {+ // SAFETY: JIT code passes live pointers.+ let vm = unsafe { &*vm };+ let frame = NonNull::new(frame).expect("JIT code passes its frame");+ let site = construct_site(frame, pc);+ let control = finish_direct_call_frames(vm, frame, &site, status);+ if !control.continues_in_frame() {+ return control.0;+ }+ let value = Value::from_bits(value);+ let this_argument = value.is_object().then(|| value.as_object());+ finish_construct(vm, &site, this_argument, this_argument.is_none(), None, control).0}/// What `libjs_jit_prepare_call_environment()` returns, in two registers.diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex 8962c58da96..79cbb650109 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -190,6 +190,8 @@ pub struct JitState {/// The call stub JIT code shares (see `libjs_jit::codegen::generate_call_stub()`), generated the first time a/// compile job needs it, if there is one.call_stub: OnceCell<Option<ExecutableMemory>>,+ /// The construct stub JIT code shares (see `libjs_jit::codegen::generate_construct_stub()`).+ construct_stub: OnceCell<Option<ExecutableMemory>>,/// The installed code that depends on things staying as they are.pub(crate) dependents: dependencies::Dependents,/// The id the next installed code gets (see `JitCode::id()`).@@ -238,6 +240,7 @@ impl JitState {runtime_function_addresses: OnceCell::new(),entry_trampoline: OnceCell::new(),call_stub: OnceCell::new(),+ construct_stub: OnceCell::new(),dependents: dependencies::Dependents::default(),next_code_id: Cell::new(1),htmldda_objects_exist: Cell::new(false),@@ -461,6 +464,24 @@ impl JitState {.map_or(0, |memory| memory.address() as u64)}+ /// The address of the construct stub for code with this runtime info, or 0.+ pub(crate) fn construct_stub(&self, runtime: &libjs_jit::snapshot::RuntimeInfo) -> u64 {+ self.construct_stub+ .get_or_init(|| {+ let code = libjs_jit::codegen::generate_construct_stub::<libjs_jit::asm::MacroAssembler>(runtime)+ .expect("the construct stub compiles")?;+ ExecutableMemory::allocate(+ &self.code_allocator,+ &[code.as_slice()],+ &["construct stub"],+ self.options.perf_map,+ )+ .pop()+ })+ .as_ref()+ .map_or(0, |memory| memory.address() as u64)+ }+pub(crate) fn runtime_function_addresses(&self) -> &runtime_info::RuntimeFunctionAddresses {self.runtime_function_addresses.get_or_init(runtime_info::RuntimeFunctionAddresses::look_up)diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex 564733fb415..1fcf30471c9 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -508,6 +508,12 @@ pub fn runtime_info(jit_call: jit_function_address!(super::calls::libjs_jit_call),call_forwarding_arguments: jit_function_address!(super::calls::libjs_jit_call_forwarding_arguments),finish_direct_call: jit_function_address!(super::calls::libjs_jit_finish_direct_call),+ prepare_construct: jit_function_address!(super::calls::libjs_jit_prepare_construct),+ construct_result_error: jit_function_address!(super::calls::libjs_jit_construct_result_error),+ finish_direct_construct: jit_function_address!(super::calls::libjs_jit_finish_direct_construct),+ construct_stub: 0,+ construct_this: jit_function_address!(super::calls::libjs_jit_construct_this),+ throw_call_stack_size_exceeded: jit_function_address!(super::calls::libjs_jit_throw_call_stack_size_exceeded),raw_native_exception: addresses.raw_native_exception,push_inlined_call_frames: jit_function_address!(super::entry_exit::libjs_jit_push_inlined_call_frames),finish_inlined_direct_call: jit_function_address!(super::entry_exit::libjs_jit_finish_inlined_direct_call),@@ -558,6 +564,7 @@ pub fn runtime_info(dynamic_calls: dynamic_call_layout(vm),};info.dynamic_calls.call_stub = vm.jit.call_stub(&info);+ info.construct_stub = vm.jit.construct_stub(&info);info}diff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.jsindex 873c2d87445..ecc33b9e484 100644--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js@@ -1395,3 +1395,294 @@ describe("fields of base constructs in hot callers", () => {});});});++describe("constructs in hot callers that are not inlined", () => {+ // NB: A branch before super() and sites that see several constructors keep constructs from being inlined.+ test("return overrides of base and derived constructors", () => {+ const object = {};+ class A {+ constructor(mode) {+ if (mode === "object") return object;+ if (mode === "number") return 1;+ }+ }+ class B extends A {+ constructor(mode) {+ if (mode === "no super") {+ if (mode === "never") super();+ } else if (mode === "twice") {+ super();+ super();+ } else {+ super(mode === "parent object" ? "object" : undefined);+ }+ if (mode === "object") return object;+ if (mode === "number") return 1;+ if (mode === "undefined") return undefined;+ if (mode === "this before super") return this;+ }+ }+ const constructors = [A, B];+ repeat(i => {+ const C = constructors[i & 1];+ expect(new C("plain")).toBeInstanceOf(C);+ expect(new C("object")).toBe(object);+ if (C === A) {+ expect(new C("number")).toBeInstanceOf(A);+ return;+ }+ expect(new C("undefined")).toBeInstanceOf(B);+ expect(new C("parent object")).toBe(object);+ if (i % 50 === 1) {+ expect(() => new C("number")).toThrowWithMessage(TypeError, "Derived constructor return invalid value");+ expect(() => new C("no super")).toThrowWithMessage(ReferenceError, "|this| has not been initialized");+ expect(() => new C("twice")).toThrowWithMessage(ReferenceError, "|this| is already initialized");+ }+ });+ });++ test("exceptions at each stage keep the constructor in stack traces", () => {+ class A {+ constructor(stage) {+ if (stage === "base") throw new Error("base");+ }+ }+ class B extends A {+ constructor(stage) {+ if (stage === "before super") throw new Error("before super");+ if (stage) super(stage);+ else super(stage);+ if (stage === "after super") throw new Error("after super");+ }+ }+ repeat(i => {+ expect(new B(undefined)).toBeInstanceOf(B);+ if (i % 50 !== 0) return;+ for (const stage of ["base", "before super", "after super"]) {+ let caught;+ try {+ new B(stage);+ } catch (error) {+ caught = error;+ }+ expect(caught.message).toBe(stage);+ expect(caught.stack.includes("at B (")).toBeTrue();+ if (stage === "base") expect(caught.stack.includes("at A (")).toBeTrue();+ }+ });+ });++ test("new.target in the constructor and through super()", () => {+ let seen = [];+ class A {+ constructor() {+ seen.push(new.target);+ }+ }+ class B extends A {+ constructor(flag) {+ seen.push(new.target);+ if (flag) super();+ else super();+ }+ }+ class C extends B {}+ const constructors = [A, B, C];+ repeat(i => {+ seen = [];+ const D = constructors[i % 3];+ new D(i & 1);+ expect(seen.every(target => target === D)).toBeTrue();+ seen = [];+ const object = Reflect.construct(B, [i & 1], C);+ expect(Object.getPrototypeOf(object)).toBe(C.prototype);+ expect(seen).toEqual([C, C]);+ });+ });++ test("prototypes that change, are getters or are not objects", () => {+ function F() {+ this.a = 1;+ }+ class B extends F {+ constructor(flag) {+ if (flag) super();+ else super();+ }+ }+ const original = F.prototype;+ const replacement = {};+ const getterTarget = new Proxy(function () {}, {+ get: (target, key) => (key === "prototype" ? replacement : target[key]),+ });+ repeat(i => {+ const C = i & 1 ? F : B;+ const mode = i % 5;+ if (mode === 0) F.prototype = original;+ if (mode === 1) F.prototype = replacement;+ if (mode === 2) F.prototype = 1;+ if (mode === 3) {+ F.prototype = original;+ const object = Reflect.construct(C, [i & 2], getterTarget);+ expect(Object.getPrototypeOf(object)).toBe(replacement);+ expect(object.a).toBe(1);+ return;+ }+ if (mode === 4) F.prototype = null;+ const object = new C(i & 2);+ const expected = C === B ? B.prototype : F.prototype;+ if (typeof expected === "object" && expected !== null) expect(Object.getPrototypeOf(object)).toBe(expected);+ else expect(Object.getPrototypeOf(object)).toBe(Object.prototype);+ expect(object.a).toBe(1);+ });+ F.prototype = original;+ });++ test("a throwing prototype getter of the new target", () => {+ class A {+ constructor() {+ this.a = 1;+ }+ }+ let throws = false;+ const Target = new Proxy(function () {}, {+ get(target, key) {+ if (key !== "prototype") return target[key];+ if (throws) throw new Error("prototype");+ return A.prototype;+ },+ });+ const targets = [A, Target];+ repeat(i => {+ throws = i % 10 === 0;+ if (throws) expect(() => Reflect.construct(A, [], Target)).toThrowWithMessage(Error, "prototype");+ else expect(Reflect.construct(A, [], targets[i & 1]).a).toBe(1);+ });+ });++ test("a polymorphic site with base, derived, plain, bound and native constructors", () => {+ class A {+ constructor(x) {+ this.x = x;+ }+ }+ class B extends A {+ constructor(x) {+ super(x + 1);+ }+ }+ function F(x) {+ this.x = x + 2;+ }+ const Bound = A.bind(null, 10);+ const constructors = [A, B, F, Bound, Array, Object, Date];+ repeat(i => {+ const C = constructors[i % constructors.length];+ const object = new C(i);+ if (C === Array) expect(object.length).toBe(i);+ else if (C === Object) expect(object instanceof Number).toBeTrue();+ else if (C === Date) expect(object).toBeInstanceOf(Date);+ else if (C === Bound) expect(object.x).toBe(10);+ else expect(object.x).toBe(i + (C === B ? 1 : C === F ? 2 : 0));+ });+ });++ test("class constructors called without new throw", () => {+ class A {}+ class B extends A {}+ const constructors = [A, B];+ repeat(i => {+ const C = constructors[i & 1];+ expect(new C()).toBeInstanceOf(C);+ if (i % 100 === 0) expect(() => C()).toThrow(TypeError);+ });+ });++ test("recursion and stack overflow", () => {+ class Node {+ constructor(depth) {+ if (depth > 0) this.child = new Node(depth - 1);+ else this.child = null;+ }+ }+ class Derived extends Node {+ constructor(depth) {+ if (depth > 0) super(depth);+ else super(0);+ }+ }+ repeat(i => {+ let node = new (i & 1 ? Node : Derived)(10);+ let depth = 0;+ while (node.child) {+ node = node.child;+ depth++;+ }+ expect(depth).toBe(10);+ });+ class Deep {+ constructor() {+ new Deep();+ }+ }+ expect(() => new Deep()).toThrow(InternalError);+ expect(new Node(3).child.child.child.child).toBeNull();+ });++ test("constructors with an environment and with eval or arrows reading this", () => {+ class A {+ constructor(x) {+ this.x = x;+ }+ }+ class B extends A {+ constructor(x) {+ const read = () => this;+ if (x) super(x);+ else super(0);+ expect(read()).toBe(this);+ }+ }+ class C extends A {+ constructor(x) {+ if (x) super(x);+ else super(0);+ eval("this.y = 1");+ }+ }+ const constructors = [B, C];+ repeat(i => {+ const object = new constructors[i & 1](i);+ expect(object.x).toBe(i);+ if (i & 1) expect(object.y).toBe(1);+ });+ });++ test("base constructors with fields", () => {+ let count = 0;+ class A {+ a = ++count;+ #b = 2;+ b() {+ return this.#b;+ }+ constructor(x) {+ this.x = x;+ }+ }+ class B extends A {+ c = this.a + 1;+ constructor(x) {+ if (x) super(x);+ else super(0);+ }+ }+ const constructors = [A, B];+ repeat(i => {+ const object = new constructors[i & 1](i);+ expect(object.a).toBe(count);+ expect(object.b()).toBe(2);+ if (i & 1) expect(object.c).toBe(count + 1);+ });+ });+});