Truly independent web browser
LibJS/JIT: Keep uses of a binding behind its initialization check
Tim Ledbetter04e282db33a1
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex a3e5b6c946b..590d8b2328e 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -99,12 +99,12 @@ A node that relies on a check takes the check's value as its input, never the chitself. Checks that exit (`CheckObject`, `CheckShape`, `CheckValue`, `CheckClosure`,`CheckAccessorFunction`, `CheckElements`, `CheckTypedArray`, `CheckArray`,`CheckNonNegativeInt32`, `CheckIdentityComparable`, `CheckAppendableArray`, `CheckBounds`,-`CheckTypedArrayStorage`, `CheckNotHole`) have their input 0 as their value, refined: known to-pass. `CheckInt32` refines and unboxes at once. A branch refines on its edges with `Refine`, the-textbook pi node: it takes the branch's inputs and returns input 0, at the head of the block that-only that edge reaches. So every check is a data dependency of what relies on it: passes move or-share a load exactly when they can move or share its check, without control dependencies and-without pinning loads by making them read everything.+`CheckTypedArrayStorage`, `CheckNotHole`, `CheckInitialized`) have their input 0 as their value,+refined: known to pass. `CheckInt32` refines and unboxes at once. A branch refines on its edges+with `Refine`, the textbook pi node: it takes the branch's inputs and returns input 0, at the+head of the block that only that edge reaches. So every check is a data dependency of what relies+on it: passes move or share a load exactly when they can move or share its check, without control+dependencies and without pinning loads by making them read everything.Passes see through refinements where that is sound: check elimination keeps its facts about theunrefined value, and leaves the uses of a check it removes on the value the check refined.@@ -165,6 +165,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m| CheckBounds | Exits unless the index (input 0) is below the count (input 1), unsigned. The value is the index, refined. | E | | | cse || CheckTypedArrayStorage | Exits unless the storage offset of a typed array (input 0) is valid. Typed arrays whose length the snapshot knows to be fixed use it as a constant past this check, so accesses with a constant index rely on it alone. The value is the offset, refined. | E | | | cse || CheckNotHole | Exits at holes (the empty value). The value is input 0, refined. | E | | | cse |+| CheckInitialized | Exits unless the binding or local variable (input 0) is initialized (not the empty value). The value is input 0, refined. | E | | | cse || AssumeValid | Exits if the code was invalidated; a patchable no-op (section 5). | E | Any | | || AssumeLegacyArgumentsUnread | After an instruction whose calls may run code reading the legacy `arguments` of inlined frames; escape analysis makes it an `AssumeValid` or removes it (section 4, "Legacy arguments"). | E | Any | | || **Object memory** | | | | | |diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex fdb7b50f386..9eeb0be188b 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -51,8 +51,17 @@ impl GraphBuilder<'_> {},Instruction::ThrowIfTDZ { src } => {let value = self.read(src)?;- let empty = self.constant(value::EMPTY);- self.build_throwing_check(BranchCondition::TaggedEquals { equal: true }, vec![value, empty], true)+ let initialized = self.check_initialized(value)?;+ if let Some(slot) = self.function.layout.tracked_index(src)+ && let SlotState::Value { node, in_sync } = self.frame.slots[slot]+ && node == value+ {+ self.frame.slots[slot] = SlotState::Value {+ node: initialized,+ in_sync,+ };+ }+ Ok(Flow::Continue)}Instruction::ThrowIfNotObject { src } => {let value = self.read(src)?;@@ -149,6 +158,20 @@ impl GraphBuilder<'_> {Ok(Flow::Continue)}+ /// `value`, the value of a binding or local variable, refined to be+ /// initialized. Where it is not, the code exits for the interpreter to+ /// throw, or the instruction's slow path throws if such an exit was taken+ /// there before, or if the value is known to be uninitialized.+ pub(super) fn check_initialized(&mut self, value: NodeId) -> Result<NodeId, CompileFailure> {+ if self.graph.constant_value(value) != Some(value::EMPTY) && self.may_speculate(ExitKind::Uninitialized) {+ return Ok(self.emit_checked(Op::CheckInitialized, vec![value], None));+ }+ let empty = self.constant(value::EMPTY);+ let condition = BranchCondition::TaggedEquals { equal: true };+ self.build_throwing_check(condition, vec![value, empty], true)?;+ Ok(self.refine(condition, false, vec![value, empty]))+ }+/// Writes `src` to `dst` where `condition` holds of it, and the result/// of the instruction's slow path, in a cold block, otherwise.fn build_conversion(diff --git a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs b/Libraries/LibJS/JIT/Rust/src/builder/environments.rsindex 6b8041d54d1..6032b85a66e 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/environments.rs@@ -169,14 +169,11 @@ impl GraphBuilder<'_> {// NB: Reading an uninitialized binding of a declarative environment// throws a ReferenceError, so the instruction continues with the// binding's value only.- if !initialized {- let empty = self.constant(value::EMPTY);- self.build_throwing_check(- BranchCondition::TaggedEquals { equal: true },- vec![binding, empty],- true,- )?;- }+ let binding = if initialized {+ binding+ } else {+ self.check_initialized(binding)?+ };let binding = match self.function.executablediff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 54f8fa777aa..84225e0eb3e 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -884,12 +884,18 @@ impl<'a> GraphBuilder<'a> {merged.slots[slot] = SlotState::Value { node, in_sync: false };continue;};- let first = values[0].0;- let needs_phi = values.iter().any(|(node, _)| *node != first) || assigned;+ let shared = values+ .iter()+ .map(|(node, _)| *node)+ .find(|candidate| values.iter().all(|(node, _)| self.graph.refines(*node, *candidate)));// NB: A loop header's phi gets the values its back edges bring,// which frame memory need not hold.let in_sync = values.iter().all(|(_, in_sync)| *in_sync) && !(is_loop_header && assigned);- let node = if needs_phi {+ let node = if let Some(node) = shared+ && !assigned+ {+ node+ } else {// NB: Phis start out tagged; representation selection// unboxes them later.let inputs = incoming@@ -898,8 +904,6 @@ impl<'a> GraphBuilder<'a> {.map(|((predecessor, _), (node, _))| self.tagged_at_end_of(*predecessor, *node)).collect();self.add_phi(inputs)- } else {- first};merged.slots[slot] = SlotState::Value { node, in_sync };}@@ -1037,7 +1041,11 @@ impl<'a> GraphBuilder<'a> {self.graph.nodes[node.index()].inputs.push(value);}SlotState::Value { node, .. } => {- if !matches!(self.frame.slots[slot], SlotState::Value { node: current, .. } if current == node) {+ let unchanged = matches!(+ self.frame.slots[slot],+ SlotState::Value { node: current, .. } if self.graph.has_value_of(current, node)+ );+ if !unchanged {// NB: Only slots assigned in the loop can change, and those have phis.return Err(CompileFailure::InvalidBytecode {pc: self.function.pc,diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex 681a02f50da..0a262ab0d83 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -124,6 +124,9 @@ pub enum ExitKind {OutOfBounds,/// A value had another type than the instruction's feedback had seen.BadType,+ /// A binding or local variable speculated to be initialized was not, so+ /// the interpreter throws its ReferenceError.+ Uninitialized,/// A node that may exit, which loop invariant code motion moved out of a/// block that not every iteration of its loop runs, exited before the/// loop. Exits of this kind are recorded at the loop header, and keepdiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 7167dc878d9..6dc6c9067d5 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -1558,6 +1558,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.branch64(Condition::NotEqual, self.input(node_id, 0), scratch, exit);}+ Op::CheckInitialized => {+ let exit = self.exit_site(node_id);+ self.masm+ .branch64_imm(Condition::Equal, self.input(node_id, 0), value::EMPTY as i64, exit);+ }Op::Typeof => self.emit_typeof(node_id),Op::TypeofIs { kind, equal } => self.emit_typeof_is(node_id, *kind, *equal),Op::EmptyToUndefined => {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 9bebc8c4551..fc8d5219841 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1884,18 +1884,29 @@ impl FakeEnvironment {}/// Runs `instructions` with the lexical and variable environments set, and-/// returns the result and how often a slow path that counts ran.+/// returns the result and how often a slow path that counts ran. `exits` are+/// the exits taken before, by the index of their instruction.fn run_with_environments(instructions: Vec<Instruction>,arguments: &[u64],lexical: &FakeEnvironment,variable: &FakeEnvironment,+ exits: &[(usize, ExitKind)],) -> (JitResult, u64) {let program = assemble(|_| instructions.clone());- let (result, machine) = run_program(&program, arguments, |machine| {- machine.frame[1] = lexical.address();- machine.frame[12] = variable.address();- });+ let exit_sites = exits+ .iter()+ .map(|(index, kind)| (program.offsets[*index], *kind))+ .collect();+ let (result, machine) = run_program_with_snapshot(+ &program,+ arguments,+ |snapshot| snapshot.executables[0].exit_sites = exit_sites,+ |machine| {+ machine.frame[1] = lexical.address();+ machine.frame[12] = variable.address();+ },+ );(result, machine.vm[VM_SLOW_PUTS_WORD])}@@ -1914,7 +1925,7 @@ fn bindings() {);let middle = FakeEnvironment::new(&[value::int32(5)], &[0], None, Some(&outer));let inner = FakeEnvironment::new(&[value::int32(9)], &[BINDING_MUTABLE], Some(1), Some(&middle));- let get = |hops, index, initialized| {+ let get = |hops, index, initialized, exits: &[(usize, ExitKind)]| {let get = if initialized {Instruction::GetInitializedBinding {value_feedback: 0,@@ -1935,22 +1946,25 @@ fn bindings() {&[],&inner,&outer,+ exits,);result};- assert_eq!(get(0, 0, false), returned(value::int32(9)));- assert_eq!(get(1, 0, true), returned(value::int32(5)));- assert_eq!(get(2, 3, false), returned(value::int32(4)));+ let uninitialized_exit = [(1, ExitKind::Uninitialized)];+ assert_eq!(get(0, 0, false, &[]), returned(value::int32(9)));+ assert_eq!(get(1, 0, true, &[]), returned(value::int32(5)));+ assert_eq!(get(2, 3, false, &[]), returned(value::int32(4)));+ assert_eq!(get(2, 1, false, &[]).status, RESUME, "uninitialized bindings exit");assert_eq!(- get(2, 1, false).status,+ get(2, 1, false, &uninitialized_exit).status,EXIT_INTERPRETER,- "uninitialized bindings throw"+ "uninitialized bindings throw where they exited before");// Initialized bindings are never checked; the returned empty value becomes undefined.- assert_eq!(get(2, 1, true), returned(value::UNDEFINED));+ assert_eq!(get(2, 1, true, &[]), returned(value::UNDEFINED));// The callee and an undefined `this`.- let callee_and_this = |hops, index, returned_operand| {+ let callee_and_this = |hops, index, returned_operand, exits: &[(usize, ExitKind)]| {run_with_environments(vec![Instruction::Enter,@@ -1968,12 +1982,17 @@ fn bindings() {&[],&inner,&outer,+ exits,).0};- assert_eq!(callee_and_this(2, 2, r(5)), returned(value::int32(3)));- assert_eq!(callee_and_this(2, 2, r(6)), returned(value::UNDEFINED));- assert_eq!(callee_and_this(2, 1, r(5)).status, EXIT_INTERPRETER);+ assert_eq!(callee_and_this(2, 2, r(5), &[]), returned(value::int32(3)));+ assert_eq!(callee_and_this(2, 2, r(6), &[]), returned(value::UNDEFINED));+ assert_eq!(callee_and_this(2, 1, r(5), &[]).status, RESUME);+ assert_eq!(+ callee_and_this(2, 1, r(5), &uninitialized_exit).status,+ EXIT_INTERPRETER+ );// Sets of initialized mutable bindings, with their flags in the shape,// after the shape's in the rare data, or in rare data only.@@ -1995,6 +2014,7 @@ fn bindings() {&[value::int32(77)],&inner,&outer,+ &[],).1};@@ -2029,6 +2049,7 @@ fn bindings() {&[value::int32(8), value::TRUE],&inner,&outer,+ &[],);assert_eq!(result, returned(value::int32(0)));assert_eq!(outer.values[1], value::int32(8));@@ -2567,7 +2588,9 @@ fn checks_take_the_slow_path_only_when_they_fail() {Instruction::Return { value: c(1) },]});- let (result, machine) = run_program(&program, &[argument], |machine| {+ let pc = program.offsets[1];+ let exits = |snapshot: &mut Snapshot| snapshot.executables[0].exit_sites = vec![(pc, ExitKind::Uninitialized)];+ let (result, machine) = run_program_with_snapshot(&program, &[argument], exits, |machine| {// The this value register.machine.frame[FRAME_HEADER_WORDS + 2] = argument;});@@ -2610,6 +2633,17 @@ fn checks_take_the_slow_path_only_when_they_fail() {"{value:#x}");}++ let program = assemble(|_| {+ vec![+ Instruction::Enter,+ Instruction::ThrowIfTDZ { src: argument(0) },+ Instruction::Return { value: c(1) },+ ]+ });+ let (result, machine) = run_program(&program, &[value::EMPTY], |_| {});+ assert_eq!(result.status, RESUME);+ assert_eq!(machine.vm[VM_SLOW_PUTS_WORD], 0);}#[test]diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex f4c04e9f7aa..d8779191763 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -336,6 +336,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {| Op::LoadPropertyIteratorKey => with_inputs(op.name()),Op::CheckBounds| Op::CheckNotHole+ | Op::CheckInitialized| Op::CheckTypedArray| Op::CheckArray| Op::CheckNonNegativeInt32diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 9cab76ee60f..a3332a38814 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -421,8 +421,8 @@ impl Comparison {/// `CheckShape`, `CheckValue`, `CheckClosure`, `CheckAccessorFunction`,/// `CheckElements`, `CheckTypedArray`, `CheckArray`, `CheckNonNegativeInt32`,/// `CheckIdentityComparable`, `CheckAppendableArray`, `CheckBounds`,-/// `CheckTypedArrayStorage`, `CheckNotHole`), and a `Refine` on the edge of a-/// branch, has that input as its value, refined:+/// `CheckTypedArrayStorage`, `CheckNotHole`, `CheckInitialized`), and a+/// `Refine` on the edge of a branch, has that input as its value, refined:/// known to pass. Nodes that rely on the check take the refined value as their/// input instead of the input itself, so that the check is a data dependency/// of theirs: passes move or share them exactly when they can move or share@@ -717,6 +717,10 @@ pub enum Op {/// `LoadElementAt` finds there) from here on. Exits with/// `ExitKind::OutOfBounds` where it is one.CheckNotHole,+ /// The tagged input 0, the value of a binding or local variable, which+ /// is known to be initialized (not the empty value) from here on. Exits+ /// with `ExitKind::Uninitialized` where it is not.+ CheckInitialized,/// The address of the cell in the tagged input 0, as a `Repr::Pointer`./// Nodes accessing an object take it as an extra input, so that one/// decoding of the tagged value serves all of them.@@ -1435,7 +1439,7 @@ impl Op {writes: Locations::ELEMENTS,..P::PURE},- Op::CheckBounds | Op::CheckNotHole | Op::CheckTypedArrayStorage => P::PURE,+ Op::CheckBounds | Op::CheckNotHole | Op::CheckInitialized | Op::CheckTypedArrayStorage => P::PURE,Op::AllocateObject { .. } => P {allocates: true,..P::PURE@@ -1723,6 +1727,7 @@ impl Op {Op::LoadElementAt { .. } => "LoadElementAt",Op::StoreElementAt { .. } => "StoreElementAt",Op::CheckNotHole => "CheckNotHole",+ Op::CheckInitialized => "CheckInitialized",Op::CellAddress => "CellAddress",Op::AllocateObject { .. } => "AllocateObject",Op::InitializeNamed { .. } => "InitializeNamed",@@ -1832,7 +1837,8 @@ impl Op {| Op::CheckAppendableArray| Op::CheckBounds| Op::CheckTypedArrayStorage- | Op::CheckNotHole => Some(0),+ | Op::CheckNotHole+ | Op::CheckInitialized => Some(0),_ => None,}}@@ -1864,6 +1870,7 @@ impl Op {Op::CheckObject => Some(ExitKind::NotObject),Op::CheckElements { .. } | Op::CheckTypedArray => Some(ExitKind::BadElements),Op::CheckBounds | Op::CheckNotHole | Op::CheckTypedArrayStorage => Some(ExitKind::OutOfBounds),+ Op::CheckInitialized => Some(ExitKind::Uninitialized),Op::CheckInt32 | Op::CheckFloat64Int32 => Some(ExitKind::NotInt32),Op::CheckArray => Some(ExitKind::BadType),Op::CheckNonNegativeInt32 => Some(ExitKind::Overflow),@@ -2403,6 +2410,41 @@ impl Graph {}id}++ /// Whether `id` is `value`, or refines it through any number of+ /// refinements.+ pub fn refines(&self, mut id: NodeId, value: NodeId) -> bool {+ while id != value {+ let Some(index) = self.node(id).op.refined_input() else {+ return false;+ };+ id = self.node(id).inputs[index];+ }+ true+ }++ /// Whether `id` always has the value of `value`, because it refines+ /// `value` or a phi whose inputs all have that value.+ pub fn has_value_of(&self, id: NodeId, value: NodeId) -> bool {+ let mut pending = vec![id];+ let mut seen = Vec::new();+ while let Some(mut node) = pending.pop() {+ while node != value+ && let Some(index) = self.node(node).op.refined_input()+ {+ node = self.node(node).inputs[index];+ }+ if node == value || seen.contains(&node) {+ continue;+ }+ seen.push(node);+ if !matches!(self.node(node).op, Op::Phi) {+ return false;+ }+ pending.extend(self.node(node).inputs.iter().copied());+ }+ true+ }}#[cfg(test)]diff --git a/Tests/LibJS/Runtime/jit/environment-bindings.js b/Tests/LibJS/Runtime/jit/environment-bindings.jsindex 3afc312814c..32067744eaa 100644--- a/Tests/LibJS/Runtime/jit/environment-bindings.js+++ b/Tests/LibJS/Runtime/jit/environment-bindings.js@@ -12,6 +12,112 @@ test("reading an uninitialized binding throws", () => {expect(() => readsEarly(true)).toThrowWithMessage(ReferenceError, "value");});+test("reading the truthiness of an uninitialized binding in a loop throws", () => {+ function makeReader(early) {+ const read = () => {+ let result = 0;+ for (let i = 0; i < 2; ++i) result = !value;+ return result;+ };+ if (early) return read;+ let value = undefined;+ return read;+ }+ const initialized = makeReader(false);+ const uninitialized = makeReader(true);+ jit.prepare(initialized);+ for (let i = 0; i < 10; ++i) expect(initialized()).toBeTrue();+ for (let i = 0; i < 3; ++i) {+ jit.discard(initialized);+ const compiled = jit.compile(initialized);+ if (!jit.forcesExits) expect(compiled).toBe(jit.enabled);+ expect(uninitialized).toThrowWithMessage(ReferenceError, "value");+ expect(initialized()).toBeTrue();+ }+});++test("reading the truthiness of an uninitialized local in a loop throws", () => {+ function read(clause) {+ let result = 0;+ switch (clause) {+ case 0:+ let value = undefined;+ case 1:+ for (let i = 0; i < 2; ++i) result = !value;+ }+ return result;+ }+ jit.prepare(read);+ for (let i = 0; i < 10; ++i) {+ expect(read(0)).toBeTrue();+ expect(read(2)).toBe(0);+ }+ for (let i = 0; i < 3; ++i) {+ jit.discard(read);+ const compiled = jit.compile(read);+ if (!jit.forcesExits) expect(compiled).toBe(jit.enabled);+ expect(() => read(1)).toThrowWithMessage(ReferenceError, "not initialized");+ expect(read(0)).toBeTrue();+ }+});++test("reading the truthiness of an uninitialized local in a branch of a loop throws", () => {+ function read(clause, choose) {+ let result = 0;+ switch (clause) {+ case 0:+ let value = undefined;+ case 1:+ for (let i = 0; i < 2; ++i) {+ if (choose) result = !value;+ }+ }+ return result;+ }+ jit.prepare(read);+ for (let i = 0; i < 10; ++i) {+ expect(read(0, true)).toBeTrue();+ expect(read(0, false)).toBe(0);+ }+ for (let i = 0; i < 3; ++i) {+ jit.discard(read);+ const compiled = jit.compile(read);+ if (!jit.forcesExits) expect(compiled).toBe(jit.enabled);+ expect(() => read(1, true)).toThrowWithMessage(ReferenceError, "not initialized");+ expect(read(0, true)).toBeTrue();+ }+});++test("reading the truthiness of a local checked in both branches of a loop throws", () => {+ function read(clause, choose) {+ let result = 0;+ let copy = 0;+ switch (clause) {+ case 0:+ let value = undefined;+ case 1:+ for (let i = 0; i < 2; ++i) {+ if (choose) copy = value;+ else copy = value;+ result = !copy;+ }+ }+ return result;+ }+ jit.prepare(read);+ for (let i = 0; i < 10; ++i) {+ expect(read(0, true)).toBeTrue();+ expect(read(0, false)).toBeTrue();+ }+ for (let i = 0; i < 3; ++i) {+ jit.discard(read);+ const compiled = jit.compile(read);+ if (!jit.forcesExits) expect(compiled).toBe(jit.enabled);+ expect(() => read(1, true)).toThrowWithMessage(ReferenceError, "not initialized");+ expect(read(0, true)).toBeTrue();+ }+});+test("assigning a constant binding throws", () => {function assigns(assign) {const constant = 1;