Skip to content

Truly independent web browser

LibJS: Call native accessors directly from JIT code

Andreas Kling511ebf9122cd
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 0a05956edef..f09651a519d 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -223,6 +223,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| **Calls** | | | | | |
| CallDirect | A `Call` to its feedback's ECMAScript target, entering its code directly. | L, throws | Any | Any | call, allocates |
| CallNative | A `Call` to its feedback's native target, in the interpreter's lightweight frame. | L, throws | Any | Any | call, allocates |
+| CallNativeAccessor | The raw native getter (of a `GetById` or `GetLength`) or setter (of a `PutById`) that the checks before it established the property has, called like `CallNative` calls its target. A getter of a platform object attribute backed by a field reads the main world wrapper it would return inline where there is one, if the interpreter validated the cache entries for that. The getter's result (for the setter, its result too). | L, throws | Any | Any | call, allocates |
| CallForwardingArguments | `f.apply(this, arguments)` with an arguments object never created. | L, throws | Any | Any | call, allocates |
| CallSlowPath | One bytecode instruction through the interpreter's slow path, on SSA operands, with SSA outputs, with a frame state after the instruction. `saves_registers`: in a cold block, preserving every register. | L unless it saves registers; throws per opcode | Any | Any | call unless it saves registers; allocates |
| SlowPathOutput | A further output of the `CallSlowPath` right before it, which is its input (the verifier checks that it follows it). | | | | |
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
index ac54d043faf..1b44a8a193e 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
@@ -180,21 +180,31 @@ impl CacheEntry {
}
}
+ /// Where the accessor whose `part` the entry calls is, if compiled code
+ /// may call it there: in the receiver (no prototype) or in a prototype,
+ /// at an offset. Setters are only called in prototypes.
+ pub fn accessor_location(&self, part: AccessorPart) -> Option<(Option<CellId>, u32)> {
+ let prototype = |holder: Holder| match holder {
+ Holder::Receiver => None,
+ Holder::Prototype { prototype, .. } => Some(prototype),
+ };
+ match (self.action, part) {
+ (Action::Get { holder, offset }, AccessorPart::Getter) => Some((prototype(holder), offset)),
+ (
+ Action::Set {
+ holder: Holder::Prototype { prototype, .. },
+ offset,
+ },
+ AccessorPart::Setter,
+ ) => Some((Some(prototype), offset)),
+ _ => None,
+ }
+ }
+
/// Whether the entry calls the `part` of an accessor of a function the
/// compiler may inline.
pub fn calls_accessor(&self, part: AccessorPart) -> bool {
- let action_matches = matches!(
- (self.action, part),
- (Action::Get { .. }, AccessorPart::Getter)
- | (
- Action::Set {
- holder: Holder::Prototype { .. },
- ..
- },
- AccessorPart::Setter
- )
- );
- action_matches
+ self.accessor_location(part).is_some()
&& self
.accessor_function
.is_some_and(|function| function.inline_executable.is_some())
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 462272eabe4..2daa6888325 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -437,7 +437,7 @@ impl GraphBuilder<'_> {
/// Makes compiled code check at entry that the interpreter stack has room
/// for a frame of `bytes` that a call pushes on top of the frames of the
/// inlined calls it is in, so the call need not check.
- fn reserve_call_frame(&mut self, bytes: u64) {
+ pub(super) fn reserve_call_frame(&mut self, bytes: u64) {
let frame_bytes = self.function.inline.as_ref().map_or(0, |call| call.frame_bytes) + bytes;
self.graph.materialized_frame_bytes = self.graph.materialized_frame_bytes.max(frame_bytes);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index bca9402b860..192b75d3950 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -1631,9 +1631,15 @@ impl<'a> GraphBuilder<'a> {
}
}
Instruction::GetLength { dst, base, cache, .. } => {
+ // NB: Lengths of arrays never reach the cache, so where the site saw arrays, its cache does not show
+ // all receivers.
+ let saw_arrays = self
+ .keyed_feedback_bits(instruction)
+ .is_some_and(|bits| bits & crate::snapshot::keyed_feedback_bits::MAGICAL_LENGTH != 0);
if !self.try_build_arguments_length(dst, base)?
&& !self.try_build_array_length(instruction, dst, base)?
&& !self.try_build_typed_array_length(dst, base, cache)?
+ && (saw_arrays || !self.try_build_native_getter(dst, base, cache)?)
{
return Ok(None);
}
@@ -1718,6 +1724,9 @@ impl<'a> GraphBuilder<'a> {
if let Some(flow) = self.try_inline_getter(dst, base, cache)? {
return Ok(Some(flow));
}
+ if self.try_build_native_getter(dst, base, cache)? {
+ return Ok(Some(Flow::Continue));
+ }
if !self.try_build_get_by_id(dst, base, cache)? {
return Ok(None);
}
@@ -1726,6 +1735,9 @@ impl<'a> GraphBuilder<'a> {
if let Some(flow) = self.try_inline_setter(base, src, cache)? {
return Ok(Some(flow));
}
+ if self.try_build_native_setter(base, src, cache)? {
+ return Ok(Some(Flow::Continue));
+ }
if !self.try_build_put_by_id(base, src, cache)? && !self.try_build_add_named(base, src, cache)? {
return Ok(None);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
index 62d719d59e6..88a50cdd58b 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
@@ -47,6 +47,7 @@ use crate::ir::Op;
use crate::ir::ShapeCheck;
use crate::snapshot::CellId;
use crate::snapshot::Intrinsic;
+use crate::snapshot::NativeCallTarget;
use crate::snapshot::keyed_feedback_bits;
/// A check that a key is the one a keyed access speculates on: `key` must
@@ -254,7 +255,10 @@ impl GraphBuilder<'_> {
}
)
&& entry.action == first.action
- && entry.accessor_function == Some(accessor)
+ && entry.accessor_function.is_some_and(|entry_accessor| {
+ entry_accessor.function == accessor.function
+ && entry_accessor.cached_value_offset == accessor.cached_value_offset
+ })
});
let gates = [ExitKind::NotObject, ExitKind::BadShape, ExitKind::UnexpectedValue];
if !same_cached_getter || !gates.into_iter().all(|kind| self.may_speculate(kind)) {
@@ -312,11 +316,7 @@ impl GraphBuilder<'_> {
let Some(getter) = first.accessor_function else {
return Ok(false);
};
- let Action::Get {
- holder: Holder::Prototype { prototype, .. },
- offset,
- } = first.action
- else {
+ let location @ Some((Some(_), _)) = first.accessor_location(AccessorPart::Getter) else {
return Ok(false);
};
// NB: Typed arrays of each kind reach the getter through the prototype
@@ -324,16 +324,7 @@ impl GraphBuilder<'_> {
let same_length_getter = getter.intrinsic == Some(Intrinsic::TypedArrayPrototypeLength)
&& entries.iter().all(|entry| {
entry.holds_accessor
- && matches!(
- entry.action,
- Action::Get {
- holder: Holder::Prototype {
- prototype: entry_prototype,
- ..
- },
- offset: entry_offset,
- } if entry_prototype == prototype && entry_offset == offset
- )
+ && entry.accessor_location(AccessorPart::Getter) == location
&& entry.accessor_function.map(|accessor| accessor.function) == Some(getter.function)
});
let gates = [
@@ -390,6 +381,108 @@ impl GraphBuilder<'_> {
Some((entries, index))
}
+ /// The entries of the instruction's property cache if they all call the
+ /// `part` of the same accessor property (at one offset of the receiver,
+ /// or of one prototype) with the same raw native function, with the
+ /// target through which JIT code calls it (see `try_build_native_getter()`).
+ fn native_accessor_entries(&self, cache: u32, part: AccessorPart) -> Option<(Vec<CacheEntry>, NativeCallTarget)> {
+ // NB: Calls in inlined callees need their inlined frames, which these calls do not build.
+ if self.function.is_virtual() {
+ return None;
+ }
+ let entries = self.cache_entries(cache)?;
+ let first = entries[0];
+ let accessor = first.accessor_function?;
+ let mut target = accessor.native?;
+ let location = first.accessor_location(part)?;
+ let same_accessor = entries.iter().all(|entry| {
+ entry.holds_accessor
+ && entry.accessor_location(part) == Some(location)
+ && entry.accessor_function.map(|accessor| accessor.function) == Some(accessor.function)
+ });
+ let gates = [ExitKind::NotObject, ExitKind::BadShape, ExitKind::UnexpectedValue];
+ if !same_accessor || !gates.into_iter().all(|kind| self.may_speculate(kind)) {
+ return None;
+ }
+ // NB: Like the interpreter, read a getter's value without calling it only for shapes it ran on.
+ let validated = |entry: &CacheEntry| {
+ entry
+ .accessor_function
+ .and_then(|accessor| accessor.native)
+ .is_some_and(|native| native.direct_getter.is_some())
+ };
+ if !entries.iter().all(validated) {
+ target.direct_getter = None;
+ }
+ Some((entries, target))
+ }
+
+ /// A `CallNativeAccessor` node calling the `part` of an accessor, the
+ /// raw native function `target`, with `inputs`, whose frame state resumes
+ /// after the instruction with its result in `dst`.
+ fn emit_native_accessor_call(
+ &mut self,
+ part: AccessorPart,
+ target: NativeCallTarget,
+ inputs: Vec<NodeId>,
+ dst: u32,
+ ) -> NodeId {
+ let argument_count = inputs.len() as u64 - 1;
+ let slots_offset = u64::from(self.runtime.offsets.execution_context_slots);
+ self.reserve_call_frame(slots_offset + 8 * argument_count);
+ self.embed(target.function);
+ self.embed(target.realm);
+ let op = Op::CallNativeAccessor {
+ pc: self.function.pc,
+ part,
+ target,
+ };
+ let node = self.emit(op, inputs, Some(Repr::Tagged));
+ let frame_state = self.resume_after_frame_state(dst);
+ self.graph.nodes[node.index()].frame_state = Some(frame_state);
+ node
+ }
+
+ /// Builds `dst = base.property` for a property that holds an accessor
+ /// whose getter is a raw native function, like the getters of platform
+ /// objects, as a direct call of it: the instruction's cache entries must
+ /// all find the same getter at the same place (see
+ /// `native_accessor_entries()`).
+ pub(super) fn try_build_native_getter(
+ &mut self,
+ dst: Operand,
+ base: Operand,
+ cache: u32,
+ ) -> Result<bool, CompileFailure> {
+ let Some((entries, target)) = self.native_accessor_entries(cache, AccessorPart::Getter) else {
+ return Ok(false);
+ };
+ let (object, getter) = self.check_accessor_call(base, &entries, AccessorPart::Getter)?;
+ debug_assert!(getter.is_none(), "all entries have the same checked getter");
+ let value = self.emit_native_accessor_call(AccessorPart::Getter, target, vec![object], dst.raw());
+ self.write(dst, value)?;
+ Ok(true)
+ }
+
+ /// Builds `base.property = src` for a property that a prototype holds as
+ /// an accessor whose setter is a raw native function, as a direct call of
+ /// it, like `try_build_native_getter()`.
+ pub(super) fn try_build_native_setter(
+ &mut self,
+ base: Operand,
+ src: Operand,
+ cache: u32,
+ ) -> Result<bool, CompileFailure> {
+ let Some((entries, target)) = self.native_accessor_entries(cache, AccessorPart::Setter) else {
+ return Ok(false);
+ };
+ let value = self.read(src)?;
+ let (object, setter) = self.check_accessor_call(base, &entries, AccessorPart::Setter)?;
+ debug_assert!(setter.is_none(), "all entries have the same checked setter");
+ self.emit_native_accessor_call(AccessorPart::Setter, target, vec![object, value], Operand::INVALID);
+ Ok(true)
+ }
+
/// Checks that `base` is an object of the shapes of `entries`, which all
/// call the `part` of the accessor at their property offset, and that
/// the accessor has the function the entries saw: in the object, or in
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index 62bd9491dc2..497ee812c81 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -1048,6 +1048,92 @@ pub(crate) mod property_access {
);
}
+ #[test]
+ fn native_getters_read_wrappers_directly_only_through_validated_entries() {
+ use crate::snapshot::AccessorFunctionSnapshot;
+ use crate::snapshot::DirectGetterFields;
+ use crate::snapshot::NativeCallTarget;
+ let program = assemble(|_| vec![get_by_id(r(5), a(0), 0), Instruction::Return { value: r(5) }]);
+ let entry = |shape: u64, validated: bool| {
+ let target = NativeCallTarget {
+ function: CellId(0x9000),
+ realm: CellId(0xa000),
+ entry: 0xb000,
+ direct_getter: validated.then_some(DirectGetterFields {
+ wrapper_implementation: 8,
+ implementation_value: 16,
+ main_world_wrapper: 24,
+ weak_impl_value: 32,
+ }),
+ };
+ let mut entry = own(PropertyCacheEntryType::GetOwnProperty, shape, 1);
+ entry.holds_accessor = true;
+ entry.accessor_function = Some(AccessorFunctionSnapshot {
+ function: target.function,
+ intrinsic: None,
+ inline_executable: None,
+ cached_value_offset: None,
+ native: Some(target),
+ });
+ entry
+ };
+ let text = dump_with_caches(&program, vec![cache(vec![entry(0x100, true)])], Vec::new());
+ assert!(text.contains("CallNativeAccessor @0 Getter 0x9000 direct"), "{text}");
+ // The interpreter validates only the first entry of a cache.
+ for entries in [vec![entry(0x100, false)], vec![entry(0x100, true), entry(0x200, false)]] {
+ let text = dump_with_caches(&program, vec![cache(entries)], Vec::new());
+ assert!(text.contains("CallNativeAccessor @0 Getter 0x9000"), "{text}");
+ assert!(!text.contains("0x9000 direct"), "{text}");
+ }
+
+ // GetLength sites that saw arrays do not speculate on the getter of the other receivers.
+ let get_length = assemble(|_| {
+ vec![
+ Instruction::GetLength {
+ value_feedback: 0,
+ keyed_feedback: 0,
+ dst: r(5),
+ base: a(0),
+ base_identifier: None,
+ cache: 0,
+ },
+ Instruction::Return { value: r(5) },
+ ]
+ });
+ for (feedback, calls_getter) in [
+ (None, true),
+ (Some(crate::snapshot::keyed_feedback_bits::MAGICAL_LENGTH), false),
+ ] {
+ let mut snapshot = snapshot_for(&get_length, test_layout());
+ snapshot.executables[0].property_caches = vec![cache(vec![entry(0x100, true)])];
+ snapshot.executables[0].feedback.keyed = feedback
+ .map(|bits| crate::snapshot::KeyedFeedbackSnapshot { bits })
+ .into_iter()
+ .collect();
+ snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;
+ let text = dump(&optimized_graph(&snapshot), &test_layout());
+ assert_eq!(text.contains("CallNativeAccessor"), calls_getter, "{text}");
+ }
+
+ // Entries that validated the getter differently still share its cached value.
+ let cached = |shape: u64, validated: bool| {
+ let mut entry = entry(shape, validated);
+ entry.entry_type = PropertyCacheEntryType::GetPropertyInPrototypeChain;
+ entry.prototype = Some(CellId(0x7000));
+ entry.prototype_chain_validity = Some(CellId(0x8000));
+ if let Some(accessor) = entry.accessor_function.as_mut() {
+ accessor.cached_value_offset = Some(2);
+ }
+ entry
+ };
+ let text = dump_with_caches(
+ &program,
+ vec![cache(vec![cached(0x100, true), cached(0x200, false)])],
+ Vec::new(),
+ );
+ assert!(text.contains("LoadNamed +2"), "{text}");
+ }
+
#[test]
fn cached_getters_check_identity_and_load_from_the_receiver() {
use crate::snapshot::AccessorFunctionSnapshot;
@@ -1061,6 +1147,7 @@ pub(crate) mod property_access {
intrinsic: None,
inline_executable: None,
cached_value_offset: Some(2),
+ native: None,
});
let text = dump_with_caches(&program, vec![cache(vec![entry])], Vec::new());
assert!(text.contains("CheckShape [0x100]"), "{text}");
@@ -1639,6 +1726,7 @@ pub(crate) mod inlining {
function: CellId(*getter),
intrinsic: None,
inline_executable: Some(1),
+ native: None,
}),
holds_accessor: true,
..own(PropertyCacheEntryType::GetOwnProperty, 0x100 + 0x100 * index as u64, 0)
@@ -1700,6 +1788,7 @@ pub(crate) mod inlining {
function: CellId(CALLEE_FUNCTION + index * 0x100),
intrinsic: None,
inline_executable: Some(1),
+ native: None,
}),
holds_accessor: true,
..own(PropertyCacheEntryType::GetOwnProperty, 0x100 + index * 0x100, 0)
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
index fd656faf7a9..5f88257c6a8 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
@@ -41,11 +41,13 @@ use crate::code::INLINED_CALL_SITE_BIT;
use crate::code::JitStatus;
use crate::code::SiteKind;
use crate::inline_vec::InlineVec;
+use crate::ir::AccessorPart;
use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::value;
use crate::snapshot::CellId;
use crate::snapshot::DirectCallTarget;
+use crate::snapshot::DirectGetterFields;
use crate::snapshot::EnvironmentTemplateSnapshot;
use crate::snapshot::InlinedFunctionSnapshot;
use crate::snapshot::NativeCallTarget;
@@ -1164,10 +1166,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
this_operand,
&argument_operands,
next_pc,
- dst,
+ Some(dst),
site.as_ref(),
temps,
- [slow, check, done],
+ Some(slow),
+ [check, done],
)?;
// The generic call reads its operands from the frame.
@@ -1190,14 +1193,144 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.emit_load_call_result(node, dst, site.as_ref())
}
+ /// `CallNativeAccessor`: calls the raw native getter or setter that the
+ /// checks before the node established the property has, like
+ /// `CallNative` calls its target, with input 0 as the `this` value and
+ /// input 1 as the setter's argument. The value is the getter's result
+ /// (for the setter, its result too), in the return register.
+ pub(super) fn emit_call_native_accessor(
+ &mut self,
+ node: NodeId,
+ pc: u32,
+ part: AccessorPart,
+ target: NativeCallTarget,
+ ) -> Result<(), CompileFailure> {
+ let invalid = |reason| CompileFailure::InvalidBytecode { pc, reason };
+ let decoded = self.decoded(0, pc)?;
+ let next_pc = decoded.next_pc();
+ let (dst, arguments) = match (part, decoded.instruction) {
+ (AccessorPart::Getter, Instruction::GetById { dst, .. } | Instruction::GetLength { dst, .. }) => {
+ (Some(dst), Vec::new())
+ }
+ (AccessorPart::Setter, Instruction::PutById { .. }) => {
+ (None, vec![CallOperand::Register(self.input(node, 1))])
+ }
+ _ => return Err(invalid("native accessor call of another instruction")),
+ };
+ let this_operand = CallOperand::Register(self.input(node, 0));
+ let temps = [self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)];
+ let check = self.masm.new_label();
+ let done = self.masm.new_label();
+
+ if let (AccessorPart::Getter, Some(fields)) = (part, target.direct_getter) {
+ self.emit_direct_getter_load(self.input(node, 0), fields, temps, done);
+ }
+
+ // Stack traces show the caller at its access.
+ let program_counter = self.frame_field(self.runtime.offsets.execution_context_program_counter);
+ self.masm.store_imm32(&program_counter, pc);
+
+ // NB: The result stays in the return register. Needs no native stack
+ // check: the prologue made the same check, with the stack pointer
+ // the code keeps until its epilogue.
+ self.emit_native_frame_call(
+ target,
+ this_operand,
+ &arguments,
+ next_pc,
+ None,
+ None,
+ temps,
+ None,
+ [check, done],
+ )?;
+
+ // NB: A function that threw continues at the next instruction only
+ // if the frame does, where the getter's destination has its value.
+ self.masm.bind(check);
+ self.emit_continuation_check(next_pc, &[]);
+ if let Some(dst) = dst {
+ let address = self.slot_address(dst.raw())?;
+ self.masm.load64(M::RETURN_GPRS[0], &address);
+ } else {
+ self.masm.move_imm64(M::RETURN_GPRS[0], value::UNDEFINED);
+ }
+ self.masm.bind(done);
+ Ok(())
+ }
+
+ /// The getter of a platform object attribute backed by a field, without
+ /// calling it, as the interpreter reads it: the main world wrapper of the
+ /// field's implementation (or null), into the return register, jumping to
+ /// `done`. Falls through, with `object` intact, where the getter must run:
+ /// for a receiver that is not the main world wrapper of its implementation,
+ /// a field whose implementation has no main world wrapper yet, or a global
+ /// object (which the getter returns as its window proxy).
+ fn emit_direct_getter_load(
+ &mut self,
+ object: Gpr,
+ fields: DirectGetterFields,
+ [receiver, implementation, temp]: [Gpr; 3],
+ done: Label,
+ ) {
+ let offsets = self.runtime.offsets;
+ let layout = self.runtime.layout;
+ let scratch = self.pinned.scratch;
+ let call = self.masm.new_label();
+ let field = |base: Gpr, offset: u32| Address::new(base, offset as i32);
+
+ // NB: An ordinary object made from a wrapper's prototype has the wrapper's shape, but no implementation.
+ self.emit_unbox_cell(receiver, object);
+ self.masm.load16(scratch, &field(receiver, offsets.object_flags));
+ self.masm.branch_test32(
+ Condition::Zero,
+ scratch,
+ u32::from(layout.object_flag_is_platform_object),
+ call,
+ );
+ self.masm
+ .load64(implementation, &field(receiver, fields.wrapper_implementation));
+ self.masm.branch64_imm(Condition::Equal, implementation, 0, call);
+ self.masm
+ .load64(temp, &field(implementation, fields.main_world_wrapper));
+ self.masm.branch64_imm(Condition::Equal, temp, 0, call);
+ self.masm.load64(temp, &field(temp, fields.weak_impl_value));
+ self.masm.branch64(Condition::NotEqual, temp, receiver, call);
+
+ let not_null = self.masm.new_label();
+ self.masm
+ .load64(implementation, &field(implementation, fields.implementation_value));
+ self.masm.branch64_imm(Condition::NotEqual, implementation, 0, not_null);
+ self.masm.move_imm64(M::RETURN_GPRS[0], value::NULL);
+ self.masm.jump(done);
+
+ self.masm.bind(not_null);
+ self.masm
+ .load64(temp, &field(implementation, fields.main_world_wrapper));
+ self.masm.branch64_imm(Condition::Equal, temp, 0, call);
+ self.masm.load64(temp, &field(temp, fields.weak_impl_value));
+ self.masm.branch64_imm(Condition::Equal, temp, 0, call);
+ self.masm.load16(scratch, &field(temp, offsets.object_flags));
+ self.masm.branch_test32(
+ Condition::NonZero,
+ scratch,
+ u32::from(layout.object_flag_is_global_object),
+ call,
+ );
+ self.box_cell_with_tag(M::RETURN_GPRS[0], temp, value::OBJECT_TAG);
+ self.masm.jump(done);
+ self.masm.bind(call);
+ }
+
/// Calls a raw native function the way the interpreter's `Call` fast
/// path does: in a lightweight frame without an executable, linked to the
/// calling frame, whose slots are the arguments, built in `temps`. Jumps
- /// to `slow` (before anything observable happened) if the native stack is
- /// too full (the code checked at entry that the interpreter stack has
- /// room), to `check` once the runtime unwound the frame of a function
- /// that threw, and to `done` once the result is in `dst`, or for a call
- /// at an inlined call `site`, in the return register.
+ /// to `slow` (before anything observable happened) if there is one and
+ /// the native stack is too full (the code checked at entry that the
+ /// interpreter stack has room), to `check` once the runtime unwound the
+ /// frame of a function that threw, and to `done` once the result is in
+ /// `dst`, or for a call at an inlined call `site` or without `dst`, in
+ /// the return register.
#[allow(clippy::too_many_arguments)]
fn emit_native_frame_call(
&mut self,
@@ -1205,10 +1338,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
this_operand: CallOperand,
arguments: &[CallOperand],
next_pc: u32,
- dst: crate::bytecode::Operand,
+ dst: Option<crate::bytecode::Operand>,
site: Option<&InlinedCallSite>,
[native_frame, temp, other]: [Gpr; 3],
- [slow, check, done]: [Label; 3],
+ slow: Option<Label>,
+ [check, done]: [Label; 2],
) -> Result<(), CompileFailure> {
let runtime = self.runtime;
let offsets = runtime.offsets;
@@ -1229,7 +1363,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// The native function runs on this native stack, so take the generic
// path (which throws) if it is nearly exhausted.
- self.emit_native_stack_check(slow);
+ if let Some(slow) = slow {
+ self.emit_native_stack_check(slow);
+ }
// Allocate the frame on the interpreter stack, above room for the
// frames of the inlined calls at an inlined call site.
@@ -1283,7 +1419,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
4,
u64::from(site.map_or(next_pc, InlinedCallSite::return_pc)),
),
- (offsets.execution_context_caller_dst_raw, 4, u64::from(dst.raw())),
+ (
+ offsets.execution_context_caller_dst_raw,
+ 4,
+ u64::from(dst.map_or(Operand::INVALID, |dst| dst.raw())),
+ ),
]);
constants.push((offsets.execution_context_function, 8, target.function.0));
constants.push((offsets.execution_context_realm, 8, target.realm.0));
@@ -1327,7 +1467,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.store64(&vm_field(offsets.vm_interpreter_stack_top), scratch);
self.masm
.store64(&vm_field(offsets.vm_running_execution_context), frame);
- if site.is_none() {
+ if let (None, Some(dst)) = (site, dst) {
let destination = self.slot_address(dst.raw())?;
self.masm.store64(&destination, value_register);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index b7059969e2e..405b35d9075 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -1462,6 +1462,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::Generic { opcode, executable, pc } => {
self.emit_generic(*opcode, *executable, *pc)?;
}
+ Op::CallNativeAccessor { pc, part, target } => {
+ self.emit_call_native_accessor(node_id, *pc, *part, *target)?;
+ }
Op::CallDirect { executable, pc, .. } | Op::CallNative { executable, pc, .. } => {
let (executable, pc) = (*executable, *pc);
// NB: A call in an inlined callee that does not run without
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
index 5583161fefe..3ad49376c12 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
@@ -1170,6 +1170,8 @@ const FLAG_MAY_INTERFERE: u16 = 1 << 4;
const FLAG_IS_EXTENSIBLE: u16 = 1 << 0;
const FLAG_REQUIRES_SLOW_ADD_OWN_PROPERTY: u16 = 1 << 8;
const FLAG_IS_ECMASCRIPT_FUNCTION: u16 = 1 << 6;
+const FLAG_IS_PLATFORM_OBJECT: u16 = 1 << 9;
+const FLAG_IS_GLOBAL_OBJECT: u16 = 1 << 10;
const PACKED: u8 = 1;
const HOLEY: u8 = 2;
@@ -1192,6 +1194,8 @@ fn fake_object_layout() -> RuntimeLayout {
shape_prototype: 0,
object_flag_is_typed_array: FLAG_IS_TYPED_ARRAY,
object_flag_is_htmldda: HTMLDDA_FLAG,
+ object_flag_is_platform_object: FLAG_IS_PLATFORM_OBJECT,
+ object_flag_is_global_object: FLAG_IS_GLOBAL_OBJECT,
object_flag_requires_slow_add_own_property: FLAG_REQUIRES_SLOW_ADD_OWN_PROPERTY,
named_properties_capacity: -8,
shape_property_count: 80,
@@ -2968,6 +2972,192 @@ fn get_by_id_through_property_caches() {
assert_eq!(fake.get(fake.value()), MARKER);
}
+/// A raw native getter's `ThrowCompletionOr<Value>`, in the return registers.
+#[repr(C)]
+struct FakeNativeResult {
+ value: u64,
+ is_error: u64,
+}
+
+const NATIVE_GETTER_RESULT: u64 = (value::UNDEFINED_TAG as u64) << 48 | 0xFEED;
+
+extern "C" fn fake_native_getter(_vm: u64) -> FakeNativeResult {
+ FakeNativeResult {
+ value: NATIVE_GETTER_RESULT,
+ is_error: 0,
+ }
+}
+
+#[test]
+fn get_by_id_reads_direct_getter_wrappers_inline() {
+ use crate::builder::tests::property_access::{cache, own};
+ use crate::snapshot::{
+ AccessorFunctionSnapshot, CellId, DirectGetterFields, NativeCallTarget, PropertyCacheEntryType,
+ };
+ // A wrapper whose implementation is in its word 10, with an accessor
+ // property 1 whose getter reads the implementation's word 2, and the
+ // main world wrapper of that through the implementation's word 1 and
+ // the weak reference's word 1.
+ let function = vec![0u64; 4];
+ let mut accessor = vec![0u64; 3];
+ accessor[1] = function.as_ptr() as u64;
+ let accessor_value = u64::from(0xFFFC_u16) << 48 | accessor.as_ptr() as u64;
+ let mut fake = FakeCachedObject::new(&[value::int32(10), accessor_value]);
+ let mut result = vec![0u64; 2];
+ let mut result_weak = vec![0, result.as_ptr() as u64];
+ let result_implementation = [0, result_weak.as_ptr() as u64, 0];
+ let mut weak = vec![0, fake.object.as_ptr() as u64];
+ let mut implementation = vec![0, weak.as_ptr() as u64, result_implementation.as_ptr() as u64];
+ fake.object[1] = u64::from(FLAG_IS_PLATFORM_OBJECT);
+ fake.object[10] = implementation.as_ptr() as u64;
+ let target = NativeCallTarget {
+ function: CellId(function.as_ptr() as u64),
+ realm: CellId(0x7000),
+ entry: fake_native_getter as *const () as u64,
+ direct_getter: Some(DirectGetterFields {
+ wrapper_implementation: 80,
+ implementation_value: 16,
+ main_world_wrapper: 8,
+ weak_impl_value: 8,
+ }),
+ };
+ let mut entry = own(PropertyCacheEntryType::GetOwnProperty, fake.shape.as_ptr() as u64, 1);
+ entry.holds_accessor = true;
+ entry.accessor_function = Some(AccessorFunctionSnapshot {
+ function: target.function,
+ intrinsic: None,
+ inline_executable: None,
+ cached_value_offset: None,
+ native: Some(target),
+ });
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ Instruction::GetById {
+ value_feedback: 0,
+ dst: r(5),
+ base: argument(0),
+ property: crate::bytecode::PropertyKeyTableIndex(0),
+ base_identifier: None,
+ cache: 1,
+ },
+ Instruction::Return { value: r(5) },
+ ]
+ });
+ let get = |fake: &FakeCachedObject| {
+ let (result, _) = run_program_with_snapshot(
+ &program,
+ &[fake.value()],
+ |snapshot| snapshot.executables[0].property_caches = vec![cache(Vec::new()), cache(vec![entry])],
+ |machine| machine.frame[4] = fake.executable.as_ptr() as u64,
+ );
+ assert_eq!(result.status, RETURNED);
+ result.value
+ };
+ assert_eq!(get(&fake), object_value(&result));
+ implementation[2] = 0;
+ assert_eq!(get(&fake), value::NULL);
+ implementation[2] = result_implementation.as_ptr() as u64;
+
+ // The getter runs for a global object (which it returns as its window
+ // proxy), an implementation without a main world wrapper, a receiver
+ // that is not its implementation's main world wrapper, and an object
+ // that is no platform object.
+ result[1] = u64::from(FLAG_IS_GLOBAL_OBJECT);
+ assert_eq!(get(&fake), NATIVE_GETTER_RESULT);
+ result[1] = 0;
+ result_weak[1] = 0;
+ assert_eq!(get(&fake), NATIVE_GETTER_RESULT);
+ result_weak[1] = result.as_ptr() as u64;
+ weak[1] = 0x8000;
+ assert_eq!(get(&fake), NATIVE_GETTER_RESULT);
+ weak[1] = fake.object.as_ptr() as u64;
+ fake.object[1] = 0;
+ assert_eq!(get(&fake), NATIVE_GETTER_RESULT);
+ std::hint::black_box((&function, &accessor, &result, &result_weak, &weak, &implementation));
+}
+
+/// The VM words where `fake_native_setter()` puts the `this` value and the
+/// argument it was called with.
+const VM_NATIVE_SETTER_CALL_WORDS: usize = 10;
+
+extern "C" fn fake_native_setter(vm: *mut u64) -> FakeNativeResult {
+ // SAFETY: The VM's word 0 is the running frame, the setter's own, and the
+ // fake VM has room for the words the call is recorded in.
+ unsafe {
+ let frame = *vm as *const u64;
+ *vm.add(VM_NATIVE_SETTER_CALL_WORDS) = *frame.add(15);
+ *vm.add(VM_NATIVE_SETTER_CALL_WORDS + 1) = *frame.add(FRAME_HEADER_WORDS);
+ }
+ FakeNativeResult {
+ value: value::UNDEFINED,
+ is_error: 0,
+ }
+}
+
+#[test]
+fn put_by_id_calls_native_setters_of_prototypes() {
+ use crate::builder::tests::property_access::{cache, own};
+ use crate::snapshot::{AccessorFunctionSnapshot, CellId, NativeCallTarget, PropertyCacheEntryType};
+ // A prototype whose property 0 is an accessor with a native setter.
+ let function = vec![0u64; 4];
+ let mut accessor = vec![0u64; 3];
+ accessor[2] = function.as_ptr() as u64;
+ let accessor_value = u64::from(0xFFFC_u16) << 48 | accessor.as_ptr() as u64;
+ let prototype = FakeCachedObject::new(&[accessor_value]);
+ let validity = vec![1u64];
+ let fake = FakeCachedObject::new(&[value::int32(10)]);
+ let target = NativeCallTarget {
+ function: CellId(function.as_ptr() as u64),
+ realm: CellId(0x7000),
+ entry: fake_native_setter as *const () as u64,
+ direct_getter: None,
+ };
+ let mut entry = own(
+ PropertyCacheEntryType::ChangePropertyInPrototypeChain,
+ fake.shape.as_ptr() as u64,
+ 0,
+ );
+ entry.prototype = Some(CellId(prototype.object.as_ptr() as u64));
+ entry.prototype_chain_validity = Some(CellId(validity.as_ptr() as u64));
+ entry.prototype_chain_valid = true;
+ entry.holds_accessor = true;
+ entry.accessor_function = Some(AccessorFunctionSnapshot {
+ function: target.function,
+ intrinsic: None,
+ inline_executable: None,
+ cached_value_offset: None,
+ native: Some(target),
+ });
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ Instruction::PutById {
+ base: argument(0),
+ property: crate::bytecode::PropertyKeyTableIndex(0),
+ src: argument(1),
+ kind: 0,
+ cache: 1,
+ base_identifier: None,
+ },
+ Instruction::Return { value: c(0) },
+ ]
+ });
+ let (result, machine) = run_program_with_snapshot(
+ &program,
+ &[fake.value(), value::int32(42)],
+ |snapshot| snapshot.executables[0].property_caches = vec![cache(Vec::new()), cache(vec![entry])],
+ |machine| machine.frame[4] = fake.executable.as_ptr() as u64,
+ );
+ assert_eq!(result.status, RETURNED);
+ assert_eq!(machine.vm[VM_SLOW_PUTS_WORD], 0);
+ assert_eq!(
+ machine.vm[VM_NATIVE_SETTER_CALL_WORDS..VM_NATIVE_SETTER_CALL_WORDS + 2],
+ [fake.value(), value::int32(42)]
+ );
+ std::hint::black_box((&function, &accessor, &validity));
+}
+
#[test]
fn put_by_id_adds_properties_through_property_caches() {
let mut fake = FakeCachedObject::new(&[value::int32(10), value::int32(11), value::EMPTY]);
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 061dc9e7ec3..06d09a73306 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -209,6 +209,13 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
let stores = if *stores_operands { " storing operands" } else { "" };
with_inputs(&format!("CallNative {location}{frames}{stores}"))
}
+ Op::CallNativeAccessor { pc, part, target } => {
+ let direct = if target.direct_getter.is_some() { " direct" } else { "" };
+ with_inputs(&format!(
+ "CallNativeAccessor @{pc} {part:?} {:#x}{direct}",
+ target.function.0
+ ))
+ }
Op::AllocateObject {
shape,
property_count,
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 205e65715f9..82fb8197cf8 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -31,6 +31,7 @@ use crate::code::ResumeMode;
use crate::snapshot::CellId;
use crate::snapshot::HelperResult;
use crate::snapshot::Intrinsic;
+use crate::snapshot::NativeCallTarget;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct NodeId(pub u32);
@@ -575,6 +576,18 @@ pub enum Op {
inlined_frame_bytes: u32,
stores_operands: bool,
},
+ /// The `GetById` or `GetLength` (for the getter) or `PutById` (for the
+ /// setter) at `pc` of the compiled function (never of an inlined call),
+ /// whose checks established that the property is an accessor whose
+ /// `part` is the raw native function `target`: calls it like
+ /// `CallNative` calls its target, with input 0 as the `this` value and
+ /// input 1 (for the setter) as the argument. The value is the getter's
+ /// result (for the setter, its result too).
+ CallNativeAccessor {
+ pc: u32,
+ part: AccessorPart,
+ target: NativeCallTarget,
+ },
/// The running frame's passed argument count, as an int32 value.
ArgumentCount,
/// The raw pointer in `field` of the running frame's execution context,
@@ -1491,16 +1504,18 @@ impl Op {
reads: Locations::FRAME,
..P::PURE
},
- Op::Generic { .. } | Op::CallDirect { .. } | Op::CallNative { .. } | Op::CallForwardingArguments { .. } => {
- P {
- can_lazy_exit: true,
- is_call: true,
- reads: Locations::ALL,
- writes: Locations::ALL,
- runs_code: true,
- allocates: true,
- }
- }
+ Op::Generic { .. }
+ | Op::CallDirect { .. }
+ | Op::CallNative { .. }
+ | Op::CallNativeAccessor { .. }
+ | Op::CallForwardingArguments { .. } => P {
+ can_lazy_exit: true,
+ is_call: true,
+ reads: Locations::ALL,
+ writes: Locations::ALL,
+ runs_code: true,
+ allocates: true,
+ },
Op::Jump { .. }
| Op::Branch { .. }
| Op::BranchTruthy { .. }
@@ -1661,6 +1676,7 @@ impl Op {
Op::Generic { .. } => "Generic",
Op::CallDirect { .. } => "CallDirect",
Op::CallNative { .. } => "CallNative",
+ Op::CallNativeAccessor { .. } => "CallNativeAccessor",
Op::ArgumentCount => "ArgumentCount",
Op::LoadFrameField { .. } => "LoadFrameField",
Op::LoadArgument { .. } => "LoadArgument",
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index f2fb28204c9..4dcf19cf930 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -397,6 +397,12 @@ fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {
constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
}
}
+ // Native accessor calls build the callee's frame in temps, and return
+ // the result.
+ Op::CallNativeAccessor { .. } => {
+ constraints.temps = crate::codegen::DIRECT_CALL_TEMPS;
+ constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
+ }
// The object, its shape and the cache entry.
Op::ProbePropertyCache { .. } | Op::ProbeKeyedCache { .. } => constraints.temps = 3,
// Those, and the named property storage of property additions.
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 1ad39434a62..289eb5193e4 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -580,6 +580,24 @@ pub struct NativeCallTarget {
pub realm: CellId,
/// `ThrowCompletionOr<Value> (*)(VM&)`: the native function.
pub entry: u64,
+ /// Where the function, a getter of a platform object attribute backed by
+ /// a field, finds the wrapper it would return, if it is one and the
+ /// interpreter validated the cache entry for it (see
+ /// `PropertyLookupCacheEntry::direct_getter_validated`).
+ pub direct_getter: Option<DirectGetterFields>,
+}
+
+/// The byte offsets a `DirectGetterFunction` reads: the implementation of a
+/// wrapper, the field of the implementation the attribute returns, the weak
+/// reference of an implementation to its main world wrapper, and the cell of
+/// that weak reference. The getter returns the main world wrapper of the
+/// field's implementation, or null for a null field.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DirectGetterFields {
+ pub wrapper_implementation: u32,
+ pub implementation_value: u32,
+ pub main_world_wrapper: u32,
+ pub weak_impl_value: u32,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
@@ -689,6 +707,9 @@ pub struct AccessorFunctionSnapshot {
/// The index in `Snapshot::executables` of the function's executable,
/// if it is an inlining candidate.
pub inline_executable: Option<u32>,
+ /// The function as a raw native function that JIT code may call
+ /// directly, if it is one.
+ pub native: Option<NativeCallTarget>,
}
/// Built-in functions the compiler recognizes.
@@ -1603,6 +1624,9 @@ pub struct RuntimeLayout {
pub object_flag_is_typed_array: u16,
/// `Object::Flag::IsHTMLDDA`.
pub object_flag_is_htmldda: u16,
+ /// `Object::Flag::IsPlatformObject` and `Object::Flag::IsGlobalObject`.
+ pub object_flag_is_platform_object: u16,
+ pub object_flag_is_global_object: u16,
/// `Object::Flag::RequiresSlowAddOwnProperty`.
pub object_flag_requires_slow_add_own_property: u16,
/// The capacity (u32) of heap named property storage, relative to the
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 74c3ae33e8a..38e319bc30f 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -185,6 +185,8 @@ fn runtime_layout() -> RuntimeLayout {
shape_prototype: offset(offset_of!(Shape, prototype)),
object_flag_is_typed_array: object_flag::IS_TYPED_ARRAY,
object_flag_is_htmldda: object_flag::IS_HTMLDDA,
+ object_flag_is_platform_object: object_flag::IS_PLATFORM_OBJECT,
+ object_flag_is_global_object: object_flag::IS_GLOBAL_OBJECT,
object_flag_requires_slow_add_own_property: object_flag::REQUIRES_SLOW_ADD_OWN_PROPERTY,
// NB: Named properties beyond the inline storage live in storage with its capacity in front, like indexed
// elements.
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 83be44d62aa..248d9e171f3 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -15,8 +15,8 @@ use libjs_jit::bytecode::{EnvironmentCoordinate, ExceptionHandler, FrameLayout,
use libjs_jit::code::ExitKind;
use libjs_jit::snapshot::{
AccessorFunctionSnapshot, CallFeedbackSnapshot, CellId, ClosureTemplateSnapshot, CompileOptions, ConstructTarget,
- DirectCallTarget, EnvironmentTemplateSnapshot, ExecutableSnapshot, FeedbackSnapshot, ForwardedCallSnapshot,
- Forwarding, FunctionFrameFields, GlobalCacheSnapshot, GlobalValueSnapshot, GlobalsSnapshot,
+ DirectCallTarget, DirectGetterFields, EnvironmentTemplateSnapshot, ExecutableSnapshot, FeedbackSnapshot,
+ ForwardedCallSnapshot, Forwarding, FunctionFrameFields, GlobalCacheSnapshot, GlobalValueSnapshot, GlobalsSnapshot,
InlinedFunctionSnapshot, InliningLimits, Intrinsic, KeyedFeedbackSnapshot, LexicalEnvironmentTemplateSnapshot,
NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot, PropertyCacheEntrySnapshot,
PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, ShapeSnapshot, Snapshot, StressOptions,
@@ -36,7 +36,9 @@ use crate::gc::class::Extends;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::environment::DeclarativeEnvironment;
-use crate::layout::function_object::{EcmascriptFunctionObject, FunctionObject, RawNativeFunction};
+use crate::layout::function_object::{
+ DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, RawNativeFunction,
+};
use crate::layout::object::{Object, TYPED_ARRAY_CACHED_DATA_OFFSET_INVALID, TypedArrayBase};
use crate::layout::property_lookup_cache::{
GlobalVariableCache, PropertyLookupCache, PropertyLookupCacheEntry, PropertyLookupCacheEntryType,
@@ -419,12 +421,18 @@ impl SnapshotBuilder<'_> {
.and_then(|value| value.as_accessor().cached_value_key())
.and_then(|key| entry.shape?.lookup(&PropertyKey::from_symbol(key)))
.map(|metadata| metadata.offset);
- let accessor_function = entry_accessor_function(slot).map(|function| AccessorFunctionSnapshot {
- cached_value_offset,
- function: self.cell(function),
- intrinsic: intrinsic_of(self.vm, Some(Value::from_object(function.upcast::<Object>()).as_cell())),
- inline_executable: self
- .inline_executable_index(Some(Value::from_object(function.upcast::<Object>()).as_cell()), caller),
+ let accessor_function = entry_accessor_function(slot).map(|function| {
+ let cell = self.cell(function);
+ AccessorFunctionSnapshot {
+ cached_value_offset,
+ function: cell,
+ intrinsic: intrinsic_of(self.vm, Some(Value::from_object(function.upcast::<Object>()).as_cell())),
+ inline_executable: self.inline_executable_index(
+ Some(Value::from_object(function.upcast::<Object>()).as_cell()),
+ caller,
+ ),
+ native: self.native_accessor_target(function, cell, entry.direct_getter_validated),
+ }
});
entries.push(PropertyCacheEntrySnapshot {
entry_type,
@@ -852,11 +860,46 @@ impl SnapshotBuilder<'_> {
function: self.cell(function),
realm: self.cell(function.realm()),
entry,
+ direct_getter: None,
});
}
snapshot
}
+ /// The target through which JIT code may call an accessor's function, whose cell is `function_cell`, directly,
+ /// if it is a raw native function. Like the interpreter, JIT code reads the value of a direct getter without
+ /// calling it only through a cache entry on which the getter ran (`direct_getter_validated`).
+ fn native_accessor_target(
+ &mut self,
+ function: Gc<FunctionObject>,
+ function_cell: CellId,
+ direct_getter_validated: bool,
+ ) -> Option<NativeCallTarget> {
+ if !RAW_NATIVE_FUNCTIONS_RETURN_IN_REGISTERS {
+ return None;
+ }
+ let native_function = function.downcast::<RawNativeFunction>()?;
+ let entry = native_function.native_function(self.vm)? as usize as u64;
+ let direct_getter = function
+ .downcast::<DirectGetterFunction>()
+ .filter(|_| direct_getter_validated)
+ .map(|getter| {
+ let bytes = |word_offset: u32| word_offset * size_of::<u64>() as u32;
+ DirectGetterFields {
+ wrapper_implementation: bytes(getter.wrapper_implementation_word_offset.get()),
+ implementation_value: bytes(getter.implementation_value_word_offset.get()),
+ main_world_wrapper: bytes(getter.main_world_wrapper_word_offset.get()),
+ weak_impl_value: bytes(getter.weak_impl_value_word_offset.get()),
+ }
+ });
+ Some(NativeCallTarget {
+ function: function_cell,
+ realm: self.cell(native_function.realm()),
+ entry,
+ direct_getter,
+ })
+ }
+
/// The snapshot of an executable of the snapshot.
fn executable_snapshot(&mut self, entry: &Entry) -> ExecutableSnapshot {
let vm = self.vm;