Skip to content

Truly independent web browser

LibJS: Compile generators in the JIT

Andreas Kling9181091b9cbb
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index b85fe4d6c6f..b8eb7f195e0 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -14,10 +14,10 @@ LibJS has two tiers: the bytecode interpreter, whose instructions keep per-site
feedback, and this optimizing JIT. An executable that uses up its tier-up budget (calls and loop
iterations) is snapshotted and compiled on one of the compile threads. The interpreter keeps running
it meanwhile; the main thread installs the code when the job finishes. Loops that run long enough
-enter compiled code at their back edges (on-stack replacement). A call from compiled code into a
-function the interpreter runs counts as several invocations of it (`callee-boost`): code hot enough
-to be compiled calls it, so it is likely to be hot as well, and there is no baseline tier to run it
-in meanwhile.
+enter compiled code at their back edges (on-stack replacement), and generators enter it where they
+resume (section 4.1). A call from compiled code into a function the interpreter runs counts as
+several invocations of it (`callee-boost`): code hot enough to be compiled calls it, so it is likely
+to be hot as well, and there is no baseline tier to run it in meanwhile.
There is no baseline tier. The interpreter's caches are the baseline: the JIT translates what they
saw into speculation, and leaves to the interpreter wherever a speculation fails.
@@ -42,8 +42,8 @@ and are rematerialized at every use. Every value has a representation (`Repr`):
float64, bool or pointer. Cold blocks hold code that rarely runs (slow paths of checks); they come last
in the final block order.
-Blocks without predecessors are entries: block 0 and the on-stack replacement entries. Every block
-is reachable from one.
+Blocks without predecessors are entries: block 0, the on-stack replacement entries and the resume
+entries of generators (section 4.1). 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
@@ -121,7 +121,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| 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 reads. The verifier enforces this. | | | 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 | |
| BoxInt32, BoxBool | The tagged value of an unboxed input. | | | | cse |
| CheckInt32 | Input 0 as an int32; exits unless it is one. | E | | | cse |
| CheckNumber | Input 0 as a float64; exits unless it is a number. | E | | | cse |
@@ -198,6 +198,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| **Frames and environments** | | | | | |
| InitializeFrame, EnsureFrameInitialized | The `Enter` bytecode: publishes the frame, empties the registers and locals, copies the constants (the second only if the frame is not initialized yet). | | | Frame | |
| PublishFrame | Makes the frame the running execution context, which direct calls leave to their callee's code. | | | Frame | |
+| Suspend | Records where the frame's generator resumes (a continuation, or none once it completes) and whether the value it yields is an iterator result, right before the `Return` of a `Yield` (section 4.1). | | Frame | Frame | |
| LoadFrameField | A field of the running execution context (an environment, the realm, the executable) as a pointer. The builder loads each once per path, until an instruction may replace it. | | Frame | | |
| SetLexicalEnvironment | Makes a cell value the frame's lexical environment; its value is the environment's pointer. | | Frame | Frame | |
| LeavePrivateEnvironment | Makes the private environment's outer one the frame's. | | Frame | Frame | |
@@ -269,6 +270,23 @@ collect garbage or exit lazily before that. Eager exits publish the frame in the
the prologue's resumption in the interpreter publishes it inline.
+### 4.1 Generators
+
+A generator runs in its own frame, which it keeps while it is suspended. Compiled code suspends it
+like the interpreter's `Yield` and `YieldIteratorResult` do: `StoreSlot`s put every slot live at
+the continuation in frame memory, `Suspend` records the continuation in the frame, and `Return`
+returns the yielded value to the runtime. So a suspended generator's frame is the frame the
+interpreter would have left, whichever of the two ran 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
+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()`,
+which enters compiled code at the resume entry if the executable has code with one there, and
+interprets it otherwise. The function's start (its `Enter` and the initial `Yield`) is compiled
+like any function's. Async functions, whose `Await` suspends them, are not compiled yet.
+
## 5. Dependencies and invalidation
Compiled code may assume facts that hold until a rare runtime event (`code::Dependency`): a
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
index 15c1f95234d..8685413249a 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
@@ -84,8 +84,7 @@ const EXPANDED: Handling = Handling::Expanded(GenericInfo {
reads_whole_frame: false,
});
-const SUSPENDS: Handling =
- Handling::Unsupported("suspends a generator or async function; JIT code is only entered at function entry");
+const AWAITS: Handling = Handling::Unsupported("suspends an async function; only generators resume in JIT code");
/// How the graph builder handles `opcode`.
pub fn handling(opcode: OpCode) -> Handling {
@@ -110,7 +109,9 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::JumpNullish
| O::JumpUndefined
| O::Return
- | O::End => Handling::Native,
+ | O::End
+ | O::Yield
+ | O::YieldIteratorResult => Handling::Native,
// Truthiness, built from a truthiness branch and a phi.
O::Not | O::ToBoolean => Handling::Native,
@@ -123,7 +124,7 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::GetArgumentCount => Handling::Native,
O::Catch => Handling::Unsupported("starts an exception handler; handler blocks are not built"),
- O::Await | O::Yield | O::YieldIteratorResult => SUSPENDS,
+ O::Await => AWAITS,
// Calls.
O::Call
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 2905b44ff51..3fc990bd1ac 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -608,6 +608,7 @@ impl<'a> GraphBuilder<'a> {
self.enter_function(entry);
if self.build_osr_entries {
self.build_osr_entries()?;
+ self.build_resume_entries()?;
}
self.build_function()?;
@@ -1503,6 +1504,14 @@ impl<'a> GraphBuilder<'a> {
self.set_control(Op::Return, vec![value]);
return Ok(Some(Flow::Ended));
}
+ Instruction::Yield {
+ continuation_label,
+ value,
+ } => return self.build_suspend(continuation_label, value, false).map(Some),
+ Instruction::YieldIteratorResult {
+ continuation_label,
+ value,
+ } => return self.build_suspend(Some(continuation_label), value, true).map(Some),
Instruction::GetLexicalEnvironment { dst } => {
let address = self.frame_field(FrameField::LexicalEnvironment)?;
let environment = self.emit(Op::BoxCell, vec![address], Some(Repr::Tagged));
@@ -1736,6 +1745,56 @@ impl<'a> GraphBuilder<'a> {
Ok(Some(Flow::Continue))
}
+ /// Builds a `Yield` (or a `YieldIteratorResult`), which suspends the
+ /// generator running the compiled function and returns `value` to the
+ /// code resuming it: puts the slots live at the continuation in frame
+ /// memory, where the resume entry of the continuation (see `osr`) finds
+ /// them, and records the continuation in the frame like the
+ /// interpreter's `Yield`.
+ fn build_suspend(
+ &mut self,
+ continuation: Option<Label>,
+ value: Operand,
+ value_is_iterator_result: bool,
+ ) -> Result<Flow, CompileFailure> {
+ if self.function.is_virtual() {
+ return Err(CompileFailure::InvalidBytecode {
+ pc: self.function.pc,
+ reason: "yield in an inlined callee",
+ });
+ }
+ let value = self.read(value)?;
+ self.check_not_returning_virtual_arguments(value)?;
+ 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).clone();
+ for slot in live.iter() {
+ if self.tracks_slot(slot) {
+ self.sync_slot(slot);
+ }
+ }
+ }
+ // NB: Like the interpreter's Yield, an empty value yields `undefined`.
+ let layout = self.function.layout;
+ let arguments = layout.arguments_base()..layout.arguments_base() + layout.number_of_arguments;
+ let value = if self.graph.is_known_non_empty(value, arguments) {
+ value
+ } else {
+ self.emit(Op::EmptyToUndefined, vec![value], Some(Repr::Tagged))
+ };
+ self.emit(
+ Op::Suspend {
+ continuation: continuation.map(|label| label.0),
+ value_is_iterator_result,
+ },
+ Vec::new(),
+ None,
+ );
+ self.set_control(Op::Return, vec![value]);
+ Ok(Flow::Ended)
+ }
+
/// Builds an instruction as its handling table entry says.
fn build_by_handling(&mut self, instruction: &Instruction) -> Result<Flow, CompileFailure> {
let opcode = instruction.opcode();
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
index c2a755e6a85..497115625d4 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
@@ -19,11 +19,19 @@
//! update step of a for loop, which leads to the loop's header, the entry runs
//! that step itself instead. Its edges are forward edges into the loop and the
//! loop exit, so the values it loaded meet the other paths in phis.
+//!
+//! A generator resumes the same way: a suspended generator's frame holds every
+//! value live at the continuation it resumes at (see `build_suspend()`), so
+//! each continuation of a `Yield` or `YieldIteratorResult` gets an entry block
+//! that loads them and jumps to the continuation's block, which compiled code
+//! reaches from nowhere else. The runtime enters there like at an on-stack
+//! replacement entry.
use super::AbstractFrame;
use super::Flow;
use super::GraphBuilder;
use crate::CompileFailure;
+use crate::bytecode::Instruction;
use crate::bytecode::OpCode;
use crate::bytecode::RESERVED_REGISTER_COUNT;
use crate::bytecode::cfg::BlockIndex;
@@ -134,20 +142,75 @@ impl GraphBuilder<'_> {
}
self.graph.osr_entries.push((pc, block));
self.record_osr_loop_back_edges(pc);
+ self.note_loops_entered_at(&targets);
+ }
+ Ok(())
+ }
- // NB: The loops the entry leads into other than at their header may
- // only be reached from here over their back edges.
- for target in targets {
- for current_loop in &self.function.cfg.loops {
- if current_loop.blocks.contains(&target) && current_loop.header != target {
- self.function.osr_loop_headers[current_loop.header] = true;
- }
+ /// Builds an entry block for every continuation of a generator's
+ /// suspension in the compiled function, after the on-stack replacement
+ /// entries, before any of its bytecode blocks is started.
+ pub(super) fn build_resume_entries(&mut self) -> Result<(), CompileFailure> {
+ debug_assert!(!self.function.is_virtual());
+ for index in 0..self.function.instructions.len() {
+ let (Instruction::Yield {
+ continuation_label: Some(continuation),
+ ..
+ }
+ | Instruction::YieldIteratorResult {
+ continuation_label: continuation,
+ ..
+ }) = self.function.instructions[index].instruction
+ else {
+ continue;
+ };
+ let pc = continuation.0;
+ let target = self.block_for_label(continuation)?;
+ let target_block = &self.function.cfg.blocks[target];
+ if target_block.start_pc != pc {
+ return Err(CompileFailure::InvalidBytecode {
+ pc,
+ reason: "continuation that does not start a block",
+ });
+ }
+ // NB: An on-stack replacement entry at a back edge that starts the
+ // block resumes the frame there just the same.
+ if target_block.rpo_number.is_none() || self.graph.osr_entries.iter().any(|(entry_pc, _)| *entry_pc == pc) {
+ continue;
+ }
+ 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).clone();
+ 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);
}
}
+ self.end_with_jump(target)?;
+ self.graph.osr_entries.push((pc, block));
+ self.note_loops_entered_at(&[target]);
}
Ok(())
}
+ /// 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.
+ fn note_loops_entered_at(&mut self, targets: &[BlockIndex]) {
+ for &target in targets {
+ for current_loop in &self.function.cfg.loops {
+ if current_loop.blocks.contains(&target) && current_loop.header != target {
+ self.function.osr_loop_headers[current_loop.header] = true;
+ }
+ }
+ }
+ }
+
/// The block that the unconditional back edge at instruction `index` jumps
/// to, if it is no loop header and leads to one and nowhere else.
fn update_block_of_back_edge(&self, index: usize) -> Option<BlockIndex> {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index 996e1e6e9a5..bc71973464a 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -386,9 +386,9 @@ fn instructions_whose_feedback_is_empty_never_ran() {
fn unsupported_instructions_fail_cleanly() {
let program = assemble(|label| {
vec![
- Instruction::Yield {
- continuation_label: Some(label(1)),
- value: r(5),
+ Instruction::Await {
+ continuation_label: label(1),
+ argument: r(5),
},
Instruction::Return { value: r(5) },
]
@@ -399,7 +399,7 @@ fn unsupported_instructions_fail_cleanly() {
failure,
CompileFailure::UnsupportedInstruction {
pc: 0,
- opcode: crate::bytecode::OpCode::Yield,
+ opcode: crate::bytecode::OpCode::Await,
..
}
));
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
index dd268975590..ec0ea27ab89 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
@@ -19,6 +19,10 @@ pub const RESERVED_REGISTER_COUNT: u32 = 5;
/// The reserved register holding the frame's `this` value.
pub const THIS_VALUE_REGISTER: u32 = 2;
+/// The `yield_continuation` of a frame whose generator completes
+/// (`ExecutionContext::NO_YIELD_CONTINUATION`).
+pub const NO_YIELD_CONTINUATION: u32 = u32::MAX;
+
/// The `kind` of a `CreateArguments` that creates a mapped arguments object
/// (`ArgumentsKind::Mapped` in `Libraries/LibJS/ABI`).
pub const MAPPED_ARGUMENTS: u32 = 0;
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 1b53f130999..46c4d82ccaa 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -75,6 +75,7 @@ use crate::asm::MachineFrame;
use crate::asm::PortableMacroAssembler;
use crate::asm::disassembler;
use crate::bytecode::DecodedInstruction;
+use crate::bytecode::NO_YIELD_CONTINUATION;
use crate::bytecode::OpCode;
use crate::bytecode::OperandRole;
use crate::bytecode::SlowPathAbi;
@@ -1296,6 +1297,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let environment = self.frame_field(self.runtime.offsets.execution_context_lexical_environment);
self.masm.store64(&environment, output);
}
+ Op::Suspend {
+ continuation,
+ value_is_iterator_result,
+ } => {
+ let offsets = self.runtime.offsets;
+ let continuation = continuation.unwrap_or(NO_YIELD_CONTINUATION);
+ let mut fields = [
+ (offsets.execution_context_yield_continuation, 4, u64::from(continuation)),
+ (offsets.execution_context_yield_is_await, 1, 0),
+ (
+ offsets.execution_context_yield_value_is_iterator_result,
+ 1,
+ u64::from(*value_is_iterator_result),
+ ),
+ ];
+ self.emit_constant_fields(self.pinned.frame, self.pinned.scratch, &mut fields)?;
+ }
Op::LeavePrivateEnvironment => {
let scratch = self.pinned.scratch;
let field = self.frame_field(self.runtime.offsets.execution_context_private_environment);
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index d281c70be38..1017a00b6c4 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -111,6 +111,18 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
Op::InitializeFrame => with_inputs("InitializeFrame"),
Op::EnsureFrameInitialized => with_inputs("EnsureFrameInitialized"),
Op::PublishFrame => with_inputs("PublishFrame"),
+ Op::Suspend {
+ continuation,
+ value_is_iterator_result,
+ } => {
+ let continuation = continuation.map_or("completed".to_string(), |pc| format!("pc {pc}"));
+ let result = if *value_is_iterator_result {
+ " iterator-result"
+ } else {
+ ""
+ };
+ with_inputs(&format!("Suspend {continuation}{result}"))
+ }
Op::BoxCell => with_inputs("BoxCell"),
Op::LoadOuterEnvironment => with_inputs("LoadOuterEnvironment"),
Op::LoadEnvironmentBinding { index } => with_inputs(&format!("LoadEnvironmentBinding {index}")),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index c437b2dd220..d3553fda5a9 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -426,6 +426,16 @@ pub enum Op {
/// Does what `InitializeFrame` does, unless the frame is initialized
/// already. See `passes::frame_initialization`.
EnsureFrameInitialized,
+ /// The suspension of the `Yield` and `YieldIteratorResult` bytecodes,
+ /// right before the `Return` of the yielded value: records in the
+ /// frame where its generator resumes (`continuation`, or nowhere once it
+ /// completes) and whether the value is an iterator result already. The
+ /// `StoreSlot`s before it put every slot live at the continuation in
+ /// frame memory, from where the runtime resumes the frame.
+ Suspend {
+ continuation: Option<u32>,
+ value_is_iterator_result: bool,
+ },
/// The environment the environment at the `Repr::Pointer` input 0 is in
/// (its outer environment), as a `Repr::Pointer`. Environments keep
/// their outer environment.
@@ -1198,6 +1208,12 @@ impl Op {
writes: Locations::FRAME,
..P::PURE
},
+ // NB: It hands the frame's slots to the code that resumes it.
+ Op::Suspend { .. } => P {
+ reads: Locations::FRAME,
+ writes: Locations::FRAME,
+ ..P::PURE
+ },
Op::Phi => P::PURE,
Op::InitializeFrame | Op::EnsureFrameInitialized | Op::PublishFrame => P {
writes: Locations::FRAME,
@@ -1510,6 +1526,7 @@ impl Op {
Op::Phi => "Phi",
Op::InitializeFrame => "InitializeFrame",
Op::EnsureFrameInitialized => "EnsureFrameInitialized",
+ Op::Suspend { .. } => "Suspend",
Op::PublishFrame => "PublishFrame",
Op::BoxCell => "BoxCell",
Op::LoadOuterEnvironment => "LoadOuterEnvironment",
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
index 63c41877f33..af9d7c974ca 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
@@ -131,6 +131,9 @@ fn need(node: &Node, layout: &FrameLayout) -> Need {
Op::CallDirect { executable, .. } | Op::CallNative { executable, .. } if *executable != 0 => Need::Published,
// NB: The helper only looks at its argument.
Op::ToBoolean => Need::Nothing,
+ // NB: The generator resumes in the frame, where the interpreter
+ // needs the constants too.
+ Op::Suspend { .. } => Need::Initialized,
op => {
let properties = op.properties();
if properties.is_call || properties.can_lazy_exit {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 0f035c34839..91a65475969 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -31,7 +31,8 @@
//! - `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) reads (see `verify_frame_writes()`).
+//! reads its operands from the frame) or `Suspend` reads (see
+//! `verify_frame_writes()`).
use super::dominators::Dominators;
use crate::bytecode::FrameLayout;
@@ -93,8 +94,10 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), St
|| properties.writes != Locations::NONE)
});
let reads_frame = reader.is_some_and(|reader| {
- let properties = graph.node(*reader).op.properties();
- properties.is_call && properties.reads.intersects(Locations::FRAME)
+ let op = &graph.node(*reader).op;
+ let properties = op.properties();
+ (properties.is_call && properties.reads.intersects(Locations::FRAME))
+ || matches!(op, Op::Suspend { .. })
});
if !reads_frame {
errors.push(format!(
diff --git a/Libraries/LibJS/Rust/src/interpreter/run.rs b/Libraries/LibJS/Rust/src/interpreter/run.rs
index 6e81309d5f1..d13e4e7a520 100644
--- a/Libraries/LibJS/Rust/src/interpreter/run.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/run.rs
@@ -107,8 +107,7 @@ impl Vm {
unreachable!("throw_completion always throws");
};
context_ref.register(register::EXCEPTION).set(throw.value());
- } else if entry_point == 0 && crate::jit::entry_exit::can_enter_jit_code(self, executable_ref) {
- let result = crate::jit::entry_exit::enter_jit_code(self, context);
+ } else if let Some(result) = self.enter_jit_code_at(context, executable_ref, entry_point) {
match result.status {
EntryStatus::Returned => self.return_from_running_frame(Value(result.value)),
EntryStatus::Resume => self.run_running_frame_in_interpreter(),
@@ -150,6 +149,22 @@ impl Vm {
Ok(return_value)
}
+ /// Runs the running `context` from `entry_point` in the JIT code of its executable, if it has code with an entry
+ /// there: its entry at the function's start, or the resume entry of a generator's continuation. Returns how the
+ /// code returned, if it ran.
+ fn enter_jit_code_at(
+ &self,
+ context: NonNull<ExecutionContext>,
+ executable: &Executable,
+ entry_point: u32,
+ ) -> Option<crate::jit::code::JitResult> {
+ if entry_point != 0 {
+ return crate::jit::entry_exit::enter_jit_code_at_continuation(self, context, entry_point);
+ }
+ crate::jit::entry_exit::can_enter_jit_code(self, executable)
+ .then(|| crate::jit::entry_exit::enter_jit_code(self, context))
+ }
+
/// Runs the running execution context in the interpreter from its program counter, until it returns to a caller
/// waiting in native code or leaves the interpreter.
pub fn run_running_frame_in_interpreter(&self) {
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rs
index 3ac7dfb0a65..618ed77b15b 100644
--- a/Libraries/LibJS/Rust/src/jit/code.rs
+++ b/Libraries/LibJS/Rust/src/jit/code.rs
@@ -206,6 +206,8 @@ impl JitCode {
self.entry
}
+ /// The entry at `pc` for a frame whose memory holds every value live there: an on-stack replacement entry at a
+ /// loop back edge, or the resume entry at a continuation of a generator's suspension.
pub fn osr_entry(&self, pc: u32) -> Option<JitEntry> {
self.osr_entries
.iter()
diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rs
index 50e867742b5..9ce589db561 100644
--- a/Libraries/LibJS/Rust/src/jit/disabled.rs
+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs
@@ -153,6 +153,10 @@ pub mod entry_exit {
unreachable!("no executable has JIT code");
}
+ pub fn enter_jit_code_at_continuation(_vm: &Vm, _frame: NonNull<ExecutionContext>, _pc: u32) -> Option<JitResult> {
+ None
+ }
+
pub fn helper_enter_jit_code(_vm: &Vm) -> i64 {
unreachable!("only the profiling interpreter enters JIT code");
}
diff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
index 95f82f89136..b5fb91fb6fe 100644
--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs
+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
@@ -103,6 +103,24 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32
Some(enter_from_native_code(vm, frame, entry))
}
+/// Resumes the running frame, a generator's frame suspended at the continuation `pc`, in its executable's JIT code if
+/// that has a resume entry there. Returns how the code returned, if it ran.
+pub fn enter_jit_code_at_continuation(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32) -> Option<JitResult> {
+ assert_eq!(vm.running_execution_context(), Some(frame));
+ let frame_ref = frame_of(frame);
+ let executable = executable_of(frame_ref);
+ if !can_enter_jit_code(vm, &executable) || !frame_ref.frame_initialized.get() {
+ return None;
+ }
+ let entry = executable
+ .jit_code()
+ .expect("the executable has JIT code")
+ .osr_entry(pc)?;
+ vm.jit.count_coverage("resume-entry");
+ frame_ref.program_counter.set(pc);
+ Some(enter_from_native_code(vm, frame, entry))
+}
+
/// Runs the frame that just became the running execution context in its executable's JIT code, if it can, for the
/// interpreter's Call, which found that the executable has JIT code. Returns the control word of the interpreter's
/// `asm_helper_enter_jit_code`: negative if the interpreter leaves, 1 if the code returned (the frame is still the
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 0c75d9742e3..28d6537e8b6 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -344,6 +344,11 @@ fn runtime_layout() -> RuntimeLayout {
}
}
+const _: () = assert!(
+ libjs_jit::bytecode::NO_YIELD_CONTINUATION
+ == crate::layout::execution_context::ExecutionContext::NO_YIELD_CONTINUATION
+);
+
// NB: The compiler has its own copy of the bits of the interpreter's feedback.
const _: () = {
assert!(libjs_jit::snapshot::value_feedback::INT32 == crate::layout::feedback::value_feedback::INT32);
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index 8183ccb334b..e007dd86fb3 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -113,9 +113,15 @@ fn function_to_compile(vm: &Vm) -> Option<Gc<EcmascriptFunctionObject>> {
if vm.debugging_enabled() {
return None;
}
- // NB: Generators and async functions resume in the middle, and top-level code runs once.
+ // NB: Async functions resume in the middle, and top-level code runs once.
let function = as_ecmascript_function_object(vm.running_execution_context_ref().function.get()?)?;
- (function.kind() == FunctionKind::Normal).then_some(function)
+ is_compiled_kind(function.kind()).then_some(function)
+}
+
+/// Whether the JIT compiles functions of this kind. Generators resume in their code at the entries of their
+/// continuations.
+fn is_compiled_kind(kind: FunctionKind) -> bool {
+ matches!(kind, FunctionKind::Normal | FunctionKind::Generator)
}
/// Whether the running frame runs a builtin written in JavaScript.
@@ -420,7 +426,7 @@ fn compile(
/// Compiles the executable of `function` right away, from the feedback it has, unless it has code, is being compiled or
/// is never compiled. Returns whether it has code afterwards. For tests (see `jit::testing`).
pub fn compile_now(vm: &Vm, function: Gc<EcmascriptFunctionObject>) -> bool {
- if !vm.jit.options.enabled || vm.debugging_enabled() || function.kind() != FunctionKind::Normal {
+ if !vm.jit.options.enabled || vm.debugging_enabled() || !is_compiled_kind(function.kind()) {
return false;
}
let executable = function.compiled_executable(vm);
diff --git a/Tests/LibJS/JIT/ir/generators.js b/Tests/LibJS/JIT/ir/generators.js
new file mode 100644
index 00000000000..498345d2976
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/generators.js
@@ -0,0 +1,30 @@
+// A generator suspends in compiled code like the interpreter's Yield: it writes the slots live at the continuation to
+// its frame, records the continuation, and returns the value. It resumes at an entry block of the continuation, which
+// loads those slots from the frame like an on-stack replacement entry.
+
+function* counter(limit) {
+ for (let i = 0; i < limit; ++i) yield i;
+}
+jit.prepare(counter);
+for (let i = 0; i < 10; ++i) [...counter(5)];
+jit.compile(counter);
+
+// CHECK-FUNCTION: counter
+// CHECK-PASS: graph building
+// CHECK: LoadSlot l0
+// 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
+// CHECK-NEXT: Return (#undefined)
+// CHECK: StoreSlot l0 ([[VALUE:v[0-9]+]])
+// CHECK-NEXT: Suspend pc [[NEXT:[0-9]+]]
+// CHECK-NEXT: Return ([[VALUE]])
+// CHECK: [[CONTINUATION]] (pc [[NEXT]]) <- [[RESUME:b[0-9]+]]:
+// CHECK: osr entry at pc [[START]]: {{b[0-9]+}}
+// CHECK-NEXT: osr entry at pc [[NEXT]]: [[RESUME]]
+
+console.log([...counter(3)].join());
diff --git a/Tests/LibJS/Runtime/jit/generators.js b/Tests/LibJS/Runtime/jit/generators.js
new file mode 100644
index 00000000000..548e698af8c
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/generators.js
@@ -0,0 +1,167 @@
+// Generators run in compiled code: a call starts one there, and each resumption enters the code at the continuation
+// of the yield it was suspended at, with the values that the frame kept across the suspension.
+//
+// NB: The functions come from the GeneratorFunction constructor, so that each run of a test (see LIBJS_TEST_REPEAT)
+// compiles new ones.
+
+const GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor;
+
+function prepared(...parameters_and_body) {
+ const generator = new GeneratorFunction(...parameters_and_body);
+ jit.prepare(generator);
+ return generator;
+}
+
+function compile(generator, warm_up) {
+ for (let i = 0; i < 10; ++i) warm_up();
+ expect(jit.compile(generator)).toBe(jit.enabled);
+}
+
+describe("generators in compiled code", () => {
+ test("resume where they yielded, with the values live across their yields", () => {
+ const count = prepared(
+ "start",
+ "step",
+ "let total = 0; for (let i = start; i < start + 5; i += step) { total += i; yield [i, total, jit.inCompiledCode()]; } return total * 2;"
+ );
+ compile(count, () => [...count(0, 1)]);
+ const generator = count(10, 2);
+ const results = [];
+ for (let result = generator.next(); !result.done; result = generator.next()) results.push(result.value);
+ expect(results.map(([value, total]) => [value, total])).toEqual([
+ [10, 10],
+ [12, 22],
+ [14, 36],
+ ]);
+ if (jit.enabled && !jit.forcesExits) expect(results.every(([, , compiled]) => compiled)).toBeTrue();
+ const first = count(1, 1).next();
+ expect(first.done).toBeFalse();
+ expect(first.value.slice(0, 2)).toEqual([1, 1]);
+ const finished = count(0, 4);
+ finished.next();
+ finished.next();
+ expect(finished.next()).toEqual({ value: 8, done: true });
+ expect(finished.next()).toEqual({ value: undefined, done: true });
+ });
+
+ test("receive the values passed to next", () => {
+ const accumulate = prepared(
+ "let total = 0; while (true) { const value = yield total; if (value === undefined) return total; total += value; }"
+ );
+ compile(accumulate, () => {
+ const generator = accumulate();
+ generator.next();
+ generator.next(1);
+ generator.next(2);
+ generator.next();
+ });
+ const generator = accumulate();
+ expect(generator.next(100)).toEqual({ value: 0, done: false });
+ expect(generator.next(5)).toEqual({ value: 5, done: false });
+ expect(generator.next(0.5)).toEqual({ value: 5.5, done: false });
+ expect(generator.next("x")).toEqual({ value: "5.5x", done: false });
+ expect(generator.next()).toEqual({ value: "5.5x", done: true });
+ });
+
+ test("keep this, arguments and captured bindings across yields", () => {
+ const make = new Function(
+ "GeneratorFunction",
+ "jit",
+ "let captured = 1; const generator = function* (a, b) { yield this.x + a; captured += b; yield arguments.length + captured; yield this.x * b; }; jit.prepare(generator); return [generator, () => captured];"
+ );
+ const [generator, captured] = make(GeneratorFunction, jit);
+ compile(generator, () => [...generator.call({ x: 1 }, 2, 3)]);
+ const before = captured();
+ expect([...generator.call({ x: 10 }, 20, 30, 40)]).toEqual([30, 3 + before + 30, 300]);
+ expect(captured()).toBe(before + 30);
+ });
+
+ test("finish through return and throw", () => {
+ const guarded = prepared("let i = 0; while (true) yield i++;");
+ compile(guarded, () => {
+ const generator = guarded();
+ generator.next();
+ generator.next();
+ generator.return(5);
+ });
+ const returned = guarded();
+ expect(returned.next()).toEqual({ value: 0, done: false });
+ expect(returned.next()).toEqual({ value: 1, done: false });
+ expect(returned.return(7)).toEqual({ value: 7, done: true });
+ expect(returned.next()).toEqual({ value: undefined, done: true });
+
+ const thrown = guarded();
+ thrown.next();
+ expect(() => thrown.throw(new RangeError("stop"))).toThrowWithMessage(RangeError, "stop");
+ expect(thrown.next()).toEqual({ value: undefined, done: true });
+ });
+
+ test("delegate with yield*", () => {
+ const inner = prepared("value", "const received = yield value; yield received * 2; return value + 1;");
+ const outer = prepared(
+ "inner",
+ "let results = []; for (let i = 0; i < 3; ++i) results.push(yield* inner(i)); return results;"
+ );
+ compile(inner, () => [...inner(1)]);
+ compile(outer, () => [...outer(inner)]);
+ const generator = outer(inner);
+ const values = [];
+ let result = generator.next();
+ for (let i = 0; !result.done; ++i) {
+ values.push(result.value);
+ result = generator.next(i);
+ }
+ expect(values).toEqual([0, 0, 1, 4, 2, 8]);
+ expect(result).toEqual({ value: [1, 2, 3], done: true });
+ });
+
+ test("run in for-of loops and spreads", () => {
+ const range = prepared("count", "for (let i = 0; i < count; ++i) yield i * i;");
+ compile(range, () => [...range(3)]);
+ let total = 0;
+ for (const value of range(100)) total += value;
+ expect(total).toBe(328350);
+ expect([...range(4)]).toEqual([0, 1, 4, 9]);
+ expect(Array.from(range(0))).toEqual([]);
+ });
+
+ test("leave compiled code where a speculation fails, and keep their state", () => {
+ const add = prepared("a", "b", "let sum = a; for (let i = 0; i < 3; ++i) { sum = sum + b; yield sum; }");
+ compile(add, () => [...add(1, 2)]);
+ expect([...add(1, 2)]).toEqual([3, 5, 7]);
+ expect([...add(2147483647, 1)]).toEqual([2147483648, 2147483649, 2147483650]);
+ expect([...add("a", 1)]).toEqual(["a1", "a11", "a111"]);
+ const generator = add(1, 1);
+ expect(generator.next()).toEqual({ value: 2, done: false });
+ expect(generator.next()).toEqual({ value: 3, done: false });
+ expect(generator.next()).toEqual({ value: 4, done: false });
+ expect(generator.next()).toEqual({ value: undefined, done: true });
+ });
+
+ test("suspended generators resume after their code is discarded and compiled again", () => {
+ const values = prepared("for (let i = 0; i < 4; ++i) yield i;");
+ compile(values, () => [...values()]);
+ const generator = values();
+ expect(generator.next()).toEqual({ value: 0, done: false });
+ jit.discard(values);
+ expect(generator.next()).toEqual({ value: 1, done: false });
+ expect(jit.compile(values)).toBe(jit.enabled);
+ expect(generator.next()).toEqual({ value: 2, done: false });
+ expect(generator.next()).toEqual({ value: 3, done: false });
+ expect(generator.next()).toEqual({ value: undefined, done: true });
+ });
+
+ test("loops in generators continue in compiled code at their back edges", () => {
+ const sum = prepared(
+ "count",
+ "let total = 0; for (let i = 0; i < count; ++i) total += i % 7; yield total; yield total + 1;"
+ );
+ for (let i = 0; i < 10; ++i) [...sum(10)];
+ const generator = sum(100000);
+ let expected = 0;
+ for (let i = 0; i < 100000; ++i) expected += i % 7;
+ expect(generator.next()).toEqual({ value: expected, done: false });
+ expect(generator.next()).toEqual({ value: expected + 1, done: false });
+ expect(generator.next()).toEqual({ value: undefined, done: true });
+ });
+});