Truly independent web browser
LibJS: Check for interrupts at loop back edges in JIT code
Andreas Klingf9dcd4c8f740
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 4dbe756e655..39c365653ee 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -70,8 +70,9 @@ from them alone:- **Memory.** `reads` and `writes`: sets of abstract locations (`ir::Locations`): `FRAME`,`NAMED_SLOTS` (property values), `SHAPES` (shapes and prototypes), `ELEMENTS` (element values),`ELEMENT_COUNTS` (element storage kind, length, capacity and the storage offset of typed arrays), `GLOBAL_BINDINGS` and `BINDINGS` (the- bindings of declarative environments), `ITERATORS` (the state of iterators), and `COLLECTIONS` (the- entries of Map, Set, WeakMap and WeakSet objects). Passes ask+ bindings of declarative environments), `ITERATORS` (the state of iterators), `COLLECTIONS` (the+ entries of Map, Set, WeakMap and WeakSet objects), and `INTERRUPT`, which only `CheckInterrupt`+ writes, so that loop invariant code motion leaves it in its loop and nothing else cares. Passes askone question: whether one node's writes intersect another's reads. `runs_code`: may run othercode, which may write anything, or invalidate the compiled code. The op table below names thelocations coarsely (Named for slots and shapes, Elements for values and counts, Any for all);@@ -167,6 +168,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m| CheckNotHole | Exits at holes (the empty value). The value is input 0, refined. | E | | | cse || CheckInitialized | Exits unless the binding or local variable (input 0) is initialized (not the empty value). The value is input 0, refined. | E | | | cse || AssumeValid | Exits if the code was invalidated; a patchable no-op (section 5). | E | Any | | |+| CheckInterrupt | Exits if another thread interrupted the VM (section 9, "Interrupts"). At every loop back edge; never moved. | E | | Interrupt | || AssumeLegacyArgumentsUnread | After an instruction whose calls may run code reading the legacy `arguments` of inlined frames; escape analysis makes it an `AssumeValid` or removes it (section 4, "Legacy arguments"). | E | Any | | || **Object memory** | | | | | || LoadNamed | A named property at an offset; exits for accessors, unless the shape check of its object input ensures that it `holds_data` (the own property is writable in the checked shape, and accessor properties never are). Loads from prototypes always check: no check guards their constant object as an input, so they could move above their guards. | E unless `holds_data` | Named | | cse |@@ -468,6 +470,20 @@ the exit out of the sites they avoid once the cache has more (`Executable::jit_esince the interpreter added the shapes the code did not know. Each such exit needs a larger cache,and caches stop growing once megamorphic, so this ends.+**Interrupts.** Another thread can stop script on a VM (`Vm::request_interrupt()`). It cannot patch+compiled code the VM's thread is running, so it raises `Vm::jit_native_stack_limit` above every+stack pointer. Every entry of compiled code and every call out of it then takes the path it takes+when the stack is nearly exhausted, to the interpreter, at no cost to running code, since those+paths compare with the limit anyway. A `CheckInterrupt` right before each loop back edge compares+the same limit, for code that never calls, and exits to the back edge. The interrupt also made+every dispatch table entry of the VM the fallback handler, so the interpreter does not run the+back edge: it unwinds (`Vm::handle_exception()` catches nothing on an interrupted VM), and the frame+runs no further script.++A `CheckInterrupt` also exits where the stack really got that deep, which only a frame that entered+compiled code below the limit does; the interpreter then continues the frame, like after any exit.+The exit counts as nothing learned, and not towards discarding the code.+To be written: exit reasons, recompiles.## 10. The snapshot and the cachesdiff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex d6b52741093..b8ba9a1f728 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -1391,6 +1391,9 @@ impl<'a> GraphBuilder<'a> {let instruction = self.function.instructions[self.function.instruction_index].instruction.clone();+ if osr::is_loop_back_edge(instruction.opcode()) {+ self.emit_checked(Op::CheckInterrupt, Vec::new(), None);+ }if replaces_environments(instruction.opcode()) {self.frame.forget_environments();}diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex 0a262ab0d83..b32a4481fad 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -136,6 +136,10 @@ pub enum ExitKind {/// Something the code depended on stopped holding while it ran other/// code (see `Dependency`), so the code was invalidated.Invalidated,+ /// Another thread interrupted the VM, so script has to stop, which the+ /// interpreter does at once. Or the stack got so deep that calls leave+ /// compiled code, which is no reason to stop.+ Interrupted,/// Code that a call in an inlined function ran read the legacy/// `arguments` of the function's frame, among which were objects the/// code never allocated: the runtime created them, and the code exiteddiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex a5b1cc20c00..58671e0470d 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -1630,6 +1630,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let offset = self.masm.patchable_nop();self.invalidation_points.push((offset, exit));}+ Op::CheckInterrupt => {+ // NB: This fuses into one micro-op on x86-64, unlike a comparison of a word in memory with zero.+ let exit = self.exit_site(node_id);+ let limit = Address::new(self.pinned.vm, self.runtime.offsets.vm_jit_native_stack_limit as i32);+ self.masm.branch_if_stack_pointer_below(&limit, exit);+ }Op::HasInPrototypeChain => self.emit_has_in_prototype_chain(node_id),Op::LoadGlobalBinding { environment, index } => {let exit = self.exit_site(node_id);diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex d8779191763..f05915d18ed 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -252,6 +252,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {Op::CheckShape { shapes } => with_inputs(&format!("CheckShape [{}]", shapes_text(shapes.iter()))),Op::CheckPrototypeChainValid { validity } => format!("CheckPrototypeChainValid {:#x}", validity.0),Op::AssumeValid => "AssumeValid".to_string(),+ Op::CheckInterrupt => "CheckInterrupt".to_string(),Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread".to_string(),Op::HasInPrototypeChain => with_inputs("HasInPrototypeChain"),Op::LoadGlobalBinding { environment, index } => format!("LoadGlobalBinding {:#x}[{index}]", environment.0),diff --git a/Libraries/LibJS/JIT/Rust/src/ir/effects.rs b/Libraries/LibJS/JIT/Rust/src/ir/effects.rsindex f02b4323186..c9764d0ef68 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/effects.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/effects.rs@@ -41,6 +41,10 @@ impl Locations {/// The entries of keyed collections (Map, Set, WeakMap and WeakSet/// objects).pub const COLLECTIONS: Self = Self(1 << 8);+ /// Whether another thread interrupted the VM. Nothing reads it but+ /// `Op::CheckInterrupt`, which counts as writing it: a check has to stay+ /// in its loop, and no other node gets in its way.+ pub const INTERRUPT: Self = Self(1 << 9);/// Every location.pub const ALL: Self = Self(u16::MAX);diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex d93e52fa41b..ec38bcb3d75 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -857,6 +857,12 @@ pub enum Op {/// `Graph::legacy_arguments_guards`). Until then it is no `AssumeValid`,/// so that check elimination does not rely on it.AssumeLegacyArgumentsUnread,+ /// Exits with `ExitKind::Interrupted` if another thread interrupted the+ /// VM (`Vm::request_interrupt()`), which raised the native stack limit+ /// past the stack pointer. Every loop back edge has one, right before the+ /// instruction that jumps back, where the interpreter stops. Calls need+ /// none: the same limit sends every call and entry to the interpreter.+ CheckInterrupt,/// Loads binding `index` of the global declarative environment/// `environment`. Exits with `ExitKind::BadShape` if it is still/// uninitialized.@@ -1492,6 +1498,10 @@ impl Op {reads: Locations::ALL,..P::PURE},+ Op::CheckInterrupt => P {+ writes: Locations::INTERRUPT,+ ..P::PURE+ },Op::HasInPrototypeChain => P {reads: Locations::SHAPES,..P::PURE@@ -1748,6 +1758,7 @@ impl Op {Op::CheckShape { .. } => "CheckShape",Op::CheckPrototypeChainValid { .. } => "CheckPrototypeChainValid",Op::AssumeValid => "AssumeValid",+ Op::CheckInterrupt => "CheckInterrupt",Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread",Op::HasInPrototypeChain => "HasInPrototypeChain",Op::LoadGlobalBinding { .. } => "LoadGlobalBinding",@@ -1876,6 +1887,7 @@ impl Op {Op::CheckNonNegativeInt32 => Some(ExitKind::Overflow),Op::CheckNumber | Op::CheckIdentityComparable | Op::HasInPrototypeChain => Some(ExitKind::BadType),Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => Some(ExitKind::Invalidated),+ Op::CheckInterrupt => Some(ExitKind::Interrupted),Op::Int32Binary { op } if op.int32_can_overflow() => Some(ExitKind::Overflow),Op::CheckValue { kind, .. } => Some(*kind),Op::LoadArgument { .. } | Op::SliceArguments => Some(ExitKind::ArgumentsIndex),diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex 2819f1a2962..5550b2ed37e 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -679,9 +679,13 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indvm.jit.count_coverage("exit.from-inlined-code");}// NB: Exits in inlined builtins count for the code they were inlined into only.- // NB: Invalidated code was discarded, and its recompile sees that what it depended on no longer holds.+ // NB: Invalidated code was discarded, and its recompile sees that what it depended on no longer holds. An interrupt+ // speculated nothing, and nothing runs after it.let snapshot_executable = code.snapshot_executable(frame_state.executable);- let learned = if kind == libjs_jit::code::ExitKind::Invalidated {+ let learned = if matches!(+ kind,+ libjs_jit::code::ExitKind::Invalidated | libjs_jit::code::ExitKind::Interrupted+ ) {false} else if matches!(snapshot_executable.function, Some(InlinedFunction::Builtin(_))) {let index = compiled_executable.add_jit_builtin_exit_site((executable.as_ptr() as u64, frame_state.pc, kind));@@ -697,7 +701,8 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indcompiled_executable.note_learned_jit_exit_site();}- if code.count_exit() >= EXIT_COUNT_BEFORE_DISCARD+ if kind != libjs_jit::code::ExitKind::Interrupted+ && code.count_exit() >= EXIT_COUNT_BEFORE_DISCARD&& compiled_executable.jit_compile_state() == CompileState::Installed{compiled_executable.discard_jit_code(vm);diff --git a/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js b/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.jsindex 0d6b7e36db5..037d4259e58 100644--- a/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js+++ b/Tests/LibJS/JIT/ir/osr-unconditional-back-edge.js@@ -21,6 +21,7 @@ jit.compile(countUp);// CHECK-NEXT: [[ENTRY:b[0-9]+]]:// CHECK-NEXT: LoadSlot l0// CHECK-NEXT: LoadSlot a0+// CHECK-NEXT: CheckInterrupt// CHECK-NEXT: Jump [[HEADER:b[0-9]+]]// CHECK: [[HEADER]] (pc {{[0-9]+}}) <- [[ENTRY]], {{b[0-9]+}}, {{b[0-9]+}} loop:// CHECK: osr entry at pc {{[0-9]+}}: [[ENTRY]]