Truly independent web browser
LibJS: Flush the code of functions that have not run for a while
Andreas Klingc4d597e57fe5
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 911676d8f9f..921f5fdbe00 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -367,7 +367,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// inline frame.self.masm.bind(ecmascript_function);// NB: The executable is decoded once it is known not to be null,- // which it stays.+ // which it stays: the runtime compiles the function again if a+ // collection in it flushed the executable.let load_function_data = |codegen: &mut Self| {codegen.emit_load_compressed_cell(other,diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex 5e6b32944e6..ff402d2cadd 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -54,7 +54,7 @@ use crate::runtime::environment_shape::{EnvironmentShape, EnvironmentShapeCache}use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_key::PropertyKey;use crate::runtime::shape::ShapeKey;-use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;+use crate::runtime::shared_function_instance_data::{FlushedCode, SharedFunctionInstanceData};use crate::runtime::value::number_to_string;use crate::slice_block::{SliceBlock, SliceBlockBuilder};use crate::source_code::SourceCode;@@ -1461,34 +1461,66 @@ impl Executable {/// declares and caches of its own. While something else holds `data`, it stays as it is and can be linked again,/// into any realm. Without another holder nothing can link it again, so what only linking reads goes away.pub fn create_with_source_code(+ vm: &Vm,+ data: Arc<ExecutableData>,+ source_code: Option<&Rc<SourceCode>>,+ ) -> Gc<Executable> {+ Self::create_with_flushed_code(vm, data, source_code, None)+ }++ /// create_with_source_code() for the code of a function whose last executable was flushed, which takes over what+ /// that executable left (see `bytecode::flushing`).+ pub fn create_with_flushed_code(vm: &Vm,mut data: Arc<ExecutableData>,source_code: Option<&Rc<SourceCode>>,+ flushed_code: Option<&FlushedCode>,) -> Gc<Executable> {+ // NB: The code compiles the same every time, so it creates as many functions and has as many template objects.+ let flushed_code = flushed_code.filter(|flushed_code| {+ let fits = flushed_code.shared_function_data.len() == data.shared_function_data.len()+ && flushed_code.template_object_caches.len() == data.cache_counts().template_object as usize;+ debug_assert!(fits, "flushed code compiles to the same functions and template objects");+ fits+ });let executable = DeferGc::scope(vm, |_| {// SAFETY: The slices and the block end up in the executable, which drops the slices first.let mut tables = unsafe { SliceBlock::builder(Self::size_of_tables(&data)) };let is_strict = data.is_strict;- let shared_function_data = match Arc::get_mut(&mut data) {- Some(code) => tables.slice(code.shared_function_data.take_elements().map(|pending| {- SharedFunctionInstanceData::create_from_owned_pending_shared_function_data(- vm,- pending,- is_strict,- source_code,- )- })),- None => tables.slice(data.shared_function_data.iter().map(|pending| {- SharedFunctionInstanceData::create_from_pending_shared_function_data(- vm,- pending,- is_strict,- source_code,- )- })),+ let shared_function_data = if let Some(flushed_code) = flushed_code {+ tables.slice(flushed_code.shared_function_data.iter().copied())+ } else {+ match Arc::get_mut(&mut data) {+ Some(code) => tables.slice(code.shared_function_data.take_elements().map(|pending| {+ SharedFunctionInstanceData::create_from_owned_pending_shared_function_data(+ vm,+ pending,+ is_strict,+ source_code,+ )+ })),+ None => tables.slice(data.shared_function_data.iter().map(|pending| {+ SharedFunctionInstanceData::create_from_pending_shared_function_data(+ vm,+ pending,+ is_strict,+ source_code,+ )+ })),+ }};- vm.heap()- .allocate(|defer_gc| Self::build(vm, data, tables, shared_function_data, source_code, defer_gc))+ let template_object_caches = flushed_code.map(|flushed_code| &flushed_code.template_object_caches[..]);+ vm.heap().allocate(|defer_gc| {+ Self::build(+ vm,+ data,+ tables,+ shared_function_data,+ template_object_caches,+ source_code,+ defer_gc,+ )+ })});vm.register_executable(executable);vm.heap()@@ -1529,6 +1561,7 @@ impl Executable {mut data: Arc<ExecutableData>,mut tables: SliceBlockBuilder,shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,+ template_object_caches: Option<&[Gc<TemplateObjectCache>]>,source_code: Option<&Rc<SourceCode>>,defer_gc: &DeferGc<'_>,) -> Executable {@@ -1542,9 +1575,12 @@ impl Executable {None => tables.slice(data.property_key_table.iter().cloned().map(PropertyKey::from)),};let constants = tables.slice(data.constants.iter().map(|constant| constant_value(vm, constant)));- let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = (0..data.cache_counts().template_object)- .map(|_| TemplateObjectCache::create(vm))- .collect();+ let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = match template_object_caches {+ Some(caches) => caches.iter().copied().collect(),+ None => (0..data.cache_counts().template_object)+ .map(|_| TemplateObjectCache::create(vm))+ .collect(),+ };let object_property_iterator_caches = data.cache_counts().object_property_iterator;let environment_shape_caches = data.cache_counts().environment_shape;@@ -1590,6 +1626,23 @@ impl Executable {self.shared_function_data.len()}+ /// The shared data of the functions the bytecode creates.+ pub fn shared_function_data_slice(&self) -> &[Gc<SharedFunctionInstanceData>] {+ &self.shared_function_data+ }++ /// The caches of the template objects of the bytecode's template literals.+ pub fn template_object_caches_slice(&self) -> &[Gc<TemplateObjectCache>] {+ self.template_object_caches()+ }++ /// Visits what outlives a flush of the executable, for its shared data while it leaves the executable unvisited+ /// (see `bytecode::flushing`).+ pub fn trace_what_outlives_a_flush(&self, visitor: &mut Visitor) {+ self.shared_function_data.trace(visitor);+ self.template_object_caches().trace(visitor);+ }+pub fn class_blueprint(&self, index: u32) -> &ClassBlueprint {&self.class_blueprints()[index as usize]}diff --git a/Libraries/LibJS/Rust/src/bytecode/flushing.rs b/Libraries/LibJS/Rust/src/bytecode/flushing.rsnew file mode 100644index 00000000000..700633d77ae--- /dev/null+++ b/Libraries/LibJS/Rust/src/bytecode/flushing.rs@@ -0,0 +1,397 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Code flushing: the code of functions that nothing ran for a while goes away, and comes back through the lazy compile+//! path when the function is called again.+//!+//! Each executable counts the collections since a frame last entered it (`ExecutableHead::idle_collection_count`): the+//! interpreter's Enter, the resume of a generator and the prologue of JIT code set it to 0, and the VM's sweep callback+//! counts it up (and sets it to 0 for the executables that frames still run). The VM keeps the times of the last+//! collections, which tell how long an executable was not entered for.+//!+//! There are two layers, each with an idle time of its own:+//! - The JIT code of an executable that idled for the first one is dropped, like a discard that does not count against+//! the executable (see `Executable::flush_idle_jit_code()`).+//! - The executable of a function that idled for the second one is dropped as a whole. While a collection marks, the+//! shared data of the function does not visit such an executable, so it dies unless something else holds it: a frame+//! on a stack or in a suspended generator, JIT code that inlined it or calls it directly, a compile job, a local of+//! native code. If it dies, the shared data goes back to its lazy state. It keeps the shared data of the functions+//! the executable creates and the executable's template objects, which the next executable of its code takes over,+//! so that a recompile changes nothing that code can observe.+//!+//! A layer's idle time is its base shifted left by how often the function was compiled again after a flush in that+//! layer, up to a limit, and a function that was compiled again that often is not flushed in that layer anymore.+//! Nothing is flushed while a debugger is attached.+//!+//! LIBJS_CODE_FLUSH holds comma-separated options: `on`, `off`, `stress` (flush everything that nothing else holds at+//! every collection), `jit=SECONDS`, `bytecode=SECONDS`, `collections=N` (the fewest collections an executable idles+//! for), `backoff=N` (the largest shift of the idle times) and `max-recompiles=N`.++use core::cell::{Cell, RefCell};+use core::ptr::NonNull;+use std::collections::{HashSet, VecDeque};+use std::time::{Duration, Instant};++use crate::bytecode::executable::Executable;+use crate::gc::sweep::Sweep;+use crate::gc::weak::SweptAfterCollection;+use crate::interpreter::vm::Vm;+use crate::jit::code::CompileState;+use crate::layout::cell::Gc;+use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;++/// The flush layers, each with a count of recompiles on the shared data of a function.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FlushLayer {+ /// The JIT code of an executable.+ Jit = 0,+ /// The whole executable of a function.+ Bytecode = 1,+}++#[derive(Clone, Copy, Debug)]+pub struct CodeFlushingOptions {+ pub enabled: bool,+ /// Flush everything that nothing else holds at every collection, whatever its age.+ pub stress: bool,+ pub jit_idle_time: Duration,+ pub bytecode_idle_time: Duration,+ /// The fewest collections that an executable has to idle for to be flushed.+ pub min_idle_collections: u8,+ /// The largest left shift of the idle times by recompiles.+ pub max_backoff_shift: u8,+ /// After this many recompiles in a layer, a function is no longer flushed in that layer.+ pub max_recompiles: u8,+}++impl Default for CodeFlushingOptions {+ fn default() -> Self {+ Self {+ enabled: true,+ stress: false,+ jit_idle_time: Duration::from_secs(10),+ bytecode_idle_time: Duration::from_secs(20),+ min_idle_collections: 2,+ max_backoff_shift: 3,+ max_recompiles: 6,+ }+ }+}++impl CodeFlushingOptions {+ /// The options that LIBJS_CODE_FLUSH asks for. Options it does not know are reported and ignored.+ pub fn from_environment() -> Self {+ let mut options = Self::default();+ let Ok(value) = std::env::var("LIBJS_CODE_FLUSH") else {+ return options;+ };+ for option in value.split(',').filter(|option| !option.is_empty()) {+ let (name, argument) = option.split_once('=').unwrap_or((option, ""));+ let seconds = || {+ argument+ .parse::<f64>()+ .ok()+ .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())+ };+ let number = || argument.parse::<u8>().ok();+ let known = match name {+ "off" => {+ options.enabled = false;+ true+ }+ "on" => {+ options.enabled = true;+ true+ }+ "stress" => {+ options.stress = true;+ true+ }+ "jit" => seconds().map(|time| options.jit_idle_time = time).is_some(),+ "bytecode" => seconds().map(|time| options.bytecode_idle_time = time).is_some(),+ "collections" => number().map(|count| options.min_idle_collections = count).is_some(),+ "backoff" => number()+ .map(|shift| options.max_backoff_shift = shift.min(16))+ .is_some(),+ "max-recompiles" => number().map(|count| options.max_recompiles = count).is_some(),+ _ => false,+ };+ if !known {+ eprintln!("LIBJS_CODE_FLUSH: Ignoring the option '{option}'");+ }+ }+ options+ }+}++/// What code flushing did in a VM, for measurements.+#[derive(Default)]+pub struct CodeFlushingStats {+ pub passes: Cell<u64>,+ pub flushes: [Cell<u64>; 2],+ pub recompiles: [Cell<u64>; 2],+ /// Recompiles that made a function reach the most recompiles of a layer, which stops its flushes there.+ pub backoff_stops: [Cell<u64>; 2],+ /// Recompiles of functions whose idle time was longer than the base time because of earlier recompiles.+ pub backed_off_recompiles: [Cell<u64>; 2],+ /// Executables of the bytecode layer that something else still held.+ pub held_bytecode_candidates: Cell<u64>,+ pub flushed_bytecode_bytes: Cell<u64>,+ pub recompile_nanoseconds: Cell<u64>,+}++impl CodeFlushingStats {+ fn count(counter: &Cell<u64>, amount: u64) {+ counter.set(counter.get().saturating_add(amount));+ }+}++/// A flush pass, from the start of the marking of a collection to its sweep.+#[derive(Clone, Copy)]+struct Pass {+ now: Instant,+ /// The layers in which to flush whatever nothing else holds, whatever its age, by bit (see `FlushLayer`).+ forced_layers: u8,+}++impl Pass {+ fn forces(self, layer: FlushLayer) -> bool {+ self.forced_layers & (1 << layer as u8) != 0+ }+}++/// Every flush layer, as bits.+pub const ALL_FLUSH_LAYERS: u8 = 1 << FlushLayer::Jit as u8 | 1 << FlushLayer::Bytecode as u8;++/// The most collections whose times the VM keeps, one more than an idle collection count can be.+const KEPT_COLLECTION_TIMES: usize = u8::MAX as usize + 1;++/// The shared data of a function that a flush pass found, which does not keep it alive.+struct FlushCandidate(Gc<SharedFunctionInstanceData>);++// SAFETY: A pass finds its candidates while its collection marks, each in the trace of its own shared data, which is+// live then. The sweep callback of that collection takes the bytecode candidates, and its post-GC task the JIT+// candidates, neither of which allocates while it holds them. begin_pass() drops whatever is left before the+// next collection marks, so no candidate ever outlives a collection.+unsafe impl SweptAfterCollection for FlushCandidate {}++/// The code flushing state of a VM.+pub struct CodeFlushing {+ pub options: CodeFlushingOptions,+ /// When the last collections swept, the latest last.+ collection_times: RefCell<VecDeque<Instant>>,+ flush_at_next_collection: Cell<u8>,+ pass: Cell<Option<Pass>>,+ /// The shared data whose executable it did not visit in the marking of this collection.+ bytecode_candidates: RefCell<Vec<FlushCandidate>>,+ /// The shared data whose executable's JIT code idled long enough in this collection.+ jit_candidates: RefCell<Vec<FlushCandidate>>,+ pub stats: CodeFlushingStats,+}++thread_local! {+ /// The code flushing state of the VM whose collection marks on this thread, while it runs a flush pass.+ static ACTIVE_PASS: Cell<Option<NonNull<CodeFlushing>>> = const { Cell::new(None) };+}++impl CodeFlushing {+ pub fn new(options: CodeFlushingOptions) -> Self {+ Self {+ options,+ collection_times: RefCell::new(VecDeque::with_capacity(KEPT_COLLECTION_TIMES)),+ flush_at_next_collection: Cell::new(0),+ pass: Cell::new(None),+ bytecode_candidates: RefCell::default(),+ jit_candidates: RefCell::default(),+ stats: CodeFlushingStats::default(),+ }+ }++ /// Makes the next collection flush whatever nothing else holds in `layers` (bits of `FlushLayer`), whatever its+ /// age. Only for tests.+ pub fn flush_at_next_collection(&self, layers: u8) {+ self.flush_at_next_collection.set(layers);+ }++ /// Starts a flush pass for the collection that is about to mark the live cells, if the VM flushes code now.+ pub fn begin_pass(&self, vm: &Vm) {+ // NB: Only a collection uses up a forced flush; other markings (such as graph dumps) leave it for the next one.+ if !vm.heap().is_marking_for_collection() {+ return;+ }+ // NB: The candidates are not traced, so none may outlive the collection that found them, flush pass or not.+ self.bytecode_candidates.borrow_mut().clear();+ self.jit_candidates.borrow_mut().clear();+ let forced_layers = self.flush_at_next_collection.replace(0);+ if !(self.options.enabled || forced_layers != 0) || vm.debugging_enabled() {+ return;+ }+ self.pass.set(Some(Pass {+ now: Instant::now(),+ forced_layers: if self.options.stress {+ ALL_FLUSH_LAYERS+ } else {+ forced_layers+ },+ }));+ CodeFlushingStats::count(&self.stats.passes, 1);+ ACTIVE_PASS.set(Some(NonNull::from(self)));+ }++ /// Whether the idle time of an executable that idled for `idle_collections` collections is long enough to flush+ /// it in `layer` in this pass, for a function that was compiled again `recompiles` times after flushes there.+ fn idled_long_enough(&self, pass: Pass, layer: FlushLayer, idle_collections: u8, recompiles: u8) -> bool {+ if recompiles >= self.options.max_recompiles {+ return false;+ }+ if pass.forces(layer) {+ return true;+ }+ if pass.forced_layers != 0 || !self.options.enabled {+ return false;+ }+ if idle_collections == 0 || idle_collections < self.options.min_idle_collections {+ return false;+ }+ let times = self.collection_times.borrow();+ let Some(&idle_since) = times+ .len()+ .checked_sub(usize::from(idle_collections))+ .and_then(|index| times.get(index))+ else {+ return false;+ };+ let base = match layer {+ FlushLayer::Jit => self.options.jit_idle_time,+ FlushLayer::Bytecode => self.options.bytecode_idle_time,+ };+ let shift = recompiles.min(self.options.max_backoff_shift);+ pass.now.saturating_duration_since(idle_since) >= base.saturating_mul(1u32 << shift)+ }++ /// For the marking of a collection: whether the shared data `shared_data` should leave its executable unvisited,+ /// as it idled long enough to be flushed. Notes the shared data for the end of the pass.+ fn consider(&self, pass: Pass, shared_data: &SharedFunctionInstanceData, executable: Gc<Executable>) -> bool {+ if !shared_data.can_flush_code() {+ return false;+ }+ let idle_collections = executable.head.idle_collection_count.get();+ if executable.jit_compile_state() == CompileState::Installed+ && self.idled_long_enough(+ pass,+ FlushLayer::Jit,+ idle_collections,+ shared_data.recompile_count(FlushLayer::Jit),+ )+ {+ self.jit_candidates+ .borrow_mut()+ .push(FlushCandidate(Gc::from_ref(shared_data)));+ }+ if !self.idled_long_enough(+ pass,+ FlushLayer::Bytecode,+ idle_collections,+ shared_data.recompile_count(FlushLayer::Bytecode),+ ) {+ return false;+ }+ self.bytecode_candidates+ .borrow_mut()+ .push(FlushCandidate(Gc::from_ref(shared_data)));+ true+ }++ /// Ends the flush pass of the collection whose marks are final: flushes the executables of the candidates that+ /// died, and has the VM flush the JIT code of the others once the collection is over.+ pub fn finish_pass(&self, vm: &Vm, sweep: &Sweep<'_>) {+ ACTIVE_PASS.set(None);+ self.note_collection();+ if self.pass.take().is_none() {+ return;+ }+ let candidates = core::mem::take(&mut *self.bytecode_candidates.borrow_mut());+ for FlushCandidate(shared_data) in candidates {+ let Some(executable) = shared_data.executable() else {+ continue;+ };+ if !sweep.is_dead(executable) {+ CodeFlushingStats::count(&self.stats.held_bytecode_candidates, 1);+ continue;+ }+ CodeFlushingStats::count(&self.stats.flushes[FlushLayer::Bytecode as usize], 1);+ CodeFlushingStats::count(&self.stats.flushed_bytecode_bytes, executable.bytecode().len() as u64);+ shared_data.flush_executable(executable, sweep);+ }+ if !self.jit_candidates.borrow().is_empty() {+ vm.enqueue_code_flushing_task();+ }+ }++ /// Notes that a collection ran now.+ fn note_collection(&self) {+ let mut times = self.collection_times.borrow_mut();+ if times.len() == KEPT_COLLECTION_TIMES {+ times.pop_front();+ }+ times.push_back(Instant::now());+ }++ /// Drops the JIT code of the executables that idled long enough in the last collection, once it is over. Frames+ /// that still run an executable on a stack keep its code.+ pub fn flush_idle_jit_code(&self, vm: &Vm) {+ let candidates = core::mem::take(&mut *self.jit_candidates.borrow_mut());+ if candidates.is_empty() {+ return;+ }+ let mut running = HashSet::new();+ vm.for_each_live_execution_context(|frame| {+ if let Some(executable) = frame.executable.get() {+ running.insert(executable.as_ptr());+ }+ core::ops::ControlFlow::Continue(())+ });+ for FlushCandidate(shared_data) in candidates {+ let Some(executable) = shared_data.executable() else {+ continue;+ };+ if executable.jit_compile_state() != CompileState::Installed+ || running.contains(&Executable::head(executable).as_ptr())+ {+ continue;+ }+ CodeFlushingStats::count(&self.stats.flushes[FlushLayer::Jit as usize], 1);+ shared_data.note_flushed_jit_code();+ executable.flush_idle_jit_code(vm);+ }+ }++ /// Notes that a function whose code was flushed in `layer` was compiled again, `recompiles` times now.+ pub fn note_recompile(&self, layer: FlushLayer, recompiles: u8) {+ CodeFlushingStats::count(&self.stats.recompiles[layer as usize], 1);+ if recompiles > 1 && self.options.max_backoff_shift != 0 {+ CodeFlushingStats::count(&self.stats.backed_off_recompiles[layer as usize], 1);+ }+ if recompiles == self.options.max_recompiles {+ CodeFlushingStats::count(&self.stats.backoff_stops[layer as usize], 1);+ }+ }+}++/// For the marking of a collection: whether `shared_data` should leave its executable unvisited, as it idled long+/// enough to be flushed. Outside of a flush pass, it never should.+pub fn bytecode_flush_candidate(shared_data: &SharedFunctionInstanceData, executable: Gc<Executable>) -> bool {+ let Some(flushing) = ACTIVE_PASS.get() else {+ return false;+ };+ // SAFETY: The VM sets the pass when its collection starts marking and clears it in the sweep callback of that+ // collection, and the VM outlives its collections.+ let flushing = unsafe { flushing.as_ref() };+ let Some(pass) = flushing.pass.get() else {+ return false;+ };+ flushing.consider(pass, shared_data, executable)+}diff --git a/Libraries/LibJS/Rust/src/bytecode/mod.rs b/Libraries/LibJS/Rust/src/bytecode/mod.rsindex 4ec2f32b3da..1587b729c69 100644--- a/Libraries/LibJS/Rust/src/bytecode/mod.rs+++ b/Libraries/LibJS/Rust/src/bytecode/mod.rs@@ -24,6 +24,7 @@//! - `op` -- Instruction structs the interpreter reads (generated from interpreter.flap by build.rs)//! - `executable` -- Executable: the cell that holds bytecode and its caches//! - `feedback` -- What the profiling interpreter observes for the optimizing JIT, per executable+//! - `flushing` -- Dropping the code of functions that did not run for a while//! - `property_access` -- Property lookups through the inline caches//! - `class_blueprint` -- Classes as the runtime keeps them@@ -42,6 +43,8 @@ pub mod executable;pub mod executable_data;#[cfg(not(test))]pub mod feedback;+#[cfg(not(test))]+pub mod flushing;pub mod instruction;mod native_disassembler;pub mod operand;diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rsindex 99d0f1d4884..e1d962de651 100644--- a/Libraries/LibJS/Rust/src/gc/capi.rs+++ b/Libraries/LibJS/Rust/src/gc/capi.rs@@ -96,6 +96,7 @@ unsafe extern "C" {// NB: The functions that take a reference to the heap have no other preconditions.pub safe fn gc_heap_collect_garbage(heap: &GCHeap, collection_type: i32, print_report: bool);pub safe fn gc_heap_is_collecting_everything(heap: &GCHeap) -> bool;+ pub safe fn gc_heap_is_marking_for_collection(heap: &GCHeap) -> bool;pub safe fn gc_heap_undefer_gc(heap: &GCHeap);pub safe fn gc_heap_deferral_state(heap: &GCHeap,diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rsindex 0881491b7a0..0beffc296b3 100644--- a/Libraries/LibJS/Rust/src/gc/heap.rs+++ b/Libraries/LibJS/Rust/src/gc/heap.rs@@ -728,6 +728,11 @@ impl Heap {}}+ /// Whether the heap gathers its roots and marks the live cells for a collection now, rather than for a graph dump.+ pub fn is_marking_for_collection(&self) -> bool {+ capi::gc_heap_is_marking_for_collection(self.handle())+ }+pub fn should_collect_on_every_allocation(&self) -> bool {capi::gc_heap_should_collect_on_every_allocation(self.handle())}diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rsindex 835b3f6ef3e..066a2886316 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs@@ -606,6 +606,9 @@ pub fn call_construct(&& function.constructor_kind() == ConstructorKind::Base&& !function.has_class_data(){+ // NB: Taken before anything allocates: a collection could flush the code of the function otherwise, which this+ // local keeps from happening (see `bytecode::flushing`).+ let executable = function.inline_call_executable();let prototype = asm_try!(vm,pc,@@ -620,7 +623,7 @@ pub fn call_construct();let Some(context) = vm.push_inline_frame(function,- function.inline_call_executable(),+ executable,arguments,pc + instruction.length(),instruction.dst.0.into(),diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex fbc247e42cc..fbd286382c9 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -26,6 +26,7 @@ use crate::bytecode::executable::{Executable, KeyedPropertyLookupCache, PropertyLookupCache, StaticPropertyLookupCacheSite,StaticPropertyLookupCaches,};+use crate::bytecode::flushing::{CodeFlushing, CodeFlushingOptions};use crate::bytecode::property_access::Strict;use crate::debugger::Debugger;use crate::embedding::hooks::Embedder;@@ -635,6 +636,7 @@ pub struct Vm {saved_execution_context_stacks: RefCell<Vec<SavedExecutionContextStack>>,host_classes: RefCell<HostClassRegistry>,pub jit: JitState,+ pub code_flushing: CodeFlushing,}const _: () = assert!(core::mem::offset_of!(Vm, head) == 0);@@ -777,6 +779,7 @@ impl Vm {saved_execution_context_stacks: RefCell::new(Vec::new()),host_classes: RefCell::new(HashMap::default()),jit: JitState::new(JitOptions::from_environment()),+ code_flushing: CodeFlushing::new(CodeFlushingOptions::from_environment()),};// SAFETY: The caller provides storage for a Vm.unsafe { storage.write(vm) };@@ -1175,6 +1178,7 @@ impl Vm {}fn gather_roots(&self, visitor: &mut Visitor) {+ self.code_flushing.begin_pass(self);self.jit.trace(visitor);self.for_each_execution_context_top_to_bottom(|context| {context.trace(visitor);@@ -1568,6 +1572,15 @@ impl Vm {self.jit.dependents.remove_dead_entries(sweep);}+ /// Has the JIT code that idled long enough in this collection flushed once the collection is over.+ pub(crate) fn enqueue_code_flushing_task(&self) {+ // SAFETY: The VM outlives its heap, whose collections run the task.+ unsafe {+ self.heap()+ .enqueue_post_gc_task(flush_idle_jit_code, core::ptr::from_ref(self).cast_mut().cast());+ }+ }+pub fn register_executable(&self, executable: Gc<Executable>) {let (tier, tier_up_budget) = tier_up::initial_tier(&self.jit);executable.set_interpreter_tier(tier);@@ -2233,6 +2246,7 @@ unsafe extern "C" fn sweep(context: *mut c_void) {let vm = unsafe { &*context.cast::<Vm>() };// SAFETY: LibGC runs sweep callbacks once the marks are final, before it sweeps the cells that died.let sweep = unsafe { Sweep::new(vm) };+ vm.code_flushing.finish_pass(vm, &sweep);vm.remove_dead_cells_from_weak_containers(&sweep);vm.remove_dead_strings_from_weak_caches(&sweep);vm.remove_dead_cells_from_property_lookup_caches(&sweep);@@ -2243,6 +2257,12 @@ unsafe extern "C" fn sweep(context: *mut c_void) {}}+unsafe extern "C" fn flush_idle_jit_code(context: *mut c_void) {+ // SAFETY: The task was enqueued with the VM as its context.+ let vm = unsafe { &*context.cast::<Vm>() };+ vm.code_flushing.flush_idle_jit_code(vm);+}+unsafe extern "C" fn enqueue_cleanup_jobs_of_finalization_registries_with_dead_cells(context: *mut c_void) {// SAFETY: The task was enqueued with the VM as its context.let vm = unsafe { &*context.cast::<Vm>() };diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex 8f6d92cbe1d..360ed6da56f 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -221,7 +221,12 @@ fn construct_ecmascript_function_from_jit(// 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).// NB: The frame does not use the construct return rule of Return, which knows nothing of derived constructors;// steps 10 to 17 are below.- let executable = function.bytecode_executable().expect("a constructor has an executable");+ // NB: The prototype lookup above may have run code and collected garbage, which may have flushed the+ // constructor's code (see `bytecode::flushing`).+ let executable = match function.compiled_executable(vm) {+ Ok(executable) => executable,+ Err(throw) => return handle_asm_exception(vm, site.pc, throw.value()),+ };let argument_count = u32::try_from(arguments.len()).expect("the argument count fits in u32");let Some(callee_frame) = vm.push_inline_frame_without_this(function,@@ -972,6 +977,14 @@ pub unsafe extern "C" fn libjs_jit_prepare_call_environment({super::allocation::make_call_environment_template(vm, function, environment);}+ // NB: The allocations may have collected garbage and flushed the function's code (see `bytecode::flushing`),+ // which the calling stub loads again from the function. The call takes the generic path if it cannot compile.+ if function.compiled_executable(vm).is_err() {+ return CallEnvironment {+ environment: 0,+ this_value: 0,+ };+ }CallEnvironment {environment: environment.map_or(0, |environment| environment.as_ptr() as u64),this_value: this_value.0,diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 64f0ec281f3..9e320b9ccff 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -461,6 +461,9 @@ pub struct ExecutableJitState {/// Whether the executable is refused once its discarded code is detached, because it was refused while frames/// still ran that code (see `refuse_jit_compile_once_detached()`).refused_once_detached: Cell<bool>,+ /// Whether the discarded code is discarded because the executable idled (see `flush_idle_jit_code()`), which does+ /// not count as a discard.+ discarded_while_idle: Cell<bool>,/// The loads and stores of bindings of the environments of the executable's closure (see `jit::snapshot`). The/// bytecode never changes, so snapshots find them once.pub(crate) captured_binding_accesses: OnceCell<CapturedBindingAccesses>,@@ -710,6 +713,19 @@ impl Executable {self.head.tier_up_budget.set(super::tier_up::recompile_budget(&vm.jit));}+ /// Drops the JIT code of an executable that idled long enough (see `bytecode::flushing`), like discard_jit_code()+ /// but without counting a discard: it says nothing about the code. The executable has to get hot again to be+ /// compiled again.+ pub fn flush_idle_jit_code(&self, vm: &Vm) {+ self.jit_state().discarded_while_idle.set(true);+ self.discard_jit_code(vm);+ if self.jit_compile_state() == CompileState::Discarding {+ self.head+ .tier_up_budget+ .set(super::tier_up::initial_tier_up_budget(&vm.jit));+ }+ }+/// Drops the JIT code of an executable whose code was discarded if no live frame of the executable is run by JIT/// code. Returns whether it did.///@@ -752,6 +768,14 @@ impl Executable {let state = self.jit_state();let (table, slot) = self.jit_entry_table_slot(vm).expect("the code is attached");table.detach_code(slot);+ if state.discarded_while_idle.replace(false) && !state.refused_once_detached.get() {+ vm.jit.count_coverage("flush");+ self.set_jit_compile_state(CompileState::None);+ self.head+ .tier_up_budget+ .set(super::tier_up::initial_tier_up_budget(&vm.jit));+ return;+ }vm.jit.count_coverage("discard");let discard_count = state.discard_count.get() + 1;state.discard_count.set(discard_count);diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rsindex 81f2dc2b975..450ab47d435 100644--- a/Libraries/LibJS/Rust/src/jit/disabled.rs+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs@@ -116,6 +116,10 @@ pub mod code {pub fn discard_jit_code(&self, _vm: &Vm) {unreachable!("no executable has JIT code");}++ pub fn flush_idle_jit_code(&self, _vm: &Vm) {+ unreachable!("no executable has JIT code");+ }}}@@ -132,6 +136,8 @@ pub mod tier_up {}pub fn finish_top_level_code(_vm: &Vm, _executable: &crate::bytecode::executable::Executable) {}++ pub fn wait_for_compile_jobs(_vm: &Vm) {}}pub mod entry_exit {diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex af396957698..8962c58da96 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -394,6 +394,11 @@ impl JitState {id}+ /// Whether compile jobs run on the compile threads.+ pub(crate) fn has_compile_jobs(&self) -> bool {+ !self.jobs.borrow().is_empty()+ }+/// Forgets every compile job, whose results are dropped when they finish.pub(crate) fn abandon_compile_jobs(&self) {self.jobs.borrow_mut().clear();diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex fb8e43d27f7..8ece0737f06 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -301,6 +301,9 @@ pub fn on_budget_exhausted(vm: &Vm, pc: u32, is_loop: bool) {refuse_jit_compile(vm, &executable);return;};+ if let Some(function) = code.function() {+ function.shared_data().note_jit_compile(vm);+ }compile(vm, executable, code.function(), is_loop.then_some(pc), options.sync);if executable.jit_compile_state() == CompileState::Queued {executable.head.tier_up_budget.set(QUEUED_BUDGET);@@ -527,6 +530,7 @@ pub fn compile_now(vm: &Vm, function: Gc<EcmascriptFunctionObject>) -> bool {}if executable.jit_compile_state() == CompileState::None {executable.ensure_feedback().update_value_feedback();+ function.shared_data().note_jit_compile(vm);compile(vm, executable, Some(function), None, true);}executable.jit_compile_state() == CompileState::Installed@@ -557,6 +561,17 @@ pub(crate) fn wait_for_compile_job(vm: &Vm, executable: &Executable) {}}+/// Waits for every compile job to finish and installs its code. Only for tests.+pub fn wait_for_compile_jobs(vm: &Vm) {+ let Some(queue) = vm.jit.started_compile_queue() else {+ return;+ };+ install_compile_results(vm, vm.jit.take_held_compile_results(), &DeferGc::new(vm));+ while vm.jit.has_compile_jobs() {+ install_compile_results(vm, queue.wait_for_finished(), &DeferGc::new(vm));+ }+}+/// Installs the code of finished compile jobs.fn install_compile_results(vm: &Vm, results: Vec<(u64, CompileResult)>, defer_gc: &DeferGc<'_>) {let finished: Vec<(CompileJob, CompileResult)> = resultsdiff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex 32bcaee0228..67bb5dcba07 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -634,7 +634,6 @@ impl EcmascriptFunctionObject {if should_dump_bytecode() {rust_executable.dump();}- shared_data.clear_compile_inputs();Ok(rust_executable)}@@ -657,8 +656,6 @@ impl EcmascriptFunctionObject {) -> ThrowCompletionOr<Value> {let function = as_ecmascript_function(object);- debug_assert!(function.bytecode_executable().is_some());-// 1. Let callerContext be the running execution context.// NOTE: No-op, kept by the VM in its execution context stack.@@ -711,8 +708,6 @@ impl EcmascriptFunctionObject {) -> ThrowCompletionOr<Gc<Object>> {let function = as_ecmascript_function(object);- debug_assert!(function.bytecode_executable().is_some());-// 1. Let callerContext be the running execution context.// NOTE: No-op, kept by the VM in its execution context stack.@@ -979,9 +974,9 @@ impl EcmascriptFunctionObject {// 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody// 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbodyfn ordinary_call_evaluate_body(&self, vm: &Vm, context: &ExecutionContext) -> ThrowCompletionOr<Value> {- let executable = self- .bytecode_executable()- .expect("a function is compiled before it is called");+ // NB: The function was compiled before the call, but its code may have been flushed since (see+ // `bytecode::flushing`), as nothing held it while the call allocated.+ let executable = self.compiled_executable(vm)?;let result = vm.run_executable(NonNull::from(context), executable, 0);// NOTE: Running the bytecode should eventually return a completion.diff --git a/Libraries/LibJS/Rust/src/runtime/generator_object.rs b/Libraries/LibJS/Rust/src/runtime/generator_object.rsindex 0c8e337d712..3c2884b4cff 100644--- a/Libraries/LibJS/Rust/src/runtime/generator_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/generator_object.rs@@ -56,9 +56,10 @@ impl GeneratingFunction {pub fn bytecode_executable(self, vm: &Vm) -> Gc<Executable> {match self {+ // NB: The generating function runs, so its executable is not flushed.GeneratingFunction::Ecmascript(function) => function.bytecode_executable()- .expect("a generating function is compiled before it is called"),+ .expect("a generating function is compiled while it runs"),GeneratingFunction::NativeJavaScriptBacked(function) => function.bytecode_executable(vm).must(),}}diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rsindex 1b10584cb11..a894f1f115d 100644--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs@@ -13,13 +13,15 @@ use ak::{Utf16FlyString, Utf16String};use libjs_runtime_macros::Trace;pub use crate::ast::FunctionKind;-use crate::bytecode::executable::Executable;+use crate::bytecode::executable::{Executable, TemplateObjectCache};use crate::bytecode::executable_data::{FunctionSfdMetadata, PendingSharedFunctionData, PrecompiledFunction};+use crate::bytecode::flushing::{self, FlushLayer};use crate::compile::FunctionPayload;use crate::compile::SharedFunctionDescription;use crate::gc::class::{GcCell, define_cell};use crate::gc::defer_gc::DeferGc;use crate::gc::gc_ref_cell::GcRefCell;+use crate::gc::sweep::Sweep;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;use crate::layout::cell::{CellHeaderTail, Gc};@@ -67,13 +69,20 @@ pub enum ClassFieldInitializerName {Empty,}-/// What a function's executable is made from when it is first called, which only one thing can be at a time.+/// What a function's executable is made from when it is first called, which only one thing can be at a time. A+/// function keeps its payload once it compiled, which it compiles from again if its executable gets flushed.enum CompileInput {None,- /// The function is not parsed yet: its source and its row there, which its tree is parsed from.+ /// The function's source and its row there, which its tree is parsed from.Unparsed(Arc<FunctionPayload>),/// Freshly compiled bytecode.- PrecompiledBytecode(Arc<PrecompiledFunction>),+ PrecompiledBytecode(Box<PrecompiledInput>),+}++/// Bytecode compiled ahead of the first call, and the payload it was compiled from, if the function has one.+struct PrecompiledInput {+ precompiled: Arc<PrecompiledFunction>,+ payload: Option<Arc<FunctionPayload>>,}/// A CompileInput in one word: the pointer, with what it points at in its lowest bits.@@ -82,7 +91,7 @@ struct CompileInputSlot(Cell<*mut ()>);// NB: The pointers in a slot leave room for its tag.const _: () = assert!(align_of::<FunctionPayload>() > CompileInputSlot::TAG_MASK- && align_of::<PrecompiledFunction>() > CompileInputSlot::TAG_MASK+ && align_of::<PrecompiledInput>() > CompileInputSlot::TAG_MASK);impl CompileInputSlot {@@ -101,8 +110,8 @@ impl CompileInputSlot {self.0.set(match input {CompileInput::None => core::ptr::null_mut(),CompileInput::Unparsed(payload) => Self::tagged(Arc::into_raw(payload).cast_mut(), Self::TAG_UNPARSED),- CompileInput::PrecompiledBytecode(precompiled) => {- Self::tagged(Arc::into_raw(precompiled).cast_mut(), Self::TAG_PRECOMPILED_BYTECODE)+ CompileInput::PrecompiledBytecode(input) => {+ Self::tagged(Box::into_raw(input), Self::TAG_PRECOMPILED_BYTECODE)}});}@@ -119,13 +128,20 @@ impl CompileInputSlot {unsafe {match word.addr() & Self::TAG_MASK {Self::TAG_UNPARSED => CompileInput::Unparsed(Arc::from_raw(pointer.cast())),- Self::TAG_PRECOMPILED_BYTECODE => CompileInput::PrecompiledBytecode(Arc::from_raw(pointer.cast())),+ Self::TAG_PRECOMPILED_BYTECODE => CompileInput::PrecompiledBytecode(Box::from_raw(pointer.cast())),_ => CompileInput::None,}}}}+impl CompileInputSlot {+ /// Whether the input is the payload of the function, which it compiled from at least once.+ fn is_unparsed(&self) -> bool {+ self.0.get().addr() & Self::TAG_MASK == Self::TAG_UNPARSED+ }+}+impl Drop for CompileInputSlot {fn drop(&mut self) {drop(self.take());@@ -153,6 +169,21 @@ struct SharedFunctionInstanceDataRareData {/// Functions with parameter expressions may have a separate var environment.var_environment_bindings_count: Cell<u32>,var_environment_shape: NullableMember<EnvironmentShape>,+ /// What the last executable of the function left for the next one, while its code is flushed.+ flushed_code: GcRefCell<Option<Box<FlushedCode>>>,+ /// How often the function was compiled again after a flush, in each `FlushLayer`.+ recompile_counts: Cell<[u8; 2]>,+ /// Whether the JIT code of the function's executable was flushed since it was last compiled.+ jit_code_flushed: Cell<bool>,+}++/// What a flushed executable leaves for the next executable of its code, which nothing that code observes may tell+/// apart from it: the shared data of the functions it creates, which closures created before share with those created+/// later, and its template objects, which belong to their site in the code.+#[derive(Default, Trace)]+pub struct FlushedCode {+ pub shared_function_data: Vec<Gc<SharedFunctionInstanceData>>,+ pub template_object_caches: Vec<Gc<TemplateObjectCache>>,}/// The parts of the shared data of a function that the interpreter does not read.@@ -190,10 +221,17 @@ const _: () = assert!(MAX_CONSTRUCT_RESERVE_UPDATES as u64 <= asm_call_metadata:define_cell!(SharedFunctionInstanceData, Other);-// SAFETY: Visits the executable, the call environment template and every cell the storage holds.+// SAFETY: Visits the executable, the call environment template and every cell the storage holds. While a collection+// flushes code, an executable that idled long enough is left to what else holds it, and the cells that outlive+// a flush of it are visited instead (see `bytecode::flushing`).unsafe impl Trace for SharedFunctionInstanceData {fn trace(&self, visitor: &mut Visitor) {- self.executable.trace(visitor);+ match self.executable() {+ Some(executable) if flushing::bytecode_flush_candidate(self, executable) => {+ executable.trace_what_outlives_a_flush(visitor);+ }+ _ => self.executable.trace(visitor),+ }self.call_environment_template.trace(visitor);match self.script_or_module.get() {ScriptOrModule::Empty => {}@@ -604,9 +642,73 @@ impl SharedFunctionInstanceData {/// does.pub fn set_precompiled_bytecode_executable(&self, precompiled: Arc<PrecompiledFunction>) {self.set_metadata(&precompiled.metadata);+ let payload = match self.storage.compile_input.take() {+ CompileInput::Unparsed(payload) => Some(payload),+ CompileInput::None | CompileInput::PrecompiledBytecode(_) => None,+ };self.storage.compile_input- .set(CompileInput::PrecompiledBytecode(precompiled));+ .set(CompileInput::PrecompiledBytecode(Box::new(PrecompiledInput {+ precompiled,+ payload,+ })));+ }++ /// Whether the function's executable can be flushed, as the function can compile its code again.+ pub fn can_flush_code(&self) -> bool {+ self.storage.compile_input.is_unparsed()+ }++ /// How often the function was compiled again after its code was flushed in `layer`.+ pub fn recompile_count(&self, layer: FlushLayer) -> u8 {+ self.storage+ .rare_data+ .get()+ .map_or(0, |rare_data| rare_data.recompile_counts.get()[layer as usize])+ }++ /// Counts a recompile in `layer` after a flush there.+ fn note_recompile(&self, vm: &Vm, layer: FlushLayer) {+ let rare_data = self.rare_data();+ let mut counts = rare_data.recompile_counts.get();+ counts[layer as usize] = counts[layer as usize].saturating_add(1);+ rare_data.recompile_counts.set(counts);+ vm.code_flushing.note_recompile(layer, counts[layer as usize]);+ }++ /// Drops the function's executable, which no one else holds, and goes back to the lazy state from which the next+ /// call compiles the function again. Keeps what the next executable takes over. Only the sweep callback of a+ /// collection calls this, through its Sweep.+ pub fn flush_executable(&self, executable: Gc<Executable>, _: &Sweep<'_>) {+ assert!(self.can_flush_code());+ let flushed_code = FlushedCode {+ shared_function_data: executable.shared_function_data_slice().to_vec(),+ template_object_caches: executable.template_object_caches_slice().to_vec(),+ };+ self.rare_data().flushed_code.replace(Some(Box::new(flushed_code)));+ self.set_executable(None);+ }++ /// Whether the function's executable was flushed, and not compiled again yet.+ pub fn has_flushed_code(&self) -> bool {+ self.storage+ .rare_data+ .get()+ .is_some_and(|rare_data| rare_data.flushed_code.borrow().is_some())+ }++ /// Notes that the JIT code of the function's executable was flushed.+ pub fn note_flushed_jit_code(&self) {+ self.rare_data().jit_code_flushed.set(true);+ }++ /// Notes that the JIT compiles the function's executable, which counts as a recompile if its JIT code was flushed.+ pub fn note_jit_compile(&self, vm: &Vm) {+ if let Some(rare_data) = self.storage.rare_data.get()+ && rare_data.jit_code_flushed.replace(false)+ {+ self.note_recompile(vm, FlushLayer::Jit);+ }}/// Sets [[ClassFieldInitializerName]] to a name the frontend found, as rust_sfd_set_class_field_initializer_name@@ -843,7 +945,11 @@ impl SharedFunctionInstanceData {let source_code = shared_data.source_code();let payload = match shared_data.storage.compile_input.take() {- CompileInput::PrecompiledBytecode(precompiled) => {+ CompileInput::PrecompiledBytecode(input) => {+ let PrecompiledInput { precompiled, payload } = *input;+ if let Some(payload) = payload {+ shared_data.storage.compile_input.set(CompileInput::Unparsed(payload));+ }// NB: This stays the only reference to the code if nothing else holds the function.let executable = Arc::try_unwrap(precompiled).map_or_else(|shared| shared.executable.clone(), |unique| unique.executable);@@ -856,19 +962,37 @@ impl SharedFunctionInstanceData {CompileInput::Unparsed(payload) => payload,CompileInput::None => panic!("a function that was not compiled yet knows how to compile"),};+ let started = shared_data.has_flushed_code().then(std::time::Instant::now);let precompiled =crate::compile::compile_function(&payload, builtin_abstract_operations_enabled, vm.native_stack_limit());+ shared_data.storage.compile_input.set(CompileInput::Unparsed(payload));let Ok(precompiled) = precompiled else {- shared_data.storage.compile_input.set(CompileInput::Unparsed(payload));return vm.throw_completion(ErrorKind::RangeError, ErrorType::CallStackSizeExceeded, &[]);};shared_data.set_metadata(&precompiled.metadata);- Ok(Executable::create_with_source_code(+ let Some(started) = started else {+ return Ok(Executable::create_with_source_code(+ vm,+ precompiled.executable,+ source_code.as_ref(),+ ));+ };+ // NB: The flushed code stays in the shared data, which visits it, until the new executable holds it.+ let executable = Executable::create_with_flushed_code(vm,precompiled.executable,source_code.as_ref(),- ))+ shared_data.rare_data().flushed_code.borrow().as_deref(),+ );+ shared_data.rare_data().flushed_code.replace(None);+ let elapsed = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);+ let stats = &vm.code_flushing.stats;+ stats+ .recompile_nanoseconds+ .set(stats.recompile_nanoseconds.get().saturating_add(elapsed));+ shared_data.note_recompile(vm, FlushLayer::Bytecode);+ Ok(executable)}}diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rsindex a2235b169f5..2d6ef5fd995 100644--- a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs+++ b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs@@ -14,6 +14,7 @@ use ak::Utf16FlyString;use super::javascript_test_runner::{JSFileResult, parse_module, parse_script};use super::test_runner::{Case, Suite, TestResult, get_time_in_ms, relative_path};+use crate::bytecode::flushing::{ALL_FLUSH_LAYERS, FlushLayer};use crate::bytecode::property_access::Strict;use crate::gc::class::{Extends, ExternalMemorySize, GcCell};use crate::interpreter::vm::Vm;@@ -26,6 +27,7 @@ use crate::runtime::abstract_operations::{call, can_be_held_weakly};use crate::runtime::array_buffer::{ArrayBuffer, Order, detach_array_buffer};use crate::runtime::completion::ThrowCompletionOr;use crate::runtime::date::clear_system_time_zone_cache;+use crate::runtime::ecmascript_function_object::EcmascriptFunctionObject;use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;use crate::runtime::finalization_registry::FinalizationRegistry;@@ -50,6 +52,8 @@ pub const EXPOSED_GLOBAL_FUNCTIONS: &[(&str, RawNativeFunctionPointer)] = &[),("setDictionaryGeneration", raw_native!(set_dictionary_generation)),("gc", raw_native!(collect_garbage)),+ ("flushCode", raw_native!(flush_code)),+ ("isCodeFlushed", raw_native!(is_code_flushed)),("collectGarbageOnEveryAllocation",raw_native!(collect_garbage_on_every_allocation),@@ -121,6 +125,40 @@ fn collect_garbage(vm: &Vm) -> ThrowCompletionOr<Value> {Ok(Value::UNDEFINED)}+/// Runs collections that flush the code of every function that nothing but the function holds, whatever its age:+/// only the JIT code if the argument is "jit", and the whole executable otherwise.+fn flush_code(vm: &Vm) -> ThrowCompletionOr<Value> {+ let layers = if vm.argument(0).is_undefined() {+ ALL_FLUSH_LAYERS+ } else if vm.argument(0).to_primitive_string(vm)?.to_utf8() == "jit" {+ 1 << FlushLayer::Jit as u8+ } else {+ ALL_FLUSH_LAYERS+ };+ // NB: A compile job holds its executable, which would keep the code from being flushed.+ crate::jit::tier_up::wait_for_compile_jobs(vm);+ vm.code_flushing.flush_at_next_collection(layers);+ vm.heap().collect_garbage();+ // NB: JIT code holds its executable until it is flushed after the first collection, so the second one can flush+ // the bytecode too.+ if layers != 1 << FlushLayer::Jit as u8 {+ vm.code_flushing.flush_at_next_collection(layers);+ vm.heap().collect_garbage();+ }+ Ok(Value::UNDEFINED)+}++/// Whether the code of a function was flushed, and not compiled again yet.+fn is_code_flushed(vm: &Vm) -> ThrowCompletionOr<Value> {+ let Some(function) = as_if::<EcmascriptFunctionObject>(vm.argument(0)) else {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&vm.argument(0)]);+ };+ let shared_data = function.shared_data();+ Ok(Value::from_bool(+ shared_data.executable().is_none() && shared_data.has_flushed_code(),+ ))+}+fn collect_garbage_on_every_allocation(vm: &Vm) -> ThrowCompletionOr<Value> {let heap = vm.heap();let previous = heap.should_collect_on_every_allocation();diff --git a/Tests/LibJS/Runtime/code-flushing.js b/Tests/LibJS/Runtime/code-flushing.jsnew file mode 100644index 00000000000..b03713232f7--- /dev/null+++ b/Tests/LibJS/Runtime/code-flushing.js@@ -0,0 +1,197 @@+// The code of a function that did not run for a while is flushed, and compiled again when the function is called+// again. flushCode() flushes everything that nothing but its function holds, and code must behave the same afterwards.++// NB: The bodies of these tests never run in JIT code, which would hold the code of the functions it inlines. The+// functions they declare keep their shared data across the harness's repeated runs of a test, so that each run+// would add recompiles, which stop the flushes of a function after six. So the body runs once.+function flushingTest(name, body) {+ let ran = false;+ test(name, function run() {+ if (ran) return;+ ran = true;+ if (typeof jit !== "undefined") {+ jit.neverCompile(run);+ jit.neverCompile(body);+ }+ body();+ });+}++describe("flushed functions", () => {+ flushingTest("a flushed function compiles again when it is called", () => {+ function add(a, b) {+ return a + b;+ }+ expect(add(1, 2)).toBe(3);+ flushCode();+ expect(isCodeFlushed(add)).toBeTrue();+ expect(add(3, 4)).toBe(7);+ expect(isCodeFlushed(add)).toBeFalse();+ });++ flushingTest("closures keep working over the code of flushed functions", () => {+ function makeCounter(start) {+ let count = start;+ return {+ increment: () => ++count,+ read() {+ return count;+ },+ };+ }+ const before = makeCounter(10);+ expect(before.increment()).toBe(11);+ flushCode();+ expect(isCodeFlushed(makeCounter)).toBeTrue();+ expect(isCodeFlushed(before.increment)).toBeTrue();+ expect(before.increment()).toBe(12);+ expect(before.read()).toBe(12);+ const after = makeCounter(0);+ expect(after.increment()).toBe(1);+ expect(before.read()).toBe(12);+ });++ flushingTest("template objects stay the same across recompiles", () => {+ const tag = strings => strings;+ function direct() {+ return tag`a${1}b`;+ }+ function outer() {+ return () => tag`c${2}d`;+ }+ const first = direct();+ const innerBefore = outer();+ const nestedFirst = innerBefore();+ flushCode();+ expect(isCodeFlushed(direct)).toBeTrue();+ expect(isCodeFlushed(outer)).toBeTrue();+ expect(direct()).toBe(first);+ expect(outer()()).toBe(nestedFirst);+ expect(innerBefore()).toBe(nestedFirst);+ });++ flushingTest("recompiled code gives the same results", () => {+ class Point {+ #secret = 7;+ static origin = new Point(0, 0);+ constructor(x, y) {+ this.x = x;+ this.y = y;+ }+ get sum() {+ return this.x + this.y + this.#secret;+ }+ *coordinates() {+ yield this.x;+ yield this.y;+ }+ }+ function work(values, { scale = 2 } = {}) {+ let total = 0;+ for (const [index, value] of values.entries()) {+ try {+ if (value < 0) throw new RangeError(`negative at ${index}`);+ total += value * scale;+ } catch (error) {+ total -= index;+ }+ }+ const point = new Point(arguments.length, total);+ return [total, point.sum, [...point.coordinates()], Point.origin.sum, typeof eval("scale")];+ }+ const expected = JSON.stringify(work([1, -2, 3], { scale: 3 }));+ flushCode();+ expect(isCodeFlushed(work)).toBeTrue();+ expect(JSON.stringify(work([1, -2, 3], { scale: 3 }))).toBe(expected);+ flushCode();+ expect(isCodeFlushed(work)).toBeTrue();+ expect(JSON.stringify(work([1, -2, 3], { scale: 3 }))).toBe(expected);+ });++ flushingTest("exceptions report the same stack and position after recompiles", () => {+ function thrower(value) {+ if (value > 0) return thrower(value - 1);+ throw new Error("deep");+ }+ function stackOf() {+ try {+ thrower(2);+ } catch (error) {+ return error.stack;+ }+ }+ // NB: The frames below stackOf() differ only in the line it is called from.+ const framesUpToStackOf = stack => stack.split("\n").slice(0, 5).join("\n");+ const expected = framesUpToStackOf(stackOf());+ expect(expected.includes("at thrower (")).toBeTrue();+ expect(expected.includes("at stackOf (")).toBeTrue();+ flushCode();+ expect(isCodeFlushed(thrower)).toBeTrue();+ expect(framesUpToStackOf(stackOf())).toBe(expected);+ });++ flushingTest("functions are flushed six times at most", () => {+ function often() {+ return "often";+ }+ for (let i = 0; i < 6; ++i) {+ expect(often()).toBe("often");+ flushCode();+ expect(isCodeFlushed(often)).toBeTrue();+ }+ expect(often()).toBe("often");+ flushCode();+ expect(isCodeFlushed(often)).toBeFalse();+ });+});++describe("code that something else holds", () => {+ flushingTest("running functions keep their code", () => {+ function running() {+ flushCode();+ return isCodeFlushed(running);+ }+ expect(running()).toBeFalse();+ });++ flushingTest("suspended generators keep their code", () => {+ function* numbers() {+ let i = 0;+ while (true) yield i++;+ }+ const iterator = numbers();+ expect(iterator.next().value).toBe(0);+ flushCode();+ expect(isCodeFlushed(numbers)).toBeFalse();+ expect(iterator.next().value).toBe(1);+ const other = numbers();+ expect(other.next().value).toBe(0);+ expect(iterator.next().value).toBe(2);+ });++ flushingTest("suspended async functions keep their code", () => {+ let resolve;+ const promise = new Promise(resolver => (resolve = resolver));+ async function later() {+ const value = await promise;+ return value + 1;+ }+ let result;+ later().then(value => (result = value));+ flushCode();+ expect(isCodeFlushed(later)).toBeFalse();+ resolve(41);+ runQueuedPromiseJobs();+ expect(result).toBe(42);+ });++ flushingTest("finished generators let their code go", () => {+ function* once() {+ yield 1;+ }+ expect([...once()]).toEqual([1]);+ flushCode();+ expect(isCodeFlushed(once)).toBeTrue();+ expect([...once()]).toEqual([1]);+ });+});diff --git a/Tests/LibJS/Runtime/jit/code-flushing.js b/Tests/LibJS/Runtime/jit/code-flushing.jsnew file mode 100644index 00000000000..e2046ea8c4b--- /dev/null+++ b/Tests/LibJS/Runtime/jit/code-flushing.js@@ -0,0 +1,70 @@+// The JIT code of a function that did not run for a while is flushed, and the function runs in the interpreter until+// it gets hot again. flushCode("jit") flushes the JIT code of every function no frame runs, whatever its age.++// NB: The functions the tests declare keep their shared data across the harness's repeated runs of a test, so that each+// run would add recompiles, which stop the flushes of a function after six. So the body runs once.+function flushingTest(name, body) {+ let ran = false;+ test(name, () => {+ if (ran) return;+ ran = true;+ body();+ });+}++function compileHot(f, warmUp) {+ jit.prepare(f);+ warmUp();+ return jit.compile(f);+}++flushingTest("flushed JIT code compiles again", () => {+ function scale(value) {+ return value * 3 + 1;+ }+ const warmUp = () => {+ for (let i = 0; i < 10; ++i) expect(scale(i)).toBe(i * 3 + 1);+ };+ expect(compileHot(scale, warmUp)).toBe(jit.enabled);+ expect(jit.isCompiled(scale)).toBe(jit.enabled);+ flushCode("jit");+ expect(jit.isCompiled(scale)).toBeFalse();+ expect(scale(5)).toBe(16);+ expect(compileHot(scale, warmUp)).toBe(jit.enabled);+ expect(scale(7)).toBe(22);+});++flushingTest("callers of flushed JIT code keep working", () => {+ function callee(value) {+ let result = value;+ for (let i = 0; i < 3; ++i) result = result * 2 + 1;+ return result;+ }+ function caller(value) {+ return callee(value) + callee(value + 1);+ }+ const warmUp = () => {+ for (let i = 0; i < 10; ++i) expect(caller(i)).toBe(16 * i + 22);+ };+ expect(compileHot(callee, warmUp)).toBe(jit.enabled);+ expect(compileHot(caller, warmUp)).toBe(jit.enabled);+ flushCode("jit");+ expect(jit.isCompiled(callee)).toBeFalse();+ expect(jit.isCompiled(caller)).toBeFalse();+ expect(caller(2)).toBe(54);+ expect(compileHot(caller, warmUp)).toBe(jit.enabled);+ expect(caller(3)).toBe(70);+});++flushingTest("running functions keep their JIT code", () => {+ function running(flush) {+ if (flush) flushCode("jit");+ return jit.isCompiled(running);+ }+ jit.prepare(running);+ for (let i = 0; i < 10; ++i) running(false);+ expect(jit.compile(running)).toBe(jit.enabled);+ // NB: Forced exits can discard the code of the running function on their own.+ const compiled = running(true);+ if (!jit.forcesExits) expect(compiled).toBe(jit.enabled);+});