Truly independent web browser
LibJS/JIT: Decide branches that a branch on the same values decided
Andreas Kling1225eb56559d
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 21543eff735..683d6cd0304 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -314,7 +314,7 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i| Representation selection | Phis of int32, bool or float64 values become unboxed phis, and int32 inputs of float64 phis are converted. Tagged inputs of an int32 phi that the code checks somewhere (or of the phis connected to it) are checked where they enter, exiting to the start of the phi's block, unless such a check exited there before. || Simplification | Again, for what unboxing made foldable. || Global value numbering | A CSE-able node computing what a dominating node computed is replaced by it, so that check elimination sees one value where the builder computed it twice (like the index of `k[Math.abs(j)]` in two expressions). Memory reads are left to check elimination. |-| Check elimination | A forward dataflow of facts removes checks that passed already and reuses loads whose value is known; may turn shape checks into `AssumeValid` plus a stable shape dependency. |+| Check elimination | A forward dataflow of facts removes checks that passed already, decides branches that a branch on the same values decided before, and reuses loads whose value is known; may turn shape checks into `AssumeValid` plus a stable shape dependency. || Simplification | Again, for what the branches that check elimination decided left foldable (like the double path of `Math.abs` of an int32). || Global value numbering | Again, for the nodes that check elimination and simplification made the same. || Loop invariant code motion | Gives loops entered from several blocks a merged preheader, then moves effect-free nodes with inputs from outside the loop to it; nodes that may exit only from blocks every iteration runs, exiting to the loop header, and not where that kind of exit was taken there before. |diff --git a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rsindex d6431e3a0c3..32238071234 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs@@ -15,7 +15,9 @@//! until what the back edges bring agrees with it.//!//! Branches on the kind of a value tell their targets what it is, and-//! become jumps where what is known decides them.+//! become jumps where what is known decides them. So do branches on values+//! alone (comparisons, builtin tests), which go the way a branch on the same+//! values went before.//!//! With those facts, checks that already passed are removed, loads of a//! property whose value is known are replaced by that value (including@@ -35,6 +37,7 @@use super::edit;use super::edit::Constants;use super::edit::Replacements;+use super::facts::BranchKey;use super::facts::ElementCount;use super::facts::Facts;use super::facts::Location;@@ -242,6 +245,32 @@ fn visit_block(facts.set_failed(value, condition);return vec![(if_true, passed), (if_false, facts)];}+ // A branch on values alone goes the way a branch on the same values+ // went before.+ if let Op::Branch {+ condition,+ if_true,+ if_false,+ } = graph.node(control).op+ {+ let inputs = graph+ .node(control)+ .inputs+ .iter()+ .map(|input| decisions.value(graph, *input))+ .collect::<InlineVec<NodeId, 2>>();+ if let Some(key) = BranchKey::of(graph, condition, &inputs) {+ if let Some(holds) = facts.branch_outcome(&key) {+ let target = if holds { if_true } else { if_false };+ decisions.controls.push((control, Op::Jump { target }));+ return vec![(target, facts)];+ }+ let mut passed = facts.clone();+ passed.set_branch_outcome(key, true);+ facts.set_branch_outcome(key, false);+ return vec![(if_true, passed), (if_false, facts)];+ }+ }let Op::ShapeSwitch { cases } = graph.node(control).op.clone() else {let successors = graph.successors(block);let Some((last, others)) = successors.split_last() else {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs b/Libraries/LibJS/JIT/Rust/src/passes/facts.rsindex cb513967a51..9876a33bad9 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/facts.rs@@ -94,6 +94,51 @@ impl<K: Ord, V> FactMap<K, V> {}}+/// A branch on a condition that tests nothing but the values of its inputs,+/// which never change, so that a branch decides every later one on the same+/// values: the condition, and the inputs, where constants are their values.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub struct BranchKey {+ condition: u64,+ inputs: [BranchInput; 2],+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum BranchInput {+ Absent,+ Value(NodeId),+ Constant(u64),+}++impl BranchKey {+ /// The key of a branch on `condition` of `inputs` (as the analysis knows+ /// them), if the condition tests their values alone.+ pub fn of(graph: &Graph, condition: BranchCondition, inputs: &[NodeId]) -> Option<Self> {+ let condition = match condition {+ BranchCondition::Bool => 0,+ BranchCondition::Int32(comparison) => 1 << 32 | comparison as u64,+ BranchCondition::Float64(comparison) => 2 << 32 | comparison as u64,+ BranchCondition::TaggedEquals { equal } => 3 << 32 | u64::from(equal),+ BranchCondition::Builtin(builtin) => 4 << 32 | u64::from(builtin),+ BranchCondition::BindingMutable { index } => 5 << 32 | u64::from(index),+ _ => return None,+ };+ let input = |index: usize| match inputs.get(index) {+ None => BranchInput::Absent,+ Some(input) => graph+ .constant_value(*input)+ .map_or(BranchInput::Value(*input), BranchInput::Constant),+ };+ if inputs.len() > 2 {+ return None;+ }+ Some(Self {+ condition,+ inputs: [input(0), input(1)],+ })+ }+}+/// What kind of value a value is known to be, which never changes.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ValueKind {@@ -280,6 +325,9 @@ pub(super) struct Facts {/// be by its definition: what replaces a check that is known to pass,/// so that the nodes using it stay behind the check that passed.refinements: Rc<FactMap<NodeId, NodeId>>,+ /// Whether branches on conditions of the values they test alone (see+ /// `BranchKey`) held, where they went the same way on every path here.+ branch_outcomes: Rc<FactMap<BranchKey, bool>>,}impl Facts {@@ -324,6 +372,19 @@ impl Facts {Kinds::of_condition(condition).is_some()}+ /// Whether a branch like the one `key` names held, if it went the same+ /// way on every path here.+ pub fn branch_outcome(&self, key: &BranchKey) -> Option<bool> {+ self.branch_outcomes.get(key).copied()+ }++ /// Records whether a branch like the one `key` names held.+ pub fn set_branch_outcome(&mut self, key: BranchKey, holds: bool) {+ if self.branch_outcome(&key) != Some(holds) {+ Rc::make_mut(&mut self.branch_outcomes).insert(key, holds);+ }+ }+/// Records that `value` is of `kind`, narrowing what was known.pub fn set_value_kind(&mut self, value: NodeId, kind: ValueKind) {self.narrow_kinds(value, Kinds::of(kind));@@ -635,6 +696,9 @@ impl Facts {unvalidated.extend(other.unvalidated.iter().copied());});merged.code_valid &= other.code_valid;+ narrow_unless_shared(&mut merged.branch_outcomes, &other.branch_outcomes, |outcomes| {+ outcomes.retain(|key, holds| other.branch_outcomes.get(key) == Some(holds));+ });narrow_unless_shared(&mut merged.refinements, &other.refinements, |refinements| {refinements.retain(|key, value| other.refinements.get(key) == Some(value));});diff --git a/Tests/LibJS/JIT/ir/check-elimination-branch-outcomes.js b/Tests/LibJS/JIT/ir/check-elimination-branch-outcomes.jsnew file mode 100644index 00000000000..d81a23a5bde--- /dev/null+++ b/Tests/LibJS/JIT/ir/check-elimination-branch-outcomes.js@@ -0,0 +1,38 @@+// A branch on values alone, like a comparison, goes the way a branch on the same values went before, where only one+// edge of that branch leads, and becomes a jump there.++function nested(a, b) {+ if (a < b) {+ if (a < b) return 1;+ return 2;+ }+ if (a < b) return 3;+ return 4;+}+jit.prepare(nested);+for (let i = 0; i < 10; ++i) nested(i, 5);+jit.compile(nested);++// CHECK-FUNCTION: nested+// CHECK-PASS: check elimination+// CHECK-COUNT-1: BranchBool+// CHECK: Return (#4)+// CHECK: Return (#1)++// Where both edges meet again, neither outcome is known.++function merged(a, b, c) {+ let s = 0;+ if (a < b) s = c;+ if (a < b) s = (s + 1) | 0;+ return s;+}+jit.prepare(merged);+for (let i = 0; i < 10; ++i) merged(i, 5, 7);+jit.compile(merged);++// CHECK-FUNCTION: merged+// CHECK-PASS: check elimination+// CHECK-COUNT-2: BranchBool++console.log(nested(1, 2), nested(2, 1), merged(1, 2, 3), merged(2, 1, 3));