Skip to content

Truly independent web browser

LibJS: Compile async functions and async generators in the JIT

Andreas Klingf27720e1b085
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 7b6c2f86269..f0191818737 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), 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.
+enter compiled code at their back edges (on-stack replacement), and generators and async functions
+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.
@@ -203,7 +203,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 | |
+| Suspend | Records where the frame's generator or async function resumes (a continuation, or none once it completes) and what the value it returns is (yielded, an iterator result, or awaited), right before the `Return` of a `Yield`, `YieldIteratorResult` or `Await` (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 | |
@@ -275,7 +275,7 @@ 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
+### 4.1 Generators and async functions
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
@@ -283,6 +283,11 @@ the continuation in frame memory, `Suspend` records the continuation in the fram
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.
+Async functions and async generators are generators to the runtime: `AsyncFunctionDriverWrapper`
+and `AsyncGenerator` resume them the same way, and their `Await` suspends them like a `Yield`, except
+that `Suspend` marks the value as awaited (`yield_is_await`), which tells an async generator to
+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
continuation's block, which nothing else in compiled code reaches. Both kinds of entry are listed in
@@ -290,8 +295,9 @@ continuation's block, which nothing else in compiled code reaches. Both kinds of
`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. A continuation starts by reading the completion the generator resumed
-with (`GetCompletionFields`), which compiled code loads from the generator object. 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.
+with (`GetCompletionFields`), which compiled code loads from the generator object; an async
+generator's completion comes from its `AsyncGenerator` through the slow path. The function's start
+(its `Enter` and the initial `Yield`) is compiled like any function's.
## 5. Dependencies and invalidation
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
index 21bc51b78d6..c1e5830926c 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
@@ -84,8 +84,6 @@ const EXPANDED: Handling = Handling::Expanded(GenericInfo {
reads_whole_frame: false,
});
-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 {
use OpCode as O;
@@ -111,7 +109,8 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::Return
| O::End
| O::Yield
- | O::YieldIteratorResult => Handling::Native,
+ | O::YieldIteratorResult
+ | O::Await => Handling::Native,
// Truthiness, built from a truthiness branch and a phi.
O::Not | O::ToBoolean => Handling::Native,
@@ -124,7 +123,6 @@ 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 => 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 4ebd7e65b30..0a85862c44b 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -92,6 +92,7 @@ use crate::ir::Locations;
use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
+use crate::ir::SuspendKind;
use crate::ir::value;
use crate::snapshot::CallFeedbackSnapshot;
use crate::snapshot::CellId;
@@ -1507,11 +1508,27 @@ impl<'a> GraphBuilder<'a> {
Instruction::Yield {
continuation_label,
value,
- } => return self.build_suspend(continuation_label, value, false).map(Some),
+ } => {
+ return self
+ .build_suspend(continuation_label, value, SuspendKind::Yield)
+ .map(Some);
+ }
Instruction::YieldIteratorResult {
continuation_label,
value,
- } => return self.build_suspend(Some(continuation_label), value, true).map(Some),
+ } => {
+ return self
+ .build_suspend(Some(continuation_label), value, SuspendKind::YieldIteratorResult)
+ .map(Some);
+ }
+ Instruction::Await {
+ continuation_label,
+ argument,
+ } => {
+ return self
+ .build_suspend(Some(continuation_label), argument, SuspendKind::Await)
+ .map(Some);
+ }
Instruction::GetLexicalEnvironment { dst } => {
let address = self.frame_field(FrameField::LexicalEnvironment)?;
let environment = self.emit(Op::BoxCell, vec![address], Some(Repr::Tagged));
@@ -1745,22 +1762,22 @@ 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`.
+ /// Builds a `Yield`, `YieldIteratorResult` or `Await`, which suspends
+ /// the generator or async function 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 instruction.
fn build_suspend(
&mut self,
continuation: Option<Label>,
value: Operand,
- value_is_iterator_result: bool,
+ kind: SuspendKind,
) -> Result<Flow, CompileFailure> {
if self.function.is_virtual() {
return Err(CompileFailure::InvalidBytecode {
pc: self.function.pc,
- reason: "yield in an inlined callee",
+ reason: "suspension in an inlined callee",
});
}
let value = self.read(value)?;
@@ -1775,7 +1792,8 @@ impl<'a> GraphBuilder<'a> {
}
}
}
- // NB: Like the interpreter's Yield, an empty value yields `undefined`.
+ // NB: Like the interpreter's Yield and Await, 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) {
@@ -1786,7 +1804,7 @@ impl<'a> GraphBuilder<'a> {
self.emit(
Op::Suspend {
continuation: continuation.map(|label| label.0),
- value_is_iterator_result,
+ kind,
},
Vec::new(),
None,
@@ -1796,10 +1814,10 @@ impl<'a> GraphBuilder<'a> {
}
/// Builds `GetCompletionFields` (`Handling::Expanded`), which a
- /// resumed generator starts with: the type and the value of the
- /// completion it resumed with, which the generator object it finds in
- /// its accumulator holds, and the slow path for other completion
- /// sources (async generators).
+ /// resumed generator or async function starts with: the type and the
+ /// value of the completion it resumed with, which the generator object
+ /// it finds in its accumulator holds, and the slow path for other
+ /// completion sources (async generators).
pub(super) fn build_get_completion_fields(
&mut self,
type_dst: Operand,
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
index 497115625d4..42def8b10ac 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
@@ -20,12 +20,12 @@
//! 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.
+//! Generators and async functions resume the same way: a suspended frame holds
+//! every value live at the continuation it resumes at (see `build_suspend()`),
+//! so each continuation of a `Yield`, `YieldIteratorResult` or `Await` 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;
@@ -147,9 +147,10 @@ impl GraphBuilder<'_> {
Ok(())
}
- /// 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.
+ /// Builds an entry block for every continuation of a suspension of a
+ /// generator or async function 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() {
@@ -160,6 +161,10 @@ impl GraphBuilder<'_> {
| Instruction::YieldIteratorResult {
continuation_label: continuation,
..
+ }
+ | Instruction::Await {
+ continuation_label: continuation,
+ ..
}) = self.function.instructions[index].instruction
else {
continue;
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index bc71973464a..fc074431d21 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -384,22 +384,14 @@ fn instructions_whose_feedback_is_empty_never_ran() {
#[test]
fn unsupported_instructions_fail_cleanly() {
- let program = assemble(|label| {
- vec![
- Instruction::Await {
- continuation_label: label(1),
- argument: r(5),
- },
- Instruction::Return { value: r(5) },
- ]
- });
+ let program = assemble(|_| vec![Instruction::Catch { dst: r(5) }, Instruction::Return { value: r(5) }]);
let snapshot = snapshot_for(&program, test_layout());
let failure = build_graph(&snapshot).unwrap_err();
assert!(matches!(
failure,
CompileFailure::UnsupportedInstruction {
pc: 0,
- opcode: crate::bytecode::OpCode::Await,
+ opcode: crate::bytecode::OpCode::Catch,
..
}
));
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index a709a6c0701..69354a721e1 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -94,6 +94,7 @@ use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::ShapeCheck;
+use crate::ir::SuspendKind;
use crate::ir::value;
use crate::regalloc::Allocation;
use crate::regalloc::Location;
@@ -1300,19 +1301,20 @@ 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,
- } => {
+ Op::Suspend { continuation, kind } => {
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_is_await,
+ 1,
+ u64::from(*kind == SuspendKind::Await),
+ ),
(
offsets.execution_context_yield_value_is_iterator_result,
1,
- u64::from(*value_is_iterator_result),
+ u64::from(*kind == SuspendKind::YieldIteratorResult),
),
];
self.emit_constant_fields(self.pinned.frame, self.pinned.scratch, &mut fields)?;
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 456dea1ca4f..d7b299e867e 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -12,6 +12,7 @@ use super::Graph;
use super::NodeId;
use super::Op;
use super::ShapeCheck;
+use super::SuspendKind;
use super::value;
use crate::bytecode::FrameLayout;
use crate::bytecode::Operand;
@@ -112,17 +113,14 @@ 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,
- } => {
+ Op::Suspend { continuation, kind } => {
let continuation = continuation.map_or("completed".to_string(), |pc| format!("pc {pc}"));
- let result = if *value_is_iterator_result {
- " iterator-result"
- } else {
- ""
+ let kind = match kind {
+ SuspendKind::Yield => "",
+ SuspendKind::YieldIteratorResult => " iterator-result",
+ SuspendKind::Await => " await",
};
- with_inputs(&format!("Suspend {continuation}{result}"))
+ with_inputs(&format!("Suspend {continuation}{kind}"))
}
Op::BoxCell => with_inputs("BoxCell"),
Op::LoadOuterEnvironment => with_inputs("LoadOuterEnvironment"),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 09651f651bb..be1c447a847 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -206,6 +206,20 @@ pub enum TypeofKind {
Function,
}
+/// Which bytecode a `Suspend` suspends the frame for, which tells the code
+/// resuming it what the returned value is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SuspendKind {
+ /// A generator's `Yield`.
+ Yield,
+ /// A generator's `YieldIteratorResult`, whose value is an iterator
+ /// result already.
+ YieldIteratorResult,
+ /// An `Await` of an async function or async generator, whose value is
+ /// the awaited one.
+ Await,
+}
+
/// Which function of an accessor property an access calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessorPart {
@@ -430,15 +444,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.
+ /// The suspension of the `Yield`, `YieldIteratorResult` and `Await`
+ /// bytecodes, right before the `Return` of the yielded or awaited value:
+ /// records in the frame where its generator or async function resumes
+ /// (`continuation`, or nowhere once it completes) and what the value is
+ /// (`kind`). 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,
+ kind: SuspendKind,
},
/// The environment the environment at the `Repr::Pointer` input 0 is in
/// (its outer environment), as a `Repr::Pointer`. Environments keep
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index ffe66574b16..4c9593ff5c1 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -26,7 +26,6 @@ use crate::layout::value::Value;
use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
use crate::runtime::realm_watchpoints;
-use crate::runtime::shared_function_instance_data::FunctionKind;
/// `threshold` invocations.
fn threshold_budget(options: &Options) -> i32 {
@@ -113,15 +112,11 @@ fn function_to_compile(vm: &Vm) -> Option<Gc<EcmascriptFunctionObject>> {
if vm.debugging_enabled() {
return None;
}
- // NB: Async functions resume in the middle, and top-level code runs once.
+ // NB: Top-level code runs once, like the body of a module with top-level await, which runs as an async function.
+ // Generators, async functions and async generators resume in their code at the entries of their
+ // continuations.
let function = as_ecmascript_function_object(vm.running_execution_context_ref().function.get()?)?;
- 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)
+ (!function.shared_data().is_module_wrapper()).then_some(function)
}
/// Whether the running frame runs a builtin written in JavaScript.
@@ -426,7 +421,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() || !is_compiled_kind(function.kind()) {
+ if !vm.jit.options.enabled || vm.debugging_enabled() {
return false;
}
let executable = function.compiled_executable(vm);
diff --git a/Tests/LibJS/JIT/ir/async-functions.js b/Tests/LibJS/JIT/ir/async-functions.js
new file mode 100644
index 00000000000..ebe1ccc1dd8
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/async-functions.js
@@ -0,0 +1,43 @@
+// An async function suspends at an await in compiled code like the interpreter's Await: it writes the slots live at
+// the continuation to its frame, records the continuation and that the value is awaited, and returns the value. It
+// resumes at an entry block of the continuation, which loads those slots from the frame like a generator's resume
+// entry, and reads the completion it resumed with from its generator object.
+
+async function sum(values) {
+ let total = 0;
+ for (const value of values) total += await value;
+ return total;
+}
+jit.prepare(sum);
+const warm_up = [];
+for (let i = 0; i < 10; ++i) warm_up.push(sum([1, 2, 3]));
+
+// CHECK-FUNCTION: sum
+// CHECK-PASS: graph building
+// CHECK: LoadSlot r5
+// CHECK-NEXT: LoadSlot r6
+// CHECK-NEXT: LoadSlot r7
+// CHECK-NEXT: LoadSlot r12
+// 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: [[VALUE:v[0-9]+]] = EmptyToUndefined
+// CHECK-NEXT: Suspend pc [[NEXT:[0-9]+]] await
+// CHECK-NEXT: Return ([[VALUE]])
+// CHECK: [[CONTINUATION]] (pc [[NEXT]]) <- [[RESUME:b[0-9]+]]:
+// CHECK: [[GENERATOR:v[0-9]+]]:pointer = RefineGeneratorObject
+// CHECK-NEXT: LoadGeneratorCompletionType ([[GENERATOR]])
+// CHECK-NEXT: BoxInt32
+// CHECK-NEXT: LoadGeneratorCompletionValue ([[GENERATOR]])
+// CHECK-NOT: Exit NoFeedback
+// CHECK: Suspend completed
+// CHECK-NEXT: Return
+// CHECK: osr entry at pc [[START]]: {{b[0-9]+}}
+// CHECK-NEXT: osr entry at pc [[NEXT]]: [[RESUME]]
+
+Promise.all(warm_up).then(() => {
+ jit.compile(sum);
+ sum([4, 5, 6]).then(total => console.log(total));
+});
diff --git a/Tests/LibJS/Runtime/jit/async-functions.js b/Tests/LibJS/Runtime/jit/async-functions.js
new file mode 100644
index 00000000000..9ab23a26e56
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/async-functions.js
@@ -0,0 +1,217 @@
+// Async functions and async generators run in compiled code: a call starts one there, and each resumption enters the
+// code at the continuation of the await it was suspended at, with the values that the frame kept across the
+// suspension.
+//
+// NB: The functions come from the AsyncFunction and AsyncGeneratorFunction constructors, so that each run of a test
+// (see LIBJS_TEST_REPEAT) compiles new ones.
+
+const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
+const AsyncGeneratorFunction = Object.getPrototypeOf(async function* () {}).constructor;
+
+function prepared(constructor, ...parameters_and_body) {
+ const function_ = new constructor(...parameters_and_body);
+ jit.prepare(function_);
+ return function_;
+}
+
+function settle(promise) {
+ let result;
+ promise.then(
+ value => (result = { value }),
+ error => (result = { error })
+ );
+ runQueuedPromiseJobs();
+ return result;
+}
+
+function compile(function_, warm_up) {
+ for (let i = 0; i < 10; ++i) warm_up();
+ runQueuedPromiseJobs();
+ expect(jit.compile(function_)).toBe(jit.enabled);
+}
+
+describe("async functions in compiled code", () => {
+ test("resume where they awaited, with the values live across their awaits", () => {
+ const count = prepared(
+ AsyncFunction,
+ "start",
+ "step",
+ "let total = 0; const steps = []; for (let i = start; i < start + 5; i += step) { total += await i; steps.push([i, total, jit.inCompiledCode()]); } return [total * 2, steps];"
+ );
+ compile(count, () => count(0, 1));
+ const { value } = settle(count(10, 2));
+ const [doubled, steps] = value;
+ expect(doubled).toBe(72);
+ expect(steps.map(([i, total]) => [i, total])).toEqual([
+ [10, 10],
+ [12, 22],
+ [14, 36],
+ ]);
+ if (jit.enabled && !jit.forcesExits) expect(steps.every(([, , compiled]) => compiled)).toBeTrue();
+ });
+
+ test("receive the values of the promises they await", () => {
+ const add = prepared(
+ AsyncFunction,
+ "a",
+ "b",
+ "const x = await a; const y = await Promise.resolve(b); return x + y + (await { valueOf: () => 0 }).valueOf();"
+ );
+ compile(add, () => add(1, 2));
+ expect(settle(add(3, 4))).toEqual({ value: 7 });
+ expect(settle(add(Promise.resolve("x"), "y"))).toEqual({ value: "xy0" });
+ expect(settle(add(1.5, Promise.resolve(2)))).toEqual({ value: 3.5 });
+ });
+
+ test("wait for pending promises", () => {
+ const wait = prepared(
+ AsyncFunction,
+ "promise",
+ "suffix",
+ "const value = await promise; return value + suffix;"
+ );
+ compile(wait, () => wait(Promise.resolve(1), 1));
+ let resolve;
+ const promise = new Promise(r => (resolve = r));
+ let result;
+ wait(promise, "!").then(value => (result = value));
+ runQueuedPromiseJobs();
+ expect(result).toBeUndefined();
+ resolve("done");
+ runQueuedPromiseJobs();
+ expect(result).toBe("done!");
+ });
+
+ test("reject when an awaited promise rejects or they throw", () => {
+ const rethrow = prepared(
+ AsyncFunction,
+ "promise",
+ "fail",
+ "const value = await promise; if (fail) throw new TypeError(value); return value;"
+ );
+ compile(rethrow, () => rethrow(1, false));
+ expect(settle(rethrow(5, false))).toEqual({ value: 5 });
+ const rejected = settle(rethrow(Promise.reject(new RangeError("rejected")), false));
+ expect(rejected.error).toBeInstanceOf(RangeError);
+ expect(rejected.error.message).toBe("rejected");
+ const thrown = settle(rethrow("thrown", true));
+ expect(thrown.error).toBeInstanceOf(TypeError);
+ expect(thrown.error.message).toBe("thrown");
+ });
+
+ test("keep this, arguments and captured bindings across awaits", () => {
+ const make = new Function(
+ "AsyncFunction",
+ "jit",
+ "let captured = 1; const async_function = async function (a, b) { const x = this.x + (await a); captured += await b; return [x, arguments.length + captured, this.x * b]; }; jit.prepare(async_function); return [async_function, () => captured];"
+ );
+ const [async_function, captured] = make(AsyncFunction, jit);
+ compile(async_function, () => async_function.call({ x: 1 }, 2, 3));
+ const before = captured();
+ expect(settle(async_function.call({ x: 10 }, 20, 30, 40))).toEqual({ value: [30, 3 + before + 30, 300] });
+ expect(captured()).toBe(before + 30);
+ });
+
+ test("leave compiled code where a speculation fails, and keep their state", () => {
+ const add = prepared(
+ AsyncFunction,
+ "a",
+ "b",
+ "let sum = a; const sums = []; for (let i = 0; i < 3; ++i) { sum = sum + (await b); sums.push(sum); } return sums;"
+ );
+ compile(add, () => add(1, 2));
+ expect(settle(add(1, 2))).toEqual({ value: [3, 5, 7] });
+ expect(settle(add(2147483647, 1))).toEqual({ value: [2147483648, 2147483649, 2147483650] });
+ expect(settle(add("a", 1))).toEqual({ value: ["a1", "a11", "a111"] });
+ });
+
+ test("suspended async functions resume after their code is discarded and compiled again", () => {
+ const values = prepared(
+ AsyncFunction,
+ "promises",
+ "const results = []; for (const promise of promises) results.push(await promise); return results;"
+ );
+ compile(values, () => values([1, 2]));
+ const resolvers = [];
+ const promises = [0, 1, 2].map(() => new Promise(resolve => resolvers.push(resolve)));
+ let result;
+ values(promises).then(value => (result = value));
+ resolvers[0]("a");
+ runQueuedPromiseJobs();
+ jit.discard(values);
+ resolvers[1]("b");
+ runQueuedPromiseJobs();
+ expect(jit.compile(values)).toBe(jit.enabled);
+ resolvers[2]("c");
+ runQueuedPromiseJobs();
+ expect(result).toEqual(["a", "b", "c"]);
+ });
+
+ test("compile async arrow functions and async methods once they get hot", () => {
+ const make = new Function(
+ "return [async (x) => (await x) * 2, { async method(x) { return (await x) + this.offset; }, offset: 10 }];"
+ );
+ const [arrow, object] = make();
+ let total = 0;
+ for (let i = 0; i < 1000; ++i) {
+ arrow(i).then(value => (total += value));
+ object.method(i).then(value => (total += value));
+ }
+ runQueuedPromiseJobs();
+ expect(total).toBe(999000 + 499500 + 10000);
+ });
+});
+
+describe("async generators in compiled code", () => {
+ test("yield and await with the values live across both", () => {
+ const values = prepared(
+ AsyncGeneratorFunction,
+ "count",
+ "let total = 0; for (let i = 0; i < count; ++i) { total += await i; yield [i, total, jit.inCompiledCode()]; } return total;"
+ );
+ const collect = async generator => {
+ const results = [];
+ for await (const value of generator) results.push(value);
+ return results;
+ };
+ compile(values, () => collect(values(3)));
+ const { value } = settle(collect(values(4)));
+ expect(value.map(([i, total]) => [i, total])).toEqual([
+ [0, 0],
+ [1, 1],
+ [2, 3],
+ [3, 6],
+ ]);
+ if (jit.enabled && !jit.forcesExits) expect(value.every(([, , compiled]) => compiled)).toBeTrue();
+
+ const generator = values(2);
+ const first = settle(generator.next()).value;
+ expect(first.done).toBeFalse();
+ expect(first.value.slice(0, 2)).toEqual([0, 0]);
+ settle(generator.next());
+ expect(settle(generator.next()).value).toEqual({ value: 1, done: true });
+ });
+
+ test("receive the values passed to next and finish through return", () => {
+ const accumulate = prepared(
+ AsyncGeneratorFunction,
+ "let total = 0; while (true) { const value = await (yield total); if (value === undefined) return total; total += value; }"
+ );
+ compile(accumulate, () => {
+ const generator = accumulate();
+ generator.next();
+ generator.next(1);
+ generator.next();
+ });
+ const generator = accumulate();
+ expect(settle(generator.next(100)).value).toEqual({ value: 0, done: false });
+ expect(settle(generator.next(Promise.resolve(5))).value).toEqual({ value: 5, done: false });
+ expect(settle(generator.next(0.5)).value).toEqual({ value: 5.5, done: false });
+ expect(settle(generator.next()).value).toEqual({ value: 5.5, done: true });
+
+ const returned = accumulate();
+ settle(returned.next());
+ expect(settle(returned.return(7)).value).toEqual({ value: 7, done: true });
+ expect(settle(returned.next()).value).toEqual({ value: undefined, done: true });
+ });
+});