Skip to content

Truly independent web browser

LibJS: Call Map.prototype.get and has from JIT code without a frame

Andreas Klingf84fa5869281
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 970a522f0c6..18d74f4980f 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -67,7 +67,8 @@ from them alone:
- **Memory.** `reads` and `writes`: sets of abstract locations (`ir::Locations`): `FRAME`,
`NAMED_SLOTS` (property values), `SHAPES` (shapes and prototypes), `ELEMENTS` (element values),
`ELEMENT_COUNTS` (element storage kind, length, capacity and the storage offset of typed arrays), `GLOBAL_BINDINGS` and `BINDINGS` (the
- bindings of declarative environments), and `ITERATORS` (the state of iterators). Passes ask
+ bindings of declarative environments), `ITERATORS` (the state of iterators), and `COLLECTIONS` (the
+ entries of Map, Set, WeakMap and WeakSet objects). Passes ask
one question: whether one node's writes intersect another's reads. `runs_code`: may run other
code, which may write anything, or invalidate the compiled code. The op table below names the
locations coarsely (Named for slots and shapes, Elements for values and counts, Any for all);
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/effects.rs b/Libraries/LibJS/JIT/Rust/src/ir/effects.rs
index ece8f29f282..f02b4323186 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/effects.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/effects.rs
@@ -14,7 +14,7 @@
/// A set of abstract locations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
-pub struct Locations(u8);
+pub struct Locations(u16);
impl Locations {
pub const NONE: Self = Self(0);
@@ -38,8 +38,11 @@ impl Locations {
pub const BINDINGS: Self = Self(1 << 6);
/// The internal state of iterators.
pub const ITERATORS: Self = Self(1 << 7);
+ /// The entries of keyed collections (Map, Set, WeakMap and WeakSet
+ /// objects).
+ pub const COLLECTIONS: Self = Self(1 << 8);
/// Every location.
- pub const ALL: Self = Self(u8::MAX);
+ pub const ALL: Self = Self(u16::MAX);
/// Named properties: their values and which objects have them.
pub const NAMED: Self = Self::NAMED_SLOTS.union(Self::SHAPES);
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index bdcc919e39f..c447fd45177 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -744,6 +744,10 @@ pub enum Intrinsic {
StringPrototypeTrimEnd,
/// `RegExp.prototype.exec`.
RegExpPrototypeExec,
+ /// `Map.prototype.get`.
+ MapPrototypeGet,
+ /// `Map.prototype.has`.
+ MapPrototypeHas,
}
/// A `this` value or argument of a builtin whose runtime helper JIT code
@@ -861,6 +865,15 @@ impl Intrinsic {
reads: Locations::NAMED,
writes: Locations::NAMED_SLOTS,
}),
+ // NB: The helpers decline for receivers that are no Map, which
+ // the slow path throws for.
+ Intrinsic::MapPrototypeGet | Intrinsic::MapPrototypeHas => Some(HelperCall {
+ receiver: HelperOperand::Value,
+ arguments: &[HelperOperand::Value],
+ result: HelperResult::Value,
+ reads: Locations::COLLECTIONS,
+ writes: Locations::NONE,
+ }),
_ => None,
}
}
diff --git a/Libraries/LibJS/Rust/src/jit/helper_calls.rs b/Libraries/LibJS/Rust/src/jit/helper_calls.rs
index 01422f73b68..4d24d50659d 100644
--- a/Libraries/LibJS/Rust/src/jit/helper_calls.rs
+++ b/Libraries/LibJS/Rust/src/jit/helper_calls.rs
@@ -13,6 +13,8 @@ use libjs_jit::snapshot::Intrinsic;
use crate::interpreter::vm::Vm;
use crate::layout::value::Value;
+use crate::runtime::keyed_collections::canonicalize_keyed_collection_key;
+use crate::runtime::map::Map;
use crate::runtime::regexp_prototype::regexp_builtin_exec_running_no_code;
use crate::runtime::string_prototype::{StringPrototype, trim_primitive_string};
use crate::utf16::TrimMode;
@@ -34,6 +36,8 @@ pub fn address(intrinsic: Intrinsic) -> u64 {
Intrinsic::StringPrototypeTrimStart => string_trim_start as *const (),
Intrinsic::StringPrototypeTrimEnd => string_trim_end as *const (),
Intrinsic::RegExpPrototypeExec => regexp_exec as *const (),
+ Intrinsic::MapPrototypeGet => map_get as *const (),
+ Intrinsic::MapPrototypeHas => map_has as *const (),
Intrinsic::FunctionPrototypeApply
| Intrinsic::FunctionPrototypeCall
| Intrinsic::ArrayPrototypePush
@@ -156,3 +160,30 @@ extern "C" fn regexp_exec(vm: &Vm, regexp: u64, string_value: u64) -> u64 {
regexp_builtin_exec_running_no_code(vm, Value(regexp), string(string_value).as_string())
.map_or(Value::EMPTY.0, |result| result.0)
}
+
+/// The Map a `this` value is, if it is one.
+fn map(value: u64) -> Option<crate::layout::cell::Gc<Map>> {
+ let value = Value(value);
+ if !value.is_object() {
+ return None;
+ }
+ value.as_object().downcast::<Map>()
+}
+
+/// `map.get(key)`, or the empty value if the `this` value is no Map.
+extern "C" fn map_get(_vm: &Vm, map_value: u64, key: u64) -> u64 {
+ let Some(map) = map(map_value) else {
+ return Value::EMPTY.0;
+ };
+ map.map_get(canonicalize_keyed_collection_key(Value(key)))
+ .unwrap_or(Value::UNDEFINED)
+ .0
+}
+
+/// `map.has(key)`, or the empty value if the `this` value is no Map.
+extern "C" fn map_has(_vm: &Vm, map_value: u64, key: u64) -> u64 {
+ let Some(map) = map(map_value) else {
+ return Value::EMPTY.0;
+ };
+ Value::from_bool(map.map_has(canonicalize_keyed_collection_key(Value(key)))).0
+}
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 900029f03d7..cb4dac65e9f 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -49,6 +49,7 @@ use crate::runtime::boolean_constructor::BooleanConstructor;
use crate::runtime::bound_function::BoundFunction;
use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;
use crate::runtime::function_prototype::{self, FunctionPrototype};
+use crate::runtime::map_prototype;
use crate::runtime::math_object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
use crate::runtime::object_constructor::ObjectConstructor;
@@ -171,7 +172,7 @@ fn intrinsic_of(vm: &Vm, cell: Option<Gc<CellHeader>>) -> Option<Intrinsic> {
}
/// The intrinsics the compiler knows by their native functions (of any realm).
-static NATIVE_INTRINSICS: [(&RawNativeFunctionPointer, Intrinsic); 21] = [
+static NATIVE_INTRINSICS: [(&RawNativeFunctionPointer, Intrinsic); 23] = [
(&function_prototype::APPLY_FUNCTION, Intrinsic::FunctionPrototypeApply),
(&function_prototype::CALL_FUNCTION, Intrinsic::FunctionPrototypeCall),
(&array_prototype::PUSH_FUNCTION, Intrinsic::ArrayPrototypePush),
@@ -220,6 +221,8 @@ static NATIVE_INTRINSICS: [(&RawNativeFunctionPointer, Intrinsic); 21] = [
Intrinsic::StringPrototypeTrimStart,
),
(&string_prototype::TRIM_END_FUNCTION, Intrinsic::StringPrototypeTrimEnd),
+ (&map_prototype::GET_FUNCTION, Intrinsic::MapPrototypeGet),
+ (&map_prototype::HAS_FUNCTION, Intrinsic::MapPrototypeHas),
];
/// The builtin `%ArrayIteratorPrototype%.next` of the realm, if `%ArrayIteratorPrototype%` holds it.
diff --git a/Libraries/LibJS/Rust/src/runtime/map_prototype.rs b/Libraries/LibJS/Rust/src/runtime/map_prototype.rs
index f84027f6779..82301f24fc0 100644
--- a/Libraries/LibJS/Rust/src/runtime/map_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/map_prototype.rs
@@ -35,6 +35,11 @@ use crate::runtime::realm::Realm;
/// %Map.prototype.set%, which the Map constructor calls directly when it finds it as the adder.
pub(crate) static SET_FUNCTION: RawNativeFunctionPointer = raw_native!(MapPrototype::set);
+/// %Map.prototype.get%, which JIT code calls through a runtime helper.
+pub(crate) static GET_FUNCTION: RawNativeFunctionPointer = raw_native!(MapPrototype::get);
+/// %Map.prototype.has%, which JIT code calls through a runtime helper.
+pub(crate) static HAS_FUNCTION: RawNativeFunctionPointer = raw_native!(MapPrototype::has);
+
/// %Map.prototype%.
#[repr(C)]
#[derive(Trace)]
@@ -93,14 +98,14 @@ impl MapPrototype {
.entries_function
.set(Some(entries_function));
define_native_function(&names.forEach, raw_native!(MapPrototype::for_each), 1);
- define_native_function(&names.get, raw_native!(MapPrototype::get), 1);
+ define_native_function(&names.get, GET_FUNCTION, 1);
define_native_function(&names.getOrInsert, raw_native!(MapPrototype::get_or_insert), 2);
define_native_function(
&names.getOrInsertComputed,
raw_native!(MapPrototype::get_or_insert_computed),
2,
);
- define_native_function(&names.has, raw_native!(MapPrototype::has), 1);
+ define_native_function(&names.has, HAS_FUNCTION, 1);
define_native_function(&names.keys, raw_native!(MapPrototype::keys), 0);
define_native_function(&names.set, SET_FUNCTION, 2);
define_native_function(&names.values, raw_native!(MapPrototype::values), 0);
diff --git a/Tests/LibJS/JIT/ir/map-lookups.js b/Tests/LibJS/JIT/ir/map-lookups.js
new file mode 100644
index 00000000000..2a501bfaa54
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/map-lookups.js
@@ -0,0 +1,22 @@
+// Map.prototype.has and Map.prototype.get, where the call sites saw only them, become calls of their runtime helpers,
+// which decline (with the empty value) for receivers that are no Map, so that the slow path calls the builtin.
+
+function lookup(map, key) {
+ return map.has(key) ? map.get(key) : 0;
+}
+jit.prepare(lookup);
+const map = new Map([
+ [1, 10],
+ [2, 20],
+]);
+for (let i = 0; i < 10; ++i) lookup(map, i & 3);
+jit.compile(lookup);
+
+// CHECK-FUNCTION: lookup
+// CHECK-PASS: graph building
+// CHECK: [[HAS:v[0-9]+]] = CallIntrinsic MapPrototypeHas ([[MAP:v[0-9]+]], [[KEY:v[0-9]+]])
+// CHECK-NEXT: BranchTaggedEquals ([[HAS]], #empty)
+// CHECK: [[GET:v[0-9]+]] = CallIntrinsic MapPrototypeGet ([[MAP]], [[KEY]])
+// CHECK-NEXT: BranchTaggedEquals ([[GET]], #empty)
+
+console.log(lookup(map, 2));
diff --git a/Tests/LibJS/Runtime/jit/map-lookups.js b/Tests/LibJS/Runtime/jit/map-lookups.js
new file mode 100644
index 00000000000..6a9388e6145
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/map-lookups.js
@@ -0,0 +1,79 @@
+// JIT code calls Map.prototype.get and Map.prototype.has through runtime helpers, without a native frame. The helpers
+// decline for receivers that are no Map, which the builtins then throw for.
+//
+// NB: The functions come from new Function, so that each run of a test (see LIBJS_TEST_REPEAT) compiles new ones.
+
+function compiled(parameters, body, warm_up) {
+ const f = new Function(...parameters, body);
+ jit.prepare(f);
+ for (let i = 0; i < 10; ++i) warm_up(f);
+ expect(jit.compile(f)).toBe(jit.enabled);
+ return f;
+}
+
+describe("Map lookups in compiled code", () => {
+ test("get and has find what set stored, with canonicalized keys", () => {
+ const map = new Map([
+ [1, "one"],
+ ["a", "letter"],
+ [0, "zero"],
+ [NaN, "nan"],
+ ]);
+ const object = {};
+ map.set(object, "object");
+ const get = compiled(["map", "key"], "return map.get(key);", f => f(map, 1));
+ const has = compiled(["map", "key"], "return map.has(key);", f => f(map, 1));
+ expect(get(map, 1)).toBe("one");
+ expect(get(map, 1.0)).toBe("one");
+ expect(get(map, "1")).toBeUndefined();
+ expect(get(map, "a")).toBe("letter");
+ expect(get(map, -0)).toBe("zero");
+ expect(get(map, NaN)).toBe("nan");
+ expect(get(map, object)).toBe("object");
+ expect(get(map, {})).toBeUndefined();
+ expect(get(map)).toBeUndefined();
+ expect(has(map, 1)).toBeTrue();
+ expect(has(map, -0)).toBeTrue();
+ expect(has(map, NaN)).toBeTrue();
+ expect(has(map, 2)).toBeFalse();
+ expect(has(map, object)).toBeTrue();
+ expect(has(map)).toBeFalse();
+ });
+
+ test("lookups see changes between them", () => {
+ const lookups = compiled(
+ ["map"],
+ "const results = [map.get(1), map.has(1)]; map.set(1, 'changed'); results.push(map.get(1)); map.delete(1); results.push(map.get(1), map.has(1)); return results;",
+ f => f(new Map([[1, "first"]]))
+ );
+ expect(lookups(new Map([[1, "first"]]))).toEqual(["first", true, "changed", undefined, false]);
+ expect(lookups(new Map())).toEqual([undefined, false, "changed", undefined, false]);
+ });
+
+ test("subclass instances are maps", () => {
+ class CountingMap extends Map {}
+ const map = new CountingMap([["x", 1]]);
+ const get = compiled(["map", "key"], "return map.get(key);", f => f(new Map([["x", 2]]), "x"));
+ expect(get(map, "x")).toBe(1);
+ expect(get(map, "y")).toBeUndefined();
+ });
+
+ test("receivers that are no Map throw like the builtins", () => {
+ const get = compiled(["map", "key"], "return Map.prototype.get.call(map, key);", f => f(new Map(), 1));
+ const has = compiled(["map", "key"], "return Map.prototype.has.call(map, key);", f => f(new Map(), 1));
+ for (const receiver of [new Set([1]), new WeakMap(), {}, 1, "map", undefined, null]) {
+ expect(() => get(receiver, 1)).toThrow(TypeError);
+ expect(() => has(receiver, 1)).toThrow(TypeError);
+ }
+ expect(get(new Map([[1, "one"]]), 1)).toBe("one");
+ expect(has(new Map([[1, "one"]]), 1)).toBeTrue();
+ });
+
+ test("replaced methods are called", () => {
+ const get = compiled(["map", "key"], "return map.get(key);", f => f(new Map(), 1));
+ const map = new Map([[1, "one"]]);
+ map.get = key => `replaced ${key}`;
+ expect(get(map, 1)).toBe("replaced 1");
+ expect(get(new Map([[1, "one"]]), 1)).toBe("one");
+ });
+});