Truly independent web browser
LibJS: Let collections move the cells executables and JIT code use
Andreas Kling6d95cc0b6873
diff --git a/Libraries/LibJS/JIT/Rust/src/artifact.rs b/Libraries/LibJS/JIT/Rust/src/artifact.rsindex 09c0aae5777..d44dab4d4b2 100644--- a/Libraries/LibJS/JIT/Rust/src/artifact.rs+++ b/Libraries/LibJS/JIT/Rust/src/artifact.rs@@ -134,7 +134,7 @@ const CALL_WORDS_WITH_OBJECTS: usize = 8;const OBJECT_WORDS: usize = 6;const OBJECT_KIND: usize = 0;const OBJECT_ALLOCATION: usize = 1;-/// The shape or the sample, as two words.+/// The shape or the sample slot, as two words.const OBJECT_CELL: usize = 2;/// Where the locations of the properties start in the run of a site.const OBJECT_PROPERTIES: usize = 4;@@ -475,7 +475,7 @@ impl<'a> ArtifactWriter<'a> {for (kind, allocation, property_count) in objects {let (kind, cell) = match kind {VirtualObjectDescriptorKind::Object { shape } => (OBJECT_KIND_OBJECT, shape),- VirtualObjectDescriptorKind::Closure { sample } => (OBJECT_KIND_CLOSURE, sample),+ VirtualObjectDescriptorKind::Closure { sample_slot } => (OBJECT_KIND_CLOSURE, sample_slot),};let mut words = [0; OBJECT_WORDS];words[OBJECT_KIND] = kind;@@ -1114,7 +1114,7 @@ impl<'a, W: Word> ObjectView<'a, W> {let cell = CellId(from_halves(&self.record[OBJECT_CELL..]));match self.record[OBJECT_KIND].word() {OBJECT_KIND_OBJECT => VirtualObjectDescriptorKind::Object { shape: cell },- OBJECT_KIND_CLOSURE => VirtualObjectDescriptorKind::Closure { sample: cell },+ OBJECT_KIND_CLOSURE => VirtualObjectDescriptorKind::Closure { sample_slot: cell },kind => unreachable!("{kind} is no kind of object"),}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rsindex 1b26ab630cf..24c7ca2e07d 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs@@ -26,6 +26,7 @@ use crate::code::Repr;use crate::ir::FrameField;use crate::ir::NodeId;use crate::ir::Op;+use crate::snapshot::ClosureTemplateSnapshot;use crate::snapshot::ObjectShapeCacheSnapshot;use crate::snapshot::ShapeSnapshot;@@ -179,10 +180,15 @@ impl GraphBuilder<'_, '_> {if has_home_object {return Ok(false);}- let Some((sample, inline_executable)) = self.snapshot[self.function.executable.closure_templates]+ let Some(&ClosureTemplateSnapshot {+ sample_slot,+ shape,+ shared_data,+ inline_executable,+ ..+ }) = self.snapshot[self.function.executable.closure_templates].get(shared_function_data_index as usize).and_then(Option::as_ref)- .map(|closure| (closure.sample, closure.inline_executable))else {return Ok(false);};@@ -191,7 +197,8 @@ impl GraphBuilder<'_, '_> {// they are not strict, arrow functions and methods included.let legacy_caller =inline_executable.is_some_and(|index| self.snapshot.executables[index as usize].is_non_strict_function());- self.embed(sample);+ self.embed(shape);+ self.embed(shared_data);let environment = self.frame_field(FrameField::LexicalEnvironment)?;// NB: Only inlined functions without a private environment have closure templates, but the frames of inlined// closures have the environments of the closure.@@ -205,7 +212,7 @@ impl GraphBuilder<'_, '_> {Op::AllocateFunction {executable: self.function.index,shared_function_data_index,- sample,+ sample_slot,legacy_caller,},&[environment, private_environment],diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 5a8a99e973a..0942c036dfa 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -1329,10 +1329,15 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {/// The `CellAddress` of the cell `value`, a constant for constants.fn cell_address(&mut self, value: NodeId) -> NodeId {match self.graph.constant_value(value) {- Some(bits) => self.typed_constant(- self.runtime.heap_region_base + (bits & self.runtime.heap_region_offset_mask),- Repr::Pointer,- ),+ Some(bits) => {+ let address = self.runtime.heap_region_base + (bits & self.runtime.heap_region_offset_mask);+ // NB: Only checks that always exit see constants that hold no cell.+ let pattern = self.runtime.shifted_is_cell_pattern;+ if bits & pattern == pattern {+ self.embed(CellId(address));+ }+ self.typed_constant(address, Repr::Pointer)+ }None => self.emit(Op::CellAddress, &[value], Some(Repr::Pointer)),}}diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex 5f931152456..29c70dd4780 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -381,10 +381,11 @@ pub enum VirtualObjectDescriptorKind {/// A plain object of `shape`, with the values of its properties in/// offset order.Object { shape: CellId },- /// A closure like `sample`, the sample of a closure template, with the- /// lexical and private environments at the two locations, which are- /// `Repr::Pointer`, the latter null for none.- Closure { sample: CellId },+ /// A closure like the sample of a closure template in `sample_slot` (see+ /// `ClosureTemplateSnapshot::sample_slot`), with the lexical and private+ /// environments at the two locations, which are `Repr::Pointer`, the+ /// latter null for none.+ Closure { sample_slot: CellId },}/// Set in the return pc (`ExecutionContext::caller_return_pc`) of the frame ofdiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rsindex af70f362e75..19fccce3c6a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs@@ -37,7 +37,7 @@ pub(super) enum AllocationCall {Object(CellId, u32),/// `ArrayAllocationInfo::slow_path` with the element count.Array(u32),- /// `FunctionAllocationInfo::slow_path` with the closure template and+ /// `FunctionAllocationInfo::slow_path` with the sample slot and/// the environments in the node's inputs.Function(CellId),/// `RuntimeInfo::create_lexical_environment` with the parent in the@@ -229,7 +229,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {self.masm.move_imm32(arguments[1], count);self.masm.call_absolute(self.runtime.array_allocation.slow_path);}- AllocationCall::Function(sample) => {+ AllocationCall::Function(sample_slot) => {// NB: The inputs may be in any argument register but// the first two.let scratch = self.pinned.scratch;@@ -237,7 +237,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {self.masm.move64(arguments[2], self.input(allocation.node, 0));self.masm.move64(arguments[3], scratch);self.masm.move64(arguments[0], self.pinned.vm);- self.masm.move_imm64(arguments[1], sample.0);+ self.masm.move_imm64(arguments[1], sample_slot.0);self.masm.call_absolute(self.runtime.function_allocation.slow_path);}AllocationCall::Environment(shape_cache, capacity) => {@@ -608,7 +608,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {.copied().flatten().ok_or(CompileFailure::CodeGeneration)?;- let (entry, resume) = self.defer_allocation(node, AllocationCall::Function(closure.sample));+ let (entry, resume) = self.defer_allocation(node, AllocationCall::Function(closure.sample_slot));// NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.let (function, temp) = (self.temp(node, 0), self.temp(node, 1));let objects = self.runtime.object_allocation;diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rsindex 15bffe50d32..4986941dd72 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs@@ -194,7 +194,7 @@ impl SiteSource<'_> {};let kind = match kind {VirtualObjectKind::Object { shape } => VirtualObjectDescriptorKind::Object { shape },- VirtualObjectKind::Closure { sample } => VirtualObjectDescriptorKind::Closure { sample },+ VirtualObjectKind::Closure { sample_slot } => VirtualObjectDescriptorKind::Closure { sample_slot },};let property_count = u32::try_from(graph.node(*object).inputs.len()).expect("inputs fit in u32");(kind, allocation.0, property_count)diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex ebfd93a3cda..efbdb264d01 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -333,9 +333,9 @@ fn write_op(f: &mut fmt::Formatter<'_>, layout: &FrameLayout, op: &Op, inputs: &..} => inputs.after(f, format_args!("VirtualObject {:#x}", shape.0)),Op::VirtualObject {- kind: VirtualObjectKind::Closure { sample },+ kind: VirtualObjectKind::Closure { sample_slot },..- } => inputs.after(f, format_args!("VirtualObject closure {:#x}", sample.0)),+ } => inputs.after(f, format_args!("VirtualObject closure {:#x}", sample_slot.0)),Op::AllocateEnvironment { shape_cache, capacity } => {inputs.after(f, format_args!("AllocateEnvironment {shape_cache} capacity {capacity}"))}diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 44719b2b4e6..40ebb4faeeb 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -427,11 +427,11 @@ pub enum VirtualObjectKind {/// A plain object of `shape`, whose properties are the inputs in offset/// order.Object { shape: CellId },- /// A closure like `sample`, the sample of the closure template the- /// `AllocateFunction` it stands for copies, with the lexical and private- /// environments in inputs 0 and 1: cell pointers, the latter null for- /// none.- Closure { sample: CellId },+ /// A closure like the sample in `sample_slot`, of the closure template+ /// the `AllocateFunction` it stands for copies, with the lexical and+ /// private environments in inputs 0 and 1: cell pointers, the latter null+ /// for none.+ Closure { sample_slot: CellId },}/// Defines `Op` and `Op::name()`, the name of each variant, so that names cannot drift from the variants. Everything@@ -827,14 +827,14 @@ define_ops! {/// an inlined one's), a copy of its closure template (see/// `FunctionAllocationInfo`) with the lexical environment (a cell/// pointer) in input 0 and the private environment in input 1. Like- /// `AllocateObject`, the node only allocates. `sample` is the sample- /// of the template. `legacy_caller` tells whether the frames of+ /// `AllocateObject`, the node only allocates. `sample_slot` holds the+ /// sample of the template. `legacy_caller` tells whether the frames of/// inlined calls of the closure show it as the legacy "caller" of the/// functions they call.AllocateFunction {executable: u32,shared_function_data_index: u32,- sample: CellId,+ sample_slot: CellId,legacy_caller: bool,},/// A new lexical environment of the compiled function's@@ -1632,6 +1632,7 @@ pub struct FrameState<'z> {pub struct Graph<'z> {/// Where the lists of the graph are, and where its nodes, blocks and frame states get their lists.pub zone: &'z Zone,+ /// Every node the graph ever had: passes remove nodes from blocks, never from here.pub nodes: ZoneVec<'z, Node<'z>>,/// Blocks in linear order. Block 0 is the entry, and every block comes/// after all its predecessors except those reaching it over a loop backdiff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 863e261ca73..76b4ac657bc 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -169,6 +169,42 @@ pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch, compiled: &mut Compil)}+/// The cells the code embeds, which keep their addresses for as long as it lives: those the graph lists, those of its+/// constants and of the values its checks compare against, and those of the constants of the compiled executable, which+/// the code writes into the frames it initializes. Values that hold cells end up in the code and in its tables as they+/// are, so the cells of all of them stay where they are.+fn embedded_cells<'w>(graph: &ir::Graph<'_>, snapshot: &Snapshot, work: &'w Zone) -> ak::ZoneVec<'w, snapshot::CellId> {+ let runtime = &snapshot.runtime;+ let pattern = runtime.shifted_is_cell_pattern;+ let values = graph.nodes.iter().filter_map(|node| match node.op {+ ir::Op::Constant(bits) if node.repr == Some(code::Repr::Tagged) => Some(bits),+ ir::Op::CheckValue { expected, .. } => Some(expected),+ _ => None,+ });+ let frame_constants = snapshot+ .executables+ .first()+ .map_or(&[][..], |executable| &snapshot[executable.constants]);+ let mut value_cells = ak::ZoneVec::from_iter_in(+ values+ .chain(frame_constants.iter().copied())+ .filter(|bits| bits & pattern == pattern)+ .map(|bits| runtime.heap_region_base + (bits & runtime.heap_region_offset_mask)),+ work,+ );+ value_cells.sort_unstable();+ value_cells.dedup();+ let mut listed = ak::ZoneVec::from_slice_in(&graph.embedded_cells, work);+ listed.sort_unstable();+ let mut cells = ak::ZoneVec::from_slice_in(&graph.embedded_cells, work);+ for cell in value_cells.into_iter().map(snapshot::CellId) {+ if listed.binary_search(&cell).is_err() {+ cells.push(cell);+ }+ }+ cells+}+/// With `StressOptions::few_registers`, how many registers values get/// besides the ones calls use.const STRESS_EXTRA_REGISTERS: u32 = 2;@@ -265,6 +301,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(work,)?;generated.osr_entries.sort_unstable();+ let embedded_cells = embedded_cells(&graph, snapshot, work);let layout = artifact.finish(&Tail {osr_entries: &generated.osr_entries,@@ -272,7 +309,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(osr_outer_loop_back_edges: &graph.osr_outer_loop_back_edges,uncaught_handlers: &graph.uncaught_handlers,invalidation_patches: &generated.invalidation_patches,- embedded_cells: &graph.embedded_cells,+ embedded_cells: &embedded_cells,dependencies: &graph.dependencies,},&mut compiled.words,diff --git a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rsindex af005dd3f11..920f1bf1efc 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs@@ -371,8 +371,8 @@ fn shapes_before_uses<'w>(shapes.insert(node, (shape, property_count));}// NB: A closure has one shape, and no properties that this pass knows.- Op::AllocateFunction { sample, .. } if candidates.contains(&node) => {- shapes.insert(node, (sample, 0));+ Op::AllocateFunction { sample_slot, .. } if candidates.contains(&node) => {+ shapes.insert(node, (sample_slot, 0));}Op::AddNamed {shape, property_count, ..@@ -630,8 +630,8 @@ fn replace_objects<'w>(graph: &mut Graph, analysis: &Analysis, work: &'w Zone) -shapes.insert(node, (shape, property_count));removed.insert(node.index());}- Op::AllocateFunction { sample, .. } if is_replaced(node) => {- shapes.insert(node, (sample, 0));+ Op::AllocateFunction { sample_slot, .. } if is_replaced(node) => {+ shapes.insert(node, (sample_slot, 0));removed.insert(node.index());}Op::AddNamed {@@ -751,7 +751,7 @@ fn virtualize_frame_state(}let (shape, _) = *shapes.get(&root).expect("replaced objects have shapes");let kind = if analysis.closures.contains(&root) {- VirtualObjectKind::Closure { sample: shape }+ VirtualObjectKind::Closure { sample_slot: shape }} else {VirtualObjectKind::Object { shape }};diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 4f9d6d778e9..3b66ca387ed 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -281,9 +281,14 @@ pub struct OrdinaryHasInstanceSnapshot {/// apart from their environments.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ClosureTemplateSnapshot {- /// The function object itself. Code that copies it embeds it, which- /// keeps everything it refers to alive.- pub sample: CellId,+ /// The address of the slot that holds the sample, a function object+ /// the closures are copies of, which is no cell: the code that copies+ /// the sample keeps the slot, and the sample may move.+ pub sample_slot: CellId,+ /// The cells the words refer to, the shape and the shared function+ /// data of the sample, which code that copies the words embeds.+ pub shape: CellId,+ pub shared_data: CellId,/// Its bytes (see `FunctionAllocationInfo`).pub words: List<u64>,/// The index in `Snapshot::executables` of the closures' executable, if@@ -1564,7 +1569,7 @@ pub struct ArrayAllocationInfo {/// `RuntimeOffsets::ecmascript_function_environment` and/// `ecmascript_function_private_environment`. If `allocator` is 0, there is/// no fast path. Slow path:-/// `ECMAScriptFunctionObject* libjs_jit_clone_function(VM*, ECMAScriptFunctionObject* sample, Environment*, PrivateEnvironment*)`.+/// `ECMAScriptFunctionObject* libjs_jit_clone_function(VM*, Value const* sample_slot, Environment*, PrivateEnvironment*)`.#[derive(Debug, Clone, Copy, Default)]pub struct FunctionAllocationInfo {pub allocator: u64,diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex 138a304711f..332b043c036 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -1173,7 +1173,8 @@ unsafe impl Trace for ObjectPropertyIteratorCacheData {fn trace(&self, visitor: &mut Visitor) {self.shape.trace(visitor);self.prototype_chain_validity.trace(visitor);- self.property_values.trace(visitor);+ // SAFETY: The values are written once, when the cell is made, and only its finalizer frees them.+ unsafe { self.property_values.trace_owned(visitor) };self.storage.trace(visitor);}}@@ -2370,7 +2371,12 @@ fn parse_big_int_literal(literal: &str) -> SignedBigInteger {// alive.unsafe impl Trace for ExecutableHead {fn trace(&self, visitor: &mut Visitor) {- visitor.visit_values(&self.constants);+ // NB: The constants are visited as owned values, so that a collection that moves their cells rewrites them where+ // they are. They are in the tables of the executable, which nothing writes once it is built, and only its+ // destructor frees. JIT code that embeds a constant lists its cell among the cells it embeds, which keeps+ // the cell where it is while the code lives.+ // SAFETY: See above.+ unsafe { visitor.visit_owned_values(&self.constants) };}}diff --git a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rsindex b0b8ec5fc32..7c952d45a2d 100644--- a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs+++ b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs@@ -15,6 +15,7 @@ use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};use super::visitor::{Trace, Visitor};use crate::layout::buffer::{BlockSlice, InterpreterBuffer, ThinSlice};+use crate::layout::value::Value;use crate::slice_block::THIN_SLICE_HEADER_SIZE;/// Mirrors AK::Vector's growth policy.@@ -144,6 +145,21 @@ impl<T: Copy> Default for InterpreterBuffer<T> {}}+impl InterpreterBuffer<Value> {+ /// Visits the values as owned values (see Visitor::visit_owned_values()).+ ///+ /// # Safety+ ///+ /// As for Visitor::visit_owned_values(): nothing may change or free the buffer until the collection is over.+ pub unsafe fn trace_owned(&self, visitor: &mut Visitor) {+ if self.is_empty() {+ return;+ }+ // SAFETY: The first `size` elements are initialized, and the caller vouches for the memory.+ unsafe { visitor.visit_owned_values(ak::slice_from_raw_parts(self.data.get(), self.size())) };+ }+}+// SAFETY: Visits every element.unsafe impl<T: Copy + Trace> Trace for InterpreterBuffer<T> {fn trace(&self, visitor: &mut Visitor) {diff --git a/Libraries/LibJS/Rust/src/gc/sweep.rs b/Libraries/LibJS/Rust/src/gc/sweep.rsindex 621d2e7bdda..f3c393a0cf1 100644--- a/Libraries/LibJS/Rust/src/gc/sweep.rs+++ b/Libraries/LibJS/Rust/src/gc/sweep.rs@@ -45,7 +45,10 @@ impl<'vm> Sweep<'vm> {/// Whether the collection may move cells, which is when what holds cells without visiting their slots hands over/// the slots of those that survived (see record_slot()).pub fn moves_cells(&self) -> bool {- capi::gc_heap_is_moving_cells(self.0.heap().handle())+ // NB: The VM lets go of its heap before the collection that destroys the heap, which moves nothing.+ self.0+ .heap_if_held()+ .is_some_and(|heap| capi::gc_heap_is_moving_cells(heap.handle()))}/// Has the collection rewrite `slot`, which holds a cell that survived it, if the cell moves, as it rewrites the slotsdiff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 43cb0dcd6a6..80d235ee212 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -934,6 +934,11 @@ impl Vm {self.heap.get().expect("the VM has a heap")}+ /// The heap, unless the VM let go of it, as it does while the heap is destroyed.+ pub(crate) fn heap_if_held(&self) -> Option<&Heap> {+ self.heap.get()+ }+pub fn interpreter_stack(&self) -> &InterpreterStack {&self.head.interpreter_stack}@@ -1619,7 +1624,7 @@ impl Vm {/// Drops the weak cache entries of strings that died in this collection, and every entry of the caches that each/// collection empties.fn remove_dead_strings_from_weak_caches(&self, sweep: &Sweep<'_>) {- // NB: The caches forget strings that move. The interned strings do not move.+ // NB: The caches forget strings that move.let is_dead = |string: Gc<PrimitiveString>| sweep.is_dead_or_moving(string);for cache_slot in self.fly_string_cache.iter() {if cache_slot.get().is_some_and(is_dead) {@@ -1631,9 +1636,17 @@ impl Vm {*entry = StringToAtomCacheEntry::default();}}- self.interned_strings- .borrow_mut()- .retain(|_, string| !sweep.is_dead(*string));+ let mut interned_strings = self.interned_strings.borrow_mut();+ interned_strings.retain(|_, string| !sweep.is_dead(*string));+ if sweep.moves_cells() {+ // NB: The table is keyed by the identity of the fly strings, which moves of the strings do not change.+ for string in interned_strings.values() {+ // SAFETY: Only creating an interned string changes the table, which nothing does until the collection+ // is over.+ unsafe { sweep.record_slot(string) };+ }+ }+ drop(interned_strings);self.characters_to_atom_cache.borrow_mut().fill_with(CharactersToAtomCacheEntry::default);diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rsindex d735ea12ff1..427f36e0d94 100644--- a/Libraries/LibJS/Rust/src/jit/allocation.rs+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs@@ -592,19 +592,36 @@ fn closure_template(Some((sample, words))}-/// The closure templates as the snapshot carries them, with their samples as cells the code embeds.+/// The slots that hold the samples of the closure templates of JIT code, each in a box of its own, so that its address+/// stays the same. The code passes the address of a slot to `libjs_jit_clone_function()` and keeps it in the+/// descriptions of the closures it never allocated, rather than embedding the sample, so that the sample can move: the+/// code keeps the slots, and visits them as owned values (see Visitor::visit_owned_values()).+pub type SampleSlots = Vec<Box<Value>>;++/// The closure templates as the snapshot carries them, with the samples in slots added to `sample_slots`. `cell` notes+/// a cell the snapshot refers to: the samples, until the code is installed, and the cells the words refer to, which+/// the code embeds.pub fn closure_template_snapshots(templates: ClosureTemplates,- mut cell: impl FnMut(Gc<EcmascriptFunctionObject>) -> CellId,+ mut cell: impl FnMut(Gc<CellHeader>) -> CellId,+ sample_slots: &mut SampleSlots,_defer_gc: &DeferGc<'_>,snapshot: &mut SnapshotWriter,) -> List<Option<ClosureTemplateSnapshot>> {let rows = snapshot.begin();for template in templates {- snapshot.push(template.map(|(sample, words)| ClosureTemplateSnapshot {- sample: cell(sample),- words,- inline_executable: None,+ snapshot.push(template.map(|(sample, words)| {+ cell(sample.upcast());+ let slot = Box::new(Value::from_object(sample.upcast::<Object>()));+ let sample_slot = CellId(core::ptr::from_ref::<Value>(&slot).expose_provenance() as u64);+ sample_slots.push(slot);+ ClosureTemplateSnapshot {+ sample_slot,+ shape: cell(sample.shape().upcast()),+ shared_data: cell(sample.shared_data().upcast()),+ words,+ inline_executable: None,+ }}));}snapshot.end(rows)@@ -645,18 +662,27 @@ pub extern "C" fn libjs_jit_allocate_array(vm: &Vm, count: u32) -> *mut Array {array.as_ptr()}-/// `ECMAScriptFunctionObject* libjs_jit_clone_function(VM*, ECMAScriptFunctionObject* sample, Environment*,+/// `ECMAScriptFunctionObject* libjs_jit_clone_function(VM*, Value const* sample_slot, Environment*,/// PrivateEnvironment*)`: a closure like the sample of a closure template, with the given environments.///-/// JIT code calls this with its VM, a sample it embeds and live environments (or null private environment).+/// JIT code calls this with its VM, a slot that holds a sample, which the code keeps (see `SampleSlots`), and live+/// environments (or null private environment).#[jit_abi]pub extern "C" fn libjs_jit_clone_function(vm: &Vm,- sample: Gc<EcmascriptFunctionObject>,+ sample_slot: &Value,environment: Option<Gc<Environment>>,private_environment: Option<Gc<PrivateEnvironment>>,) -> *mut EcmascriptFunctionObject {- clone_function(vm, sample, environment, private_environment).as_ptr()+ clone_function(vm, sample_in(sample_slot), environment, private_environment).as_ptr()+}++/// The sample a slot of `SampleSlots` holds.+pub fn sample_in(sample_slot: &Value) -> Gc<EcmascriptFunctionObject> {+ sample_slot+ .as_cell()+ .downcast::<EcmascriptFunctionObject>()+ .expect("a sample slot holds an ECMAScript function")}/// A closure like the sample of a closure template, with the given environments.diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex f11d1ee71cb..82358bfdf16 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -18,6 +18,7 @@ use libjs_jit::code::ExitKind;pub use libjs_jit::code::INLINED_CALL_SITE_BIT;use libjs_runtime_macros::Trace;+use super::allocation::SampleSlots;use super::data_memory::DataMemory;use super::entry_table::{JIT_ENTRY_SLOT_MASK, JitEntryTable, NO_JIT_ENTRY_SLOT};use super::executable_memory::ExecutableMemory;@@ -186,6 +187,9 @@ pub struct JitCode {/// keep their addresses for as long as the code may run.embedded_cells: Vec<Gc<CellHeader>>,snapshot_executables: Vec<SnapshotExecutable>,+ /// The slots of the samples the code copies closures of, whose addresses the code holds rather than those of the+ /// samples. A collection rewrites them where they are when a sample moves.+ sample_slots: SampleSlots,/// Identifies the code among all code the VM installed, for the dependencies it registers (see/// `super::dependencies`).id: u64,@@ -240,6 +244,7 @@ impl JitCode {layout,embedded_cells,snapshot_executables,+ sample_slots: Vec::new(),id: 0,invalidated: Cell::new(false),site_index_frame_offset: 0,@@ -307,6 +312,11 @@ impl JitCode {self.id = id;}+ /// Gives the code the slots of the samples it copies closures of.+ pub fn set_sample_slots(&mut self, sample_slots: SampleSlots, _defer_gc: &DeferGc<'_>) {+ self.sample_slots = sample_slots;+ }+/// Whether the handler whose `Catch` is at `pc` has no catch entry only because it never caught an exception/// before the compile, so that a compile now would give it one.pub fn compiled_before_handler_caught(&self, pc: u32) -> bool {@@ -434,6 +444,10 @@ unsafe impl Trace for JitCode {visitor.visit(materialized.object);}self.snapshot_executables.trace(visitor);+ for slot in &self.sample_slots {+ // SAFETY: Nothing writes the slots, and only dropping the code, which no sweep callback does, frees them.+ unsafe { visitor.visit_owned_values(core::slice::from_ref(&**slot)) };+ }}}diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex d2a2004cd85..31c6afbf0d8 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -121,6 +121,8 @@ pub struct CompileJob {pub executable: Gc<Executable>,pub cells: Vec<Gc<CellHeader>>,pub snapshot_executables: Vec<SnapshotExecutable>,+ #[gc(untraced = "the cells keep the samples alive and in place until the code is installed")]+ pub sample_slots: allocation::SampleSlots,}/// With the "stress-install" option, finished compile jobs wait for at most this many tier-up checks.diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 9e65abf1e4f..7be0838d635 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -27,7 +27,7 @@ use libjs_jit::snapshot::{};use super::allocation::{- allocation_infos, closure_template_snapshots, closure_templates, function_environment_template,+ SampleSlots, allocation_infos, closure_template_snapshots, closure_templates, function_environment_template,lexical_environment_templates,};use super::code::{CapturedBindingAccesses, InlinedFunction, SnapshotExecutable, speculated_cache_size};@@ -87,6 +87,8 @@ pub struct CapturedSnapshot<'d> {pub snapshot: Box<Snapshot>,pub cells: Deferred<'d, Vec<Gc<CellHeader>>>,pub snapshot_executables: Deferred<'d, Vec<SnapshotExecutable>>,+ /// The slots of the samples of the closure templates, whose samples are among the cells.+ pub sample_slots: Deferred<'d, SampleSlots>,}/// An executable of the snapshot.@@ -116,6 +118,7 @@ struct SnapshotBuilder<'vm> {/// The samples of the closure templates of inlined functions, by executable and template index, until the/// inlining candidates they are get their indices.closure_samples: Vec<(u32, usize, Gc<EcmascriptFunctionObject>)>,+ sample_slots: SampleSlots,/// The lexical environment templates of the compiled executable.lexical_environment_templates: List<Option<LexicalEnvironmentTemplateSnapshot>>,/// The environment templates of the direct calls of the executable whose snapshot is being made.@@ -411,11 +414,35 @@ fn note_cell<T: Extends<CellHeader>>(cells: &mut Vec<Gc<CellHeader>>, cell: Gc<TCellId(cell.as_ptr() as u64)}+/// Adds the environments of `function`, whose addresses its FunctionFrameFields hold, to `cells`.+fn note_frame_field_cells(cells: &mut Vec<Gc<CellHeader>>, function: Gc<EcmascriptFunctionObject>) {+ if let Some(environment) = function.environment() {+ note_cell(cells, environment);+ }+ if let Some(environment) = function.private_environment() {+ note_cell(cells, environment);+ }+}+impl SnapshotBuilder<'_> {fn cell<T: Extends<CellHeader>>(&mut self, cell: Gc<T>) -> CellId {note_cell(&mut self.cells, cell)}+ /// The bits of `value`, whose cell, if it has one, is added to the cells the snapshot refers to.+ fn value_bits(&mut self, value: Value) -> u64 {+ if value.is_cell() {+ note_cell(&mut self.cells, value.as_cell());+ }+ value.0+ }++ /// function_frame_fields() of `function`, whose environments are added to the cells the snapshot refers to.+ fn frame_fields(&mut self, function: Gc<EcmascriptFunctionObject>) -> FunctionFrameFields {+ note_frame_field_cells(&mut self.cells, function);+ function_frame_fields(function)+ }+/// Adds `rows` to the snapshot as a list.fn list<T: Row>(&mut self, rows: impl IntoIterator<Item = T>) -> List<T> {let list = self.snapshot.begin();@@ -860,12 +887,15 @@ impl SnapshotBuilder<'_> {&& snapshot.inline_executable.is_some(){// NB: The bound function, which the code checks the callee against and so embeds, keeps its bound values- // alive.+ // alive. The snapshot notes their cells, which keeps them in place until the code is installed.let bound_arguments = bound.bound_arguments();- snapshot.bound_this = bound.bound_this().0;+ snapshot.bound_this = self.value_bits(bound.bound_this());snapshot.bound_arguments_start = u32::try_from(self.bound_arguments.len()).ok()?;snapshot.bound_argument_count = u32::try_from(bound_arguments.len()).ok()?;- self.bound_arguments.extend(bound_arguments.iter().map(|value| value.0));+ for &value in bound_arguments {+ let bits = self.value_bits(value);+ self.bound_arguments.push(bits);+ }}Some(snapshot)}@@ -1114,7 +1144,7 @@ impl SnapshotBuilder<'_> {entry,registers_and_locals_count: executable.registers_and_locals_count(),registers_and_locals_and_constants_count: executable.head.registers_and_locals_and_constants_count.get(),- function_fields: function_frame_fields(function),+ function_fields: self.frame_fields(function),environment,closures,}@@ -1227,7 +1257,8 @@ impl SnapshotBuilder<'_> {let cells = &mut self.cells;closure_template_snapshots(templates.into_inner(),- |sample| note_cell(cells, sample),+ |cell| note_cell(cells, cell),+ &mut self.sample_slots,defer_gc,&mut self.snapshot,)@@ -1308,7 +1339,12 @@ impl SnapshotBuilder<'_> {.expect("the constant count fits in u32"),number_of_arguments: executable.number_of_arguments(),},- constants: self.list(executable.constants().iter().map(|constant| constant.0)),+ constants: {+ for &constant in executable.constants() {+ self.value_bits(constant);+ }+ self.list(executable.constants().iter().map(|constant| constant.0))+ },exception_handlers: self.list(executable.exception_handlers().iter().map(|handler| ExceptionHandler {start_offset: handler.start_offset,end_offset: handler.end_offset,@@ -1333,7 +1369,7 @@ impl SnapshotBuilder<'_> {InlinedFunction::Builtin(function) => self.inlined_builtin(function),}),function_fields: match entry.function {- Some(InlinedFunction::Ecmascript(function)) => Some(function_frame_fields(function)),+ Some(InlinedFunction::Ecmascript(function)) => Some(self.frame_fields(function)),// NB: The compiled function's script tells which inlined calls// run in it.None => Some(self.compiled_function_fields),@@ -1597,6 +1633,7 @@ pub fn capture_snapshot<'d>(compiled_function_fields,closure_templates: List::empty(),closure_samples: Vec::new(),+ sample_slots: Vec::new(),environment_templates: Vec::new(),bound_arguments: Vec::new(),lexical_environment_templates: List::empty(),@@ -1605,10 +1642,14 @@ pub fn capture_snapshot<'d>(literal_instance_fields: HashMap::new(),derived_instance_fields: HashMap::new(),};+ if let Some(function) = function {+ note_frame_field_cells(&mut builder.cells, function);+ }let cells = &mut builder.cells;builder.closure_templates = closure_template_snapshots(closure_templates.into_inner(),- |sample| note_cell(cells, sample),+ |cell| note_cell(cells, cell),+ &mut builder.sample_slots,defer_gc,&mut builder.snapshot,);@@ -1676,6 +1717,7 @@ pub fn capture_snapshot<'d>(snapshot,cells,entries,+ sample_slots,..} = builder;super::compile_queue::give_back_open_lists(snapshot.finish());@@ -1707,6 +1749,7 @@ pub fn capture_snapshot<'d>(CapturedSnapshot {snapshot,cells: defer_gc.cover(cells),+ sample_slots: defer_gc.cover(sample_slots),snapshot_executables: defer_gc.cover(entries.iter()diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex f8f586811a1..d0cb78f9940 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -9,6 +9,7 @@use core::ops::ControlFlow;use core::ptr::NonNull;+use super::allocation::SampleSlots;use super::code::{CompileState, FRUITLESS_LOOP_CHECKS_AFTER_INSTALL, JitCode, SnapshotExecutable};use super::compile_queue::{CompileResult, Compiled};use super::data_memory::DataMemory;@@ -354,6 +355,7 @@ fn install(compiled: Compiled,memory: ExecutableMemory,snapshot: SnapshotExecutables,+ sample_slots: SampleSlots,defer_gc: &DeferGc<'_>,) {let artifact = compiled.artifact();@@ -388,6 +390,7 @@ fn install(snapshot,defer_gc,);+ code.set_sample_slots(sample_slots, defer_gc);code.set_id(id);code.set_frame_offsets(compiled.site_index_frame_offset, compiled.register_dump_frame_offset);let dependencies = artifact.dependencies().collect::<Vec<_>>();@@ -416,6 +419,7 @@ fn finish_compile(result: CompileResult,memory: Option<ExecutableMemory>,snapshot_executables: SnapshotExecutables,+ sample_slots: SampleSlots,defer_gc: &DeferGc<'_>,) {assert_eq!(executable.jit_compile_state(), CompileState::Queued);@@ -446,7 +450,15 @@ fn finish_compile(eprintln!("JIT code for {}:\n{dump}", super::describe_executable(&executable));}if let Some(memory) = memory {- install(vm, executable, compiled, memory, snapshot_executables, defer_gc);+ install(+ vm,+ executable,+ compiled,+ memory,+ snapshot_executables,+ sample_slots,+ defer_gc,+ );}if executable.jit_compile_state() != CompileState::Installed {executable.set_jit_compile_state(CompileState::None);@@ -486,6 +498,7 @@ fn compile(snapshot,cells,snapshot_executables,+ sample_slots,} = capture_snapshot(vm, executable, function, realm, osr_pc, &defer_gc);if sync {// NB: Nothing collects garbage while compiling on this thread, so the snapshot's cells stay alive.@@ -509,6 +522,7 @@ fn compile(result,memory,snapshot_executables.into_inner(),+ sample_slots.into_inner(),&defer_gc,);drop(defer_gc);@@ -520,6 +534,7 @@ fn compile(executable,cells: cells.into_inner(),snapshot_executables: snapshot_executables.into_inner(),+ sample_slots: sample_slots.into_inner(),},&defer_gc,);@@ -617,6 +632,14 @@ fn install_compile_results(vm: &Vm, results: Vec<(u64, CompileResult)>, defer_gcfor ((job, result), install) in finished.into_iter().zip(verdicts) {let memory = install.then(|| memories.next().expect("there is memory for each installed code"));- finish_compile(vm, job.executable, result, memory, job.snapshot_executables, defer_gc);+ finish_compile(+ vm,+ job.executable,+ result,+ memory,+ job.snapshot_executables,+ job.sample_slots,+ defer_gc,+ );}}diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex c15d69c5114..8223b22a5d9 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -27,7 +27,7 @@ use libjs_abi::register;use libjs_jit::code::{CALLEE_SLOT, Repr, ResumeMode, SiteKind, ValueLocation, VirtualObjectDescriptorKind};use libjs_runtime_macros::Trace;-use super::allocation::clone_function;+use super::allocation::{clone_function, sample_in};use super::code::{CompileState, EXIT_COUNT_BEFORE_DISCARD, FRUITLESS_LOOP_CHECKS_AFTER_EXIT, FrameState, InlinedFunction, JitCode,Site,@@ -222,12 +222,12 @@ impl<'a> SiteValues<'a> {}let shape = match description.kind() {VirtualObjectDescriptorKind::Object { shape } => shape,- VirtualObjectDescriptorKind::Closure { sample } => {- // SAFETY: The code embeds the sample, which keeps it alive.- let sample = unsafe { Gc::from_non_null(NonNull::new(sample.0 as *mut _).expect("a sample")) };+ VirtualObjectDescriptorKind::Closure { sample_slot } => {+ // SAFETY: The code keeps the slots of its samples (see `SampleSlots`).+ let sample_slot = unsafe { &*core::ptr::with_exposed_provenance::<Value>(sample_slot.0 as usize) };let closure = clone_function(self.vm,- sample,+ sample_in(sample_slot),read_cell_address(description.property(0).expect("a closure has environments"), self.dump),read_cell_address(description.property(1).expect("a closure has environments"), self.dump),)diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rsindex 397d44c1456..0654cd5fad9 100644--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs@@ -45,13 +45,7 @@ impl ExternalMemorySize for PrimitiveString {// SAFETY: A string's own data holds no cells. The deferred kinds trace the strings they are made of.unsafe impl Trace for PrimitiveString {- fn trace(&self, visitor: &mut Visitor) {- // NB: The VM's table of interned strings holds them weakly, and there may only be one interned string with the- // same contents, so an interned string stays where it is rather than being forgotten.- if self.is_interned() {- visitor.pin(Gc::from_ref(self));- }- }+ fn trace(&self, _: &mut Visitor) {}}#[repr(C)]diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rsindex e57afeca4c4..ba6d9c113c5 100644--- a/Libraries/LibJS/Rust/src/runtime/shape.rs+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs@@ -291,7 +291,8 @@ unsafe impl Trace for ShapeStorage {// SAFETY: Visits the keys.unsafe impl Trace for OwnStringKeys {fn trace(&self, visitor: &mut Visitor) {- visitor.visit_values(&self.keys);+ // SAFETY: The keys are the shape's own, which only with_own_string_keys() replaces, and nothing writes them.+ unsafe { visitor.visit_owned_values(&self.keys) };}}diff --git a/Tests/LibJS/Runtime/gc-moving-cells.js b/Tests/LibJS/Runtime/gc-moving-cells.jsindex 906c1afdc28..712fe917153 100644--- a/Tests/LibJS/Runtime/gc-moving-cells.js+++ b/Tests/LibJS/Runtime/gc-moving-cells.js@@ -95,6 +95,40 @@ const weakBefore = {registryTarget: addressOf(weakHolder.registryTarget),};+// Constants of executables are slots the collector can rewrite. Strings this long are not interned.+const constantString = () =>+ "a constant string that is long enough not to be interned, which only this function holds ..............................................................................................................................................................................................................................";+const constantBigInt = () => 123456789012345678901234567890n;+const internedConstant = () => "an interned constant";+// NB: JIT code that embeds a constant keeps its cell where it is.+jit.neverCompile(constantString);+jit.neverCompile(constantBigInt);+jit.neverCompile(internedConstant);+const constantsBefore = {+ string: addressOf(constantString()),+ bigint: addressOf(constantBigInt()),+ interned: addressOf(internedConstant()),+};++// The key strings of for-in caches and of the own keys of shapes are slots the collector can rewrite.+const keyed = { firstKey: 1, secondKey: 2 };+const forInKeys = object => {+ const keys = [];+ for (const key in object) keys.push(key);+ return keys;+};+forInKeys(keyed);+Object.keys(keyed);++// JIT code that creates closures copies a sample, which the code keeps in a slot the collector can rewrite, so the+// sample can move.+function makeAdder(n) {+ return x => x + n;+}+jit.prepare(makeAdder);+for (let i = 0; i < 10; ++i) makeAdder(i)(i);+jit.compile(makeAdder);+runAfterMovingCollection(() => {test("objects with inline storage keep their properties when they move", () => {expect(addressOf(holder.small)).not.toBe(before.small);@@ -198,6 +232,31 @@ runAfterMovingCollection(() => {expect(addressOf(weakHolder.registryTarget)).not.toBe(weakBefore.registryTarget);expect(registry.unregister(weakHolder.registryToken)).toBeTrue();});++ test("constants of executables move", () => {+ expect(addressOf(constantString())).not.toBe(constantsBefore.string);+ expect(constantString().startsWith("a constant string")).toBeTrue();+ expect(constantString().length).toBeGreaterThan(256);+ expect(addressOf(constantBigInt())).not.toBe(constantsBefore.bigint);+ expect(constantBigInt()).toBe(123456789012345678901234567890n);+ });++ test("interned strings move, and stay the interned strings of their contents", () => {+ expect(addressOf(internedConstant())).not.toBe(constantsBefore.interned);+ expect(internedConstant()).toBe("an interned constant");+ const object = { "an interned constant": 1 };+ expect(object[internedConstant()]).toBe(1);+ });++ test("cached key strings keep their contents when they move", () => {+ expect(forInKeys(keyed)).toEqual(["firstKey", "secondKey"]);+ expect(Object.keys(keyed)).toEqual(["firstKey", "secondKey"]);+ });++ test("compiled code creates closures after their sample moved", () => {+ const adders = Array.from({ length: 10 }, (_, i) => makeAdder(i));+ expect(adders.map((adder, i) => adder(i))).toEqual(Array.from({ length: 10 }, (_, i) => 2 * i));+ });});runAfterMovingCollection(() => {