Skip to content

Truly independent web browser

LibJS: Keep every frame slot in an SSA value in the JIT's builder

Andreas Kling3acedb360da6
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 9a43f4197ec..29bbbc316c3 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -46,15 +46,17 @@ Blocks without predecessors are entries: block 0, the on-stack replacement entri
entries of generators (section 4.1) and the catch entries of exception handlers (section 4.2). Every
block is reachable from one.
-The compiled function's slots are SSA values. The builder tracks, per slot, whether only frame
-memory holds it or which value holds it (and whether memory holds that too). Merges and loop
-headers never write frame memory: a slot that every path leaves in memory stays there, a slot the
-paths disagree on (or a loop assigns) gets a phi, with loads at the predecessors that only have it
-in memory. Frame memory is written only where something reads it: before calls that read the
-frame (`StoreSlot`), where the compiled function assigns an argument that its legacy `arguments`
-shows (which any code it calls can read), and by exits and leaves through the translator. The
-this value register is the exception at loop headers: slow paths write it to memory, so loops
-keep it there.
+The compiled function's slots are SSA values. The builder tracks, per slot (the reserved registers
+included), which value holds it and whether frame memory holds that value too. Values come from
+frame memory (`LoadSlot`) where the code starts using it: every slot live at an entry, and the slots
+a node that writes the frame wrote, right after it. Merges and loop headers never write frame
+memory: a slot the paths disagree on (or a loop assigns) gets a phi, except that a slot every path
+loaded, and memory still holds, is loaded again at the merge (loop invariant code motion takes such
+loads out of loops). The loads at the start of the function move down to where their uses meet,
+outside of loops, as far as nothing on the way may write the slot's memory. Frame memory is written
+only where something reads it: before calls that read the frame and before `Suspend` (`StoreSlot`),
+where the compiled function assigns an argument that its legacy `arguments` shows (which any code it
+calls can read), and by exits and leaves through the translator.
### 3.1 Effects
@@ -127,8 +129,8 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| **Values** | | | | | |
| Constant | A NaN-boxed constant. | | | | cse |
| Phi | One input per predecessor, in predecessor order. | | | | |
-| LoadSlot | Reads a frame slot. | | Frame | | |
-| StoreSlot | Writes input 0 to a frame slot: a reserved register (the this value, the saved lexical environment), a written constant, an argument the legacy `arguments` shows, or a slot the next call reading the frame or `Suspend` reads. The verifier enforces this. | | | Frame | |
+| LoadSlot | Reads a frame slot: at an entry, right after a node that writes it, or at a merge of loads of it. | | Frame | | |
+| StoreSlot | Writes input 0 to a frame slot: a written constant, an argument the legacy `arguments` shows, or a slot the next call reading the frame or `Suspend` reads. The verifier enforces this. | | | Frame | |
| BoxInt32, BoxBool | The tagged value of an unboxed input. | | | | cse |
| CheckInt32 | Input 0 as an int32; exits unless it is one. | E | | | cse |
| CheckFloat64Int32 | The float64 input 0 as an int32; exits unless it is one (-0 is none). What an int32 check of a boxed double becomes once checks of doubles no longer go. | E | | | cse |
@@ -318,7 +320,8 @@ that `Suspend` marks the value as awaited (`yield_is_await`), which tells an asy
await it rather than yield it.
Each continuation then gets a resume entry (`builder/osr.rs`), like an on-stack replacement entry:
-a block without predecessors that loads the slots live there from the frame and jumps to the
+a block without predecessors that loads the slots live there from the frame (the accumulator the
+runtime resumes with among them) and jumps to the
continuation's block, which nothing else in compiled code reaches. Both kinds of entry are listed in
`Graph::osr_entries` by pc, since both continue a frame whose memory holds every value at that pc.
`GeneratorObject::execute()` runs the generator from its continuation through `run_executable()`,
@@ -358,7 +361,7 @@ compiled again with the entry once catches keep happening there.
Callees with handlers are inlined only if none of their handlers caught an exception before the
compile, and their handlers get no blocks at all. An exception that one of them catches unwinds into
the callee's materialized frame, the leave writes the frames, and the interpreter runs the handler.
-Inlined frames do not list their exception register in frame states, so the leave keeps the
+No frame state lists an exception register, which only the runtime writes, so the leave keeps the
exception the unwinder put there. The leave counts such a catch like an exit, so that the code is
compiled again once catches keep happening there, and the recompile calls the callee instead.
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
index 1ab66346307..4f45312348d 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
@@ -131,7 +131,7 @@ impl GraphBuilder<'_> {
self.function
.layout
.tracked_index(operand)
- .is_some_and(|slot| matches!(self.frame.slots[slot], super::SlotState::Value { node, .. } if self.is_virtual_arguments(node)))
+ .is_some_and(|slot| self.is_virtual_arguments(self.frame.slots[slot].node))
}
/// Builds `CreateArguments` as a virtual arguments object, if it can be
@@ -178,10 +178,7 @@ impl GraphBuilder<'_> {
let slot = layout
.tracked_index(Operand::from_raw(layout.arguments_base() + argument))
.expect("arguments are tracked");
- match self.frame.slots[slot] {
- super::SlotState::Value { node, .. } => Some(node),
- super::SlotState::InMemory => unreachable!("inlined callees hold their slots as values"),
- }
+ Some(self.frame.slots[slot].node)
}
/// The values the call of the inlined callee being built passed it, all
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
index 379d8ec3bf1..eae094e1a06 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
@@ -19,7 +19,6 @@
//! same entries.
use super::GraphBuilder;
-use super::SlotState;
use crate::bytecode::Operand;
use crate::ir::AccessorPart;
use crate::ir::Block;
@@ -245,10 +244,7 @@ impl GraphBuilder<'_> {
if cache.kind != PropertyCacheKind::Megamorphic {
return None;
}
- let SlotState::Value { node, .. } = self.peek(object) else {
- return None;
- };
- let shape = self.fresh_shape(node)?;
+ let shape = self.fresh_shape(self.peek(object)?.node)?;
let entry = cache
.entries
.iter()
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
index bfe890c8040..a4912c52dd3 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
@@ -55,13 +55,8 @@ impl GraphBuilder<'_> {
// NB: The operand can be a copy of the local that is checked, when the frame is too large for
// instructions to name the local.
for slot in &mut self.frame.slots {
- if let SlotState::Value { node, in_sync } = *slot
- && node == value
- {
- *slot = SlotState::Value {
- node: initialized,
- in_sync,
- };
+ if slot.node == value {
+ slot.node = initialized;
}
}
Ok(Flow::Continue)
@@ -208,21 +203,20 @@ impl GraphBuilder<'_> {
.layout
.tracked_index(this_register)
.expect("the this value register is tracked");
- let known = match self.frame.slots[slot] {
- SlotState::Value { node, .. } => Some(self.graph.constant_value(node)),
- SlotState::InMemory => None,
- };
+ let known = self.graph.constant_value(self.frame.slots[slot].node);
// NB: An inlined callee's `this` is bound by its caller, or empty if
// the callee never reads it.
- if self.function.is_virtual() && known.is_some_and(|bits| bits != Some(value::EMPTY)) {
+ if self.function.is_virtual() && known != Some(value::EMPTY) {
return Ok(Flow::Continue);
}
- if known.flatten().is_some_and(|bits| bits != value::EMPTY) {
+ if known.is_some_and(|bits| bits != value::EMPTY) {
return Ok(Flow::Continue);
}
let frame_state = self.eager_frame_state();
let this_value = self.read(this_register)?;
- let in_sync = matches!(self.frame.slots[slot], SlotState::Value { in_sync: true, .. });
+ // NB: The slow path writes the this value it resolves to the frame, so frame memory holds the result where it
+ // held the this value before.
+ let in_sync = self.frame.slots[slot].in_sync;
let empty = self.constant(value::EMPTY);
let (hot, cold) = self.branch_with_cold_side(
BranchCondition::TaggedEquals { equal: true },
@@ -234,7 +228,7 @@ impl GraphBuilder<'_> {
let resolved = self.emit_call_slow_path(Vec::new(), frame_state, Some(Repr::Tagged));
self.join_blocks(vec![hot, cold]);
let result = self.add_phi(vec![this_value, resolved]);
- self.frame.slots[slot] = SlotState::Value { node: result, in_sync };
+ self.frame.slots[slot] = SlotState { node: result, in_sync };
Ok(Flow::Continue)
}
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 50da7f7e1c1..669d4f66eb6 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -448,19 +448,41 @@ impl<'a> GraphBuilder<'a> {
self.graph.add_frame_state(frame_state)
}
+ /// Like `resume_after_frame_state()`, for an instruction that writes the slots `outputs` to the frame where it
+ /// does not continue: the frame state lists them as held by the frame. Frames of inlined calls have no slots in
+ /// sync to say so.
+ pub(super) fn resume_after_frame_state_with_outputs_in_frame(
+ &mut self,
+ dst: u32,
+ outputs: &[usize],
+ ) -> FrameStateId {
+ let live = self.function.liveness.live_out(self.function.instruction_index);
+ let mut frame_state = self.new_frame_state(&live, ResumeMode::ResumeAfter { dst });
+ for slot in outputs.iter().copied().filter(|slot| live.contains(*slot)) {
+ let operand = self.function.layout.operand_for_tracked_index(slot).raw();
+ frame_state.values.retain(|(listed, _)| *listed != operand);
+ // NB: Exits never clear the reserved registers, which frames keep.
+ if slot >= crate::bytecode::RESERVED_REGISTER_COUNT as usize
+ && let Err(position) = frame_state.in_frame.binary_search(&operand)
+ {
+ frame_state.in_frame.insert(position, operand);
+ }
+ }
+ self.graph.add_frame_state(frame_state)
+ }
+
/// The slots in `live` whose value frame memory holds, which a frame
/// state of the function being walked lists without a value: the
- /// compiled function's slots that are in sync, and the slots a slow path
- /// wrote into the frames pushed for it. Reserved registers are not
- /// listed.
+ /// compiled function's slots that are in sync. Reserved registers are
+ /// not listed.
fn frame_state_in_frame(&self, live: &BitSet) -> Vec<u32> {
- let is_virtual = self.function.is_virtual();
+ if self.function.is_virtual() {
+ return Vec::new();
+ }
// NB: Exits never clear the reserved registers, which frames keep.
live.iter()
- .filter(|slot| *slot >= crate::bytecode::RESERVED_REGISTER_COUNT as usize)
- .filter(|slot| match self.frame.slots[*slot] {
- SlotState::InMemory => true,
- SlotState::Value { in_sync, .. } => in_sync && !is_virtual,
+ .filter(|slot| {
+ *slot >= crate::bytecode::RESERVED_REGISTER_COUNT as usize && self.frame.slots[*slot].in_sync
})
.map(|slot| self.function.layout.operand_for_tracked_index(slot).raw())
.collect()
@@ -468,25 +490,24 @@ impl<'a> GraphBuilder<'a> {
/// The values a frame state of the function being walked lists for the
/// slots in `live`: those frame memory does not hold, or every one for
- /// virtual frames but their exception register. Inlined callees that are
+ /// virtual frames, but the exception register. Inlined callees that are
/// not strict list all their passed arguments too, since their legacy
/// `arguments` shows them in the frames exits and slow paths materialize.
fn frame_state_values(&self, live: &BitSet) -> Vec<(u32, NodeId)> {
let is_virtual = self.function.is_virtual();
- // NB: Materialized frames start with an empty exception register, and only the runtime writes it: when a
- // handler of the frame catches an exception, before a leave writes the rest of the frame.
+ // NB: Only the runtime writes the exception register (materialized frames start with it empty): when a
+ // handler of the frame catches an exception, before a leave writes the rest of the frame, which must keep
+ // it. Compiled code only ever holds what frame memory holds.
let exception_register = self
.function
.layout
.tracked_index(Operand::from_raw(crate::bytecode::EXCEPTION_REGISTER));
let mut values = live
.iter()
- .filter(|slot| !is_virtual || Some(*slot) != exception_register)
- .filter_map(|slot| match self.frame.slots[slot] {
- SlotState::Value { node, in_sync } if is_virtual || !in_sync => {
- Some((self.function.layout.operand_for_tracked_index(slot).raw(), node))
- }
- _ => None,
+ .filter(|slot| Some(*slot) != exception_register)
+ .filter_map(|slot| {
+ let SlotState { node, in_sync } = self.frame.slots[slot];
+ (is_virtual || !in_sync).then(|| (self.function.layout.operand_for_tracked_index(slot).raw(), node))
})
.collect::<Vec<_>>();
for (operand, node) in self.legacy_argument_values() {
@@ -515,9 +536,7 @@ impl<'a> GraphBuilder<'a> {
let mut values = Vec::new();
for argument in 0..layout.number_of_arguments {
let slot = (layout.registers_and_locals_count + argument) as usize;
- if let SlotState::Value { node, .. } = self.frame.slots[slot] {
- values.push((layout.arguments_base() + argument, node));
- }
+ values.push((layout.arguments_base() + argument, self.frame.slots[slot].node));
}
for (argument, node) in (layout.number_of_arguments..).zip(&call.untracked_arguments) {
values.push((layout.arguments_base() + argument, *node));
@@ -684,10 +703,10 @@ impl<'a> GraphBuilder<'a> {
let Instruction::Call { callee, .. } = instruction else {
return Ok(None);
};
- let SlotState::Value { node, .. } = self.peek(*callee) else {
+ let Some(slot) = self.peek(*callee) else {
return Ok(None);
};
- match self.graph.constant_value(node) {
+ match self.graph.constant_value(slot.node) {
Some(bits) => self.try_direct_call_of_function(instruction, bits),
None => Ok(None),
}
@@ -814,16 +833,6 @@ impl<'a> GraphBuilder<'a> {
.function_fields
.is_some_and(|fields| fields.has_script_or_module_of(&compiled_function_fields))
};
- if self.function.has_legacy_arguments() {
- let layout = self.function.layout;
- let arguments_are_values = (0..layout.number_of_arguments).all(|argument| {
- let slot = (layout.registers_and_locals_count + argument) as usize;
- matches!(self.frame.slots[slot], SlotState::Value { .. })
- });
- if !arguments_are_values {
- return None;
- }
- }
let inlined = core::iter::once(&self.function).chain(self.callers.iter().skip(1));
if !inlined
.into_iter()
@@ -1077,9 +1086,7 @@ impl<'a> GraphBuilder<'a> {
/// phi of a few function constants in the current block, like the
/// methods a property lookup found for the shapes it switched on.
fn callee_cases(&self, callee: Operand) -> Option<Vec<(u64, Option<u32>)>> {
- let SlotState::Value { node, .. } = self.peek(callee) else {
- return None;
- };
+ let node = self.peek(callee)?.node;
// NB: Phis of loop headers get the inputs of their back edges later.
let block = &self.graph.blocks[self.block.index()];
if block.is_loop_header || !block.phis.contains(&node) {
@@ -1119,12 +1126,7 @@ impl<'a> GraphBuilder<'a> {
}
// NB: The phi reaches only the first case, so only the callee's slot,
// which each case gives its function, may hold it.
- let holders = self
- .frame
- .slots
- .iter()
- .filter(|slot| matches!(slot, SlotState::Value { node, .. } if *node == callee_phi))
- .count();
+ let holders = self.frame.slots.iter().filter(|slot| slot.node == callee_phi).count();
if holders != 1 {
return None;
}
@@ -1216,10 +1218,9 @@ impl<'a> GraphBuilder<'a> {
unreachable!("calls are generic instructions");
};
// NB: Every case continues with the frame the call starts with, but
- // for the destination, which the cases' values join in, and slots
- // only frame memory held, which reading the operands in a case
- // may load. The slow path keeps the destination in an SSA value,
- // and touches no other slot.
+ // for the destination, which the cases' values join in. The slow
+ // path keeps the destination in an SSA value, and touches no
+ // other slot.
let Some(dst_slot) = self.function.layout.tracked_index(*dst) else {
return Ok(None);
};
@@ -1227,22 +1228,17 @@ impl<'a> GraphBuilder<'a> {
.chain(std::iter::once(*this_value))
.chain(arguments.iter().copied())
.collect::<Vec<_>>();
- if self.is_reserved(*dst)
- || self.graph.legacy_arguments.contains(&dst.raw())
+ if self.graph.legacy_arguments.contains(&dst.raw())
|| info.reads_whole_frame
|| crate::codegen::slow_path_call(OpCode::Call).is_none()
- || !super::slow_paths::is_ssa_slow_path_output(&self.function.layout, *dst, self.function.is_virtual())
|| operands.iter().any(|operand| self.holds_virtual_arguments(*operand))
{
return Ok(None);
}
- let SlotState::Value {
+ let SlotState {
node: callee_phi,
in_sync: callee_in_sync,
- } = self.peek(*callee)
- else {
- unreachable!("the callee is a phi");
- };
+ } = self.peek(*callee).expect("the callee is a phi");
let callee_slot = self
.function
.layout
@@ -1251,12 +1247,7 @@ impl<'a> GraphBuilder<'a> {
let edges = self.callee_case_edges(callee_phi, &cases);
let callee_value = match edges {
Some(_) => None,
- None => {
- for operand in &operands {
- self.read(*operand)?;
- }
- Some(self.read(*callee)?)
- }
+ None => Some(self.read(*callee)?),
};
let join = self.block;
let frame = self.frame.clone();
@@ -1270,7 +1261,7 @@ impl<'a> GraphBuilder<'a> {
// NB: Here the callee is the case's function, which frame
// states of the case give it as.
let function = self.constant(*bits);
- self.frame.slots[callee_slot] = SlotState::Value {
+ self.frame.slots[callee_slot] = SlotState {
node: function,
in_sync: callee_in_sync,
};
@@ -1310,15 +1301,11 @@ impl<'a> GraphBuilder<'a> {
.expect("calls have a slow path on values"),
};
if matches!(flow, Flow::Continue) {
- let SlotState::Value { node, .. } = self.frame.slots[dst_slot] else {
- unreachable!("the destination holds the call's value");
- };
+ let node = self.frame.slots[dst_slot].node;
debug_assert!(
(0..frame.slots.len()).all(|slot| slot == dst_slot
|| (slot == callee_slot && edges.is_some())
- || frame.slots[slot] == self.frame.slots[slot]
- || (frame.slots[slot] == SlotState::InMemory
- && matches!(self.frame.slots[slot], SlotState::Value { in_sync: true, .. }))),
+ || frame.slots[slot] == self.frame.slots[slot]),
"cases change no slot but the destination"
);
results.push((self.block, node, *bits));
@@ -1345,7 +1332,7 @@ impl<'a> GraphBuilder<'a> {
} else {
self.add_phi(functions)
};
- self.frame.slots[callee_slot] = SlotState::Value {
+ self.frame.slots[callee_slot] = SlotState {
node: function,
in_sync: callee_in_sync,
};
@@ -1426,7 +1413,7 @@ impl<'a> GraphBuilder<'a> {
else {
return Ok(None);
};
- let SlotState::Value { node: closure, .. } = self.peek(*callee) else {
+ let Some(SlotState { node: closure, .. }) = self.peek(*callee) else {
return Ok(None);
};
let Op::AllocateFunction {
@@ -2284,13 +2271,13 @@ impl<'a> GraphBuilder<'a> {
let empty = self.constant(value::EMPTY);
let undefined = self.constant(value::UNDEFINED);
let mut slots = vec![
- SlotState::Value {
+ SlotState {
node: empty,
in_sync: true,
};
layout.tracked_slot_count()
];
- slots[crate::bytecode::THIS_VALUE_REGISTER as usize] = SlotState::Value {
+ slots[crate::bytecode::THIS_VALUE_REGISTER as usize] = SlotState {
node: receiver,
in_sync: true,
};
@@ -2299,7 +2286,7 @@ impl<'a> GraphBuilder<'a> {
.tracked_index(Operand::from_raw(layout.arguments_base() + argument))
.expect("arguments are tracked");
let node = argument_values.get(argument as usize).copied().unwrap_or(undefined);
- slots[slot] = SlotState::Value { node, in_sync: true };
+ slots[slot] = SlotState { node, in_sync: true };
}
let callee_frame = AbstractFrame {
slots,
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 137f83f636a..f58c464527d 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -7,26 +7,16 @@
//! The graph builder: one forward walk over the bytecode in reverse post
//! order that turns it into SSA IR.
//!
-//! The builder keeps an abstract frame: for every register, local and
-//! argument slot, either the SSA value it currently holds (and whether frame
-//! memory is in sync with that value), or nothing when frame memory is the
-//! only place that has it. `Mov` only renames, constants become constant
-//! nodes, and slow paths and calls take the values of their operands as
-//! inputs and give their outputs as values (see `slow_paths`). Values move
-//! between frame memory and SSA values lazily: `LoadSlot` on the first use
-//! of a slot that is only in memory, and `StoreSlot` of out of sync slots
-//! where memory must hold them: before calls that read the frame (`Generic`
-//! nodes, which read the whole frame, and calls that read their operands
-//! there). Merges and loop back edges never write frame memory: a slot every
-//! path leaves in memory stays there, and the others get phis, with loads at
-//! the predecessors that only have them in memory. The verifier checks that
-//! `StoreSlot` writes nothing else (see `passes::verify`).
-//!
-//! The reserved registers live only in frame memory: every read is a
-//! `LoadSlot` and every write a `StoreSlot`. The exception is the this value
-//! register, which only frame setup and `ResolveThisBinding` write: it is
-//! loaded once at entry and tracked like other slots, except at loop
-//! headers, where it stays in memory wherever memory holds it.
+//! The builder keeps an abstract frame: for every register (the reserved ones included), local and argument slot, the
+//! SSA value it currently holds, and whether frame memory holds that value too (`in_sync`). `Mov` only renames,
+//! constants become constant nodes, and slow paths and calls take the values of their operands as inputs and give their
+//! outputs as values (see `slow_paths`). Values come from frame memory only where the code starts using it: `LoadSlot`
+//! of every slot live at an entry (the function's start, and those that continue a frame, see `osr`), and of the slots
+//! a node that writes the frame wrote, right after it. Values go back to frame memory only where something reads them
+//! there: `StoreSlot` of out of sync slots before calls that read the frame (`Generic` nodes, and calls that read their
+//! operands there) and before `Suspend`, and of the arguments that the legacy `arguments` of the compiled function
+//! shows, which any code it calls can read. Merges and loop back edges never write frame memory: slots that differ get
+//! phis. The verifier checks that `StoreSlot` writes nothing else (see `passes::verify`).
//!
//! Every bytecode basic block becomes one IR block. Phis are created lazily
//! at forward merges, and eagerly at loop headers for slots assigned in the
@@ -94,6 +84,7 @@ use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::SuspendKind;
use crate::ir::value;
+use crate::passes::dominators::Dominators;
use crate::snapshot::CallFeedbackSnapshot;
use crate::snapshot::CellId;
use crate::snapshot::ExecutableSnapshot;
@@ -198,12 +189,13 @@ struct ArgumentsVirtualization<'a> {
inlined_callees_virtualized: &'a Cell<bool>,
}
+/// What the abstract frame knows about one slot: the value it holds, and whether frame memory holds that value too.
+/// Frame states list a slot that is in sync as held by the frame (see `ir::FrameState::in_frame`), so that it keeps
+/// no value alive, and nodes that read the frame need no store of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum SlotState {
- /// Only frame memory has the slot's value.
- InMemory,
- /// The slot holds `node`. If `in_sync`, frame memory holds it as well.
- Value { node: NodeId, in_sync: bool },
+struct SlotState {
+ node: NodeId,
+ in_sync: bool,
}
/// How many allocated objects the graph builder knows the shapes of at once
@@ -215,6 +207,8 @@ const MAX_FRESH_SHAPES: usize = 16;
/// execution context.
#[derive(Debug, Clone)]
struct AbstractFrame {
+ /// Every slot holds a value. Slots that are not live hold `undefined` where the walk does not know their values
+ /// (at entries and merges), as in sync, so that nothing ever stores them, though frame memory may hold anything.
slots: Vec<SlotState>,
/// For each `FrameField` (in the order of `FrameField::ALL`), the value
/// the field holds on this path, once loaded or set (see
@@ -227,11 +221,16 @@ struct AbstractFrame {
}
impl AbstractFrame {
- /// A frame whose slots are only in frame memory and whose fields are
- /// not loaded yet.
- fn in_memory(slot_count: usize) -> Self {
+ /// A frame whose slots all hold `value` in sync and whose fields are not loaded yet.
+ fn filled(slot_count: usize, value: NodeId) -> Self {
Self {
- slots: vec![SlotState::InMemory; slot_count],
+ slots: vec![
+ SlotState {
+ node: value,
+ in_sync: true,
+ };
+ slot_count
+ ],
fields: [None; FrameField::ALL.len()],
fresh_shapes: Vec::new(),
}
@@ -300,11 +299,174 @@ fn loops_replacing_environments(cfg: &Cfg, instructions: &[DecodedInstruction])
.collect()
}
-/// Whether an operand is a reserved register that lives in frame memory: one
-/// other than `this` of the compiled function. Inlined frames (`is_virtual`)
-/// have no memory, so theirs are tracked.
-fn is_reserved(operand: Operand, is_virtual: bool) -> bool {
- operand.raw() < RESERVED_REGISTER_COUNT && operand.raw() != THIS_VALUE_REGISTER && !is_virtual
+/// Whether `op` may write the frame memory of `slot` (an operand) in a frame whose arguments start at
+/// `arguments_base`.
+fn writes_slot_memory(op: &Op, slot: u32, arguments_base: u32) -> bool {
+ match op {
+ Op::StoreSlot { slot: stored } => *stored == slot,
+ // NB: They empty the registers after the reserved ones and the locals, and copy the constants.
+ Op::InitializeFrame | Op::EnsureFrameInitialized => (RESERVED_REGISTER_COUNT..arguments_base).contains(&slot),
+ // NB: They write fields of the frame, not its slots.
+ Op::PublishFrame | Op::SetLexicalEnvironment | Op::LeavePrivateEnvironment => false,
+ _ => {
+ let properties = op.properties();
+ properties.runs_code || properties.writes.intersects(Locations::FRAME)
+ }
+ }
+}
+
+/// OPTIMIZATION: Moves the loads at the start of the compiled function (see `GraphBuilder::load_entry_slots()`) down
+/// the dominator tree, to the block where their uses meet, or the closest one outside of loops above
+/// it: those of slots that keep their values (`unwritten_slots`, as operands) anywhere, and the others
+/// where nothing on the way there may write their frame memory. Values that only code far from the
+/// start or on a few paths uses then do not take registers or spill slots from the start.
+fn sink_entry_loads(graph: &mut Graph, unwritten_slots: &BitSet, arguments_base: u32) {
+ let entry = BlockId(0);
+ let loads = graph
+ .block(entry)
+ .body
+ .iter()
+ .copied()
+ .filter(|node| matches!(graph.node(*node).op, Op::LoadSlot { .. }))
+ .collect::<Vec<_>>();
+ if loads.is_empty() {
+ return;
+ }
+ let mut is_load = BitSet::new(graph.nodes.len());
+ for load in &loads {
+ is_load.insert(load.index());
+ }
+ let dominators = Dominators::compute(graph);
+ // NB: A phi uses its input at the end of the predecessor it comes from, a frame state uses its values (and those
+ // of its parents) where its node is, and the frame state at the start of a block uses its values before the
+ // block, at the end of its immediate dominator.
+ let mut meet: HashMap<NodeId, BlockId> = HashMap::default();
+ let add_use = |value: NodeId, block: BlockId, meet: &mut HashMap<NodeId, BlockId>| {
+ if !is_load.contains(value.index()) {
+ return;
+ }
+ let mut common = *meet.entry(value).or_insert(block);
+ while !dominators.dominates(common, block) {
+ common = dominators
+ .idom(common)
+ .expect("the entry dominates every use of its loads");
+ }
+ meet.insert(value, common);
+ };
+ let add_frame_state_uses = |mut frame_state: Option<FrameStateId>, block: BlockId, meet: &mut HashMap<_, _>| {
+ while let Some(id) = frame_state {
+ let state = graph.frame_state(id);
+ for (_, value) in &state.values {
+ add_use(*value, block, meet);
+ }
+ frame_state = state.parent;
+ }
+ };
+ for (index, block) in graph.blocks.iter().enumerate() {
+ let block_id = BlockId::from_index(index);
+ if let Some(dominator) = dominators.idom(block_id) {
+ add_frame_state_uses(block.start_frame_state, dominator, &mut meet);
+ }
+ for phi in &block.phis {
+ for (input, predecessor) in graph.node(*phi).inputs.iter().zip(&block.predecessors) {
+ add_use(*input, *predecessor, &mut meet);
+ }
+ }
+ for node in block.body.iter().chain(&block.control) {
+ let data = graph.node(*node);
+ for input in &data.inputs {
+ add_use(*input, block_id, &mut meet);
+ }
+ add_frame_state_uses(data.frame_state, block_id, &mut meet);
+ }
+ }
+ let mut in_loop = BitSet::new(graph.blocks.len());
+ for (index, block) in graph.blocks.iter().enumerate() {
+ let header = BlockId::from_index(index);
+ if block.is_loop_header && dominators.is_reachable(header) {
+ let back_edge_sources = dominators.back_edge_sources(graph, header);
+ for member in dominators.loop_blocks(graph, header, &back_edge_sources).iter() {
+ in_loop.insert(member);
+ }
+ }
+ }
+ for load in loads {
+ let Some(mut target) = meet.get(&load).copied() else {
+ continue;
+ };
+ while in_loop.contains(target.index()) {
+ target = dominators.idom(target).expect("the entry is in no loop");
+ }
+ if target == entry {
+ continue;
+ }
+ let Op::LoadSlot { slot } = graph.node(load).op else {
+ unreachable!("only loads sink");
+ };
+ let keeps_value = unwritten_slots.capacity() > slot as usize && unwritten_slots.contains(slot as usize);
+ // NB: The other slots sink no further than the first node that may write their memory, on the way to the
+ // target block (every block from where it can be reached, before it) or in it.
+ let writes = |node: &NodeId| !keeps_value && writes_slot_memory(&graph.node(*node).op, slot, arguments_base);
+ if !keeps_value {
+ let mut on_the_way = BitSet::new(graph.blocks.len());
+ let mut pending = graph.block(target).predecessors.clone();
+ while let Some(block) = pending.pop() {
+ if block == target || on_the_way.contains(block.index()) {
+ continue;
+ }
+ on_the_way.insert(block.index());
+ pending.extend(graph.block(block).predecessors.iter().copied());
+ }
+ if on_the_way.iter().any(|block| {
+ graph.blocks[block]
+ .body
+ .iter()
+ .chain(&graph.blocks[block].control)
+ .any(writes)
+ }) {
+ continue;
+ }
+ }
+ // NB: The load goes before the first node of the block that uses it, ahead of the nodes built for the same
+ // instruction before that one, like a load of an operand the instruction reads, or at the end of the
+ // block. Refinements stay at the heads of their blocks, and refine values their single predecessors
+ // branched on, which therefore use them as well.
+ let uses = |node: &NodeId| {
+ let data = graph.node(*node);
+ let mut frame_state = data.frame_state;
+ let mut used = data.inputs.contains(&load);
+ while let Some(id) = frame_state.filter(|_| !used) {
+ let state = graph.frame_state(id);
+ used = state.values.iter().any(|(_, value)| *value == load);
+ frame_state = state.parent;
+ }
+ used
+ };
+ let body = &graph.blocks[target.index()].body;
+ let heads = body
+ .iter()
+ .take_while(|node| matches!(graph.node(**node).op, Op::Refine { .. }))
+ .count();
+ if body[..heads].iter().any(uses) {
+ continue;
+ }
+ if body[..heads].iter().any(writes) {
+ continue;
+ }
+ let mut position = heads
+ + body[heads..]
+ .iter()
+ .position(|node| uses(node) || writes(node))
+ .unwrap_or(body.len() - heads);
+ if let Some(user) = body.get(position) {
+ let pc = graph.node(*user).pc;
+ while position > heads && graph.node(body[position - 1]).pc == pc {
+ position -= 1;
+ }
+ }
+ graph.blocks[entry.index()].body.retain(|node| *node != load);
+ graph.blocks[target.index()].body.insert(position, load);
+ }
}
/// What ends the instruction currently being built.
@@ -425,7 +587,7 @@ struct Function<'a> {
osr_loop_headers: Vec<bool>,
/// Constant slots some instruction writes. The interpreter keeps a copy of
/// the constants in the frame, and writes to a constant operand change that
- /// copy, so such slots live in frame memory like the reserved registers.
+ /// copy, so such slots live in frame memory.
written_constants: &'a BitSet,
/// Index of the instruction being built.
instruction_index: usize,
@@ -577,7 +739,6 @@ impl<'a> GraphBuilder<'a> {
reason: "no executable",
})?;
let function = Function::new(0, executable, decoded_function(executable, &decoded[0])?, false)?;
- let slot_count = function.layout.tracked_slot_count();
let arguments_base = function.layout.arguments_base();
let legacy_arguments = if executable.supports_legacy_arguments {
arguments_base..arguments_base + function.layout.number_of_arguments
@@ -596,7 +757,8 @@ impl<'a> GraphBuilder<'a> {
order: Vec::new(),
constants: HashMap::default(),
block: BlockId(0),
- frame: AbstractFrame::in_memory(slot_count),
+ // NB: Replaced by the frame of the first block built.
+ frame: AbstractFrame::filled(0, NodeId(0)),
function,
callers: Vec::new(),
inlined_instructions: 0,
@@ -626,6 +788,7 @@ impl<'a> GraphBuilder<'a> {
if self.snapshot.options.runs_once && self.build_osr_entries && builds_entry_at_osr_pc {
self.set_control(Op::Unreachable, Vec::new());
} else {
+ self.load_entry_slots();
self.enter_function(entry);
}
if self.build_osr_entries {
@@ -634,6 +797,7 @@ impl<'a> GraphBuilder<'a> {
self.build_catch_entries()?;
}
self.build_function()?;
+ let unwritten_slots = self.slots_kept_from_start();
let mut graph = self.graph;
for (index, executable) in self.snapshot.executables.iter().enumerate() {
@@ -663,9 +827,56 @@ impl<'a> GraphBuilder<'a> {
);
}
}
+ sink_entry_loads(&mut graph, &unwritten_slots, self.function.layout.arguments_base());
Ok(graph)
}
+ /// The slots (as operands) that hold the values the compiled function starts with wherever it runs: the arguments
+ /// and the this value register, unless instructions of the function write them. The frame's initialization
+ /// changes the other registers and the locals, and the runtime the other reserved registers.
+ fn slots_kept_from_start(&self) -> BitSet {
+ let layout = self.function.layout;
+ let mut kept = BitSet::new(layout.arguments_base() as usize + layout.number_of_arguments as usize);
+ kept.insert_range(layout.arguments_base() as usize..kept.capacity());
+ if THIS_VALUE_REGISTER < layout.registers_and_locals_count {
+ kept.insert(THIS_VALUE_REGISTER as usize);
+ }
+ for decoded in self.function.instructions {
+ if decoded.instruction.opcode() == OpCode::ResolveThisBinding {
+ kept.remove(THIS_VALUE_REGISTER as usize);
+ }
+ decoded.instruction.for_each_operand(|operand, role| {
+ if role.is_written() && (operand.raw() as usize) < kept.capacity() {
+ kept.remove(operand.raw() as usize);
+ }
+ });
+ }
+ kept
+ }
+
+ /// Makes the abstract frame the one the compiled function starts with, like the other entries' (see `osr`): the
+ /// slots live there are loaded from frame memory (loads nothing uses go away in dead code elimination).
+ fn load_entry_slots(&mut self) {
+ self.frame = self.dead_frame();
+ for slot in self.function.liveness.live_in(0).iter() {
+ self.load_slot(slot);
+ }
+ }
+
+ /// A frame whose slots are all dead: they hold `undefined` (see `AbstractFrame::slots`).
+ fn dead_frame(&mut self) -> AbstractFrame {
+ let undefined = self.constant(value::UNDEFINED);
+ AbstractFrame::filled(self.function.layout.tracked_slot_count(), undefined)
+ }
+
+ /// Loads a slot from frame memory, which then holds its value in sync.
+ fn load_slot(&mut self, slot: usize) -> NodeId {
+ let operand = self.function.layout.operand_for_tracked_index(slot);
+ let node = self.emit(Op::LoadSlot { slot: operand.raw() }, Vec::new(), Some(Repr::Tagged));
+ self.frame.slots[slot] = SlotState { node, in_sync: true };
+ node
+ }
+
/// Ends the current block with a jump to the first bytecode block of the
/// function being walked, with the current abstract frame.
fn enter_function(&mut self, from: BlockId) {
@@ -735,25 +946,8 @@ impl<'a> GraphBuilder<'a> {
self.function.instruction_index = first_instruction;
self.function.pc = self.function.instructions[first_instruction].pc;
- self.frame = if only_back_edges {
- // NB: Frame memory holds the slots the loop does not assign, and
- // the others get phis of what the back edges bring.
- let mut frame = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());
- let live = self.function.liveness.live_in(first_instruction);
- let assigned = self.function.cfg.blocks[block_index]
- .loop_index
- .map(|loop_index| self.function.loop_phi_slots[loop_index].clone());
- for slot in live.iter() {
- if self.tracks_slot(slot)
- && (slot != THIS_VALUE_REGISTER as usize || self.function.is_virtual())
- && assigned.as_ref().is_some_and(|assigned| assigned.contains(slot))
- {
- let node = self.add_phi(Vec::new());
- frame.slots[slot] = SlotState::Value { node, in_sync: false };
- }
- }
- frame
- } else if incoming.len() == 1 && !is_loop_header {
+ // NB: A loop header that only back edges reach is a merge without forward predecessors.
+ self.frame = if incoming.len() == 1 && !is_loop_header {
incoming.into_iter().next().unwrap().1
} else {
self.merge(block_index, incoming)
@@ -764,10 +958,11 @@ impl<'a> GraphBuilder<'a> {
true
}
- /// The abstract frame at the start of a merge or loop header, given the
- /// abstract frames at the end of its forward predecessors. Adds phis to
- /// the current block, and writes values back to the frame at the end of
- /// predecessors where the merged slot is only in memory.
+ /// The abstract frame at the start of a merge or loop header, given the abstract frames at the end of its forward
+ /// predecessors: each live slot holds the value they all bring, or a phi of their values where they differ. A loop
+ /// header has a phi for each live slot the loop assigns, whose back edges add their inputs (see
+ /// `reconcile_back_edge()`). So does a loop header that on-stack replacement entries reach over back edges, for
+ /// every live slot: the values there come from different entries.
fn merge(&mut self, block_index: BlockIndex, incoming: Vec<(BlockId, AbstractFrame)>) -> AbstractFrame {
let bytecode_block = &self.function.cfg.blocks[block_index];
let live = self.function.liveness.live_in(bytecode_block.instructions.start);
@@ -776,7 +971,7 @@ impl<'a> GraphBuilder<'a> {
.map(|loop_index| self.function.loop_phi_slots[loop_index].clone());
let is_loop_header = bytecode_block.is_loop_header();
- let mut merged = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());
+ let mut merged = self.dead_frame();
// NB: A field keeps its value where every path brings the same one,
// except environments at the headers of loops that may replace
// them, and every field at the headers of loops that on-stack
@@ -801,124 +996,49 @@ impl<'a> GraphBuilder<'a> {
merged.set_field(field, value);
}
}
- // NB: Reserved registers live in frame memory, except in inlined
- // callees, which track them like other slots.
- for slot in 0..merged.slots.len() {
- if !self.tracks_slot(slot) || !live.contains(slot) {
- continue;
- }
- // NB: Back edges from paths that start at an on-stack replacement
- // entry inside the loop bring the values that entry loaded,
- // so slots the loop does not assign live in the frame there.
- let invariant_in_osr_loop = self.function.osr_loop_headers[block_index]
- && assigned_in_loop
- .as_ref()
- .is_some_and(|assigned| !assigned.contains(slot));
- let values = incoming
- .iter()
- .map(|(_, frame)| match frame.slots[slot] {
- SlotState::Value { node, in_sync } if !invariant_in_osr_loop => Some((node, in_sync)),
- _ => None,
- })
- .collect::<Option<Vec<_>>>();
+ for slot in live.iter() {
let assigned = assigned_in_loop
.as_ref()
.is_some_and(|assigned| assigned.contains(slot));
+ let values = incoming.iter().map(|(_, frame)| frame.slots[slot]).collect::<Vec<_>>();
+ // NB: Back edges keep frame memory in sync with the values of the slots the loop does not assign, and
+ // the phis of the others get values memory need not hold.
+ let in_sync = values.iter().all(|value| value.in_sync) && !(is_loop_header && assigned);
+ let needs_phi = is_loop_header && (assigned || osr_loop_header);
+ let shared = values
+ .iter()
+ .map(|value| value.node)
+ .find(|candidate| values.iter().all(|value| self.graph.refines(value.node, *candidate)))
+ .filter(|_| !needs_phi);
+ // OPTIMIZATION: Where every path brings a value it loaded from the slot, which frame memory still holds,
+ // and the loop does not assign it, the merge loads the slot once more instead of taking a phi
+ // of those loads, like the merge of the start of the function and its on-stack replacement
+ // entries ahead of a loop. So does a loop header that only back edges reach, which keep
+ // frame memory in sync with the slots the loop does not assign. Loop invariant code motion
+ // takes these loads out of their loops.
let operand = self.function.layout.operand_for_tracked_index(slot);
- // NB: Frame memory holds the this value wherever it is in sync, and
- // only slow paths change it, which write it there. Loops keep
- // it there, instead of in a phi of what their back edges bring.
- if is_loop_header
- && slot == THIS_VALUE_REGISTER as usize
- && !self.function.is_virtual()
- && incoming.iter().all(|(_, frame)| {
- matches!(
- frame.slots[slot],
- SlotState::InMemory | SlotState::Value { in_sync: true, .. }
- )
- })
- {
- continue;
- }
- let Some(values) = values else {
- // NB: Frame memory holds the slot on some path. Where the
- // other paths bring values it holds too, it stays there;
- // values the loop never changes enter the loop as SSA
- // values, loaded before it, so that nodes using them can
- // move out of the loop too. Mapped arguments objects can
- // change arguments behind the code's back.
- let loop_invariant = assigned_in_loop.is_some()
- && !assigned
- && !self.function.osr_loop_headers[block_index]
- && !self.function.is_virtual()
- && slot >= RESERVED_REGISTER_COUNT as usize
- && !(operand.raw() >= self.function.layout.arguments_base()
- && self.function.may_write_parameter_bindings);
- if let [(predecessor, frame)] = incoming.as_slice()
- && is_loop_header
- && loop_invariant
- && frame.slots[slot] == SlotState::InMemory
- {
- let node = self.append_to_finished_block(
- *predecessor,
- Op::LoadSlot { slot: operand.raw() },
- Vec::new(),
- Some(Repr::Tagged),
- );
- merged.slots[slot] = SlotState::Value { node, in_sync: true };
- continue;
- }
- let all_in_frame = incoming.iter().all(|(_, frame)| {
- matches!(
- frame.slots[slot],
- SlotState::InMemory | SlotState::Value { in_sync: true, .. }
- )
+ let reloads = shared.is_none()
+ && self.callers.is_empty()
+ && !(is_loop_header && assigned)
+ && values.iter().all(|value| {
+ value.in_sync
+ && matches!(self.graph.node(self.graph.unrefined(value.node)).op,
+ Op::LoadSlot { slot } if slot == operand.raw())
});
- // NB: Frame memory changes only where instructions write it,
- // never at merges or loop back edges: a slot the loop
- // assigns gets a phi, and other paths bring their values,
- // loaded where only frame memory holds them.
- if all_in_frame && !(is_loop_header && assigned) {
- continue;
+ let node = match shared {
+ Some(node) => node,
+ None if reloads => self.emit(Op::LoadSlot { slot: operand.raw() }, Vec::new(), Some(Repr::Tagged)),
+ None => {
+ // NB: Phis start out tagged; representation selection unboxes them later.
+ let inputs = incoming
+ .iter()
+ .zip(&values)
+ .map(|((predecessor, _), value)| self.tagged_at_end_of(*predecessor, value.node))
+ .collect();
+ self.add_phi(inputs)
}
- let inputs = incoming
- .iter()
- .map(|(predecessor, frame)| match frame.slots[slot] {
- SlotState::Value { node, .. } => self.tagged_at_end_of(*predecessor, node),
- SlotState::InMemory => self.append_to_finished_block(
- *predecessor,
- Op::LoadSlot { slot: operand.raw() },
- Vec::new(),
- Some(Repr::Tagged),
- ),
- })
- .collect();
- let node = self.add_phi(inputs);
- merged.slots[slot] = SlotState::Value { node, in_sync: false };
- continue;
- };
- 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 let Some(node) = shared
- && !assigned
- {
- node
- } else {
- // NB: Phis start out tagged; representation selection
- // unboxes them later.
- let inputs = incoming
- .iter()
- .zip(&values)
- .map(|((predecessor, _), (node, _))| self.tagged_at_end_of(*predecessor, *node))
- .collect();
- self.add_phi(inputs)
};
- merged.slots[slot] = SlotState::Value { node, in_sync };
+ merged.slots[slot] = SlotState { node, in_sync };
}
merged
}
@@ -1041,47 +1161,36 @@ impl<'a> GraphBuilder<'a> {
.function
.liveness
.live_in(self.function.cfg.blocks[target].instructions.start);
- for slot in 0..header_frame.slots.len() {
- if !self.tracks_slot(slot) || !live.contains(slot) {
+ for slot in live.iter() {
+ let header_value = header_frame.slots[slot];
+ let current = self.frame.slots[slot];
+ if self.graph.block(header).phis.contains(&header_value.node) {
+ let value = self.tagged(current.node);
+ self.graph.nodes[header_value.node.index()].inputs.push(value);
continue;
}
- let operand = self.function.layout.operand_for_tracked_index(slot);
- match header_frame.slots[slot] {
- SlotState::Value { node, .. } if self.graph.block(header).phis.contains(&node) => {
- let value = self.read_tracked(slot, operand);
- let value = self.tagged(value);
- self.graph.nodes[node.index()].inputs.push(value);
- }
- SlotState::Value { 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,
- reason: "loop back edge changes a value the loop does not assign",
- });
- }
- }
- // NB: Frame memory holds the slot at the header, and the loop
- // does not assign it, so it still does. The this value is
- // the exception (see `merge()`): its memory is written
- // where the loop changed it.
- SlotState::InMemory if slot == THIS_VALUE_REGISTER as usize && !self.function.is_virtual() => {
- self.sync_slot(slot);
- }
- SlotState::InMemory => {
- if let SlotState::Value { in_sync: false, .. } = self.frame.slots[slot] {
- return Err(CompileFailure::InvalidBytecode {
- pc: self.function.pc,
- reason: "loop back edge changes a slot the loop does not assign",
- });
- }
- }
+ // NB: Only slots assigned in the loop can change, and those have phis. A load at the header (see
+ // `merge()`) reads frame memory, which keeps the value of a slot the loop does not assign, again on
+ // every iteration, also where on-stack replacement entries reach the header over back edges.
+ let reloaded = self.graph.block(header).body.contains(&header_value.node)
+ && matches!(self.graph.node(header_value.node).op, Op::LoadSlot { .. });
+ if !reloaded && !self.graph.has_value_of(current.node, header_value.node) {
+ return Err(CompileFailure::InvalidBytecode {
+ pc: self.function.pc,
+ reason: "loop back edge changes a value the loop does not assign",
+ });
}
}
+ // NB: Frame memory keeps the values of the slots the loop does not assign (see `merge()`).
+ if live
+ .iter()
+ .any(|slot| header_frame.slots[slot].in_sync && !self.frame.slots[slot].in_sync)
+ {
+ return Err(CompileFailure::InvalidBytecode {
+ pc: self.function.pc,
+ reason: "loop back edge leaves a slot out of sync that the header has in frame memory",
+ });
+ }
// NB: The fields the header knows are those the loop never replaces.
for field in FrameField::ALL {
if let Some(value) = header_frame.field(field)
@@ -1206,42 +1315,22 @@ impl<'a> GraphBuilder<'a> {
// Frame slots.
- /// Whether an operand is a reserved register that lives in frame
- /// memory (see `is_reserved()`).
- fn is_reserved(&self, operand: Operand) -> bool {
- is_reserved(operand, self.function.is_virtual())
- }
-
- /// Whether the abstract frame tracks the slot with this tracked index,
- /// instead of leaving it in frame memory.
- fn tracks_slot(&self, slot: usize) -> bool {
- slot >= RESERVED_REGISTER_COUNT as usize || slot == THIS_VALUE_REGISTER as usize || self.function.is_virtual()
- }
-
- /// What the frame holds for an operand, without building anything.
- fn peek(&self, operand: Operand) -> SlotState {
- match self.function.layout.tracked_index(operand) {
- Some(slot) if !self.is_reserved(operand) => self.frame.slots[slot],
- _ => SlotState::InMemory,
- }
+ /// What the frame holds for an operand, if it is a tracked slot (not a constant).
+ fn peek(&self, operand: Operand) -> Option<SlotState> {
+ let slot = self.function.layout.tracked_index(operand)?;
+ Some(self.frame.slots[slot])
}
/// The intrinsic function an operand holds as a constant, if any.
fn constant_intrinsic(&self, operand: Operand) -> Option<Intrinsic> {
- let SlotState::Value { node, .. } = self.peek(operand) else {
- return None;
- };
- let bits = self.graph.constant_value(node)?;
+ let bits = self.graph.constant_value(self.peek(operand)?.node)?;
self.intrinsics.get(&bits).copied()
}
/// The snapshot executable of the function an operand holds as a
/// constant, if calls of it may be inlined.
fn constant_inlinable_function(&self, operand: Operand) -> Option<u32> {
- let SlotState::Value { node, .. } = self.peek(operand) else {
- return None;
- };
- let bits = self.graph.constant_value(node)?;
+ let bits = self.graph.constant_value(self.peek(operand)?.node)?;
self.inlinable_functions.get(&bits).copied()
}
@@ -1259,18 +1348,15 @@ impl<'a> GraphBuilder<'a> {
}
}
- /// The tagged value of an operand, loading it from the frame if needed.
+ /// The tagged value of an operand.
fn read(&mut self, operand: Operand) -> Result<NodeId, CompileFailure> {
let value = self.read_value(operand)?;
Ok(self.tagged(value))
}
/// The SSA value of an operand in whatever representation the frame
- /// holds it, loading it from the frame if needed.
+ /// holds it.
fn read_value(&mut self, operand: Operand) -> Result<NodeId, CompileFailure> {
- if self.is_reserved(operand) {
- return Ok(self.emit(Op::LoadSlot { slot: operand.raw() }, Vec::new(), Some(Repr::Tagged)));
- }
if operand.raw() >= self.function.layout.arguments_base() + self.function.layout.number_of_arguments {
return Err(CompileFailure::InvalidBytecode {
pc: self.function.pc,
@@ -1278,7 +1364,7 @@ impl<'a> GraphBuilder<'a> {
});
}
match self.function.layout.tracked_index(operand) {
- Some(slot) => Ok(self.read_tracked(slot, operand)),
+ Some(slot) => Ok(self.frame.slots[slot].node),
None => {
let index = (operand.raw() - self.function.layout.constants_base()) as usize;
if index < self.function.written_constants.capacity() && self.function.written_constants.contains(index)
@@ -1299,26 +1385,7 @@ impl<'a> GraphBuilder<'a> {
}
}
- fn read_tracked(&mut self, slot: usize, operand: Operand) -> NodeId {
- match self.frame.slots[slot] {
- SlotState::Value { node, .. } => node,
- SlotState::InMemory => {
- assert!(
- !self.function.is_virtual(),
- "live slots of inlined frames always hold a value"
- );
- let node = self.emit(Op::LoadSlot { slot: operand.raw() }, Vec::new(), Some(Repr::Tagged));
- self.frame.slots[slot] = SlotState::Value { node, in_sync: true };
- node
- }
- }
- }
-
fn write(&mut self, operand: Operand, value: NodeId) -> Result<(), CompileFailure> {
- if self.is_reserved(operand) {
- self.emit(Op::StoreSlot { slot: operand.raw() }, vec![value], None);
- return Ok(());
- }
if operand.raw() >= self.function.layout.arguments_base() + self.function.layout.number_of_arguments {
return Err(CompileFailure::InvalidBytecode {
pc: self.function.pc,
@@ -1333,16 +1400,22 @@ impl<'a> GraphBuilder<'a> {
// NB: Inlined frames have no memory to be out of sync with.
let is_virtual = self.function.is_virtual();
let writes_memory = !is_virtual && self.graph.legacy_arguments.contains(&operand.raw());
- if self.frame.slots[slot]
- != (SlotState::Value {
+ // NB: Frame memory need not hold what a dead slot holds (see `AbstractFrame::slots`).
+ let unchanged = self.frame.slots[slot]
+ == (SlotState {
node: value,
in_sync: true,
})
- {
+ && self
+ .function
+ .liveness
+ .live_in(self.function.instruction_index)
+ .contains(slot);
+ if !unchanged {
if writes_memory {
self.emit(Op::StoreSlot { slot: operand.raw() }, vec![value], None);
}
- self.frame.slots[slot] = SlotState::Value {
+ self.frame.slots[slot] = SlotState {
node: value,
in_sync: is_virtual || writes_memory,
};
@@ -1352,10 +1425,11 @@ impl<'a> GraphBuilder<'a> {
/// Writes a slot's value back to frame memory if it is out of sync.
fn sync_slot(&mut self, slot: usize) {
- if let SlotState::Value { node, in_sync: false } = self.frame.slots[slot] {
+ let SlotState { node, in_sync } = self.frame.slots[slot];
+ if !in_sync {
let operand = self.function.layout.operand_for_tracked_index(slot);
self.emit(Op::StoreSlot { slot: operand.raw() }, vec![node], None);
- self.frame.slots[slot] = SlotState::Value { node, in_sync: true };
+ self.frame.slots[slot].in_sync = true;
}
}
@@ -1416,21 +1490,10 @@ impl<'a> GraphBuilder<'a> {
// NB: Inlined frames are set up by the caller.
if !self.function.is_virtual() {
self.emit(Op::InitializeFrame, Vec::new(), None);
- let this_value = self.emit(
- Op::LoadSlot {
- slot: THIS_VALUE_REGISTER,
- },
- Vec::new(),
- Some(Repr::Tagged),
- );
- self.frame.slots[THIS_VALUE_REGISTER as usize] = SlotState::Value {
- node: this_value,
- in_sync: true,
- };
}
let empty = self.constant(value::EMPTY);
for slot in RESERVED_REGISTER_COUNT as usize..self.function.layout.registers_and_locals_count as usize {
- self.frame.slots[slot] = SlotState::Value {
+ self.frame.slots[slot] = SlotState {
node: empty,
in_sync: true,
};
@@ -1865,11 +1928,8 @@ impl<'a> GraphBuilder<'a> {
if let Some(continuation) = continuation {
let block = self.block_for_label(continuation)?;
let start = self.function.cfg.blocks[block].instructions.start;
- let live = self.function.liveness.live_in(start);
- for slot in live.iter() {
- if self.tracks_slot(slot) {
- self.sync_slot(slot);
- }
+ for slot in self.function.liveness.live_in(start).iter() {
+ self.sync_slot(slot);
}
}
// NB: Like the interpreter's Yield and Await, an empty value yields
@@ -2045,8 +2105,7 @@ impl<'a> GraphBuilder<'a> {
}
/// Builds an instruction as a generic node: write back every slot it may
- /// read, run its slow path, and forget the SSA values of the slots it
- /// writes, so that later reads load them from the frame.
+ /// read, run its slow path, and load the slots it writes from the frame.
fn build_generic(&mut self, instruction: &Instruction, info: GenericInfo) -> Result<Flow, CompileFailure> {
if let Some(flow) = self.try_build_slow_path_call(instruction, info)? {
return Ok(flow);
@@ -2142,16 +2201,16 @@ impl<'a> GraphBuilder<'a> {
});
}
let out_of_sync = (0..self.frame.slots.len())
- .filter(|slot| match self.frame.slots[*slot] {
- SlotState::Value { node, in_sync: false } => {
- let needed = if writes_only_operands {
- operand_slots.contains(slot)
- } else {
- info.reads_whole_frame || live_in.contains(*slot)
- };
- needed && (!self.is_virtual_arguments(node) || info.reads_whole_frame || read_slots.contains(slot))
- }
- _ => false,
+ .filter(|slot| {
+ let SlotState { node, in_sync } = self.frame.slots[*slot];
+ let needed = if writes_only_operands {
+ operand_slots.contains(slot)
+ } else {
+ info.reads_whole_frame || live_in.contains(*slot)
+ };
+ !in_sync
+ && needed
+ && (!self.is_virtual_arguments(node) || info.reads_whole_frame || read_slots.contains(slot))
})
.collect::<Vec<_>>();
for slot in out_of_sync {
@@ -2170,21 +2229,23 @@ impl<'a> GraphBuilder<'a> {
let mut destination = None;
instruction.for_each_operand(|operand, role| {
- if !role.is_written() {
- return;
- }
- destination.get_or_insert(operand);
- if (self.is_reserved(operand) && !self.function.is_virtual()) || value_is_result {
- return;
- }
- // NB: Written constants live in frame memory, where the slow path writes them.
- if let Some(slot) = self.function.layout.tracked_index(operand) {
- self.frame.slots[slot] = SlotState::InMemory;
+ if role.is_written() {
+ destination.get_or_insert(operand);
}
});
-
+ // NB: The node writes its outputs to the frame, but for a call's result, which is its value. Where it does not
+ // continue, they hold what it wrote, or their old values, which the frame holds too (see above), so its
+ // frame state lists them as held by the frame. Where it continues, they are loaded from there. Written
+ // constants live in frame memory, where the slow path writes them.
+ let frame_outputs = if value_is_result { Vec::new() } else { written_slots };
+ for slot in &frame_outputs {
+ self.frame.slots[*slot].in_sync = true;
+ }
let frame_state = self.resume_after_frame_state(destination.map_or(Operand::INVALID, Operand::raw));
self.graph.nodes[node.index()].frame_state = Some(frame_state);
+ for slot in frame_outputs {
+ self.load_slot(slot);
+ }
if value_is_result && let Some(destination) = destination {
self.write(destination, node)?;
}
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
index d75cfee4beb..d2815bc2ef1 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
@@ -35,16 +35,15 @@
//! state to the frame and running the `Catch` itself, or the interpreter
//! after running the `Catch` (see `ARCHITECTURE.md`, section 4.2).
-use super::AbstractFrame;
use super::Flow;
use super::GraphBuilder;
use crate::CompileFailure;
use crate::bytecode::Instruction;
use crate::bytecode::Label;
use crate::bytecode::OpCode;
-use crate::bytecode::RESERVED_REGISTER_COUNT;
use crate::bytecode::cfg::BlockIndex;
use crate::bytecode::cfg::Loop;
+use crate::ir::BlockId;
/// Whether instructions with this opcode are loop back edges, which count
/// loop iterations in the interpreter.
@@ -102,18 +101,7 @@ impl GraphBuilder<'_> {
{
continue;
}
- let block = self.start_new_block(Vec::new());
- self.frame = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());
- self.function.instruction_index = index;
- self.function.pc = pc;
- self.function.eager_frame_state = None;
- let live = self.function.liveness.live_in(index);
- for slot in live.iter() {
- if slot >= RESERVED_REGISTER_COUNT as usize {
- let operand = self.function.layout.operand_for_tracked_index(slot);
- self.read_tracked(slot, operand);
- }
- }
+ let block = self.start_entry_block(index);
// NB: A back edge that starts its block is entered through
// that block, so that loops with their test at the bottom
// are entered at their header like from the function entry.
@@ -242,25 +230,27 @@ impl GraphBuilder<'_> {
if self.graph.osr_entries.iter().any(|(entry_pc, _)| *entry_pc == pc) {
return Ok(());
}
- let block = self.start_new_block(Vec::new());
- self.frame = AbstractFrame::in_memory(self.function.layout.tracked_slot_count());
- let start = target_block.instructions.start;
- self.function.instruction_index = start;
- self.function.pc = pc;
- self.function.eager_frame_state = None;
- let live = self.function.liveness.live_in(start);
- for slot in live.iter() {
- if slot >= RESERVED_REGISTER_COUNT as usize {
- let operand = self.function.layout.operand_for_tracked_index(slot);
- self.read_tracked(slot, operand);
- }
- }
+ let block = self.start_entry_block(target_block.instructions.start);
self.end_with_jump(target)?;
self.graph.osr_entries.push((pc, block));
self.note_loops_entered_at(&[target]);
Ok(())
}
+ /// Starts an entry block into a frame that is running at the instruction with the given index: a block without
+ /// predecessors that loads every slot live there from the frame, whose memory holds them all.
+ fn start_entry_block(&mut self, index: usize) -> BlockId {
+ let block = self.start_new_block(Vec::new());
+ self.frame = self.dead_frame();
+ self.function.instruction_index = index;
+ self.function.pc = self.function.instructions[index].pc;
+ self.function.eager_frame_state = None;
+ for slot in self.function.liveness.live_in(index).iter() {
+ self.load_slot(slot);
+ }
+ block
+ }
+
/// Notes the loops that an entry leads into other than at their header,
/// over its edges to `targets`, which may only be reached from there over
/// their back edges.
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs
index f95343a426b..e7d9769cd85 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs
@@ -8,7 +8,6 @@
use super::Flow;
use super::GraphBuilder;
-use super::SlotState;
use crate::CompileFailure;
use crate::bytecode::Operand;
use crate::code::Repr;
@@ -35,14 +34,10 @@ impl GraphBuilder<'_> {
let receiver = self.read(receiver)?;
let keys = self.read(keys)?;
let cursor_value = self.read(cursor)?;
- // NB: Once there are no more keys, the value stays what it was. It is
- // dead before the instruction, which writes it, and inlined frames
- // drop dead slots at merges: there it becomes undefined, as the
- // slow path writes it once done.
- let old_value = match self.peek(dst_value) {
- SlotState::InMemory if self.function.is_virtual() => self.constant(value::UNDEFINED),
- _ => self.read(dst_value)?,
- };
+ // NB: Once there are no more keys, the value stays what it was. It is dead before the instruction, which
+ // writes it, so where the walk does not know its value it is undefined (see `AbstractFrame::slots`), as
+ // the slow path writes it once done.
+ let old_value = self.read(dst_value)?;
let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;
let receiver = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![receiver], true);
self.branch_to_slow_path(
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs
index f4da788d12e..3c30d29f450 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs
@@ -12,8 +12,6 @@
use super::Flow;
use super::GenericInfo;
use super::GraphBuilder;
-use super::SlotState;
-use super::is_reserved;
use crate::CompileFailure;
use crate::bytecode::FrameLayout;
use crate::bytecode::Instruction;
@@ -36,12 +34,10 @@ pub(crate) struct SlowPathOperands {
pub(crate) outputs: Vec<(u32, u32)>,
}
-/// Whether `operand`, an output of a slow path in a frame of `layout` (an
-/// inlined callee's if `is_virtual`), becomes an SSA value: a tracked slot
-/// that does not live in frame memory, which the compiled function's
-/// reserved registers other than `this` do.
-pub(crate) fn is_ssa_slow_path_output(layout: &FrameLayout, operand: Operand, is_virtual: bool) -> bool {
- !is_reserved(operand, is_virtual) && layout.tracked_index(operand).is_some()
+/// Whether `operand`, an output of a slow path in a frame of `layout`, becomes an SSA value: any slot but a
+/// constant, which instructions may write too, and which lives in frame memory.
+pub(crate) fn is_ssa_slow_path_output(layout: &FrameLayout, operand: Operand) -> bool {
+ layout.tracked_index(operand).is_some()
}
/// The operands of a JS call instruction, whose slow path is the runtime's
@@ -100,10 +96,6 @@ impl GraphBuilder<'_> {
Ok(SlowPathOperands { inputs, outputs })
}
- fn is_ssa_output(&self, operand: Operand) -> bool {
- is_ssa_slow_path_output(&self.function.layout, operand, self.function.is_virtual())
- }
-
/// Builds an instruction as a call of its slow path on SSA values (see
/// `Op::CallSlowPath`), unless its slow path reads more of the frame than
/// its operands: then returns `None`, and the instruction becomes a
@@ -156,7 +148,7 @@ impl GraphBuilder<'_> {
} else if operands
.outputs
.first()
- .is_some_and(|(_, operand)| self.is_ssa_output(Operand::from_raw(*operand)))
+ .is_some_and(|(_, operand)| is_ssa_slow_path_output(&self.function.layout, Operand::from_raw(*operand)))
{
Some(Repr::Tagged)
} else {
@@ -178,28 +170,24 @@ impl GraphBuilder<'_> {
// frame then gets the frame state's values, with the old values
// of the outputs the slow path did not write, except that it
// writes back the outputs it reads (as the interpreter does on
- // exceptions), and outputs that live in frame memory hold what it
- // wrote there.
- for (field, operand) in &operands.outputs {
- let operand = Operand::from_raw(*operand);
- let Some(slot) = self.function.layout.tracked_index(operand) else {
- continue;
- };
- let is_input_output =
- !info.is_js_call && slow_path_layout(opcode).fields[*field as usize].role == OperandRole::InOut;
- if !self.is_ssa_output(operand) || is_input_output {
- if self.is_reserved(operand) && !self.function.is_virtual() {
- continue;
- }
- self.frame.slots[slot] = SlotState::InMemory;
- }
- }
- let frame_state = self.resume_after_frame_state(destination.map_or(Operand::INVALID, Operand::raw));
+ // exceptions): the frame state lists those as held by the frame.
+ let input_outputs = operands
+ .outputs
+ .iter()
+ .filter(|(field, _)| {
+ !info.is_js_call && slow_path_layout(opcode).fields[*field as usize].role == OperandRole::InOut
+ })
+ .filter_map(|(_, operand)| self.function.layout.tracked_index(Operand::from_raw(*operand)))
+ .collect::<Vec<_>>();
+ let frame_state = self.resume_after_frame_state_with_outputs_in_frame(
+ destination.map_or(Operand::INVALID, Operand::raw),
+ &input_outputs,
+ );
self.graph.nodes[node.index()].frame_state = Some(frame_state);
for (index, (_, operand)) in operands.outputs.iter().enumerate() {
let operand = Operand::from_raw(*operand);
- if !self.is_ssa_output(operand) {
+ if !is_ssa_slow_path_output(&self.function.layout, operand) {
continue;
}
let value = if index == 0 {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index 9a73ae9eecc..92a9a932f6b 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -258,8 +258,8 @@ fn if_else_merges_with_phis() {
[[B0]]:
Jump [[B1]]
[[B1]] (pc 0) <- [[B0]]:
- [[V1]] = LoadSlot a0
[[V2]] = LoadSlot r5
+ [[V1]] = LoadSlot a0
BranchTruthy ([[V2]]) -> [[B2]], [[B3]], fallback [[B4]]
[[B2]] <- [[B1]]:
Jump [[B8]]
@@ -734,8 +734,8 @@ fn calls_write_back_their_arguments_and_values_survive_them() {
[[B0]]:
Jump [[B1]]
[[B1]] (pc 0) <- [[B0]]:
- [[V1]] = LoadSlot a0
[[V2]] = LoadSlot r5
+ [[V1]] = LoadSlot a0
[[V3]] = CallSlowPath Call @3 ([[V2]], [[V2]], [[V1]]) [[[FS0]]]
Return ([[V1]])
frame states:
@@ -768,14 +768,52 @@ fn trivial_frame_operations_are_native() {
[[B1]] (pc 0) <- [[B0]]:
[[V1]]:pointer = LoadFrameField LexicalEnvironment
[[V2]] = BoxCell ([[V1]])
- StoreSlot r3 (#undefined)
[[V5]] = IsCallable ([[V2]])
[[V6]]:pointer = SetLexicalEnvironment ([[V2]])
LeavePrivateEnvironment
CallSlowPath Throw @21 ([[V5]]) [[[FS0]]]
Unreachable
frame states:
- [[FS0]]: pc 21 after {}
+ [[FS0]]: pc 21 after {r3=#undefined}
+ ",
+ );
+}
+
+#[test]
+fn reserved_registers_hold_values_like_other_registers() {
+ // A slow path gives its output as a value, also where it writes a reserved register, and frame states list the
+ // value, which frame memory does not hold.
+ let program = assemble(|_| {
+ vec![
+ Instruction::Exp {
+ arith_feedback: 0,
+ dst: r(4),
+ lhs: a(0),
+ rhs: a(0),
+ },
+ Instruction::Exp {
+ arith_feedback: 0,
+ dst: r(5),
+ lhs: r(4),
+ rhs: a(0),
+ },
+ Instruction::Return { value: r(4) },
+ ]
+ });
+ assert_dump(
+ &dump_of(&program),
+ "
+ [[B0]]:
+ Jump [[B1]]
+ [[B1]] (pc 0) <- [[B0]]:
+ [[A]] = LoadSlot a0
+ [[X]] = CallSlowPath Exp @0 ([[A]], [[A]]) [[[FS0]]]
+ [[Y]] = CallSlowPath Exp @6 ([[X]], [[A]]) [[[FS1]]]
+ [[RESULT]] = EmptyToUndefined ([[X]])
+ Return ([[RESULT]])
+ frame states:
+ [[FS0]]: pc 0 after -> r4 {} frame [a0]
+ [[FS1]]: pc 6 after -> r5 {r4=[[X]]}
",
);
}
@@ -2131,8 +2169,8 @@ pub(crate) mod inlining {
// The caller's `this` is loaded once, and the callee's flows through
// the merge without being reloaded.
let dump = dump_inlined(&caller, &callee, function(true, true));
- assert!(dump.contains("v2 = LoadSlot r2\n"), "{dump}");
- assert!(dump.contains("v16 = EmptyToUndefined (v2)\n"), "{dump}");
+ assert!(dump.contains("v3 = LoadSlot r2\n"), "{dump}");
+ assert!(dump.contains("v20 = EmptyToUndefined (v3)\n"), "{dump}");
assert_eq!(dump.matches("LoadSlot r2").count(), 1, "{dump}");
}
@@ -2359,7 +2397,7 @@ pub(crate) mod inlining {
snapshot.executables[0].feedback.call[0].forwarded = Some(forwarded(Forwarding::Call));
let text = dump(&optimized_graph(&snapshot), &test_layout());
// The function `call` is called on is checked, and gets the second argument.
- assert!(text.contains("CheckValue 0xfff9000000005000 (v4)"), "{text}");
+ assert!(text.contains("CheckValue 0xfff9000000005000 (v6)"), "{text}");
assert!(text.contains("Return (#10)"), "{text}");
// A bound function in a0 called with c1, bound to 7.
@@ -2432,7 +2470,7 @@ pub(crate) mod inlining {
let text = dump(&graph, &test_layout());
// NB: The callee, the `this` value (the sloppy callee reads it) and
// the argument are inputs.
- let expected = format!("CallDirect @{} (v4, #0, #10) [fs", caller().offsets[1]);
+ let expected = format!("CallDirect @{} (v6, #0, #10) [fs", caller().offsets[1]);
assert!(text.contains(&expected), "{text}");
// NB: The call's value is its result.
assert!(!text.contains("LoadSlot r5"), "{text}");
@@ -2454,7 +2492,7 @@ pub(crate) mod inlining {
many.executables[0].feedback.call[0].direct_call = Some(target);
let text = dump(&optimized_graph(&many), &test_layout());
let expected = format!(
- "CallDirect @{} storing operands (v4, #0, #10, #10, #10, #10, #10, #10) [fs",
+ "CallDirect @{} storing operands (v6, #0, #10, #10, #10, #10, #10, #10) [fs",
many_arguments.offsets[1]
);
assert!(text.contains(&expected), "{text}");
@@ -2531,6 +2569,29 @@ mod arguments {
assert!(text.contains("Generic CreateArguments"), "{text}");
}
+ #[test]
+ fn generic_nodes_are_followed_by_loads_of_the_slots_they_write() {
+ // Where the node does not continue, the frame holds what it wrote to its outputs, or their old values.
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ create_arguments(true),
+ Instruction::Return { value: l(0) },
+ ]
+ });
+ assert_dump(
+ &build(&program, |_| {}),
+ "
+ Generic CreateArguments @1 [[[FS0]]]
+ [[ARGUMENTS]] = LoadSlot l0
+ [[RESULT]] = EmptyToUndefined ([[ARGUMENTS]])
+ Return ([[RESULT]])
+ frame states:
+ [[FS0]]: pc 1 after -> l0 {} frame [l0]
+ ",
+ );
+ }
+
#[test]
fn spreads_forward_the_frame_arguments() {
let program = assemble(|_| {
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
index dc8e9d9b23b..af7eb0aed9f 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
@@ -21,7 +21,8 @@ use super::DecodedInstruction;
use super::ExceptionHandler;
use super::FrameLayout;
use super::OpCode;
-use super::RESERVED_REGISTER_COUNT;
+use super::Operand;
+use super::THIS_VALUE_REGISTER;
use crate::bitset::BitSet;
use std::ops::Range;
@@ -68,8 +69,8 @@ pub struct Loop {
/// Blocks of the loop, including the header and nested loops, in increasing order.
pub blocks: Vec<BlockIndex>,
/// Tracked slots (see `FrameLayout::tracked_index()`) written by any
- /// instruction in the loop. The reserved registers are always included,
- /// since some instructions write them implicitly.
+ /// instruction in the loop, with the this value register where a
+ /// `ResolveThisBinding` writes it without naming it.
pub assigned_slots: BitSet,
}
@@ -312,7 +313,7 @@ impl Cfg {
}
}
- let reserved_registers = 0..(RESERVED_REGISTER_COUNT.min(layout.registers_and_locals_count) as usize);
+ let this_register = layout.tracked_index(Operand::from_raw(THIS_VALUE_REGISTER));
for (loop_index, current_loop) in loops.iter_mut().enumerate() {
// The natural loop: the header plus every reachable block that
// reaches a back edge source without passing through the header.
@@ -329,9 +330,13 @@ impl Cfg {
}
current_loop.blocks = (0..self.blocks.len()).filter(|block| in_loop[*block]).collect();
- current_loop.assigned_slots.insert_range(reserved_registers.clone());
for block in &current_loop.blocks {
for instruction in &instructions[self.blocks[*block].instructions.clone()] {
+ if instruction.instruction.opcode() == OpCode::ResolveThisBinding
+ && let Some(slot) = this_register
+ {
+ current_loop.assigned_slots.insert(slot);
+ }
instruction.instruction.for_each_operand(|operand, role| {
if role.is_written()
&& let Some(slot) = layout.tracked_index(operand)
@@ -440,7 +445,7 @@ mod tests {
assert_eq!(cfg.blocks[1].predecessor_count(), 2);
let assigned = header_loop.assigned_slots.iter().collect::<Vec<_>>();
let local0 = layout.tracked_index(l(0)).unwrap();
- assert_eq!(assigned, [0, 1, 2, 3, 4, 5, local0]);
+ assert_eq!(assigned, [5, local0]);
assert_eq!(cfg.reverse_post_order, [0, 1, 3, 2]);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 1afde74f2d3..cac12296326 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -2725,11 +2725,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let ssa_outputs = outputs
.into_iter()
.filter(|operand| {
- crate::builder::is_ssa_slow_path_output(
- &frame_layout,
- crate::bytecode::Operand::from_raw(*operand),
- executable != 0,
- )
+ crate::builder::is_ssa_slow_path_output(&frame_layout, crate::bytecode::Operand::from_raw(*operand))
})
.collect::<Vec<_>>();
Ok((operands, ssa_outputs))
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 806f5134ab5..50655a4f209 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -28,11 +28,10 @@
//! that have a representation (or virtual objects);
//! - slow path calls have a frame state, and those that save registers
//! are in cold blocks;
-//! - `StoreSlot` writes only the reserved registers, written constants, the
-//! arguments the compiled function's legacy `arguments` shows, and slots
-//! that the next call reading the frame (a `Generic` node, or a call that
-//! reads its operands from the frame) or `Suspend` reads (see
-//! `verify_frame_writes()`).
+//! - `StoreSlot` writes only written constants, the arguments the compiled
+//! function's legacy `arguments` shows, and slots that the next call
+//! reading the frame (a `Generic` node, or a call that reads its operands
+//! from the frame) or `Suspend` reads (see `verify_frame_writes()`).
use super::dominators::Dominators;
use crate::bytecode::FrameLayout;
@@ -54,12 +53,9 @@ struct Place {
index: usize,
}
-/// Checks that `StoreSlot` writes frame memory only where nothing else can:
-/// the reserved registers (the this value and the saved lexical
-/// environment, which slow paths write there too), written constants, the
-/// arguments the compiled function's legacy `arguments` shows, and the slots
-/// a node that reads the frame reads, right before it. Merges and back edges
-/// never write frame memory: slots that differ get phis.
+/// Checks that `StoreSlot` writes frame memory only where something reads it: written constants, which live there,
+/// the arguments the compiled function's legacy `arguments` shows, and the slots a node that reads the frame reads,
+/// right before it. Merges and back edges never write frame memory: slots that differ get phis.
pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), String> {
let mut errors = Vec::new();
for (index, block) in graph.blocks.iter().enumerate() {
@@ -75,20 +71,21 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), St
};
let operand = Operand::from_raw(slot).raw();
let is_constant = operand >= layout.registers_and_locals_count && operand < layout.arguments_base();
- if operand < RESERVED_REGISTER_COUNT || is_constant || graph.legacy_arguments.contains(&operand) {
+ if is_constant || graph.legacy_arguments.contains(&operand) {
continue;
}
// NB: Conversions of the reader's inputs may come in between, and
- // so may the frame's initialization for stores of arguments,
- // which it leaves as they are (see `frame_initialization`).
- let is_argument = operand >= layout.arguments_base();
+ // so may the frame's initialization for stores of arguments
+ // and reserved registers, which it leaves as they are (see
+ // `frame_initialization`).
+ let survives_initialization = operand >= layout.arguments_base() || operand < RESERVED_REGISTER_COUNT;
let reader = nodes[position + 1..].iter().find(|next| {
let op = &graph.node(**next).op;
let properties = op.properties();
let initializes_frame =
matches!(op, Op::InitializeFrame | Op::EnsureFrameInitialized | Op::PublishFrame);
!matches!(op, Op::StoreSlot { .. })
- && !(is_argument && initializes_frame)
+ && !(survives_initialization && initializes_frame)
&& (properties.reads != Locations::NONE || properties.writes != Locations::NONE)
});
let reads_frame = reader.is_some_and(|reader| {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index c437b037b2a..ef0b3dcd944 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -67,14 +67,14 @@ fn straight_line_code() {
&dump_allocation(&graph, &allocation),
"
b0:
- v0 Jump
+ v7 Jump
b1:
- v5 LoadSlot -> r0
- v9 InitializeFrame temps r1, r2
- v6 CallSlowPath (#10, r0) -> r0
- v7 EmptyToUndefined (r0) -> r1
+ v6 LoadSlot -> r0
+ v14 InitializeFrame temps r1, r2
+ v11 CallSlowPath (#10, r0) -> r0
+ v12 EmptyToUndefined (r0) -> r1
moves r1 -> r0
- v8 Return (r0)
+ v13 Return (r0)
spill slots: 0
",
);
@@ -104,13 +104,13 @@ fn values_live_across_calls_are_spilled_at_their_definition() {
&dump_allocation(&graph, &allocation),
"
b0:
- v0 Jump
+ v8 Jump
b1:
- v1 LoadSlot -> r0 spill s0
- v2 LoadSlot -> r1
- v3 CallSlowPath (r1, r1, r0) -> r0 exit {6=s0}
+ v6 LoadSlot -> r0
+ v7 LoadSlot -> r1 spill s0
+ v9 CallSlowPath (r0, r0, r1) -> r0 exit {6=s0}
moves s0 -> r0
- v4 Return (r0)
+ v10 Return (r0)
spill slots: 1
",
);
@@ -249,34 +249,34 @@ fn swapping_loop_phis_go_through_a_temp_slot() {
&dump_allocation(&graph, &allocation),
"
b0:
- v0 Jump
+ v6 Jump
b1:
moves #0 -> r0, #10 -> r1
- v6 Jump
+ v11 Jump
b2:
- v7 Phi -> r0
- v8 Phi -> r1
- v9 BranchTruthy (r0)
+ v12 Phi -> r0
+ v13 Phi -> r1
+ v14 BranchTruthy (r0)
b3:
- v10 Jump
+ v15 Jump
b4:
- v11 Jump
+ v16 Jump
b5:
moves r0 -> r1
- v12 ToBoolean (r1) -> r0
- v13 Branch (r0)
+ v17 ToBoolean (r1) -> r0
+ v18 Branch (r0)
b6:
moves s0 -> r0, s1 -> r1
- v14 Jump
+ v19 Jump
b7:
moves s1 -> r1
- v15 Jump
+ v20 Jump
b8:
moves r1 -> r0
- v16 Return (r0)
+ v21 Return (r0)
b9:
moves r0 -> s2, r1 -> r0, s2 -> r1
- v17 Jump
+ v22 Jump
spill slots: 3
",
);
diff --git a/Tests/LibJS/JIT/ir/generators.js b/Tests/LibJS/JIT/ir/generators.js
index 0b163a85cfa..868b6c50aef 100644
--- a/Tests/LibJS/JIT/ir/generators.js
+++ b/Tests/LibJS/JIT/ir/generators.js
@@ -16,7 +16,6 @@ jit.compile(counter);
// CHECK-NEXT: LoadSlot a0
// CHECK-NEXT: Jump [[CONTINUATION:b[0-9]+]]
// CHECK: InitializeFrame
-// CHECK-NEXT: LoadSlot r2
// CHECK-NEXT: Suspend pc [[START:[0-9]+]]
// CHECK-NEXT: Return (#undefined)
// CHECK: Suspend completed
diff --git a/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js b/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js
index 037d4259e58..14627a0ae1e 100644
--- a/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js
+++ b/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js
@@ -17,9 +17,9 @@ jit.compile(countUp);
// CHECK-FUNCTION: countUp
// CHECK-PASS: graph building
// CHECK: b0:
-// CHECK-NEXT: Jump
+// CHECK: Jump
// CHECK-NEXT: [[ENTRY:b[0-9]+]]:
-// CHECK-NEXT: LoadSlot l0
+// CHECK: LoadSlot l0
// CHECK-NEXT: LoadSlot a0
// CHECK-NEXT: CheckInterrupt
// CHECK-NEXT: Jump [[HEADER:b[0-9]+]]
@@ -27,7 +27,7 @@ jit.compile(countUp);
// CHECK: osr entry at pc {{[0-9]+}}: [[ENTRY]]
// CHECK-PASS: loop invariant code motion
// CHECK: :int32 = Phi ({{v[0-9]+}}, #i32:0)
-// CHECK-NEXT: [[BOUND:v[0-9]+]] = LoadSlot a0
+// CHECK: [[BOUND:v[0-9]+]] = LoadSlot a0
// CHECK-NEXT: CheckInt32 ([[BOUND]])
// CHECK-NEXT: Jump [[LOOP:b[0-9]+]]
// CHECK-NEXT: [[LOOP]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}} loop:
diff --git a/Tests/LibJS/JIT/ir/osr-update-step.js b/Tests/LibJS/JIT/ir/osr-update-step.js
index dc36df3d0ae..676bdd67aca 100644
--- a/Tests/LibJS/JIT/ir/osr-update-step.js
+++ b/Tests/LibJS/JIT/ir/osr-update-step.js
@@ -18,10 +18,7 @@ jit.compile(sumOf);
// CHECK-FUNCTION: sumOf
// CHECK-PASS: graph building
-// CHECK: b0:
-// CHECK: LoadSlot a1
-// CHECK-NEXT: Jump [[HEADER:b[0-9]+]]
-// CHECK: [[HEADER]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}} loop:
+// CHECK: [[HEADER:b[0-9]+]] (pc {{[0-9]+}}) <- {{b[0-9]+}}, {{b[0-9]+}}, {{b[0-9]+}} loop:
// CHECK: Int32Add ({{v[0-9]+}}, #i32:1)
// CHECK-NEXT: BoxInt32
// CHECK-NEXT: Jump [[HEADER]]