Truly independent web browser
LibJS/JIT: Keep the data of the code generator in the work zone
Andreas Klingf357f1f659e3
diff --git a/Cargo.lock b/Cargo.lockindex af333c4d5e2..2e8f541706b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2059,6 +2059,7 @@ dependencies = [name = "libwasm_jit"version = "0.1.0"dependencies = [+ "ak","fARM64","iced-x86","libc",diff --git a/Libraries/LibJS/JIT/Rust/clippy.toml b/Libraries/LibJS/JIT/Rust/clippy.tomlindex fab2aed368a..6af6d1e76b2 100644--- a/Libraries/LibJS/JIT/Rust/clippy.toml+++ b/Libraries/LibJS/JIT/Rust/clippy.toml@@ -72,9 +72,6 @@ disallowed-types = [{ path = "std::boxed::Box", reason = "the compiler makes no block in the heap: use Zone::alloc" },{ path = "std::rc::Rc", reason = "the compiler makes no block in the heap: share a reference into a zone" },{ path = "std::sync::Arc", reason = "the compiler makes no block in the heap: share a reference into a zone" },- { path = "libjs_jit::inline_vec::InlineVec", reason = "the compiler makes no block in the heap: use ak::ZoneVec" },- { path = "libjs_jit::fast_hash::HashMap", reason = "the compiler makes no block in the heap: use ak::ZoneMap" },- { path = "libjs_jit::fast_hash::HashSet", reason = "the compiler makes no block in the heap: use ak::ZoneSet" },]disallowed-macros = [{ path = "std::vec", reason = "the compiler makes no block in the heap: use a slice, or ak::ZoneVec" },diff --git a/Libraries/LibJS/JIT/Rust/src/artifact.rs b/Libraries/LibJS/JIT/Rust/src/artifact.rsindex 5555b7cfea2..09c0aae5777 100644--- a/Libraries/LibJS/JIT/Rust/src/artifact.rs+++ b/Libraries/LibJS/JIT/Rust/src/artifact.rs@@ -21,12 +21,14 @@//! runs of words in those tables are stored one time (see `Shared`).use core::cell::Cell;-use core::ffi::CStr;use core::ops::Range;use ak::Column;+use ak::Zone;+use ak::ZoneVec;use crate::CompileFailure;+use crate::asm::JumpPatch;use crate::code::CALLEE_SLOT;use crate::code::Dependency;use crate::code::ExitKind;@@ -247,46 +249,86 @@ pub struct Tail<'a> {pub osr_outer_loop_back_edges: &'a [u32],pub uncaught_handlers: &'a [u32],/// See `Artifact::invalidation_patches()`.- pub invalidation_patches: &'a [(u32, Vec<u8>)],+ pub invalidation_patches: &'a [(u32, JumpPatch)],pub embedded_cells: &'a [CellId],pub dependencies: &'a [Dependency],}-/// Writes the tables of compiled code. The memory it takes for one compile serves the next.-pub struct ArtifactWriter {- sites: Column<u32>,- frames: Column<u32>,- calls: Shared<256>,- slots: Shared<1024>,- in_frame: Shared<256>,- objects: Column<u32>,- locations: Shared<1024>,- wide: Shared<256>,+/// Writes the tables of compiled code, in the work zone of a compile.+pub struct ArtifactWriter<'a> {+ sites: Table<'a>,+ frames: Table<'a>,+ calls: Shared<'a, 256>,+ slots: Shared<'a, 1024>,+ in_frame: Shared<'a, 256>,+ objects: Table<'a>,+ locations: Shared<'a, 1024>,+ wide: Shared<'a, 256>,+}++/// A table of the writer, which holds up to `limit` words. A compile that needs more fails.+struct Table<'a> {+ words: ZoneVec<'a, u32>,+ limit: usize,+}++impl<'a> Table<'a> {+ fn new_in(limit: usize, work: &'a Zone) -> Self {+ Self {+ words: ZoneVec::new_in(work),+ limit,+ }+ }++ fn try_push(&mut self, word: u32) -> Result<(), CompileFailure> {+ self.try_extend_from_slice(&[word])+ }++ fn try_extend_from_slice(&mut self, words: &[u32]) -> Result<(), CompileFailure> {+ if words.len() > self.limit - self.words.len() {+ return Err(CompileFailure::TooLarge);+ }+ self.words.extend_from_slice(words);+ Ok(())+ }++ fn truncate(&mut self, len: usize) {+ self.words.truncate(len);+ }+}++impl core::ops::Deref for Table<'_> {+ type Target = [u32];++ fn deref(&self) -> &[u32] {+ &self.words+ }+}++impl core::ops::DerefMut for Table<'_> {+ fn deref_mut(&mut self) -> &mut [u32] {+ &mut self.words+ }}/// A table in which a run of words that is equal to one from before takes no room of its own.-struct Shared<const INDEX_SIZE: usize> {- words: Column<u32>,+struct Shared<'a, const INDEX_SIZE: usize> {+ words: Table<'a>,/// Where runs are: for the run added last with each hash, its start plus one, or zero for none. The index finds/// nearly all of the repeats and never grows: a run that another one pushed out of its place is stored one more/// time if it comes again.index: [u32; INDEX_SIZE],}-impl<const INDEX_SIZE: usize> Shared<INDEX_SIZE> {- fn new(limit: usize, name: &'static CStr) -> Self {+impl<'a, const INDEX_SIZE: usize> Shared<'a, INDEX_SIZE> {+ fn new_in(limit: usize, work: &'a Zone) -> Self {const { assert!(INDEX_SIZE.is_power_of_two() && INDEX_SIZE > 1) };Self {- words: Column::new(limit, name),+ words: Table::new_in(limit, work),index: [0; INDEX_SIZE],}}- fn clear(&mut self) {- self.words.clear();- self.index.fill(0);- }-/// Where the run that starts at `start` and ends where the words end now is from now on: at an equal run from/// before if one is known, in place of which this run goes away.fn share(&mut self, start: usize) -> u32 {@@ -312,13 +354,7 @@ impl<const INDEX_SIZE: usize> Shared<INDEX_SIZE> {/// The most words the tables of one compile can have (see `ArtifactWriter::finish()`).pub const MAX_WORDS: usize = 1 << 25;-impl Default for ArtifactWriter {- fn default() -> Self {- Self::new()- }-}--impl ArtifactWriter {+impl<'a> ArtifactWriter<'a> {// NB: These are how much of each the tables of one compile can have. They are far above what the code of real// functions needs, and a compile that needs more fails.const MAX_SITES: usize = 1 << 20;@@ -329,46 +365,22 @@ impl ArtifactWriter {const MAX_WIDE_VALUES: usize = 1 << 20;const MAX_CALL_WORDS: usize = Self::MAX_FRAMES * CALL_WORDS_WITH_OBJECTS;- pub fn new() -> Self {+ /// A writer with no tables yet, which keeps them in `work`.+ pub fn new_in(work: &'a Zone) -> Self {// NB: So where a call record starts fits in a link.const { assert!(ArtifactWriter::MAX_CALL_WORDS < NO_CALL as usize) };Self {- sites: Column::new(Self::MAX_SITES * SITE_WORDS, c"JIT sites"),- frames: Column::new(Self::MAX_FRAMES * FRAME_WORDS, c"JIT frames"),- calls: Shared::new(Self::MAX_CALL_WORDS, c"JIT frame calls"),- slots: Shared::new(Self::MAX_SLOTS, c"JIT frame slots"),- in_frame: Shared::new(Self::MAX_SLOTS, c"JIT slots in frame"),- objects: Column::new(Self::MAX_OBJECTS * OBJECT_WORDS, c"JIT objects"),- locations: Shared::new(Self::MAX_LOCATIONS, c"JIT locations"),- wide: Shared::new(Self::MAX_WIDE_VALUES * WIDE_WORDS, c"JIT wide values"),+ sites: Table::new_in(Self::MAX_SITES * SITE_WORDS, work),+ frames: Table::new_in(Self::MAX_FRAMES * FRAME_WORDS, work),+ calls: Shared::new_in(Self::MAX_CALL_WORDS, work),+ slots: Shared::new_in(Self::MAX_SLOTS, work),+ in_frame: Shared::new_in(Self::MAX_SLOTS, work),+ objects: Table::new_in(Self::MAX_OBJECTS * OBJECT_WORDS, work),+ locations: Shared::new_in(Self::MAX_LOCATIONS, work),+ wide: Shared::new_in(Self::MAX_WIDE_VALUES * WIDE_WORDS, work),}}- /// Starts the tables of another compile.- pub fn clear(&mut self) {- self.sites.clear();- self.frames.clear();- self.calls.clear();- self.slots.clear();- self.in_frame.clear();- self.objects.clear();- self.locations.clear();- self.wide.clear();- }-- /// Gives the memory of the writer back to the system. It takes memory again when it writes.- pub fn release_memory(&mut self) {- self.clear();- self.sites.trim(0);- self.frames.trim(0);- self.calls.words.trim(0);- self.slots.words.trim(0);- self.in_frame.words.trim(0);- self.objects.trim(0);- self.locations.words.trim(0);- self.wide.words.trim(0);- }-/// Adds a frame with values in `slots` and with `in_frame` (see `FrameView::in_frame()`), both in any order./// Returns its record.pub fn add_frame(@@ -531,7 +543,7 @@ impl ArtifactWriter {/// Adds the word of a location (see `location()`) to the run of the site that is added next.pub fn add_location(&mut self, word: u32) -> Result<(), CompileFailure> {- Ok(self.locations.words.try_push(word)?)+ self.locations.words.try_push(word)}/// Adds a site with `frame` as its innermost frame, whose run of locations starts at `locations` and ends where@@ -623,7 +635,8 @@ impl ArtifactWriter {end(section, words);}- for (offset, bytes) in tail.invalidation_patches {+ for (offset, patch) in tail.invalidation_patches {+ let bytes = patch.bytes();let mut padded = [0; MAX_PATCH_LENGTH];padded[..bytes.len()].copy_from_slice(bytes);let mut record = [0; PATCH_WORDS];diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rsindex 8b571db5304..034c61b594d 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs@@ -118,7 +118,7 @@ impl VectorArrangement {}}-impl Assembler {+impl Assembler<'_> {/// Makes sure that the next `size` bytes of code go in one piece, without a veneer pool between them.pub fn reserve_room(&mut self, size: usize) {self.reserve(size);@@ -485,7 +485,8 @@ mod tests {/// SP moves in one instruction even where the immediate takes two.#[test]fn moves_sp_in_one_instruction() {- let mut asm = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::new(&mut code, &work);asm.add_any(SP, Gpr(29), -0x12345, X17); // sub x17, x29, #0x12, lsl #12; sub x17, x17, #0x345; mov sp, x17asm.add_any(X1, X2, 0x12345, X17); // add x1, x2, #0x12, lsl #12; add x1, x1, #0x345let code = asm.finish().unwrap();@@ -499,7 +500,8 @@ mod tests {/// The encodings llvm-mc gives these instructions (`llvm-mc -triple=aarch64 -mattr=+lse,+neon,+rdm`).#[test]fn encodes_like_llvm_mc() {- let mut asm = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::new(&mut code, &work);asm.clz(Width::W32, X1, X2); // clz w1, w2asm.rbit(Width::W64, X3, X4); // rbit x3, x4asm.ror_imm(Width::W64, X5, X6, 13); // ror x5, x6, #13diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rsindex 5ee8591c8f4..e0ed85901f0 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs@@ -15,6 +15,7 @@ use super::super::Fpr;use super::super::FprSet;use super::super::Gpr;use super::super::GprSet;+use super::super::JumpPatch;use super::super::Label;use super::super::MachineFrame;use super::super::NegativeZero;@@ -23,7 +24,7 @@ use super::super::Width;use super::super::Width::W32;use super::super::Width::W64;use super::*;-use std::collections::HashMap;+use ak::ZoneMap;/// Scratch register for address legalization and call targets.const ADDRESS_SCRATCH: Gpr = X16;@@ -35,16 +36,26 @@ const FP_SCRATCH: Fpr = D31;/// available for architecture specific code.////// In this layer, register 31 always means SP.-#[derive(Debug, Default)]-pub struct MacroAssembler {- pub assembler: Assembler,+#[derive(Debug)]+pub struct MacroAssembler<'a> {+ pub assembler: Assembler<'a>,/// 64-bit constants that would take more than two instructions to- /// build, loaded PC-relative from a pool after the code.- constants: Vec<(u64, Label)>,- constant_labels: HashMap<u64, Label>,+ /// build, loaded PC-relative from a pool after the code, in the order of+ /// the pool.+ constants: ZoneMap<'a, u64, Label>,/// 128-bit constants, in the same pool.- constants128: Vec<(u128, Label)>,- constant128_labels: HashMap<u128, Label>,+ constants128: ZoneMap<'a, u128, Label>,+}++/// The encodings of the registers of a set (at most 32), in its order, as the first ones of an array and their count.+fn encodings(registers: impl Iterator<Item = u8>) -> ([u8; 32], usize) {+ let mut encodings = [0; 32];+ let mut count = 0;+ for register in registers {+ encodings[count] = register;+ count += 1;+ }+ (encodings, count)}fn condition_code(condition: Condition) -> Cond {@@ -129,7 +140,7 @@ enum LogicalOp {Xor,}-impl MacroAssembler {+impl MacroAssembler<'_> {/// Turns a portable address into an encodable operand for an access of/// `1 << size_log2` bytes, using `ADDRESS_SCRATCH` when needed.fn legalize(&mut self, address: &Address, size_log2: u32) -> MemOperand {@@ -234,20 +245,18 @@ impl MacroAssembler {/// The label of `value` in the constant pool.fn constant(&mut self, value: u64) -> Label {- *self.constant_labels.entry(value).or_insert_with(|| {- let label = self.assembler.new_label();- self.constants.push((value, label));- label- })+ *self+ .constants+ .entry(value)+ .or_insert_with(|| self.assembler.new_label())}/// The label of the 128-bit `value` in the constant pool.fn constant128(&mut self, value: u128) -> Label {- *self.constant128_labels.entry(value).or_insert_with(|| {- let label = self.assembler.new_label();- self.constants128.push((value, label));- label- })+ *self+ .constants128+ .entry(value)+ .or_insert_with(|| self.assembler.new_label())}/// `dst = imm`, from the constant pool if building it would take more@@ -448,7 +457,9 @@ impl MacroAssembler {}}-impl PortableMacroAssembler for MacroAssembler {+impl PortableMacroAssembler for MacroAssembler<'_> {+ type In<'a> = MacroAssembler<'a>;+const ARCHITECTURE: Architecture = Architecture::AArch64;const ARGUMENT_GPRS: &'static [Gpr] = &[X0, X1, X2, X3, X4, X5, X6, X7];const ARGUMENT_FPRS: &'static [Fpr] = &[D0, D1, D2, D3, D4, D5, D6, D7];@@ -467,8 +478,12 @@ impl PortableMacroAssembler for MacroAssembler {const STACK_POINTER: Gpr = SP;const FRAME_POINTER: Gpr = FP;- fn new() -> Self {- Self::default()+ fn new<'a>(code: &'a mut Column<u8>, work: &'a Zone) -> MacroAssembler<'a> {+ MacroAssembler {+ assembler: Assembler::new(code, work),+ constants: ZoneMap::new_in(work),+ constants128: ZoneMap::new_in(work),+ }}fn offset(&self) -> usize {@@ -493,31 +508,32 @@ impl PortableMacroAssembler for MacroAssembler {offset}- fn jump_patch(from: usize, to: usize) -> Vec<u8> {+ fn jump_patch(from: usize, to: usize) -> JumpPatch {// NB: `b` with a 26-bit word offset.let words = (to as i64 - from as i64) / 4;assert!((-(1 << 25)..(1 << 25)).contains(&words), "code is smaller than 128 MiB");- (0x1400_0000 | (words as u32 & 0x03ff_ffff)).to_le_bytes().to_vec()+ JumpPatch::new(&(0x1400_0000 | (words as u32 & 0x03ff_ffff)).to_le_bytes())}- fn finish_with_data_offset(mut self) -> Result<(Vec<u8>, usize), AsmError> {+ fn finish(mut self) -> Result<usize, AsmError> {let data_offset = self.assembler.offset();if !self.constants128.is_empty() {self.assembler.align_data(16);- for (value, label) in std::mem::take(&mut self.constants128) {- self.assembler.bind(label);- self.assembler.data_u64(value as u64);- self.assembler.data_u64((value >> 64) as u64);+ for (value, label) in self.constants128.iter() {+ self.assembler.bind(*label);+ self.assembler.data_u64(*value as u64);+ self.assembler.data_u64((*value >> 64) as u64);}}if !self.constants.is_empty() {self.assembler.align_data(8);- for (value, label) in std::mem::take(&mut self.constants) {- self.assembler.bind(label);- self.assembler.data_u64(value);+ for (value, label) in self.constants.iter() {+ self.assembler.bind(*label);+ self.assembler.data_u64(*value);}}- Ok((self.assembler.finish()?, data_offset))+ self.assembler.finish()?;+ Ok(data_offset)}fn unreachable(&mut self) {@@ -1112,10 +1128,10 @@ impl PortableMacroAssembler for MacroAssembler {fn emit_prologue(&mut self, frame: &MachineFrame) {self.assembler.stp(FP, LR, PairOperand::PreIndex(SP, -16));self.assembler.mov_sp(FP, SP);- let gprs: Vec<u8> = frame.saved_gprs.iter().map(|register| register.0).collect();- let fprs: Vec<u8> = frame.saved_fprs.iter().map(|register| register.0).collect();- self.push_registers(&gprs, false);- self.push_registers(&fprs, true);+ let (gprs, gpr_count) = encodings(frame.saved_gprs.iter().map(|register| register.0));+ let (fprs, fpr_count) = encodings(frame.saved_fprs.iter().map(|register| register.0));+ self.push_registers(&gprs[..gpr_count], false);+ self.push_registers(&fprs[..fpr_count], true);if frame.locals_size != 0 {self.arithmetic_imm(ArithmeticOp::Sub, W64, SP, SP, i64::from(frame.locals_size));}@@ -1125,10 +1141,10 @@ impl PortableMacroAssembler for MacroAssembler {if frame.locals_size != 0 {self.arithmetic_imm(ArithmeticOp::Add, W64, SP, SP, i64::from(frame.locals_size));}- let gprs: Vec<u8> = frame.saved_gprs.iter().map(|register| register.0).collect();- let fprs: Vec<u8> = frame.saved_fprs.iter().map(|register| register.0).collect();- self.pop_registers(&fprs, true);- self.pop_registers(&gprs, false);+ let (gprs, gpr_count) = encodings(frame.saved_gprs.iter().map(|register| register.0));+ let (fprs, fpr_count) = encodings(frame.saved_fprs.iter().map(|register| register.0));+ self.pop_registers(&fprs[..fpr_count], true);+ self.pop_registers(&gprs[..gpr_count], false);self.assembler.ldp(FP, LR, PairOperand::PostIndex(SP, 16));}}diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rsindex 94a14bb3e8f..b290fa7e374 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/mod.rs@@ -21,6 +21,9 @@ use super::buffer::AsmError;use super::buffer::CodeBuffer;use super::buffer::FixupKind;use super::buffer::Label;+use ak::Column;+use ak::Zone;+use ak::ZoneVec;pub const X0: Gpr = Gpr(0);pub const X1: Gpr = Gpr(1);@@ -333,34 +336,29 @@ const VENEER_HORIZON: usize = 4096;/// redirected to veneers (a B to the label, in a pool jumped over by the/// fallthrough path) emitted between instructions.#[derive(Debug)]-pub struct Assembler {- buffer: CodeBuffer,+pub struct Assembler<'a> {+ buffer: CodeBuffer<'a>,/// Pending short-range forward branches, by fixup id.- veneer_candidates: Vec<u32>,+ veneer_candidates: ZoneVec<'a, u32>,/// The offset at which the veneer candidates must be looked at again.next_veneer_check: usize,}-impl Default for Assembler {- fn default() -> Self {+impl<'a> Assembler<'a> {+ /// An assembler that writes its code into `code`, in place of what it holds, and keeps its labels in `work`.+ pub fn new(code: &'a mut Column<u8>, work: &'a Zone) -> Self {Self {- buffer: CodeBuffer::new(),- veneer_candidates: Vec::new(),+ buffer: CodeBuffer::new(code, work),+ veneer_candidates: ZoneVec::new_in(work),next_veneer_check: usize::MAX,}}-}--impl Assembler {- pub fn new() -> Self {- Self::default()- }pub fn offset(&self) -> usize {self.buffer.offset()}- pub fn buffer(&self) -> &CodeBuffer {+ pub fn buffer(&self) -> &CodeBuffer<'a> {&self.buffer}@@ -376,18 +374,10 @@ impl Assembler {self.buffer.label_offset(label)}- pub fn finish(self) -> Result<Vec<u8>, AsmError> {+ pub fn finish(self) -> Result<&'a [u8], AsmError> {self.buffer.finish()}- /// `finish()`, with the end of the code as the data offset: the- /// assembler itself emits no constant pool.- pub fn finish_with_data_offset(self) -> Result<(Vec<u8>, usize), AsmError> {- let code = self.finish()?;- let length = code.len();- Ok((code, length))- }-/// Emits one instruction word.pub fn emit(&mut self, word: u32) {self.reserve(4);@@ -486,21 +476,26 @@ impl Assembler {/// Emits veneers for every candidate whose deadline is before `horizon`.fn emit_veneer_pool(&mut self, horizon: usize) {- let (due, remaining): (Vec<u32>, Vec<u32>) = self- .veneer_candidates- .iter()- .copied()- .partition(|id| self.deadline(*id).is_some_and(|deadline| deadline <= horizon));- self.veneer_candidates = remaining;+ let is_due = |assembler: &Self, id: u32| assembler.deadline(id).is_some_and(|deadline| deadline <= horizon);+ let due = self.veneer_candidates.iter().filter(|id| is_due(self, **id)).count();// Skip over the pool on the fallthrough path.- self.buffer.emit_u32(0x1400_0000 | (due.len() as u32 + 1));- for id in due {+ self.buffer.emit_u32(0x1400_0000 | (due as u32 + 1));+ // NB: A veneer resolves the fixup of its own candidate only, so the others stay due or not.+ let mut kept = 0;+ for index in 0..self.veneer_candidates.len() {+ let id = self.veneer_candidates[index];+ if !is_due(self, id) {+ self.veneer_candidates[kept] = id;+ kept += 1;+ continue;+ }let fixup = self.buffer.pending_fixup(id).unwrap();let veneer = self.offset();self.buffer.emit_u32(0x1400_0000);self.buffer.add_fixup(fixup.label, veneer, FixupKind::A64Branch26);self.buffer.redirect_fixup(id, veneer);}+ self.veneer_candidates.truncate(kept);}// Moves and immediates.diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/tests.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/tests.rsindex 3eaeed6ebf0..3e74c67b2e6 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/tests.rs@@ -11,9 +11,10 @@ use super::super::disassembler::assert_encodings;use super::*;fn bytes(emit: impl FnOnce(&mut Assembler)) -> Vec<u8> {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);emit(&mut assembler);- assembler.finish().unwrap()+ assembler.finish().unwrap().to_vec()}fn word_at(code: &[u8], offset: usize) -> u32 {@@ -553,7 +554,8 @@ fn branch_target(code: &[u8], offset: usize) -> usize {#[test]fn forward_branches_get_veneers_before_going_out_of_range() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let far = assembler.new_label();let near = assembler.new_label();assembler.tbz(X3, 3, far);@@ -599,7 +601,8 @@ fn veneer_pools_do_not_split_a_label_reference_from_its_fixup() {let references: [fn(&mut Assembler, Label); 2] = [|a, label| a.b(label), |a, label| a.ldr_literal(X1, label)];for reference in references {for nop_count in 8100..8192 {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.tbz(X3, 3, label);for _ in 0..nop_count {@@ -616,7 +619,8 @@ fn veneer_pools_do_not_split_a_label_reference_from_its_fixup() {#[test]fn many_pending_branches_get_veneers() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let labels: Vec<Label> = (0..300).map(|_| assembler.new_label()).collect();let mut branches = Vec::new();for (i, label) in labels.iter().enumerate() {@@ -650,7 +654,8 @@ fn many_pending_branches_get_veneers() {#[test]fn forward_branch_beyond_branch_range_fails() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.adr(X0, label);for _ in 0..(1 << 18) {@@ -662,7 +667,8 @@ fn forward_branch_beyond_branch_range_fails() {#[test]fn unbound_label_fails() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.cbz(W64, X0, label);assert_eq!(assembler.finish(), Err(AsmError::UnboundLabel));@@ -804,7 +810,7 @@ mod macro_assembler {#[test]fn register_sets_are_consistent() {- type M = MacroAssembler;+ type M = MacroAssembler<'static>;assert!(M::ALLOCATABLE_GPRS.intersection(M::SCRATCH_GPRS).is_empty());assert!(M::ALLOCATABLE_FPRS.intersection(M::SCRATCH_FPRS).is_empty());assert!(!M::ALLOCATABLE_GPRS.contains(M::STACK_POINTER));diff --git a/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs b/Libraries/LibJS/JIT/Rust/src/asm/buffer.rsindex 059e629be3e..6b3c6cba4d6 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs@@ -6,6 +6,10 @@//! The code buffer shared by both assemblers: bytes, labels and fixups.+use ak::Column;+use ak::Zone;+use ak::ZoneVec;+/// Why assembling failed.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AsmError {@@ -13,6 +17,8 @@ pub enum AsmError {UnboundLabel,/// A branch or PC-relative reference does not reach its label.BranchOutOfRange,+ /// The code does not fit in the memory it is written into.+ TooLarge,}/// A position in the code, bound once and referenced any number of times@@ -122,44 +128,60 @@ impl Checkpoint {}}-/// A growable code buffer with labels.-#[derive(Debug, Default)]-pub struct CodeBuffer {- bytes: Vec<u8>,- labels: Vec<LabelState>,- fixups: Vec<Fixup>,+/// A code buffer with labels. The code goes straight into the column it writes, and the labels and fixups are in a+/// zone.+#[derive(Debug)]+pub struct CodeBuffer<'a> {+ bytes: &'a mut Column<u8>,+ /// How many bytes were emitted past the end of the column, once it is full. The offsets go on as if they were+ /// there, but nothing is written or patched any more: `finish()` fails.+ lost: usize,+ labels: ZoneVec<'a, LabelState>,+ fixups: ZoneVec<'a, Fixup>,/// The first error hit while emitting; reported by `finish()`.error: Option<AsmError>,}-impl CodeBuffer {- pub fn new() -> Self {- Self::default()+impl<'a> CodeBuffer<'a> {+ /// A buffer that writes its code into `bytes`, in place of what it holds, and keeps its labels in `work`.+ pub fn new(bytes: &'a mut Column<u8>, work: &'a Zone) -> Self {+ bytes.clear();+ Self {+ bytes,+ lost: 0,+ labels: ZoneVec::new_in(work),+ fixups: ZoneVec::new_in(work),+ error: None,+ }}/// The current emission offset.pub fn offset(&self) -> usize {- self.bytes.len()+ self.bytes.len() + self.lost}pub fn emit_u8(&mut self, value: u8) {- self.bytes.push(value);+ self.emit_bytes(&[value]);}pub fn emit_u16(&mut self, value: u16) {- self.bytes.extend_from_slice(&value.to_le_bytes());+ self.emit_bytes(&value.to_le_bytes());}pub fn emit_u32(&mut self, value: u32) {- self.bytes.extend_from_slice(&value.to_le_bytes());+ self.emit_bytes(&value.to_le_bytes());}pub fn emit_u64(&mut self, value: u64) {- self.bytes.extend_from_slice(&value.to_le_bytes());+ self.emit_bytes(&value.to_le_bytes());}pub fn emit_bytes(&mut self, bytes: &[u8]) {- self.bytes.extend_from_slice(bytes);+ if self.lost == 0 && self.bytes.try_extend_from_slice(bytes).is_ok() {+ return;+ }+ self.set_error(AsmError::TooLarge);+ self.lost += bytes.len();}pub fn read_u32(&self, at: usize) -> u32 {@@ -272,7 +294,9 @@ impl CodeBuffer {first_fixup: fixup.next,};}- self.bytes.truncate(checkpoint.offset);+ let kept = checkpoint.offset.min(self.bytes.len());+ self.bytes.truncate(kept);+ self.lost = checkpoint.offset - kept;}/// Pads with `filler` until the offset is a multiple of `alignment`.@@ -285,14 +309,15 @@ impl CodeBuffer {/// Returns the code, or the first error. Fails if a referenced label was/// never bound.- pub fn finish(self) -> Result<Vec<u8>, AsmError> {+ pub fn finish(self) -> Result<&'a [u8], AsmError> {if let Some(error) = self.error {return Err(error);}if self.fixups.iter().any(|fixup| !fixup.resolved) {return Err(AsmError::UnboundLabel);}- Ok(self.bytes)+ let bytes: &'a Column<u8> = self.bytes;+ Ok(bytes)}fn offset_u32(offset: usize) -> u32 {@@ -300,6 +325,10 @@ impl CodeBuffer {}fn patch(&mut self, at: usize, kind: FixupKind, target: usize) {+ // NB: The code that the column had no room for is not there to patch, and the code is not finished.+ if self.lost != 0 {+ return;+ }if !kind.reaches(at, target) {self.set_error(AsmError::BranchOutOfRange);return;@@ -338,7 +367,8 @@ mod tests {#[test]fn forward_and_backward_references_are_patched() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);let label = buffer.new_label();buffer.emit_u8(0xeb);buffer.emit_u8(0);@@ -354,7 +384,8 @@ mod tests {#[test]fn rewinding_drops_code_and_its_references() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);let label = buffer.new_label();buffer.emit_u8(0xeb);buffer.emit_u8(0);@@ -376,7 +407,8 @@ mod tests {#[test]fn unbound_label_fails() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);let label = buffer.new_label();buffer.emit_u32(0x1400_0000);buffer.add_fixup(label, 0, FixupKind::A64Branch26);@@ -385,15 +417,17 @@ mod tests {#[test]fn unreferenced_unbound_label_is_fine() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);let _ = buffer.new_label();buffer.emit_u8(0xc3);- assert_eq!(buffer.finish(), Ok(vec![0xc3]));+ assert_eq!(buffer.finish(), Ok(&[0xc3][..]));}#[test]fn out_of_range_reference_fails() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);let label = buffer.new_label();buffer.emit_bytes(&[0xeb, 0]);buffer.add_fixup(label, 1, FixupKind::X86Rel8);@@ -416,7 +450,8 @@ mod tests {#[test]fn alignment_pads_with_filler() {- let mut buffer = CodeBuffer::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut buffer = CodeBuffer::new(&mut code, &work);buffer.emit_u8(0xc3);buffer.align_with(8, 0xcc);assert_eq!(diff --git a/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rsindex 6f9e3b55704..2a4c4586c73 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs@@ -26,33 +26,33 @@ pub struct DisassembledInstruction {pub pc_relative_target: Option<usize>,}-/// Disassembles `code` (assumed to start at offset 0, so branch targets are-/// code offsets) for `architecture`.-pub fn listing(architecture: Architecture, code: &[u8]) -> Vec<DisassembledInstruction> {- listing_with_data(architecture, code, code.len())-}--/// Like `listing()`, for instructions up to `data_offset` followed by the-/// 64-bit constants they load (see `PortableMacroAssembler::finish_with_data_offset`).-/// Loads of a constant list it as their `constant`.-pub fn listing_with_data(architecture: Architecture, code: &[u8], data_offset: usize) -> Vec<DisassembledInstruction> {- let mut instructions = match architecture {- Architecture::X86_64 => x86_64_listing(&code[..data_offset]),- Architecture::AArch64 => aarch64_listing(&code[..data_offset]),- };+/// Calls `visit` with each instruction of `code` (assumed to start at offset 0, so branch targets are code offsets)+/// for `architecture`, in order: those up to `data_offset`, then the 64-bit constants they load (see+/// `PortableMacroAssembler::finish`). Loads of a constant list it as their `constant`.+pub fn for_each_instruction(+ architecture: Architecture,+ code: &[u8],+ data_offset: usize,+ mut visit: impl FnMut(&DisassembledInstruction),+) {let constant_at = |target: usize| {let bytes = code.get(target..target + 8)?;(target >= data_offset).then(|| u64::from_le_bytes(bytes.try_into().expect("eight bytes")))};- for instruction in &mut instructions {+ let mut visit_instruction = |mut instruction: DisassembledInstruction| {if let Some(target) = instruction.pc_relative_target {instruction.constant = instruction.constant.or_else(|| constant_at(target));}+ visit(&instruction);+ };+ match architecture {+ Architecture::X86_64 => x86_64_instructions(&code[..data_offset], &mut visit_instruction),+ Architecture::AArch64 => aarch64_instructions(&code[..data_offset], &mut visit_instruction),}let first_constant = data_offset.next_multiple_of(8);for offset in (first_constant..code.len()).step_by(8) {let value = constant_at(offset).expect("constants fill the data");- instructions.push(DisassembledInstruction {+ visit_instruction(DisassembledInstruction {offset,length: 8,text: format!(".quad {value:#x}"),@@ -60,35 +60,36 @@ pub fn listing_with_data(architecture: Architecture, code: &[u8], data_offset: upc_relative_target: None,});}- instructions}/// The bytes of code that no decoder in this build understands.#[cfg(not(test))]-fn raw_listing(code: &[u8]) -> Vec<DisassembledInstruction> {- code.chunks(8)- .enumerate()- .map(|(index, chunk)| {- let bytes = chunk.iter().map(|byte| format!("{byte:02x}")).collect::<Vec<_>>();- DisassembledInstruction {- offset: 8 * index,- length: chunk.len(),- text: format!(".byte {}", bytes.join(" ")),- constant: None,- pc_relative_target: None,- }- })- .collect()+fn raw_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {+ use std::fmt::Write;++ for (index, chunk) in code.chunks(8).enumerate() {+ let mut text = String::from(".byte");+ for byte in chunk {+ write!(text, " {byte:02x}").unwrap();+ }+ visit(DisassembledInstruction {+ offset: 8 * index,+ length: chunk.len(),+ text,+ constant: None,+ pc_relative_target: None,+ });+ }}#[cfg(not(any(test, target_arch = "x86_64")))]-fn x86_64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {- raw_listing(code)+fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {+ raw_instructions(code, visit);}#[cfg(not(any(test, target_arch = "aarch64")))]-fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {- raw_listing(code)+fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {+ raw_instructions(code, visit);}#[cfg(any(test, target_arch = "x86_64"))]@@ -108,7 +109,7 @@ fn x86_64_formatter() -> iced_x86::IntelFormatter {}#[cfg(any(test, target_arch = "x86_64"))]-fn x86_64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {+fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {use iced_x86::Decoder;use iced_x86::DecoderOptions;use iced_x86::Formatter;@@ -116,7 +117,6 @@ fn x86_64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {let mut decoder = Decoder::with_ip(64, code, 0, DecoderOptions::NONE);let mut formatter = x86_64_formatter();- let mut instructions = Vec::new();while decoder.can_decode() {let instruction = decoder.decode();let offset = instruction.ip() as usize;@@ -132,7 +132,7 @@ fn x86_64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {let pc_relative_target = instruction.is_ip_rel_memory_operand().then(|| instruction.ip_rel_memory_address() as usize);- instructions.push(DisassembledInstruction {+ visit(DisassembledInstruction {offset,length: instruction.len(),text,@@ -140,11 +140,23 @@ fn x86_64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {pc_relative_target,});}- instructions}+/// The words of `text`, with one space between each two.#[cfg(any(test, target_arch = "aarch64"))]-fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {+fn single_spaced(text: &str) -> String {+ let mut spaced = String::with_capacity(text.len());+ for word in text.split_whitespace() {+ if !spaced.is_empty() {+ spaced.push(' ');+ }+ spaced.push_str(word);+ }+ spaced+}++#[cfg(any(test, target_arch = "aarch64"))]+fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {use farm64::format::FmtFormatter;use farm64::format::format_to_string;@@ -152,7 +164,6 @@ fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {let formatter = FmtFormatter::new();// The value each register holds after a `movz`/`movk` sequence.let mut register_values = [None::<u64>; 32];- let mut instructions = Vec::new();while decoder.can_decode() {let offset = decoder.position();let instruction = decoder.decode();@@ -160,10 +171,7 @@ fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {let text = if instruction.is_invalid() {format!(".word {word:#010x}")} else {- format_to_string(&formatter, &instruction)- .split_whitespace()- .collect::<Vec<_>>()- .join(" ")+ single_spaced(&format_to_string(&formatter, &instruction))};let register = (word & 0x1f) as usize;let shift = 16 * ((word >> 21) & 3);@@ -187,7 +195,7 @@ fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {let imm19 = ((((word >> 5) & 0x7ffff) << 13) as i32) >> 13;(offset as i64 + 4 * i64::from(imm19)) as usize});- instructions.push(DisassembledInstruction {+ visit(DisassembledInstruction {offset,length: 4,text,@@ -195,74 +203,127 @@ fn aarch64_listing(code: &[u8]) -> Vec<DisassembledInstruction> {pc_relative_target,});}- instructions}-/// One line per instruction, Intel syntax, code assumed to start at 0.#[cfg(test)]-pub fn x86_64(code: &[u8]) -> Vec<String> {- x86_64_listing(code)- .into_iter()- .map(|instruction| {- assert!(- !instruction.text.starts_with(".byte"),- "invalid x86-64 encoding in {code:02x?}"- );- instruction.text- })- .collect()-}--/// One line per instruction, code assumed to start at 0.+pub(crate) use listings::aarch64;#[cfg(test)]-pub fn aarch64(code: &[u8]) -> Vec<String> {- aarch64_range(code, 0, code.len())-}+pub(crate) use listings::aarch64_range;+#[cfg(test)]+pub(crate) use listings::assert_encodings;+#[cfg(test)]+pub(crate) use listings::listing;+#[cfg(test)]+pub(crate) use listings::listing_with_data;+#[cfg(test)]+pub(crate) use listings::x86_64;-/// Disassembles `code[start..end]`, with addresses relative to `code`.+/// Listings as lists, for tests.#[cfg(test)]-pub fn aarch64_range(code: &[u8], start: usize, end: usize) -> Vec<String> {- use farm64::format::FmtFormatter;- use farm64::format::format_to_string;+pub(crate) mod listings {+ use super::*;- let code_start = start;- let code = &code[start..end];- assert!(code.len().is_multiple_of(4));- let mut decoder = farm64::Decoder::new(code, code_start as u64, farm64::DecoderOptions::default());- let formatter = FmtFormatter::new();- let mut lines = Vec::new();- while decoder.can_decode() {- let offset = decoder.position();- let instruction = decoder.decode();- let word = u32::from_le_bytes(code[offset..offset + 4].try_into().unwrap());- assert!(!instruction.is_invalid(), "invalid AArch64 encoding {word:#010x}");- let text = format_to_string(&formatter, &instruction);- lines.push(text.split_whitespace().collect::<Vec<_>>().join(" "));+ /// The instructions of `code` (assumed to start at offset 0, so branch targets are code offsets) for+ /// `architecture`.+ pub fn listing(architecture: Architecture, code: &[u8]) -> Vec<DisassembledInstruction> {+ listing_with_data(architecture, code, code.len())}- lines-}-/// Checks a table of `"expected; disassembly" => |assembler| emission;`-/// entries, reporting every mismatch at once.-#[cfg(test)]-macro_rules! assert_encodings {- ($assembler:ty, $disassemble:path, { $($expected:expr => |$a:ident| $body:expr;)* }) => {{- let mut failures: Vec<String> = Vec::new();- $(- let mut $a = <$assembler>::new();- $body;- let (code, data_offset) = $a.finish_with_data_offset().expect("assembling failed");- let actual = $disassemble(&code[..data_offset]).join("; ");- if actual != $expected {- failures.push(format!("{}\n expected: {}\n actual: {}", stringify!($body), $expected, actual));- }- )*- assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));- }};-}+ /// Like `listing()`, for instructions up to `data_offset` followed by the 64-bit constants they load.+ pub fn listing_with_data(+ architecture: Architecture,+ code: &[u8],+ data_offset: usize,+ ) -> Vec<DisassembledInstruction> {+ let mut instructions = Vec::new();+ for_each_instruction(architecture, code, data_offset, |instruction| {+ instructions.push(instruction.clone())+ });+ instructions+ }-#[cfg(test)]-pub(crate) use assert_encodings;+ /// One line per instruction, Intel syntax, code assumed to start at 0.+ pub fn x86_64(code: &[u8]) -> Vec<String> {+ listing(Architecture::X86_64, code)+ .into_iter()+ .map(|instruction| {+ assert!(+ !instruction.text.starts_with(".byte"),+ "invalid x86-64 encoding in {code:02x?}"+ );+ instruction.text+ })+ .collect()+ }++ /// One line per instruction, code assumed to start at 0.+ pub fn aarch64(code: &[u8]) -> Vec<String> {+ aarch64_range(code, 0, code.len())+ }++ /// Disassembles `code[start..end]`, with addresses relative to `code`.+ pub fn aarch64_range(code: &[u8], start: usize, end: usize) -> Vec<String> {+ use farm64::format::FmtFormatter;+ use farm64::format::format_to_string;++ let code_start = start;+ let code = &code[start..end];+ assert!(code.len().is_multiple_of(4));+ let mut decoder = farm64::Decoder::new(code, code_start as u64, farm64::DecoderOptions::default());+ let formatter = FmtFormatter::new();+ let mut lines = Vec::new();+ while decoder.can_decode() {+ let offset = decoder.position();+ let instruction = decoder.decode();+ let word = u32::from_le_bytes(code[offset..offset + 4].try_into().unwrap());+ assert!(!instruction.is_invalid(), "invalid AArch64 encoding {word:#010x}");+ let text = format_to_string(&formatter, &instruction);+ lines.push(single_spaced(&text));+ }+ lines+ }++ /// Where the instructions end in the code that an assembler finished: at the end of the code of an assembler, and+ /// at the data offset that a macro assembler gives.+ pub(crate) trait InstructionsEnd {+ fn instructions_end(&self) -> usize;+ }++ impl InstructionsEnd for &[u8] {+ fn instructions_end(&self) -> usize {+ self.len()+ }+ }++ impl InstructionsEnd for usize {+ fn instructions_end(&self) -> usize {+ *self+ }+ }++ /// Checks a table of `"expected; disassembly" => |assembler| emission;`+ /// entries, reporting every mismatch at once.+ macro_rules! assert_encodings {+ ($assembler:ty, $disassemble:path, { $($expected:expr => |$a:ident| $body:expr;)* }) => {{+ let mut failures: Vec<String> = Vec::new();+ $(+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut $a = <$assembler>::new(&mut code, &work);+ $body;+ let end = crate::asm::disassembler::listings::InstructionsEnd::instructions_end(+ &$a.finish().expect("assembling failed"),+ );+ let actual = $disassemble(&code[..end]).join("; ");+ if actual != $expected {+ failures.push(format!("{}\n expected: {}\n actual: {}", stringify!($body), $expected, actual));+ }+ )*+ assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n"));+ }};+ }++ pub(crate) use assert_encodings;+}#[cfg(test)]mod tests {@@ -294,9 +355,10 @@ mod tests {#[test]fn lists_aarch64_code_with_constants() {- let mut masm = aarch64::MacroAssembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut masm = aarch64::MacroAssembler::new(&mut code, &work);masm.move_imm64(Gpr(9), 0x1234_0000_0000_def0);- let code = masm.finish().unwrap();+ masm.finish().unwrap();let listing = listing(Architecture::AArch64, &code);assert_eq!(listing.last().unwrap().constant, Some(0x1234_0000_0000_def0));assert!(listing[0].text.starts_with("mov"), "{listing:?}");@@ -304,17 +366,18 @@ mod tests {#[test]fn lists_loads_from_the_constant_pool() {- let mut masm = aarch64::MacroAssembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut masm = aarch64::MacroAssembler::new(&mut code, &work);masm.move_imm64(Gpr(9), 0x1234_5678_9abc_def0);- let (code, data_offset) = masm.finish_with_data_offset().unwrap();+ let data_offset = masm.finish().unwrap();let listing = listing_with_data(Architecture::AArch64, &code, data_offset);assert!(listing[0].text.starts_with("ldr"), "{listing:?}");assert_eq!(listing[0].constant, Some(0x1234_5678_9abc_def0));assert_eq!(listing.last().unwrap().text, ".quad 0x123456789abcdef0");- let mut masm = super::super::x86_64::MacroAssembler::new();+ let mut masm = super::super::x86_64::MacroAssembler::new(&mut code, &work);masm.move_imm64(Gpr(0), 0x1234_5678_9abc_def0);- let (code, data_offset) = masm.finish_with_data_offset().unwrap();+ let data_offset = masm.finish().unwrap();let listing = listing_with_data(Architecture::X86_64, &code, data_offset);assert_eq!(listing[0].constant, Some(0x1234_5678_9abc_def0), "{listing:?}");}diff --git a/Libraries/LibJS/JIT/Rust/src/asm/execution_tests.rs b/Libraries/LibJS/JIT/Rust/src/asm/execution_tests.rsindex 71abddb6405..1c53bcee836 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/execution_tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/execution_tests.rs@@ -13,7 +13,6 @@ use super::Fpr;use super::FprSet;use super::Gpr;use super::GprSet;-use super::MacroAssembler;use super::NegativeZero;use super::PortableMacroAssembler;use super::Scale;@@ -22,9 +21,11 @@ use super::executable_code::ExecutableCode;use super::x86_64::*;fn assemble(emit: impl FnOnce(&mut MacroAssembler)) -> ExecutableCode {- let mut masm = MacroAssembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut masm = MacroAssembler::new(&mut code, &work);emit(&mut masm);- ExecutableCode::new(&masm.finish().expect("assembling failed"))+ masm.finish().expect("assembling failed");+ ExecutableCode::new(&code[..])}/// The two-register return value of JIT entry points.diff --git a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rsindex c0fa49daa8a..98cd17ba108 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs@@ -18,6 +18,8 @@ use super::Gpr;use super::GprSet;use super::Label;use super::NegativeZero;+use ak::Column;+use ak::Zone;/// The stack frame a JIT function sets up in its prologue.///@@ -46,8 +48,36 @@ impl MachineFrame {}}+/// The bytes of a jump that replace the no-ops of `PortableMacroAssembler::patchable_nop()`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct JumpPatch {+ bytes: [u8; JumpPatch::MAX_LENGTH],+ length: u8,+}++impl JumpPatch {+ /// The most bytes a jump patch has.+ pub const MAX_LENGTH: usize = 8;++ pub fn new(bytes: &[u8]) -> Self {+ let mut patch = Self {+ bytes: [0; Self::MAX_LENGTH],+ length: bytes.len() as u8,+ };+ patch.bytes[..bytes.len()].copy_from_slice(bytes);+ patch+ }++ pub fn bytes(&self) -> &[u8] {+ &self.bytes[..usize::from(self.length)]+ }+}+/// Operations codegen can use on every architecture.///+/// A macro assembler type stands for its target at any lifetime: `In<'a>` is the one that writes code into memory+/// that lives for `'a`, which `new()` makes.+////// Conventions:/// - Three-operand forms: `dst` may alias any source./// - 32-bit integer operations zero-extend their result into 64 bits.@@ -80,7 +110,12 @@ pub trait PortableMacroAssembler: Sized {const STACK_POINTER: Gpr;const FRAME_POINTER: Gpr;- fn new() -> Self;+ /// The macro assembler of the same target that writes into memory that lives for `'a`.+ type In<'a>: PortableMacroAssembler;++ /// A macro assembler that writes its code into `code`, in place of what it holds, and keeps its labels and+ /// constants in `work`.+ fn new<'a>(code: &'a mut Column<u8>, work: &'a Zone) -> Self::In<'a>;fn offset(&self) -> usize;fn new_label(&mut self) -> Label;fn bind(&mut self, label: Label);@@ -90,18 +125,10 @@ pub trait PortableMacroAssembler: Sized {fn patchable_nop(&mut self) -> usize;/// The bytes of a jump from offset `from` to offset `to` of the same/// code, which replace the no-ops `patchable_nop()` emitted at `from`.- fn jump_patch(from: usize, to: usize) -> Vec<u8>;- /// Returns the code. Fails if a referenced label is unbound or a branch- /// does not reach.- fn finish(self) -> Result<Vec<u8>, AsmError>- where- Self: Sized,- {- Ok(self.finish_with_data_offset()?.0)- }- /// Like `finish()`, with the offset where the instructions end and the- /// data they load (a constant pool) begins.- fn finish_with_data_offset(self) -> Result<(Vec<u8>, usize), AsmError>;+ fn jump_patch(from: usize, to: usize) -> JumpPatch;+ /// Completes the code in the column of `new()`, and returns the offset where the instructions end and the data+ /// they load (a constant pool) begins. Fails if a referenced label is unbound or a branch does not reach.+ fn finish(self) -> Result<usize, AsmError>;/// A guaranteed trap for code that must never run.fn unreachable(&mut self);diff --git a/Libraries/LibJS/JIT/Rust/src/asm/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/mod.rsindex 257fffd072e..8791a8d7e48 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/mod.rs@@ -17,13 +17,15 @@ pub mod x86_64;pub use buffer::AsmError;pub use buffer::Label;+pub use macro_assembler::JumpPatch;pub use macro_assembler::MachineFrame;pub use macro_assembler::PortableMacroAssembler;+// NB: The macro assembler of a target, at any lifetime, stands for the target (see `PortableMacroAssembler::In`).#[cfg(target_arch = "aarch64")]-pub type MacroAssembler = aarch64::MacroAssembler;+pub type MacroAssembler = aarch64::MacroAssembler<'static>;#[cfg(target_arch = "x86_64")]-pub type MacroAssembler = x86_64::MacroAssembler;+pub type MacroAssembler = x86_64::MacroAssembler<'static>;pub mod disassembler;#[cfg(all(test, target_arch = "x86_64"))]@@ -33,6 +35,18 @@ mod execution_tests;#[cfg(test)]mod tests;+/// A column for the code that a test assembles.+#[cfg(test)]+pub(crate) fn test_code() -> ak::Column<u8> {+ ak::Column::new(1 << 24, c"test code")+}++/// A zone for the labels and the fixups of an assembler in a test.+#[cfg(test)]+pub(crate) fn test_work() -> ak::Zone {+ ak::Zone::new(1 << 30, c"test")+}+/// The instruction set an assembler emits.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Architecture {@@ -45,7 +59,7 @@ pub enum Architecture {/// On AArch64, encoding 31 means either the stack pointer or the zero register/// depending on the instruction; the encoders document which. In the/// `MacroAssembler` layer it always means the stack pointer.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]pub struct Gpr(pub u8);/// A floating point / vector register, by its hardware encoding.diff --git a/Libraries/LibJS/JIT/Rust/src/asm/tests.rs b/Libraries/LibJS/JIT/Rust/src/asm/tests.rsindex 716b062f1d2..454ae6e085e 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/tests.rs@@ -10,12 +10,14 @@ fn check_constant_pools<M: PortableMacroAssembler>() {let constants: Vec<u64> = (0..1024).map(|index| 0x1234_5678_9abc_0000 | index).collect();let vector_constant = |bits: u64| u128::from(bits) | (u128::from(!bits) << 64);let assemble = || {- let mut masm = M::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut masm = M::new(&mut code, &work);for bits in constants.iter().chain(constants.iter().rev()) {masm.call_absolute(*bits);masm.load_imm128(M::ARGUMENT_FPRS[0], vector_constant(*bits));}- masm.finish_with_data_offset().unwrap()+ let data_offset = masm.finish().unwrap();+ (code[..].to_vec(), data_offset)};let (code, data_offset) = assemble();let mut expected = vec![0; data_offset.next_multiple_of(16) - data_offset];diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rsindex 4bc568102c9..1b90d69cb12 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs@@ -138,7 +138,7 @@ pub enum ShiftX {Shr,}-impl Assembler {+impl Assembler<'_> {/// Emits a VEX prefix and opcode with ModRM for `reg`, the extra source `vvvv` and `rm`, using the two-byte form/// where it can.#[allow(clippy::too_many_arguments)]@@ -635,7 +635,8 @@ mod tests {#[test]fn rip_relative_operands() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.vbitwise_r_label(BitwiseOp::And, XMM1, XMM2, label);assembler.vmovs_r_label(Precision::Double, XMM3, label);diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rsindex d0e003c6852..0a64d8db85d 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs@@ -15,6 +15,7 @@ use super::super::Fpr;use super::super::FprSet;use super::super::Gpr;use super::super::GprSet;+use super::super::JumpPatch;use super::super::Label;use super::super::MachineFrame;use super::super::NegativeZero;@@ -23,7 +24,7 @@ use super::super::Width;use super::super::Width::W32;use super::super::Width::W64;use super::*;-use std::collections::HashMap;+use ak::ZoneMap;/// General scratch register: immediates, call targets, working values.const SCRATCH: Gpr = R11;@@ -40,16 +41,14 @@ enum Extreme {/// The macro assembler for x86-64. Wraps an `Assembler`, which stays/// available for architecture specific code.-#[derive(Debug, Default)]-pub struct MacroAssembler {- pub assembler: Assembler,+#[derive(Debug)]+pub struct MacroAssembler<'a> {+ pub assembler: Assembler<'a>,/// 64-bit constants that do not fit an immediate, loaded RIP-relative- /// from a pool after the code.- constants: Vec<(u64, Label)>,- constant_labels: HashMap<u64, Label>,+ /// from a pool after the code, in the order of the pool.+ constants: ZoneMap<'a, u64, Label>,/// 128-bit constants, in the same pool.- constants128: Vec<(u128, Label)>,- constant128_labels: HashMap<u128, Label>,+ constants128: ZoneMap<'a, u128, Label>,}fn condition_code(condition: Condition) -> Cond {@@ -137,13 +136,13 @@ fn double_flags(condition: DoubleCondition) -> DoubleFlags {}}-impl BranchGroups for MacroAssembler {- fn branch_assembler(&mut self) -> &mut Assembler {+impl<'a> BranchGroups<'a> for MacroAssembler<'a> {+ fn branch_assembler(&mut self) -> &mut Assembler<'a> {&mut self.assembler}}-impl MacroAssembler {+impl<'a> MacroAssembler<'a> {/// The bytes the prologue of `frame` moves the stack pointer down by after saving the general purpose registers.fn reserved_frame_bytes(frame: &MachineFrame) -> u32 {frame.locals_size + 8 * frame.saved_fprs.len() as u32@@ -236,20 +235,18 @@ impl MacroAssembler {/// The label of `value` in the constant pool.fn constant(&mut self, value: u64) -> Label {- *self.constant_labels.entry(value).or_insert_with(|| {- let label = self.assembler.new_label();- self.constants.push((value, label));- label- })+ *self+ .constants+ .entry(value)+ .or_insert_with(|| self.assembler.new_label())}/// The label of the 128-bit `value` in the constant pool.fn constant128(&mut self, value: u128) -> Label {- *self.constant128_labels.entry(value).or_insert_with(|| {- let label = self.assembler.new_label();- self.constants128.push((value, label));- label- })+ *self+ .constants128+ .entry(value)+ .or_insert_with(|| self.assembler.new_label())}fn compare_imm(&mut self, width: Width, lhs: Gpr, imm: i64) {@@ -327,7 +324,7 @@ impl MacroAssembler {/// `dst = lhs op rhs` for an SSE operation where `dst` must be the left operand.fn double_operation(&mut self,- operation: fn(&mut Assembler, Fpr, Fpr),+ operation: fn(&mut Assembler<'a>, Fpr, Fpr),commutative: bool,dst: Fpr,lhs: Fpr,@@ -350,7 +347,9 @@ impl MacroAssembler {}}-impl PortableMacroAssembler for MacroAssembler {+impl PortableMacroAssembler for MacroAssembler<'_> {+ type In<'a> = MacroAssembler<'a>;+const ARCHITECTURE: Architecture = Architecture::X86_64;const ARGUMENT_GPRS: &'static [Gpr] = &[RDI, RSI, RDX, RCX, R8, R9];const ARGUMENT_FPRS: &'static [Fpr] = &[XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7];@@ -367,8 +366,12 @@ impl PortableMacroAssembler for MacroAssembler {const STACK_POINTER: Gpr = RSP;const FRAME_POINTER: Gpr = RBP;- fn new() -> Self {- Self::default()+ fn new<'a>(code: &'a mut Column<u8>, work: &'a Zone) -> MacroAssembler<'a> {+ MacroAssembler {+ assembler: Assembler::new(code, work),+ constants: ZoneMap::new_in(work),+ constants128: ZoneMap::new_in(work),+ }}fn offset(&self) -> usize {@@ -394,31 +397,31 @@ impl PortableMacroAssembler for MacroAssembler {offset}- fn jump_patch(from: usize, to: usize) -> Vec<u8> {+ fn jump_patch(from: usize, to: usize) -> JumpPatch {let displacement = i32::try_from(to as i64 - (from as i64 + 5)).expect("code is smaller than 2 GiB");- let mut bytes = vec![0xe9];- bytes.extend_from_slice(&displacement.to_le_bytes());- bytes+ let [b0, b1, b2, b3] = displacement.to_le_bytes();+ JumpPatch::new(&[0xe9, b0, b1, b2, b3])}- fn finish_with_data_offset(mut self) -> Result<(Vec<u8>, usize), AsmError> {+ fn finish(mut self) -> Result<usize, AsmError> {let data_offset = self.assembler.offset();if !self.constants128.is_empty() {self.assembler.align_data(16);- for (value, label) in std::mem::take(&mut self.constants128) {- self.assembler.bind(label);- self.assembler.data_u64(value as u64);- self.assembler.data_u64((value >> 64) as u64);+ for (value, label) in self.constants128.iter() {+ self.assembler.bind(*label);+ self.assembler.data_u64(*value as u64);+ self.assembler.data_u64((*value >> 64) as u64);}}if !self.constants.is_empty() {self.assembler.align_data(8);- for (value, label) in std::mem::take(&mut self.constants) {- self.assembler.bind(label);- self.assembler.data_u64(value);+ for (value, label) in self.constants.iter() {+ self.assembler.bind(*label);+ self.assembler.data_u64(*value);}}- Ok((self.assembler.finish()?, data_offset))+ self.assembler.finish()?;+ Ok(data_offset)}fn unreachable(&mut self) {diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rsindex c4356c31264..eb03a04f642 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs@@ -36,6 +36,8 @@ use super::buffer::AsmError;use super::buffer::CodeBuffer;use super::buffer::FixupKind;use super::buffer::Label;+use ak::Column;+use ak::Zone;pub const RAX: Gpr = Gpr(0);pub const RCX: Gpr = Gpr(1);@@ -166,9 +168,9 @@ enum Prefix {}/// x86-64 machine code assembler.-#[derive(Debug, Default)]-pub struct Assembler {- buffer: CodeBuffer,+#[derive(Debug)]+pub struct Assembler<'a> {+ buffer: CodeBuffer<'a>,/// None for a raw instruction encoder; host code generation selects the CPU's optional instructions.cpu_features: Option<CpuFeatures>,/// Whether a group of instructions that ends in a branch is being emitted (see `BranchGroups::branch_group()`), whose@@ -180,8 +182,8 @@ pub struct Assembler {const BRANCH_WINDOW: usize = 32;/// Emitters of code with branches, which keep the branches within 32-byte windows.-pub trait BranchGroups: Sized {- fn branch_assembler(&mut self) -> &mut Assembler;+pub trait BranchGroups<'a>: Sized {+ fn branch_assembler(&mut self) -> &mut Assembler<'a>;/// Emits a branch with `emit`, or the instructions that macro-fuse with a branch and the branch, so that they/// neither cross nor end at the end of a 32-byte window, padding with NOPs to the next one where they would.@@ -212,26 +214,31 @@ pub trait BranchGroups: Sized {}}-impl BranchGroups for Assembler {- fn branch_assembler(&mut self) -> &mut Assembler {+impl<'a> BranchGroups<'a> for Assembler<'a> {+ fn branch_assembler(&mut self) -> &mut Assembler<'a> {self}}-impl Assembler {- pub fn new() -> Self {- Self::default()+impl<'a> Assembler<'a> {+ /// An assembler that writes its code into `code`, in place of what it holds, and keeps its labels in `work`.+ pub fn new(code: &'a mut Column<u8>, work: &'a Zone) -> Self {+ Self {+ buffer: CodeBuffer::new(code, work),+ cpu_features: None,+ in_branch_group: false,+ }}/// Selects AVX, AVX2, BMI and LZCNT only where the executing CPU supports them.- pub fn for_host() -> Self {- Self::with_cpu_features(CpuFeatures::host())+ pub fn for_host(code: &'a mut Column<u8>, work: &'a Zone) -> Self {+ Self::with_cpu_features(CpuFeatures::host(), code, work)}- pub fn with_cpu_features(cpu_features: CpuFeatures) -> Self {+ pub fn with_cpu_features(cpu_features: CpuFeatures, code: &'a mut Column<u8>, work: &'a Zone) -> Self {Self {cpu_features: Some(cpu_features),- ..Self::default()+ ..Self::new(code, work)}}@@ -243,7 +250,7 @@ impl Assembler {self.buffer.offset()}- pub fn buffer(&self) -> &CodeBuffer {+ pub fn buffer(&self) -> &CodeBuffer<'a> {&self.buffer}@@ -259,18 +266,10 @@ impl Assembler {self.buffer.label_offset(label)}- pub fn finish(self) -> Result<Vec<u8>, AsmError> {+ pub fn finish(self) -> Result<&'a [u8], AsmError> {self.buffer.finish()}- /// `finish()`, with the end of the code as the data offset: the- /// assembler itself emits no constant pool.- pub fn finish_with_data_offset(self) -> Result<(Vec<u8>, usize), AsmError> {- let code = self.finish()?;- let length = code.len();- Ok((code, length))- }-// Data emission.pub fn data_u8(&mut self, value: u8) {diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rsindex c135b719d6f..089547e9949 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs@@ -74,7 +74,7 @@ impl VexOpcode {}}-impl Assembler {+impl Assembler<'_> {/// Emit the legacy encoding with the same opcode map, mandatory prefix and operands as a VEX instruction.fn legacy(&mut self, opcode: VexOpcode, reg: u8, rm: Rm, immediate_size: usize) {let prefix = match opcode.prefix {@@ -402,7 +402,8 @@ mod tests {}),];for (expected, emit) in cases {- let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2, &mut code, &work);emit(&mut asm);assert_eq!(disassembler::x86_64(&asm.finish().unwrap()).join("; "), *expected);}@@ -439,7 +440,8 @@ mod tests {(Map0F, P66, 0x56, "orpd"),(Map0F, P66, 0x57, "xorpd"),] {- let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2, &mut code, &work);asm.vex(VexOpcode::new(prefix, map, opcode), 9, 8, VexOperand::Register(9), None);assert_eq!(disassembler::x86_64(&asm.finish().unwrap()),@@ -473,7 +475,8 @@ mod tests {] {for opcode in [0x58, 0x59] {// ADDPS/PD and MULPS/PD- let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2, &mut code, &work);for (index, dst) in [1, 9].into_iter().enumerate() {asm.vex(load, 8, 0, VexOperand::Memory(Address::new(RDI, 0)), None);asm.vex(load, 9, 0, VexOperand::Memory(Address::new(RSI, 0)), None);@@ -515,7 +518,8 @@ mod tests {for lhs in [1, 8, 9] {for rhs in [1, 8, 9] {for dst in [1, 8, 9] {- let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2, &mut code, &work);asm.vex(load, 0, 0, VexOperand::Memory(Address::new(RDI, 0)), None);asm.vmovaps_rr(Fpr(lhs), XMM0);if lhs != rhs {@@ -557,7 +561,8 @@ mod tests {for width in [Width::W32, Width::W64] {for op in [BitCount::Lzcnt, BitCount::Tzcnt] {for alias in [false, true] {- let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2);+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut asm = Assembler::with_cpu_features(CpuFeatures::X86_64_V2, &mut code, &work);let dst = if alias { RDI } else { RAX };asm.bit_count(op, width, dst, RDI);asm.mov_rr(Width::W64, RAX, dst);diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rsindex 9963fcf805b..fb7a48b10be 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs@@ -34,7 +34,7 @@ pub const fn needs_stack_probes(size: i32) -> bool {PROBES_STACK && size >= STACK_PROBE_THRESHOLD}-impl Assembler {+impl Assembler<'_> {/// Touches the stack from the address in `top`, which is at most a page below what was touched last, down to the/// address in `bottom`: every page in between, then `bottom` itself. `size` is `top - bottom` if it is known when/// the code is generated, which keeps small ranges from taking a loop. Clobbers `top` and the flags.diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rsindex 0bc4a0d828f..992808a0804 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs@@ -21,9 +21,10 @@ fn indexed(register: Gpr, index: Gpr, scale: Scale, displacement: i32) -> Addres}fn bytes(emit: impl FnOnce(&mut Assembler)) -> Vec<u8> {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);emit(&mut assembler);- assembler.finish().unwrap()+ assembler.finish().unwrap().to_vec()}#[test]@@ -346,14 +347,17 @@ fn branches_stay_within_32_byte_windows() {#[test]fn short_forward_branch_out_of_range_fails() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.jmp_short(label);assembler.nops(127);assembler.bind(label);assert!(assembler.finish().is_ok());- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());++ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.jcc_short(Cond::Equal, label);assembler.nops(128);@@ -363,7 +367,8 @@ fn short_forward_branch_out_of_range_fails() {#[test]fn unbound_label_fails() {- let mut assembler = Assembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut assembler = Assembler::new(&mut code, &work);let label = assembler.new_label();assembler.jmp(label);assert_eq!(assembler.finish(), Err(AsmError::UnboundLabel));@@ -455,7 +460,8 @@ mod macro_assembler {#[test]fn compares_move_with_the_branches_they_fuse_with() {- let mut masm = MacroAssembler::new();+ let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());+ let mut masm = MacroAssembler::new(&mut code, &work);let label = masm.new_label();masm.assembler.nops(26);masm.branch32_imm(Condition::Equal, RAX, 1000, label);@@ -543,7 +549,7 @@ mod macro_assembler {#[test]fn register_sets_are_consistent() {- type M = MacroAssembler;+ type M = MacroAssembler<'static>;assert!(M::ALLOCATABLE_GPRS.intersection(M::SCRATCH_GPRS).is_empty());assert!(M::ALLOCATABLE_FPRS.intersection(M::SCRATCH_FPRS).is_empty());assert!(!M::ALLOCATABLE_GPRS.contains(M::STACK_POINTER));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rsindex e0332cb4e34..af70f362e75 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs@@ -10,7 +10,10 @@//! of line when there is no local free cell or the heap wants to collect//! garbage.+use ak::ZoneVec;+use super::Codegen;+use super::RegisterList;use super::call::ConstantField;use super::slow_path_calls::slow_path_saved_registers;use crate::CompileFailure;@@ -19,6 +22,8 @@ use crate::asm::Condition;use crate::asm::Gpr;use crate::asm::Label;use crate::asm::PortableMacroAssembler;+use crate::ir::BlockId;+use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;use crate::ir::value;@@ -44,7 +49,7 @@ pub(super) enum AllocationCall {}/// The out of line part of an allocation: the runtime call.-pub(super) struct DeferredAllocation {+pub(super) struct DeferredAllocation<'a> {node: NodeId,call: AllocationCall,entry: Label,@@ -52,10 +57,10 @@ pub(super) struct DeferredAllocation {/// Constants the fast path stores into the new object's inline named/// properties for `InitializeNamed` nodes, which emit nothing then, as/// (byte offset in the cell, value).- constant_fields: Vec<(u32, u64)>,+ constant_fields: &'a [(u32, u64)],}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// `dst` = the value with tag `tag` of the cell pointer `src`, which is/// `src` with what the two differ in flipped: cells are in the heap/// region, which is aligned to its size, so a cell pointer is the@@ -96,7 +101,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {call,entry,resume,- constant_fields: Vec::new(),+ constant_fields: &[],});(entry, resume)}@@ -139,52 +144,58 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// The template, with the shape, the inline capacity and every inline// value undefined. The pointer to the inline storage is stored last.- let mut image = self.snapshot[info.template]- .iter()- .flat_map(|word| word.to_le_bytes())- .take(info.plain_inline_storage_offset as usize)- .collect::<Vec<u8>>();- let shape_offset = info.shape_offset as usize;- image[shape_offset..shape_offset + 4].copy_from_slice(&shape.compressed().to_le_bytes());- image[info.inline_capacity_offset as usize] =- u8::try_from(size_class.inline_capacity).map_err(|_| CompileFailure::CodeGeneration)?;- let mut fields: Vec<ConstantField> = (0u32..)- .zip(image.as_chunks::<8>().0)- .map(|(index, word)| (8 * index, 8, u64::from_le_bytes(*word)))- .filter(|(offset, _, _)| *offset != info.named_properties_offset)- .collect();+ let inline_capacity = u8::try_from(size_class.inline_capacity).map_err(|_| CompileFailure::CodeGeneration)?;+ let mut fields = self.spare_fields.take();+ fields.clear();+ let words = info.plain_inline_storage_offset as usize / 8;+ fields.extend(+ (0u32..)+ .zip(&self.snapshot[info.template][..words])+ .map(|(index, word)| (8 * index, 8, *word)),+ );+ set_field_bytes(+ &mut fields,+ info.shape_offset as usize,+ &shape.compressed().to_le_bytes(),+ );+ set_field_bytes(&mut fields, info.inline_capacity_offset as usize, &[inline_capacity]);+ fields.retain(|(offset, _, _)| *offset != info.named_properties_offset);// NB: Of several initializations of a property, the last one wins.// If it is a constant, the allocation stores it, and none of// them runs; otherwise they all run.- let initialized = self.initializations_without_gc(node);+ let initialized = initializations_without_gc(self.graph, self.block, node);self.inline_initializations- .extend(initialized.iter().map(|(_, initialization, _)| *initialization));- let last_initialization = |index: u32| initialized.iter().rev().find(|(offset, _, _)| *offset == index);+ .extend(initialized.clone().map(|(_, initialization, _)| initialization));+ let last_initialization = |index: u32| initialized.clone().rev().find(|(offset, _, _)| *offset == index);for index in 0..size_class.inline_capacity {let value = match last_initialization(index) {// NB: Stored right after allocating, before anything could// look at the object.Some((_, _, None)) => continue,- Some((_, _, Some(bits))) => *bits,+ Some((_, _, Some(bits))) => bits,None => value::UNDEFINED,};fields.push((info.plain_inline_storage_offset + 8 * index, 8, value));}- let mut constant_fields = Vec::new();- for (offset, initialization, _) in &initialized {- let Some((_, last, Some(bits))) = last_initialization(*offset) else {- continue;- };- self.absorbed_initializations.push(*initialization);- if last == initialization {- constant_fields.push((info.plain_inline_storage_offset + 8 * offset, *bits));- }- }+ let is_absorbed = |offset: u32| matches!(last_initialization(offset), Some((_, _, Some(_))));+ self.absorbed_initializations.extend(+ initialized+ .clone()+ .filter(|(offset, _, _)| is_absorbed(*offset))+ .map(|(_, initialization, _)| initialization),+ );+ let constant_fields =+ self.work+ .alloc_slice_from_iter(initialized.clone().filter_map(|(offset, initialization, _)| {+ let (_, last, bits) = last_initialization(offset)?;+ (last == initialization).then_some((info.plain_inline_storage_offset + 8 * offset, bits?))+ }));self.deferred_allocations.last_mut().expect("the allocation's slow path was deferred").constant_fields = constant_fields;self.emit_constant_fields(cell, next, &mut fields)?;+ self.spare_fields = fields;self.masm.load_effective_address(next, &at(cell, info.plain_inline_storage_offset));self.masm.store64(&at(cell, info.named_properties_offset), next);@@ -196,14 +207,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// Calls the runtime for every allocation node that did not allocate/// inline, saving the registers the call clobbers.pub(super) fn emit_deferred_allocations(&mut self) {- for allocation in std::mem::take(&mut self.deferred_allocations) {+ for allocation in self.deferred_allocations.take() {self.annotate(super::CodeAnnotation::Deferred(allocation.node));let output = self.output(allocation.node);self.masm.bind(allocation.entry);let saved = slow_path_saved_registers::<M>().without(output).iter()- .collect::<Vec<_>>();+ .collect::<RegisterList<_>>();self.emit_save_registers(&saved);let arguments = M::ARGUMENT_GPRS;match allocation.call {@@ -251,7 +262,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.call_absolute(self.runtime.rope_allocation.slow_path);}}- for (offset, bits) in &allocation.constant_fields {+ for (offset, bits) in allocation.constant_fields {self.masm.move_imm64(self.pinned.scratch, *bits);self.masm.store64(&Address::new(M::RETURN_GPRS[0], *offset as i32), self.pinned.scratch);@@ -267,38 +278,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}- /// The `InitializeNamed` nodes right after the `AllocateObject` `node`- /// in its block, before anything that could collect garbage or look at- /// the object (a call, an allocation or an exit): their offsets, and- /// their values if they are constants.- fn initializations_without_gc(&self, node: NodeId) -> Vec<(u32, NodeId, Option<u64>)> {- let body = &self.graph.block(self.block).body;- let position = body- .iter()- .position(|id| *id == node)- .expect("the node is in the block");- let mut initialized = Vec::new();- for id in &body[position + 1..] {- let next = self.graph.node(*id);- match next.op {- Op::InitializeNamed { offset } if next.inputs[0] == node => {- initialized.push((offset, *id, self.graph.constant_value(next.inputs[1])));- }- _ => {- let properties = next.op.properties();- if properties.is_call- || properties.allocates- || next.op.can_eager_exit()- || properties.can_lazy_exit- {- break;- }- }- }- }- initialized- }-/// Stores into a named property of an object being initialized, which/// is a plain data property (see `Op::InitializeNamed`).pub(super) fn emit_initialize_named(&mut self, node: NodeId, offset: u32) -> Result<(), CompileFailure> {@@ -487,32 +466,40 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {);// The array, with its packed elements if it has any.- let mut image = self.snapshot[info.template]- .iter()- .flat_map(|word| word.to_le_bytes())- .collect::<Vec<u8>>();+ let mut fields = self.spare_fields.take();+ fields.clear();+ fields.extend(+ (0u32..)+ .zip(&self.snapshot[info.template])+ .map(|(index, word)| (8 * index, 8, *word)),+ );if count != 0 {- image[layout.object_indexed_storage_kind as usize] = layout.indexed_storage_kind_packed;- let size = layout.object_indexed_array_like_size as usize;- image[size..size + 4].copy_from_slice(&count.to_le_bytes());+ set_field_bytes(+ &mut fields,+ layout.object_indexed_storage_kind as usize,+ &[layout.indexed_storage_kind_packed],+ );+ set_field_bytes(+ &mut fields,+ layout.object_indexed_array_like_size as usize,+ &count.to_le_bytes(),+ );}- let mut fields: Vec<ConstantField> = (0u32..)- .zip(image.as_chunks::<8>().0)- .map(|(index, word)| (8 * index, 8, u64::from_le_bytes(*word)))- .filter(|(offset, _, _)| {- *offset != objects.named_properties_offset && (count == 0 || *offset != layout.object_indexed_elements)- })- .collect();+ fields.retain(|(offset, _, _)| {+ *offset != objects.named_properties_offset && (count == 0 || *offset != layout.object_indexed_elements)+ });self.emit_constant_fields(array, temp, &mut fields)?;self.masm.load_effective_address(temp, &at(array, objects.inline_storage_offset));self.masm.store64(&at(array, objects.named_properties_offset), temp);if let Some(size_class) = storage_size_class {- let mut fields: Vec<ConstantField> = (0u32..)- .zip(&self.snapshot[info.storage_template])- .map(|(index, word)| (8 * index, 8, *word))- .collect();+ fields.clear();+ fields.extend(+ (0u32..)+ .zip(&self.snapshot[info.storage_template])+ .map(|(index, word)| (8 * index, 8, *word)),+ );for index in 0..size_class.capacity {let element = if index < count { value::UNDEFINED } else { value::EMPTY };fields.push((info.storage_values_offset + 8 * index, 8, element));@@ -524,6 +511,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.load_effective_address(temp, &at(storage, info.storage_values_offset));self.masm.store64(&at(array, layout.object_indexed_elements), temp);}+ self.spare_fields = fields;self.box_object(array);self.masm.bind(resume);Ok(())@@ -578,8 +566,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(template.allocator, environment, temp, entry);self.emit_count_allocation(template.cell_size, template.cell_size, temp, false);- let mut fields = template_fields(&self.snapshot[template.words], &stored);+ let mut fields = self.spare_fields.take();+ template_fields(&self.snapshot[template.words], &stored, &mut fields);self.emit_constant_fields(environment, temp, &mut fields)?;+ self.spare_fields = fields;if template.inline_binding_values {self.masm.load_effective_address(temp, &Address::new(environment, super::checked_i32(template_bytes)?));@@ -649,8 +639,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(info.allocator, function, temp, entry);self.emit_count_allocation(info.cell_size, info.cell_size, temp, false);- let mut fields = template_fields(&self.snapshot[closure.words], &stored);+ let mut fields = self.spare_fields.take();+ template_fields(&self.snapshot[closure.words], &stored, &mut fields);self.emit_constant_fields(function, temp, &mut fields)?;+ self.spare_fields = fields;self.masm.load_effective_address(temp, &at(function, objects.inline_storage_offset));self.masm.store64(&at(function, objects.named_properties_offset), temp);@@ -665,6 +657,55 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}+/// The `InitializeNamed` nodes right after the `AllocateObject` `node` in+/// `block`, before anything that could collect garbage or look at the object+/// (a call, an allocation or an exit): their offsets, and their values if+/// they are constants.+fn initializations_without_gc<'g>(+ graph: &'g Graph<'g>,+ block: BlockId,+ node: NodeId,+) -> impl DoubleEndedIterator<Item = (u32, NodeId, Option<u64>)> + Clone + 'g {+ let body = &graph.block(block).body;+ let position = body+ .iter()+ .position(|id| *id == node)+ .expect("the node is in the block");+ let initialization = move |id: NodeId| {+ let next = graph.node(id);+ match next.op {+ Op::InitializeNamed { offset } if next.inputs[0] == node => {+ Some((offset, id, graph.constant_value(next.inputs[1])))+ }+ _ => None,+ }+ };+ let rest = &body[position + 1..];+ let end = rest+ .iter()+ .position(|id| {+ let properties = graph.node(*id).op.properties();+ initialization(*id).is_none()+ && (properties.is_call+ || properties.allocates+ || graph.node(*id).op.can_eager_exit()+ || properties.can_lazy_exit)+ })+ .unwrap_or(rest.len());+ rest[..end].iter().filter_map(move |id| initialization(*id))+}++/// Writes `bytes` at byte `offset` of the cell whose words `fields` hold, one+/// field of 8 bytes for each word from the first on.+fn set_field_bytes(fields: &mut [ConstantField], offset: usize, bytes: &[u8]) {+ for (index, byte) in bytes.iter().enumerate() {+ let at = offset + index;+ let shift = 8 * (at % 8);+ let word = &mut fields[at / 8].2;+ *word = (*word & !(0xff << shift)) | (u64::from(*byte) << shift);+ }+}+/// Whether the fields at `stored` (offsets and sizes of 4 or 8 bytes), which/// allocation stores itself, are aligned to their sizes and within the first/// `template_bytes` bytes of a cell.@@ -674,16 +715,16 @@ pub(super) fn stored_fields_fit(stored: &[(u32, u32)], template_bytes: u64) -> b})}-/// The constant fields of a cell image `words` without the fields at-/// `stored` (see `stored_fields_fit()`): whole words, and the halves of the-/// words that share theirs with a 4-byte stored field.-pub(super) fn template_fields(words: &[u64], stored: &[(u32, u32)]) -> Vec<ConstantField> {+/// Makes `fields` the constant fields of a cell image `words` without the+/// fields at `stored` (see `stored_fields_fit()`): whole words, and the+/// halves of the words that share theirs with a 4-byte stored field.+pub(super) fn template_fields(words: &[u64], stored: &[(u32, u32)], fields: &mut ZoneVec<'_, ConstantField>) {let is_stored = |offset: u32, size: u32| {stored.iter().any(|&(start, length)| start < offset + size && offset < start + length)};- let mut fields = Vec::with_capacity(words.len());+ fields.clear();for (offset, word) in (0u32..).step_by(8).zip(words) {if !is_stored(offset, 8) {fields.push((offset, 8, *word));@@ -695,5 +736,4 @@ pub(super) fn template_fields(words: &[u64], stored: &[(u32, u32)]) -> Vec<Const}}}- fields}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs b/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rsindex d691811f2e9..295111b7355 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs@@ -9,6 +9,7 @@//! like `%ArrayIteratorPrototype%.next` does.use super::Codegen;+use super::RegisterList;use super::slow_path_calls::slow_path_saved_registers;use crate::asm::Address;use crate::asm::Condition;@@ -18,14 +19,14 @@ use crate::asm::PortableMacroAssembler;use crate::ir::NodeId;use crate::ir::value;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// `OpenArrayIteration`: calls `RuntimeInfo::open_array_iteration`.pub(in crate::codegen) fn emit_open_array_iteration(&mut self, node: NodeId) {let (iterable, output) = (self.input(node, 0), self.output(node));let saved = slow_path_saved_registers::<M>().without(output).iter()- .collect::<Vec<_>>();+ .collect::<RegisterList<_>>();self.emit_save_registers(&saved);self.masm.move64(M::ARGUMENT_GPRS[1], iterable);self.masm.move64(M::ARGUMENT_GPRS[0], self.pinned.vm);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rsindex f0c19001b8b..1a5027e2e31 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs@@ -7,6 +7,7 @@//! Lowering of the array ops that `Array.prototype.push` of one value is//! built from, the way its own fast path for packed arrays appends.+use super::RegisterList;use super::slow_path_calls::slow_path_saved_registers;use super::{Codegen, InputValue};use crate::asm::Address;@@ -18,7 +19,7 @@ use crate::asm::Scale;use crate::ir::NodeId;use crate::snapshot::CellId;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Calls the splice helper with the inserted values on the native/// stack. The receiver, start and delete count are in argument registers;/// store the other inputs before setting up the remaining arguments.@@ -264,7 +265,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let saved = slow_path_saved_registers::<M>().without(output).iter()- .collect::<Vec<_>>();+ .collect::<RegisterList<_>>();self.emit_save_registers(&saved);// NB: Either may be in the other's argument register.let arguments: [Gpr; 2] = [M::ARGUMENT_GPRS[0], M::ARGUMENT_GPRS[1]];@@ -279,7 +280,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// `CallStoreHoleyElement`: calls `RuntimeInfo::store_holey_element`,/// saving the registers the call clobbers.pub(in crate::codegen) fn emit_call_store_holey_element(&mut self, node: NodeId) {- let saved = slow_path_saved_registers::<M>().iter().collect::<Vec<_>>();+ let saved = slow_path_saved_registers::<M>().iter().collect::<RegisterList<_>>();self.emit_save_registers(&saved);// NB: The inputs may be in each other's argument registers, which the saves area holds the values of.for (input, argument) in M::ARGUMENT_GPRS.iter().take(3).enumerate() {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex 0f60b726524..a9cf9d7b57d 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -25,7 +25,10 @@//! interpreter's `Call` fast path builds for raw native functions, and lets//! the runtime unwind the frame if the function throws.+use ak::ZoneVec;+use super::Codegen;+use super::RegisterList;use crate::CompileFailure;use crate::asm::Address;use crate::asm::Condition;@@ -40,7 +43,6 @@ use crate::bytecode::THIS_VALUE_REGISTER;use crate::code::INLINED_CALL_SITE_BIT;use crate::code::JitStatus;use crate::code::SiteKind;-use crate::inline_vec::InlineVec;use crate::ir::AccessorPart;use crate::ir::NodeId;use crate::ir::Op;@@ -67,7 +69,7 @@ pub const DIRECT_CALL_TEMPS: u8 = 3;/// Where a call finds one of its operands.#[derive(Debug, Clone, Copy)]-enum CallOperand {+pub(super) enum CallOperand {/// The frame slot of a bytecode operand.Slot(crate::bytecode::Operand),/// A register: an input of the call's node, or a value loaded already.@@ -88,11 +90,11 @@ struct JsCall<'a> {arguments: &'a [Operand],/// The registers of the operands, for a `CallDirect` node that has them/// as inputs.- input_registers: Option<Vec<Gpr>>,+ input_registers: Option<RegisterList<Gpr>>,site: Option<InlinedCallSite>,callee_operand: CallOperand,this_operand: CallOperand,- argument_operands: Vec<CallOperand>,+ argument_operands: ZoneVec<'a, CallOperand>,/// The registers a direct call builds the callee's frame with.callee_frame: Gpr,temp: Gpr,@@ -150,7 +152,7 @@ struct FrameHeaderConstants {returns_to_native_caller: bool,}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {fn boxed_object(&self, cell: CellId) -> u64 {(u64::from(value::OBJECT_TAG) << 48) | (cell.0 & self.runtime.heap_region_offset_mask)}@@ -189,9 +191,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}).ok_or(invalid("direct call without a target"))?;if self.stores_operands(node) {- let mut operands = Vec::new();+ let mut operands = self.spare_operands.take();+ operands.clear();crate::builder::js_call_operands(decoded.instruction).for_each_input(|operand| operands.push(operand));self.emit_store_operand_inputs(node, &operands, registers)?;+ self.spare_operands = operands;}self.emit_js_call(executable, pc, Some((target, node)), None)}@@ -287,16 +291,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {});}};- let arguments = arguments.iter().copied().map(CallOperand::Slot).collect::<Vec<_>>();+ let mut operands = self.spare_call_operands.take();+ operands.clear();+ operands.extend(arguments.iter().copied().map(CallOperand::Slot));self.emit_call_stub_call(callee,new_target,- &arguments,+ &operands,pc,next_pc,dst.raw(),self.runtime.construct_stub,)?;+ self.spare_call_operands = operands;self.emit_continuation_check(next_pc, &[]);Ok(())}@@ -357,58 +364,51 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.map(|(_, node)| {(0..self.graph.node(node).inputs.len()).map(|index| self.input(node, index))- .collect::<Vec<_>>()+ .collect::<RegisterList<_>>()}).filter(|inputs| !inputs.is_empty());let site = match target {Some((_, node)) => self.inlined_call_site(node),None => None,};- let (callee_operand, this_operand, argument_operands, [callee_frame, temp, aux]) =- match (&input_registers, target) {- (Some(inputs), Some((_, node))) => {- // NB: Calls take `this` even where their target does not- // read it, for their slow paths.- let this_operand = CallOperand::Register(inputs[1]);- let argument_operands = inputs[2..]- .iter()- .map(|register| CallOperand::Register(*register))- .collect::<Vec<_>>();- if argument_operands.len() != arguments.len() {- return Err(invalid("direct call with the wrong number of inputs"));- }- let temps = [self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)];- (CallOperand::Register(inputs[0]), this_operand, argument_operands, temps)+ let mut argument_operands = self.spare_call_operands.take();+ argument_operands.clear();+ let (callee_operand, this_operand, [callee_frame, temp, aux]) = match (&input_registers, target) {+ (Some(inputs), Some((_, node))) => {+ // NB: Calls take `this` even where their target does not+ // read it, for their slow paths.+ let this_operand = CallOperand::Register(inputs[1]);+ argument_operands.extend(inputs[2..].iter().map(|register| CallOperand::Register(*register)));+ if argument_operands.len() != arguments.len() {+ return Err(invalid("direct call with the wrong number of inputs"));}- _ => {- // What the called function gets: the `this` value and the- // arguments, which `Function.prototype.call` takes from its- // own arguments.- let (this_operand, argument_operands) = match call_function {- Some(_) => (- arguments- .first()- .map_or(CallOperand::Undefined, |operand| CallOperand::Slot(*operand)),- arguments- .iter()- .skip(1)- .map(|operand| CallOperand::Slot(*operand))- .collect(),- ),- None => (- CallOperand::Slot(this_value),- arguments.iter().map(|operand| CallOperand::Slot(*operand)).collect(),- ),- };- // NB: The callee is loaded into the second register.- (- CallOperand::Register(registers[2]),- this_operand,- argument_operands,- [registers[1], registers[2], registers[4]],- )- }- };+ let temps = [self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)];+ (CallOperand::Register(inputs[0]), this_operand, temps)+ }+ _ => {+ // What the called function gets: the `this` value and the+ // arguments, which `Function.prototype.call` takes from its+ // own arguments.+ let this_operand = match call_function {+ Some(_) => {+ argument_operands.extend(arguments.iter().skip(1).map(|operand| CallOperand::Slot(*operand)));+ arguments+ .first()+ .map_or(CallOperand::Undefined, |operand| CallOperand::Slot(*operand))+ }+ None => {+ argument_operands.extend(arguments.iter().map(|operand| CallOperand::Slot(*operand)));+ CallOperand::Slot(this_value)+ }+ };+ // NB: The callee is loaded into the second register.+ (+ CallOperand::Register(registers[2]),+ this_operand,+ [registers[1], registers[2], registers[4]],+ )+ }+ };let argument_count = u32::try_from(argument_operands.len()).map_err(|_| invalid("too many arguments"))?;let slow = self.masm.new_label();let dynamic_call = if runtime.dynamic_calls.call_stub != 0 {@@ -457,12 +457,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}let Some((target, target_node)) = target else {- return self.emit_js_call_fallbacks(&call, None);+ let result = self.emit_js_call_fallbacks(&call, None);+ self.spare_call_operands = call.argument_operands;+ return result;};self.emit_direct_call_frame(&call, target, target_node)?;let returned = self.emit_direct_call_entry(&call, target, target_node)?;self.emit_js_call_fallbacks(&call, Some(target_node))?;self.masm.bind(returned);+ self.spare_call_operands = call.argument_operands;Ok(())}@@ -632,12 +635,17 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {dst: dst.raw(),returns_to_native_caller: true,};- let mut constants = self.frame_header_constants(&FrameHeaderConstants {- passed_argument_count: header.passed_argument_count,- return_pc: header.return_pc,- dst: header.dst,- returns_to_native_caller: header.returns_to_native_caller,- });+ let mut constants = self.spare_fields.take();+ constants.clear();+ self.frame_header_constants(+ &FrameHeaderConstants {+ passed_argument_count: header.passed_argument_count,+ return_pc: header.return_pc,+ dst: header.dst,+ returns_to_native_caller: header.returns_to_native_caller,+ },+ &mut constants,+ );let fields = target.function_fields;constants.extend([(offsets.execution_context_function, 8, function.function.0),@@ -670,22 +678,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {for index in argument_count..formal_count {constants.push((slot(arguments_base + index), 8, value::UNDEFINED));}- let mut overwritten = vec![offsets.execution_context_caller_frame];- if function.uses_this {- overwritten.extend([offsets.execution_context_this_value, slot(THIS_VALUE_REGISTER)]);- }- if environment.is_some() || target.closures {- overwritten.extend([- offsets.execution_context_lexical_environment,- offsets.execution_context_variable_environment,- ]);- }- if target.closures {- overwritten.extend([- offsets.execution_context_function,- offsets.execution_context_private_environment,- ]);- }+ let environments = environment.is_some() || target.closures;+ let overwritten = [+ Some(offsets.execution_context_caller_frame),+ function.uses_this.then_some(offsets.execution_context_this_value),+ function.uses_this.then_some(slot(THIS_VALUE_REGISTER)),+ environments.then_some(offsets.execution_context_lexical_environment),+ environments.then_some(offsets.execution_context_variable_environment),+ target.closures.then_some(offsets.execution_context_function),+ target.closures.then_some(offsets.execution_context_private_environment),+ ]+ .into_iter()+ .flatten()+ .collect::<RegisterList<u32>>();self.emit_constant_fields_with_vector(callee_frame,temp,@@ -693,6 +698,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Some(M::ARGUMENT_FPRS[0]),&overwritten,)?;+ self.spare_fields = constants;self.masm.store64(&field(offsets.execution_context_caller_frame), frame);if site.is_some() {self.emit_store_inlined_call_frame_pointer(&field(offsets.execution_context_caller_dst_raw));@@ -831,22 +837,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let (slow, check, done, dynamic_call) = (call.slow, call.check, call.done, call.dynamic_call);// The generic call, which the call stub also falls back to, reads// its operands from the frame.- let operand_slots = [(callee, callee_operand), (this_value, this_operand)]- .into_iter()- .chain(arguments.iter().copied().zip(argument_operands.iter().copied()))- .filter_map(|(operand, source)| match source {- CallOperand::Register(register) if input_registers.is_some() => Some((operand, register)),- _ => None,- })- .collect::<Vec<_>>();+ let operand_slots = || {+ [(callee, callee_operand), (this_value, this_operand)]+ .into_iter()+ .chain(arguments.iter().copied().zip(argument_operands.iter().copied()))+ .filter_map(|(operand, source)| match source {+ CallOperand::Register(register) if input_registers.is_some() => Some((operand, register)),+ _ => None,+ })+ };let store_operands = |codegen: &mut Self| -> Result<(), CompileFailure> {- for (operand, register) in &operand_slots {+ for (operand, register) in operand_slots() {let address = codegen.slot_address(operand.raw())?;- codegen.masm.store64(&address, *register);+ codegen.masm.store64(&address, register);}Ok(())};- let inputs = input_registers.clone().unwrap_or_default();+ let inputs = input_registers.unwrap_or_default();if call_stub != 0 {// The call stub makes every other call.self.masm.bind(dynamic_call);@@ -898,15 +905,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {_ => return None,};let frame_state = self.graph.node(node).frame_state.expect("calls have a frame state");- let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();- let outer = *chain.last().expect("a frame state chain has a frame state");+ let depth = self.graph.frame_state_chain(frame_state).count() - 1;+ let outer = self+ .graph+ .frame_state_chain(frame_state)+ .last()+ .expect("a frame state chain has a frame state");let index = u32::try_from(self.sites.len()).expect("site count fits in u32");self.sites.push((node, SiteKind::Call));Some(InlinedCallSite {index,outer_pc: self.graph.frame_state(outer).pc,frame_bytes,- depth: chain.len() - 1,+ depth,})}@@ -987,16 +998,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(template.allocator, cell, temp, no_room);self.emit_count_allocation(template.cell_size, template.cell_size, temp, false);- let mut overwritten = vec![template.binding_values_offset];- if template.binds_this {- overwritten.push(template.this_value_offset);- }- let mut fields: Vec<ConstantField> = (0u32..)- .zip(&self.snapshot[template.words])- .map(|(index, word)| (8 * index, 8, *word))- .filter(|(offset, _, _)| !overwritten.contains(offset))- .collect();+ let overwritten = [+ Some(template.binding_values_offset),+ template.binds_this.then_some(template.this_value_offset),+ ];+ let mut fields = self.spare_fields.take();+ fields.clear();+ fields.extend(+ (0u32..)+ .zip(&self.snapshot[template.words])+ .map(|(index, word)| (8 * index, 8, *word))+ .filter(|(offset, _, _)| !overwritten.contains(&Some(*offset))),+ );self.emit_constant_fields_with_vector(cell, temp, &mut fields, Some(M::ARGUMENT_FPRS[0]), &[])?;+ self.spare_fields = fields;if template.inline_binding_values {self.masm.load_effective_address(temp, &Address::new(cell, super::checked_i32(template_bytes)?));@@ -1130,8 +1145,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let invalid = |reason| CompileFailure::InvalidBytecode { pc, reason };let snapshot = &self.snapshot.executables[executable as usize];let decoded = self.decoded(executable, pc)?;- let mut stored_operands = Vec::new();- crate::builder::js_call_operands(decoded.instruction).for_each_input(|operand| stored_operands.push(operand));let next_pc = decoded.next_pc();let Instruction::Call {call_feedback,@@ -1153,36 +1166,37 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let registers = M::ARGUMENT_GPRS;if self.stores_operands(node) {+ let mut stored_operands = self.spare_operands.take();+ stored_operands.clear();+ crate::builder::js_call_operands(decoded.instruction)+ .for_each_input(|operand| stored_operands.push(operand));self.emit_store_operand_inputs(node, &stored_operands, input_registers)?;+ self.spare_operands = stored_operands;}let inputs = if self.stores_operands(node) {- Vec::new()+ RegisterList::new()} else {(0..self.graph.node(node).inputs.len()).map(|index| self.input(node, index))- .collect::<Vec<_>>()+ .collect::<RegisterList<_>>()};- let (callee_operand, this_operand, argument_operands, temps) = if inputs.is_empty() {+ let mut argument_operands = self.spare_call_operands.take();+ argument_operands.clear();+ let (callee_operand, this_operand, temps) = if inputs.is_empty() {+ argument_operands.extend(arguments.iter().map(|operand| CallOperand::Slot(*operand)));(CallOperand::Slot(callee),CallOperand::Slot(this_value),- arguments- .iter()- .map(|operand| CallOperand::Slot(*operand))- .collect::<Vec<_>>(),[registers[1], registers[2], registers[3]],)} else {if inputs.len() != 2 + arguments.len() {return Err(invalid("native call with the wrong number of inputs"));}+ argument_operands.extend(inputs[2..].iter().map(|register| CallOperand::Register(*register)));(CallOperand::Register(inputs[0]),CallOperand::Register(inputs[1]),- inputs[2..]- .iter()- .map(|register| CallOperand::Register(*register))- .collect(),[self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)],)};@@ -1226,6 +1240,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Some(slow),[check, done],)?;+ self.spare_call_operands = argument_operands;// The generic call reads its operands from the frame.self.masm.bind(slow);@@ -1262,12 +1277,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let invalid = |reason| CompileFailure::InvalidBytecode { pc, reason };let decoded = self.decoded(0, pc)?;let next_pc = decoded.next_pc();- let (dst, arguments) = match (part, decoded.instruction) {+ let (dst, argument) = match (part, decoded.instruction) {(AccessorPart::Getter, Instruction::GetById { dst, .. } | Instruction::GetLength { dst, .. }) => {- (Some(dst), Vec::new())+ (Some(dst), None)}(AccessorPart::Setter, Instruction::PutById { .. }) => {- (None, vec![CallOperand::Register(self.input(node, 1))])+ (None, Some(CallOperand::Register(self.input(node, 1))))}_ => return Err(invalid("native accessor call of another instruction")),};@@ -1290,7 +1305,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_native_frame_call(target,this_operand,- &arguments,+ argument.as_slice(),next_pc,None,None,@@ -1464,7 +1479,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// NB: Frames get their id when the debugger first needs it.self.masm.store_imm64(&field(offsets.execution_context_frame_id), 0);self.masm.store64(&field(offsets.execution_context_caller_frame), frame);- let mut constants = self.new_frame_constants(false);+ let mut constants = self.spare_fields.take();+ constants.clear();+ constants.extend(self.new_frame_constants(false));constants.extend([(offsets.execution_context_script_or_module, 8, 0),(offsets.execution_context_executable, 8, 0),@@ -1489,6 +1506,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {constants.push((offsets.execution_context_function, 8, target.function.0));constants.push((offsets.execution_context_realm, 8, target.realm.0));self.emit_constant_fields(native_frame, temp, &mut constants)?;+ self.spare_fields = constants;if site.is_some() {self.emit_store_inlined_call_frame_pointer(&field(offsets.execution_context_caller_dst_raw));}@@ -1553,7 +1571,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// Stores the header fields of a new frame at `new_frame` (allocated on/// the interpreter stack) that come from the function object and the VM,/// linked to the running frame like the interpreter's inline calls do,- /// and returns the constant ones for `emit_constant_fields()`. Its `this`+ /// and adds the constant ones to `constants`, for `emit_constant_fields()`. Its `this`/// value and slots are left to the caller. Clobbers `function_register`/// and `temp`. The fields come from snapshot executable `executable`,/// the entry of the frame's own function: closures that share one@@ -1565,12 +1583,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {function_register: Gpr,temp: Gpr,header: &FrameHeader,- ) -> Vec<ConstantField> {+ constants: &mut ZoneVec<'_, ConstantField>,+ ) {let offsets = self.runtime.offsets;let snapshot = &self.snapshot.executables[executable as usize];let function_fields = snapshot.function_fields;let builtin = snapshot.builtin;- let mut constants = Vec::new();if builtin {// NB: Frames of builtins written in JavaScript have the// environments of their caller, the running frame, and no@@ -1616,20 +1634,22 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.move_imm64(function_register, header.function.function.0);self.emit_function_fields(new_frame, function_register, temp);}- constants.extend(self.frame_header_field_constants(header));- constants+ self.frame_header_field_constants(header, constants);}- /// The constant fields of a new frame that do not depend on its- /// function object, apart from its realm.- fn frame_header_field_constants(&self, header: &FrameHeader) -> Vec<ConstantField> {+ /// Adds to `constants` the constant fields of a new frame that do not+ /// depend on its function object, apart from its realm.+ fn frame_header_field_constants(&self, header: &FrameHeader, constants: &mut ZoneVec<'_, ConstantField>) {let offsets = self.runtime.offsets;- let mut constants = self.frame_header_constants(&FrameHeaderConstants {- passed_argument_count: header.passed_argument_count,- return_pc: header.return_pc,- dst: header.dst,- returns_to_native_caller: header.returns_to_native_caller,- });+ self.frame_header_constants(+ &FrameHeaderConstants {+ passed_argument_count: header.passed_argument_count,+ return_pc: header.return_pc,+ dst: header.dst,+ returns_to_native_caller: header.returns_to_native_caller,+ },+ constants,+ );constants.extend([(offsets.execution_context_realm, 8, header.function.realm.0),(offsets.execution_context_executable, 8, header.executable.0),@@ -1640,7 +1660,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {u64::from(header.argument_count),),]);- constants}/// Stores the fields of a new frame that come from its function (whose@@ -1679,9 +1698,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// not initialized, and whether its caller waits for it in native code/// (and so runs it in JIT code until the runtime finishes it, see/// `finish_direct_call`).- pub(super) fn new_frame_constants(&self, returns_to_native_caller: bool) -> Vec<ConstantField> {+ pub(super) fn new_frame_constants(&self, returns_to_native_caller: bool) -> [ConstantField; 11] {let offsets = self.runtime.offsets;- vec![+ [(offsets.execution_context_program_counter, 4, 0),(offsets.execution_context_skip_when_determining_incumbent_counter, 4, 0),(@@ -1708,10 +1727,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {]}- /// The constant fields of a new frame that do not depend on its function.- fn frame_header_constants(&self, header: &FrameHeaderConstants) -> Vec<ConstantField> {+ /// Adds to `constants` the constant fields of a new frame that do not depend on its function.+ fn frame_header_constants(&self, header: &FrameHeaderConstants, constants: &mut ZoneVec<'_, ConstantField>) {let offsets = self.runtime.offsets;- let mut constants = self.new_frame_constants(header.returns_to_native_caller);+ constants.extend(self.new_frame_constants(header.returns_to_native_caller));constants.extend([(offsets.execution_context_passed_argument_count,@@ -1725,7 +1744,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {),(offsets.execution_context_caller_dst_raw, 4, u64::from(header.dst)),]);- constants}/// Materializes the frame of an inlined call of the@@ -1782,16 +1800,18 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {dst,returns_to_native_caller: false,};- let mut constants = match closure {+ let mut constants = self.spare_fields.take();+ constants.clear();+ match closure {Some(closure) => {self.emit_function_fields(new_frame, closure, temp);- self.frame_header_field_constants(&header)+ self.frame_header_field_constants(&header, &mut constants);}- None => self.emit_frame_header(executable, new_frame, function_register, temp, &header),- };+ None => self.emit_frame_header(executable, new_frame, function_register, temp, &header, &mut constants),+ }if let Some(new_target) = construct_new_target {let new_target = self.boxed_object(new_target);- for field in &mut constants {+ for field in &mut *constants {if field.0 == offsets.execution_context_caller_is_construct {field.2 = 1;} else if field.0 == offsets.execution_context_new_target {@@ -1818,6 +1838,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {constants.push((slot(arguments_base + index), 8, value::UNDEFINED));}self.emit_constant_fields(new_frame, temp, &mut constants)?;+ self.spare_fields = constants;self.masm.store64(&vm_field(offsets.vm_running_execution_context), new_frame);// Frame slots now address the new frame.@@ -1872,9 +1893,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let mut held = None;let mut held_vector = None;let mut next_field = 0;+ let mut bytes = self.spare_bytes.take();while next_field < fields.len() {let start = fields[next_field].0;- let mut bytes = InlineVec::<u8, 128>::new();+ bytes.clear();while let Some(&(offset, size, bits)) = fields.get(next_field) {if start + bytes.len() as u32 != offset {break;@@ -1955,6 +1977,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {index += size;}}+ self.spare_bytes = bytes;Ok(())}}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 524e300e7d4..e956fd9dd99 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -26,8 +26,13 @@//! returns a slow path control word: a continuation at the next pc once the//! result is in the destination slot, or what the runtime returned.+use ak::Column;+use ak::ZoneVec;+use super::Codegen;use super::Locals;+use super::STUB_CODE_LIMIT;+use super::STUB_ZONE_LIMIT;use super::target_registers;use crate::CompileFailure;use crate::asm::Address;@@ -48,6 +53,8 @@ use crate::regalloc::Allocation;use crate::snapshot::COMPRESSED_POINTER_SHIFT;use crate::snapshot::RuntimeInfo;use crate::snapshot::Snapshot;+use ak::ZoneMap;+use ak::ZoneSet;/// Where the stub keeps its inputs and what must survive calls into the/// runtime and the callee, relative to the stack pointer.@@ -70,7 +77,9 @@ mod local {/// Generates the call stub, or nothing if the runtime lacks a helper it/// needs (then JIT code makes those calls through `RuntimeInfo::jit_call`).-pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> Result<Option<Vec<u8>>, CompileFailure> {+pub fn generate_call_stub<M: PortableMacroAssembler>(+ runtime: &RuntimeInfo,+) -> Result<Option<Column<u8>>, CompileFailure> {let layout = runtime.dynamic_calls;if layout.object_flag_is_ecmascript_function == 0 || runtime.jit_call == 0 || runtime.finish_direct_call == 0 {return Ok(None);@@ -83,7 +92,7 @@ pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> R/// constructs through `RuntimeInfo::jit_call`).pub fn generate_construct_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo,-) -> Result<Option<Vec<u8>>, CompileFailure> {+) -> Result<Option<Column<u8>>, CompileFailure> {let layout = runtime.dynamic_calls;if layout.object_flag_is_ecmascript_function == 0|| layout.jit_entry_table == 0@@ -100,67 +109,79 @@ pub fn generate_construct_stub<M: PortableMacroAssembler>(/// Generates the code of the call stub, or with `construct` of the construct/// stub (see `Codegen::emit_call_stub()`).-fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bool) -> Result<Vec<u8>, CompileFailure> {- // NB: A stub has no graph to build: the graph stays empty, so its zone gives out nothing and takes no memory.- let zone = ak::Zone::new(0, c"JIT stub graph");+fn generate_stub<M: PortableMacroAssembler>(+ runtime: &RuntimeInfo,+ construct: bool,+) -> Result<Column<u8>, CompileFailure> {+ // NB: A stub has no graph to build: the graph stays empty. The zone holds the lists of the code generator.+ let zone = ak::Zone::new(STUB_ZONE_LIMIT, c"JIT stub");let graph = Graph::new_in(&zone);let allocation = Allocation::new_in(&zone);// NB: A stub is code for no executable. It reads no list of the runtime info.let snapshot = Snapshot::new();let (_, pinned) = target_registers::<M>();- let mut masm = M::new();+ let mut code = Column::new(STUB_CODE_LIMIT, c"JIT stub code");+ let mut masm = M::new(&mut code, &zone);let exit_stub = masm.new_label();let resume = masm.new_label();let exit_interpreter = masm.new_label();- let mut codegen = Codegen {- masm,- graph: &graph,- allocation: &allocation,- snapshot: &snapshot,- work: &zone,- runtime,- stress: crate::snapshot::StressOptions::default(),- pinned,- frame: M::frame(GprSet::EMPTY, FprSet::EMPTY, local::SIZE),- locals: Locals::default(),- gpr_dump_count: 0,- fpr_dump_count: 0,- block_labels: Vec::new(),- landing_blocks: Vec::new(),- exit_stub,- resume,- entry_resume: resume,- entry_overflow: resume,- exit_interpreter,- sites: Vec::new(),- exit_site_stubs: Vec::new(),- annotations: Vec::new(),- block: BlockId(0),- deferred_cache_probes: Vec::new(),- deferred_vm_cache_probes: Vec::new(),- leave_arguments: Vec::new(),- leave_stubs: Vec::new(),- leave_frame: None,- leave_tail: exit_stub,- frame_initialization_stub: None,- slow_path_values: None,- invalidation_points: Vec::new(),- fused_probe_failure: None,- deferred_allocations: Vec::new(),- deferred_storage_growths: Vec::new(),- absorbed_initializations: Vec::new(),- inline_initializations: Default::default(),- // NB: The stub lowers no nodes.- verify: false,- emitting: None,- requested_temps: Vec::new(),- undeclared_saves_area_uses: Default::default(),- };- codegen.emit_call_stub(construct)?;- let (code, _) = codegen- .masm- .finish_with_data_offset()- .map_err(|_| CompileFailure::CodeGeneration)?;+ {+ let mut codegen = Codegen::<M> {+ masm,+ graph: &graph,+ allocation: &allocation,+ snapshot: &snapshot,+ work: &zone,+ decoded_instructions: ZoneMap::new_in(&zone),+ runtime,+ stress: crate::snapshot::StressOptions::default(),+ pinned,+ frame: M::frame(GprSet::EMPTY, FprSet::EMPTY, local::SIZE),+ locals: Locals::default(),+ gpr_dump_count: 0,+ fpr_dump_count: 0,+ block_labels: &[],+ landing_blocks: &[],+ exit_stub,+ resume,+ entry_resume: resume,+ entry_overflow: resume,+ exit_interpreter,+ sites: ZoneVec::new_in(&zone),+ exit_site_stubs: ZoneVec::new_in(&zone),+ annotations: ZoneVec::new_in(&zone),+ block: BlockId(0),+ deferred_cache_probes: ZoneVec::new_in(&zone),+ deferred_vm_cache_probes: ZoneVec::new_in(&zone),+ leave_arguments: ZoneVec::new_in(&zone),+ leave_stubs: ZoneVec::new_in(&zone),+ leave_frame: None,+ leave_tail: exit_stub,+ frame_initialization_stub: None,+ slow_path_values: None,+ input_of_operand: ZoneMap::new_in(&zone),+ slow_path_ssa_outputs: ZoneVec::new_in(&zone),+ spare_operands: ZoneVec::new_in(&zone),+ spare_outputs: ZoneVec::new_in(&zone),+ spare_call_operands: ZoneVec::new_in(&zone),+ spare_fields: ZoneVec::new_in(&zone),+ spare_frame_values: ZoneVec::new_in(&zone),+ spare_bytes: ZoneVec::new_in(&zone),+ invalidation_points: ZoneVec::new_in(&zone),+ fused_probe_failure: None,+ deferred_allocations: ZoneVec::new_in(&zone),+ deferred_storage_growths: ZoneVec::new_in(&zone),+ absorbed_initializations: ZoneVec::new_in(&zone),+ inline_initializations: ZoneSet::new_in(&zone),+ // NB: The stub lowers no nodes.+ verify: false,+ emitting: None,+ requested_temps: &[],+ undeclared_saves_area_uses: std::cell::RefCell::new(ZoneVec::new_in(&zone)),+ };+ codegen.emit_call_stub(construct)?;+ codegen.masm.finish().map_err(super::assembly_failure)?;+ }Ok(code)}@@ -175,7 +196,7 @@ struct StubCallEnvironmentRegisters {cell: Gpr,}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Allocates the function environment of a call of the callee inline from/// its shared data's call environment template (see/// `DynamicCallLayout::shared_data_call_environment_template`), and keeps@@ -634,11 +655,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.store64(&field(offsets.execution_context_this_value), receiver);self.masm.store64(&field(slot(THIS_VALUE_REGISTER)), receiver);- let mut constants = self.emit_stub_call_site_fields(callee_frame, scratch, true);+ let mut constants = self.spare_fields.take();+ constants.clear();+ constants.extend(self.emit_stub_call_site_fields(callee_frame, scratch, true));for register in (0..RESERVED_REGISTER_COUNT).filter(|register| *register != THIS_VALUE_REGISTER) {constants.push((slot(register), 8, value::EMPTY));}self.emit_constant_fields_with_vector(callee_frame, scratch, &mut constants, Some(M::ARGUMENT_FPRS[0]), &[])?;+ self.spare_fields = constants;if construct {// The frame of a constructor has its new target, and that of a// derived constructor its this value, empty until super() binds@@ -913,7 +937,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {new_frame: crate::asm::Gpr,temp: crate::asm::Gpr,ecmascript: bool,- ) -> Vec<super::call::ConstantField> {+ ) -> [super::call::ConstantField; 11] {let offsets = self.runtime.offsets;let field = |offset: u32| Address::new(new_frame, offset as i32);let argument_count_local = self.stub_local(local::ARGUMENT_COUNT);@@ -1060,12 +1084,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.store32(&field(offsets.execution_context_slot_count), count);self.masm.store32(&field(offsets.execution_context_argument_count), count);- let mut constants = self.emit_stub_call_site_fields(native_frame, temp, false);+ let mut constants = self.spare_fields.take();+ constants.clear();+ constants.extend(self.emit_stub_call_site_fields(native_frame, temp, false));constants.extend([(offsets.execution_context_script_or_module, 8, 0),(offsets.execution_context_executable, 8, 0),]);self.emit_constant_fields_with_vector(native_frame, temp, &mut constants, Some(M::ARGUMENT_FPRS[0]), &[])?;+ self.spare_fields = constants;self.masm.load_effective_address(other,&Address::new(native_frame, offsets.execution_context_slots as i32),diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rsindex c7689c349d7..e8ebf8d8a3d 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs@@ -30,7 +30,7 @@ use crate::ir::NodeId;use crate::ir::value;use crate::snapshot::RopeAllocationInfo;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// `ConcatenateStrings`: the concatenation of two strings, or the empty/// value, as the key of a property access if `key`. Needs three temps.pub(in crate::codegen) fn emit_concatenate_strings(&mut self, node: NodeId, key: bool) {@@ -189,9 +189,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(rope.allocator, cell, other, no_free_cell);self.emit_count_allocation(rope.cell_size, rope.cell_size, other, false);- let mut fields = template_fields(&self.snapshot[rope.template], &rope_stored_fields(&rope));+ let mut fields = self.spare_fields.take();+ template_fields(&self.snapshot[rope.template], &rope_stored_fields(&rope), &mut fields);self.emit_constant_fields(cell, other, &mut fields).expect("rope string fields are near the cell");+ self.spare_fields = fields;self.masm.store32(&string_length(cell), length);// NB: The halves are compressed from their string values, whose tag// the 32-bit stores drop.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/elements.rs b/Libraries/LibJS/JIT/Rust/src/codegen/elements.rsindex f2ae48448e8..27b5d039a0a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/elements.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/elements.rs@@ -30,7 +30,7 @@ pub(super) fn scale(element: TypedArrayElement) -> Scale {}}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// The `TypedArrayBase::Kind` value of `element`.pub(super) fn typed_array_kind_value(&self, element: TypedArrayElement) -> u8 {let layout = &self.runtime.layout;diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/entry.rs b/Libraries/LibJS/JIT/Rust/src/codegen/entry.rsindex e7761851285..98e81b64762 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/entry.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/entry.rs@@ -14,6 +14,11 @@//! `JitResult trampoline(VM*, ExecutionContext* frame, entry)`, whose result//! is the entry's.+use ak::Column;+use ak::Zone;++use super::STUB_CODE_LIMIT;+use super::STUB_ZONE_LIMIT;use super::target_registers;use crate::CompileFailure;use crate::asm::FprSet;@@ -21,18 +26,18 @@ use crate::asm::GprSet;use crate::asm::PortableMacroAssembler;/// Generates the entry trampoline.-pub fn generate_entry_trampoline<M: PortableMacroAssembler>() -> Result<Vec<u8>, CompileFailure> {+pub fn generate_entry_trampoline<M: PortableMacroAssembler>() -> Result<Column<u8>, CompileFailure> {let (_, pinned) = target_registers::<M>();let arguments = M::ARGUMENT_GPRS;let frame = M::frame(GprSet::EMPTY.with(pinned.vm).with(pinned.scratch), FprSet::EMPTY, 0);- let mut masm = M::new();+ let work = Zone::new(STUB_ZONE_LIMIT, c"JIT entry trampoline");+ let mut code = Column::new(STUB_CODE_LIMIT, c"JIT entry trampoline code");+ let mut masm = M::new(&mut code, &work);masm.emit_prologue(&frame);masm.move64(pinned.vm, arguments[0]);masm.call_register(arguments[2]);masm.emit_epilogue(&frame);masm.ret();- let (code, _) = masm- .finish_with_data_offset()- .map_err(|_| CompileFailure::CodeGeneration)?;+ masm.finish().map_err(super::assembly_failure)?;Ok(code)}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rsindex 1fd36b218df..ad3f8b523ce 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs@@ -22,7 +22,7 @@ use crate::asm::Scale;use crate::ir::NodeId;use crate::ir::value;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Branches to `fail` unless binding `index` (a register) of the/// declarative environment `environment` is mutable, like the/// interpreter's `load_binding_flag`. Clobbers `temp` and the scratchdiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs b/Libraries/LibJS/JIT/Rust/src/codegen/float64.rsindex d746431c366..b8337ce2674 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs@@ -25,7 +25,7 @@ use crate::ir::value;const SIGN_BIT: u64 = 1 << 63;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// `UnboxDouble`: the double of a tagged double, its bits.pub(in crate::codegen) fn emit_unbox_double(&mut self, node: NodeId) {let (input, output) = (self.input(node, 0), self.float_output(node));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rsindex eebb3a28311..e6b40e842bd 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs@@ -589,7 +589,7 @@ fn slow_path_record(opcode: crate::bytecode::OpCode, on_values: bool) -> Record}}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Temp `index` of `node`, which its lowering declares (see `LoweringInfo::temps`). Lowerings take every temp/// they declare through this, even on paths that do not use it, so that the declarations can be checked.pub(super) fn temp(&self, node: NodeId, index: usize) -> Gpr {@@ -611,13 +611,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// Checks that the lowering of every node took exactly the temps it declares, and that only nodes that declare/// it used the saves area, whose size depends on that.pub(super) fn verify_lowerings(&self) -> Result<(), String> {- let mut errors = Vec::new();+ let mut errors = String::new();+ let mut report = |error: String| {+ if !errors.is_empty() {+ errors.push('\n');+ }+ errors.push_str(&error);+ };for block in 0..self.graph.blocks.len() {for node in self.graph.block_nodes(BlockId::from_index(block)) {let declared = lowering_info(self.graph.node(node)).temps;let requested = self.requested_temps[node.index()].get();if requested != declared {- errors.push(format!(+ report(format!("v{} ({}) takes {requested} temps, but declares {declared}",node.0,self.graph.node(node).op.name()@@ -625,19 +631,18 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}}- let mut undeclared = self.undeclared_saves_area_uses.borrow().clone();- undeclared.dedup();- for node in undeclared {- errors.push(format!(+ let mut previous = None;+ for node in self.undeclared_saves_area_uses.borrow().iter().copied() {+ if previous == Some(node) {+ continue;+ }+ previous = Some(node);+ report(format!("v{} ({}) uses the saves area, but does not declare it",node.0,self.graph.node(node).op.name()));}- if errors.is_empty() {- Ok(())- } else {- Err(errors.join("\n"))- }+ if errors.is_empty() { Ok(()) } else { Err(errors) }}}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 644e29eef67..87eb7b7c10c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -66,6 +66,7 @@ pub use slow_path::slow_path_symbol;use crate::CompileFailure;use crate::artifact::Artifact;+use crate::artifact::ArtifactWriter;use crate::asm::Address;use crate::asm::Architecture;use crate::asm::Condition;@@ -73,6 +74,7 @@ use crate::asm::Fpr;use crate::asm::FprSet;use crate::asm::Gpr;use crate::asm::GprSet;+use crate::asm::JumpPatch;use crate::asm::Label;use crate::asm::MachineFrame;use crate::asm::PortableMacroAssembler;@@ -93,7 +95,6 @@ use crate::code::JitStatus;use crate::code::Repr;use crate::code::SiteKind;use crate::code::ValueLocation;-use crate::fast_hash::{HashMap, HashSet};use crate::ir;use crate::ir::BlockId;use crate::ir::BranchCondition;@@ -109,16 +110,24 @@ use crate::regalloc::Location;use crate::regalloc::Move;use crate::regalloc::RegisterMask;use crate::regalloc::RegisterSet;-use crate::scratch::Tables;use crate::snapshot::COMPRESSED_POINTER_SHIFT;use crate::snapshot::CellId;use crate::snapshot::ExecutableSnapshot;use crate::snapshot::RuntimeInfo;use crate::snapshot::Snapshot;use crate::snapshot::StressOptions;+use ak::Column;use ak::Zone;+use ak::ZoneMap;+use ak::ZoneSet;+use ak::ZoneVec;+use sites::SiteScratch;use sites::SiteSource;+/// The most bytes of code a stub or the entry trampoline has, and of lists its code generator makes.+const STUB_CODE_LIMIT: usize = 1 << 20;+const STUB_ZONE_LIMIT: usize = 1 << 24;+/// Bit 32 of a slow path control word marks a continuation in the same frame.const CONTINUATION_BIT: u64 = 1 << 32;@@ -204,20 +213,65 @@ pub(super) fn register_of(register: u8) -> Register {}}-/// Machine code for one graph, before it becomes `CompiledCode`.-pub struct GeneratedCode {- pub code: Vec<u8>,+/// A list of at most 32 values (one for each register of a class), in an array of its own: the short lists that the+/// code generator makes for a node, mostly of registers, take no memory of a zone.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) struct RegisterList<T> {+ values: [T; 32],+ len: u8,+}++impl<T: Copy + Default> RegisterList<T> {+ pub(super) fn new() -> Self {+ Self {+ values: [T::default(); 32],+ len: 0,+ }+ }++ pub(super) fn push(&mut self, value: T) {+ self.values[usize::from(self.len)] = value;+ self.len += 1;+ }+}++impl<T: Copy + Default> Default for RegisterList<T> {+ fn default() -> Self {+ Self::new()+ }+}++impl<T> core::ops::Deref for RegisterList<T> {+ type Target = [T];++ fn deref(&self) -> &[T] {+ &self.values[..usize::from(self.len)]+ }+}++impl<T: Copy + Default> FromIterator<T> for RegisterList<T> {+ fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {+ let mut list = Self::new();+ for value in values {+ list.push(value);+ }+ list+ }+}++/// Machine code for one graph, before it becomes `CompiledCode`. The code is in the column it was generated into.+pub struct GeneratedCode<'a> {/// Where the instructions end and the constants they load begin.pub data_offset: u32,pub entry_offset: u32,/// What the code from each offset on was generated for, in emission/// order. Only `dump-asm` reads it.- pub annotations: Vec<(u32, CodeAnnotation)>,+ pub annotations: ZoneVec<'a, (u32, CodeAnnotation)>,/// The on-stack replacement entry points, as (back edge pc, code offset).- pub osr_entries: Vec<(u32, u32)>,+ pub osr_entries: ZoneVec<'a, (u32, u32)>,/// What invalidates the code: the bytes to write at each offset (see/// `Op::AssumeValid`).- pub invalidation_patches: Vec<(u32, Vec<u8>)>,+ pub invalidation_patches: ZoneVec<'a, (u32, JumpPatch)>,/// See `CompiledCode::site_index_frame_offset`.pub site_index_frame_offset: i32,/// See `CompiledCode::register_dump_frame_offset`.@@ -269,14 +323,18 @@ struct Locals {spills: u32,}-struct Codegen<'a, M: PortableMacroAssembler> {- masm: M,+/// The code generator of a graph, which keeps its lists in the work zone (`'a`) and writes code with an assembler+/// whose memory lives for `'c`.+struct Codegen<'a, 'c, M: PortableMacroAssembler> {+ masm: M::In<'c>,graph: &'a Graph<'a>,allocation: &'a Allocation<'a>,/// What the graph was built from. Executable 0 is the compiled function.snapshot: &'a Snapshot,- /// Where the instructions that code generation decodes again keep their arrays.+ /// Where the lists of the code generator are.work: &'a Zone,+ /// The instructions that code generation decoded again, by executable and pc, so that each is decoded one time.+ decoded_instructions: ZoneMap<'a, (u32, u32), DecodedInstruction<'a>>,/// The runtime info of the snapshot.runtime: &'a RuntimeInfo,stress: StressOptions,@@ -285,9 +343,9 @@ struct Codegen<'a, M: PortableMacroAssembler> {locals: Locals,gpr_dump_count: u32,fpr_dump_count: u32,- block_labels: Vec<Label>,+ block_labels: &'a [Label],/// Where control that goes to each block lands (see `landing_blocks()`).- landing_blocks: Vec<BlockId>,+ landing_blocks: &'a [BlockId],exit_stub: Label,resume: Label,/// Where the prologues resume in the interpreter.@@ -297,30 +355,30 @@ struct Codegen<'a, M: PortableMacroAssembler> {entry_overflow: Label,exit_interpreter: Label,/// The nodes of the code's sites, by site index, with what they are.- sites: Vec<(NodeId, SiteKind)>,+ sites: ZoneVec<'a, (NodeId, SiteKind)>,/// Out of line stubs that store an exit index and jump to the exit stub.- exit_site_stubs: Vec<(Label, u32)>,- annotations: Vec<(u32, CodeAnnotation)>,+ exit_site_stubs: ZoneVec<'a, (Label, u32)>,+ annotations: ZoneVec<'a, (u32, CodeAnnotation)>,/// The block being emitted.block: BlockId,- deferred_cache_probes: Vec<probes::DeferredCacheProbe>,- deferred_vm_cache_probes: Vec<probes::DeferredVmCacheProbe>,- deferred_allocations: Vec<allocation::DeferredAllocation>,- deferred_storage_growths: Vec<named_storage::DeferredStorageGrowth>,+ deferred_cache_probes: ZoneVec<'a, probes::DeferredCacheProbe>,+ deferred_vm_cache_probes: ZoneVec<'a, probes::DeferredVmCacheProbe>,+ deferred_allocations: ZoneVec<'a, allocation::DeferredAllocation<'a>>,+ deferred_storage_growths: ZoneVec<'a, named_storage::DeferredStorageGrowth>,/// `InitializeNamed` nodes whose constant the allocation of their object/// stored already.- absorbed_initializations: Vec<NodeId>,+ absorbed_initializations: ZoneVec<'a, NodeId>,/// `InitializeNamed` nodes right after the allocation of their object, which still has its properties inline.- inline_initializations: HashSet<NodeId>,+ inline_initializations: ZoneSet<'a, NodeId>,/// The slots of the compiled function's frame that hold its arguments/// object, which the code never created, when the node being emitted/// (in the compiled function or an inlined callee) leaves the code after/// its slow path: they get the object before the interpreter continues/// with the frames. Whether it is a mapped one.- leave_arguments: Vec<(u32, bool)>,+ leave_arguments: ZoneVec<'a, (u32, bool)>,/// Out of line code for slow paths that do not continue with the next/// instruction, emitted with the tails.- leave_stubs: Vec<LeaveStub>,+ leave_stubs: ZoneVec<'a, LeaveStub<'a>>,/// How the slow path of the node being emitted leaves compiled code, if/// it writes the node's frame state then (see `LeaveFrame`).leave_frame: Option<LeaveFrame>,@@ -331,60 +389,53 @@ struct Codegen<'a, M: PortableMacroAssembler> {/// While a `CallSlowPath` node that is a call is emitted: where the/// operands of its slow path are.slow_path_values: Option<SlowPathValues>,+ /// While `slow_path_values` is set: the index of the first of the node's inputs with each operand.+ input_of_operand: ZoneMap<'a, u32, usize>,+ /// While `slow_path_values` is set: the outputs that are SSA values, which no frame slot receives.+ slow_path_ssa_outputs: ZoneVec<'a, u32>,+ /// Lists that the lowering of a node fills, which keep their memory for the next node: the operands of a slow+ /// path call and the outputs it stores, the operands of a call, the constant fields an allocation stores, and+ /// the values of a frame.+ spare_operands: ZoneVec<'a, u32>,+ spare_outputs: ZoneVec<'a, (OutputSource, u32)>,+ spare_call_operands: ZoneVec<'a, call::CallOperand>,+ spare_fields: ZoneVec<'a, call::ConstantField>,+ spare_frame_values: ZoneVec<'a, (u32, ValueLocation)>,+ spare_bytes: ZoneVec<'a, u8>,/// The target of the branch on the result of the cache probe being/// emitted, which the probe branches to itself where it finds nothing/// (see `fused_probe_branch()`).fused_probe_failure: Option<Label>,/// The no-ops of `AssumeValid` nodes, with the exits that the jumps/// replacing them go to once the code is invalidated.- invalidation_points: Vec<(usize, Label)>,+ invalidation_points: ZoneVec<'a, (usize, Label)>,/// Whether to check that the lowerings match what they declare (see `verify_lowerings()`).verify: bool,/// The node whose code (inline or out of line) is being emitted, if any.emitting: Option<NodeId>,/// How many temps each node's lowering took (see `temp()`).- requested_temps: Vec<std::cell::Cell<u8>>,+ requested_temps: &'a [std::cell::Cell<u8>],/// The nodes whose code used the saves area without declaring it.- undeclared_saves_area_uses: std::cell::RefCell<Vec<NodeId>>,+ undeclared_saves_area_uses: std::cell::RefCell<ZoneVec<'a, NodeId>>,}/// The operands of the slow path of a `CallSlowPath` node that is a call,-/// which reads them from the node's inputs instead of frame slots.+/// which reads them from the node's inputs instead of frame slots (see+/// `Codegen::input_of_operand` and `Codegen::slow_path_ssa_outputs`).+#[derive(Clone, Copy)]struct SlowPathValues {node: NodeId,- /// The index of the first of the node's inputs with each operand.- input_of_operand: HashMap<u32, usize>,/// Where the inputs in registers are.registers: InputRegisters,- /// The outputs that are SSA values, which no frame slot receives.- ssa_outputs: Vec<u32>,-}--impl SlowPathValues {- /// `operands` are those of the node's inputs, in input order.- fn new(node: NodeId, operands: &[u32], registers: InputRegisters, ssa_outputs: Vec<u32>) -> Self {- // NB: Looking up each operand in a list would take time quadratic in the operand count of instructions like- // NewArray of a large array literal.- let mut input_of_operand = HashMap::with_capacity_and_hasher(operands.len(), Default::default());- for (index, operand) in operands.iter().enumerate() {- input_of_operand.entry(*operand).or_insert(index);- }- Self {- node,- input_of_operand,- registers,- ssa_outputs,- }- }}/// Where the code of a slow path call or a call finds those of its inputs/// that are in registers, once it clobbered registers.-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Copy)]pub(super) enum InputRegisters {/// In their registers, except for these, which are in the saves area,/// in the order of their words there.- Saved(Vec<Gpr>),+ Saved(RegisterList<Gpr>),/// In the register dump that publishing the frames of the inlined calls/// wrote (see `emit_publish_frames()`), since that clobbered every/// register a call clobbers.@@ -400,43 +451,44 @@ pub(super) enum InputRegisters {/// the frame. Slow paths and calls in inlined callees run in frames the/// runtime published with their headers only (see `SiteKind::Publish`),/// which the leave fills as far as they are still on the stack.-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Copy)]struct LeaveFrame {node: NodeId,/// Registers a slow path saved, with where, to restore first.- restore: Vec<(Gpr, u32)>,+ restore: RegisterList<(Gpr, u32)>,}/// The out of line part of a slow path call: what runs when the slow path/// does not continue with the next instruction.-struct LeaveStub {+#[derive(Clone, Copy)]+struct LeaveStub<'a> {label: Label,/// See `Codegen::leave_frame`.leave_frame: Option<LeaveFrame>,/// Outputs that are also inputs, stored back if the frame still runs.- input_outputs: Vec<(OutputSource, u32)>,+ input_outputs: &'a [(OutputSource, u32)],/// See `Codegen::leave_arguments`.- leave_arguments: Vec<(u32, bool)>,+ leave_arguments: &'a [(u32, bool)],}/// Generates code for `graph` with the register allocation `allocation`, whose registers came from-/// `target_registers::<M>()`, and writes the sites of the code into-/// `tables`. With `verify` (and in debug builds), checks that-/// every lowering matches its `lowering_info()`.-pub fn generate<M: PortableMacroAssembler>(- graph: &Graph,- snapshot: &Snapshot,+/// `target_registers::<M>()`, into `code` in place of what it holds, and writes the sites of the code into+/// `artifact`, which holds nothing. With `verify` (and in debug builds), checks that every lowering matches its+/// `lowering_info()`.+pub fn generate<'a, M: PortableMacroAssembler>(+ graph: &'a Graph<'a>,+ snapshot: &'a Snapshot,verify: bool,- tables: &mut Tables,- allocation: &Allocation,- work: &Zone,-) -> Result<GeneratedCode, CompileFailure> {- let Tables { artifact, sites } = tables;+ artifact: &mut ArtifactWriter<'_>,+ allocation: &'a Allocation<'a>,+ code: &mut Column<u8>,+ work: &'a Zone,+) -> Result<GeneratedCode<'a>, CompileFailure> {let (_, pinned) = target_registers::<M>();let (gpr_dump_count, fpr_dump_count) = register_dump_counts::<M>();- let mut masm = M::new();- let block_labels = graph.blocks.iter().map(|_| masm.new_label()).collect();- let landing_blocks = landing_blocks(graph, allocation);+ let mut masm = M::new(code, work);+ let block_labels = work.alloc_slice_from_iter(graph.blocks.iter().map(|_| masm.new_label()));+ let landing_blocks = landing_blocks(graph, allocation, work);let exit_stub = masm.new_label();let resume = masm.new_label();let entry_resume = masm.new_label();@@ -444,12 +496,13 @@ pub fn generate<M: PortableMacroAssembler>(let exit_interpreter = masm.new_label();let leave_tail = masm.new_label();- let mut codegen = Codegen {+ let mut codegen = Codegen::<M> {masm,graph,allocation,snapshot,work,+ decoded_instructions: ZoneMap::new_in(work),runtime: &snapshot.runtime,stress: snapshot.options.stress,pinned,@@ -464,28 +517,36 @@ pub fn generate<M: PortableMacroAssembler>(entry_resume,entry_overflow,exit_interpreter,- sites: Vec::new(),- exit_site_stubs: Vec::new(),- annotations: Vec::new(),+ sites: ZoneVec::new_in(work),+ exit_site_stubs: ZoneVec::new_in(work),+ annotations: ZoneVec::new_in(work),block: BlockId(0),- deferred_cache_probes: Vec::new(),- deferred_vm_cache_probes: Vec::new(),- deferred_allocations: Vec::new(),- deferred_storage_growths: Vec::new(),- absorbed_initializations: Vec::new(),- inline_initializations: HashSet::default(),- leave_arguments: Vec::new(),- leave_stubs: Vec::new(),+ deferred_cache_probes: ZoneVec::new_in(work),+ deferred_vm_cache_probes: ZoneVec::new_in(work),+ deferred_allocations: ZoneVec::new_in(work),+ deferred_storage_growths: ZoneVec::new_in(work),+ absorbed_initializations: ZoneVec::new_in(work),+ inline_initializations: ZoneSet::new_in(work),+ leave_arguments: ZoneVec::new_in(work),+ leave_stubs: ZoneVec::new_in(work),leave_frame: None,leave_tail,frame_initialization_stub: None,slow_path_values: None,- invalidation_points: Vec::new(),+ input_of_operand: ZoneMap::new_in(work),+ slow_path_ssa_outputs: ZoneVec::new_in(work),+ spare_operands: ZoneVec::new_in(work),+ spare_outputs: ZoneVec::new_in(work),+ spare_call_operands: ZoneVec::new_in(work),+ spare_fields: ZoneVec::new_in(work),+ spare_frame_values: ZoneVec::new_in(work),+ spare_bytes: ZoneVec::new_in(work),+ invalidation_points: ZoneVec::new_in(work),fused_probe_failure: None,verify: verify || cfg!(debug_assertions),emitting: None,- requested_temps: vec![std::cell::Cell::new(0); graph.nodes.len()],- undeclared_saves_area_uses: std::cell::RefCell::new(Vec::new()),+ requested_temps: work.alloc_slice_from_iter(graph.nodes.iter().map(|_| std::cell::Cell::new(0))),+ undeclared_saves_area_uses: std::cell::RefCell::new(ZoneVec::new_in(work)),};codegen.lay_out_frame()?;codegen.emit_prologue();@@ -506,32 +567,24 @@ pub fn generate<M: PortableMacroAssembler>(panic!("lowerings that do not match their declarations:\n{errors}");}- artifact.clear();- sites.begin(graph)?;- for (node, kind) in &codegen.sites {- codegen.with_site_source(*node, *kind, |site| site.write(sites, artifact))?;+ let mut sites = SiteScratch::new_in(graph, work)?;+ for (node, kind) in &*codegen.sites {+ codegen.with_site_source(*node, *kind, |site| site.write(&mut sites, artifact))?;+ }+ let annotations = codegen.annotations.take();+ let mut invalidation_patches = ZoneVec::with_capacity_in(codegen.invalidation_points.len(), work);+ for (offset, exit) in &*codegen.invalidation_points {+ let target = codegen.masm.label_offset(*exit).expect("exit stubs are bound");+ invalidation_patches.push((+ u32::try_from(*offset).expect("code fits in 4 GiB"),+ M::jump_patch(*offset, target),+ ));}- let annotations = std::mem::take(&mut codegen.annotations);- let invalidation_patches = codegen- .invalidation_points- .iter()- .map(|(offset, exit)| {- let target = codegen.masm.label_offset(*exit).expect("exit stubs are bound");- (- u32::try_from(*offset).expect("code fits in 4 GiB"),- M::jump_patch(*offset, target),- )- })- .collect();let site_index_frame_offset = codegen.local_frame_pointer_offset(codegen.locals.exit_index);let register_dump_frame_offset = codegen.local_frame_pointer_offset(codegen.locals.dump);- let (code, data_offset) = codegen- .masm- .finish_with_data_offset()- .map_err(|_| CompileFailure::CodeGeneration)?;+ let data_offset = codegen.masm.finish().map_err(assembly_failure)?;let data_offset = u32::try_from(data_offset).expect("code fits in 4 GiB");Ok(GeneratedCode {- code,data_offset,entry_offset: 0,annotations,@@ -542,7 +595,15 @@ pub fn generate<M: PortableMacroAssembler>(})}-/// The machine code as disassembly, under headers naming the block, IR node+/// Why a compile fails when the assembler could not finish the code.+fn assembly_failure(error: crate::asm::AsmError) -> CompileFailure {+ match error {+ crate::asm::AsmError::TooLarge => CompileFailure::TooLarge,+ crate::asm::AsmError::UnboundLabel | crate::asm::AsmError::BranchOutOfRange => CompileFailure::CodeGeneration,+ }+}++/// The machine code `code` as disassembly, under headers naming the block, IR node/// or tail each run of instructions was generated for. Calls of runtime/// helpers and well-known values are named.pub fn dump_code(@@ -550,28 +611,41 @@ pub fn dump_code(executable: &ExecutableSnapshot,runtime: &RuntimeInfo,architecture: Architecture,+ code: &[u8],generated: &GeneratedCode,artifact: Artifact<'_>,) -> String {use std::fmt::Write;- let mut symbols = vec![- (runtime.jit_call, "libjs_jit_call".to_string()),- (runtime.jit_exit, "libjs_jit_exit".to_string()),- (runtime.finish_direct_call, "libjs_jit_finish_direct_call".to_string()),- (runtime.to_boolean, "asm_helper_to_boolean".to_string()),- (runtime.heap_region_base, "js_heap_region_base".to_string()),+ let helpers = [+ (runtime.jit_call, "libjs_jit_call"),+ (runtime.jit_exit, "libjs_jit_exit"),+ (runtime.finish_direct_call, "libjs_jit_finish_direct_call"),+ (runtime.to_boolean, "asm_helper_to_boolean"),+ (runtime.heap_region_base, "js_heap_region_base"),];- for (index, address) in runtime.slow_paths.iter().enumerate() {- let opcode = u8::try_from(index).ok().and_then(OpCode::from_u8);- if let Some(symbol) = opcode.and_then(slow_path_symbol) {- symbols.push((*address, symbol));+ let symbol = |bits: u64| {+ if bits == 0 {+ return None;}- }- symbols.retain(|(address, _)| *address != 0);+ if let Some((_, symbol)) = helpers.iter().find(|(address, _)| *address == bits) {+ return Some(symbol.to_string());+ }+ runtime+ .slow_paths+ .iter()+ .enumerate()+ .filter(|(_, address)| **address == bits)+ .find_map(|(index, _)| {+ u8::try_from(index)+ .ok()+ .and_then(OpCode::from_u8)+ .and_then(slow_path_symbol)+ })+ };let describe_constant = |bits: u64| {- if let Some((_, symbol)) = symbols.iter().find(|(address, _)| *address == bits) {- return Some(symbol.clone());+ if let Some(symbol) = symbol(bits) {+ return Some(symbol);}let bytecode_end = executable.bytecode_address + executable.bytecode.len() as u64;if (executable.bytecode_address..bytecode_end).contains(&bits) {@@ -581,11 +655,12 @@ pub fn dump_code((!description.starts_with("0x")).then_some(description)};- let instructions = disassembler::listing_with_data(architecture, &generated.code, generated.data_offset as usize);let mut annotations = generated.annotations.iter().peekable();let layout = &executable.layout;let mut out = String::new();- for instruction in &instructions {+ let mut instruction_count = 0;+ disassembler::for_each_instruction(architecture, code, generated.data_offset as usize, |instruction| {+ instruction_count += 1;while let Some((_, annotation)) = annotations.next_if(|(offset, _)| *offset as usize <= instruction.offset) {match annotation {CodeAnnotation::Prologue => out.push_str("prologue:\n"),@@ -612,13 +687,13 @@ pub fn dump_code(write!(out, " ; {description}").unwrap();}out.push('\n');- }+ });let count = |kind: fn(SiteKind) -> bool| artifact.sites().filter(|site| kind(site.kind())).count();writeln!(out,"{} instructions, {} bytes, {} exits, {} leaves, {} publish sites, {} call sites",- instructions.len(),- generated.code.len(),+ instruction_count,+ code.len(),count(|kind| matches!(kind, SiteKind::Exit(_))),count(|kind| kind == SiteKind::Leave),count(|kind| kind == SiteKind::Publish),@@ -669,7 +744,7 @@ fn fused_probe_branch(graph: &Graph, allocation: &Allocation, block: BlockId) ->/// Where control that goes to each block lands: blocks that only jump on, like the edges the builder splits off/// branches, pass it on, so jumps go straight to where they lead and those blocks have no code. The first block, which/// the prologue falls into, and blocks that jump on in a cycle land in themselves.-fn landing_blocks(graph: &Graph, allocation: &Allocation) -> Vec<BlockId> {+fn landing_blocks<'a>(graph: &Graph, allocation: &Allocation, work: &'a Zone) -> &'a [BlockId] {let block_count = graph.blocks.len();let jumps_on = |index: usize| -> Option<BlockId> {let block = &graph.blocks[index];@@ -685,25 +760,23 @@ fn landing_blocks(graph: &Graph, allocation: &Allocation) -> Vec<BlockId> {_ => None,}};- (0..block_count)- .map(|index| {- let mut landing = index;- for _ in 0..block_count {- match jumps_on(landing) {- Some(target) => landing = target.index(),- None => return BlockId::from_index(landing),- }+ work.alloc_slice_from_iter((0..block_count).map(|index| {+ let mut landing = index;+ for _ in 0..block_count {+ match jumps_on(landing) {+ Some(target) => landing = target.index(),+ None => return BlockId::from_index(landing),}- BlockId::from_index(index)- })- .collect()+ }+ BlockId::from_index(index)+ }))}fn checked_i32(value: u64) -> Result<i32, CompileFailure> {i32::try_from(value).map_err(|_| CompileFailure::CodeGeneration)}-impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {+impl<'a, M: PortableMacroAssembler> Codegen<'a, '_, M> {// Frame layout./// Sizes the locals area and decides which callee-saved registers to save.@@ -800,28 +873,26 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {// load it, see `entry.rs`) and does not keep the scratch register.let mut saved = GprSet::EMPTY.with(self.pinned.frame);let mut saved_fprs = FprSet::EMPTY;- for register in self.used_registers() {- match register {- Register::General(register) if M::CALLEE_SAVED_GPRS.contains(register) => {- saved = saved.with(register);- }- Register::Float(register) if M::CALLEE_SAVED_FPRS.contains(register) => {- saved_fprs = saved_fprs.with(register);- }- _ => {}+ self.for_each_used_register(|register| match register {+ Register::General(register) if M::CALLEE_SAVED_GPRS.contains(register) => {+ saved = saved.with(register);}- }+ Register::Float(register) if M::CALLEE_SAVED_FPRS.contains(register) => {+ saved_fprs = saved_fprs.with(register);+ }+ _ => {}+ });self.frame = M::frame(saved, saved_fprs, size);// NB: The prologue addresses the lowest byte of the frame relative to the stack pointer.checked_i32(u64::from(self.frame.caller_stack_offset))?;Ok(())}- fn used_registers(&self) -> Vec<Register> {- let mut registers = Vec::new();+ /// Calls `visit` with each register that the allocation uses, once for each use.+ fn for_each_used_register(&self, mut visit: impl FnMut(Register)) {let mut add = |location: &Location| {if let Location::Register(register) = location {- registers.push(register_of(*register));+ visit(register_of(*register));}};for node in 0..self.allocation.node_count() {@@ -842,7 +913,6 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {add(&m.to);}}- registers}/// Calls `with` with what the site of kind `kind` for the frame state of@@ -858,7 +928,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let saved = slow_path_calls::slow_path_saved_registers_of::<M>(self.allocation.node(node));self.save_slot_offsets(&saved)} else {- Vec::new()+ RegisterList::new()};with(&SiteSource {graph: self.graph,@@ -879,7 +949,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {/// The `saved` registers of a slow path call, with the frame pointer/// offsets of their words in the saves area.- fn save_slot_offsets(&self, saved: &[Gpr]) -> Vec<(Gpr, i32)> {+ fn save_slot_offsets(&self, saved: &[Gpr]) -> RegisterList<(Gpr, i32)> {let frame_pointer = i64::from(self.frame.caller_stack_offset) - 16;saved.iter()@@ -937,12 +1007,17 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}/// The instruction at `pc` of executable `executable`.- fn decoded(&self, executable: u32, pc: u32) -> Result<DecodedInstruction<'a>, CompileFailure> {+ fn decoded(&mut self, executable: u32, pc: u32) -> Result<DecodedInstruction<'a>, CompileFailure> {+ if let Some(decoded) = self.decoded_instructions.get(&(executable, pc)) {+ return Ok(*decoded);+ }let bytecode = &self.snapshot[self.snapshot.executables[executable as usize].bytecode];- decode_instruction(bytecode, pc, self.work).map_err(|_| CompileFailure::InvalidBytecode {+ let decoded = decode_instruction(bytecode, pc, self.work).map_err(|_| CompileFailure::InvalidBytecode {pc,reason: "undecodable instruction",- })+ })?;+ self.decoded_instructions.insert((executable, pc), decoded);+ Ok(decoded)}/// How many elements the array of the instruction at `pc` of executable `executable` holds.@@ -1081,7 +1156,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.move_imm32(M::RETURN_GPRS[0], 0);self.emit_return(JitStatus::ExitInterpreter);- let leave_stubs = std::mem::take(&mut self.leave_stubs);+ let leave_stubs = self.leave_stubs.take();if !leave_stubs.is_empty() {self.annotate(CodeAnnotation::Tail("slow paths that did not continue"));}@@ -1097,7 +1172,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {if !self.exit_site_stubs.is_empty() {self.annotate(CodeAnnotation::Tail("exit sites"));}- for (label, index) in std::mem::take(&mut self.exit_site_stubs) {+ for (label, index) in self.exit_site_stubs.take() {let node = self.sites[index as usize].0;self.annotate(CodeAnnotation::Exit { index, node });self.masm.bind(label);@@ -1169,7 +1244,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.emit_exit_runtime_call();let control = self.local_address(self.locals.leave_control);self.masm.load64(M::RETURN_GPRS[0], &control);- self.leave_arguments = Vec::new();+ self.leave_arguments.clear();self.emit_leave_after_slow_path();}@@ -1213,8 +1288,8 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {/// Emits an entry point for every on-stack replacement entry block:/// the prologue, then a jump to the block.- fn emit_osr_entries(&mut self) -> Vec<(u32, u32)> {- let mut entries = Vec::new();+ fn emit_osr_entries(&mut self) -> ZoneVec<'a, (u32, u32)> {+ let mut entries = ZoneVec::with_capacity_in(self.graph.osr_entries.len(), self.work);for (pc, block) in &self.graph.osr_entries {let offset = u32::try_from(self.masm.offset()).expect("code fits in 4 GiB");self.emit_prologue();@@ -1406,10 +1481,10 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}let node = self.graph.node(node_id);self.emit_stress_exit(node_id);- self.leave_arguments = self.virtual_arguments_slots(node_id);+ self.find_virtual_arguments_slots(node_id);self.leave_frame = self.leave_frame_of(node_id).map(|node| LeaveFrame {node,- restore: Vec::new(),+ restore: RegisterList::new(),});match &node.op {Op::Constant(_) | Op::Phi | Op::VirtualObject { .. } | Op::Refine { .. } => {@@ -1619,7 +1694,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let (registers, published) = if self.publishes_frames(node_id) {self.emit_publish_frames_or_save_inputs(node_id)?} else {- (InputRegisters::Saved(Vec::new()), 0)+ (InputRegisters::Saved(RegisterList::new()), 0)};if matches!(self.graph.node(node_id).op, Op::CallDirect { .. }) {self.emit_call_direct(node_id, executable, pc, ®isters)?;@@ -1958,32 +2033,27 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {Ok(())}- /// The slots of the compiled function's frame, as the frame state of- /// `node` describes it, that hold the arguments object the code never- /// created, and whether it is a mapped one.- fn virtual_arguments_slots(&self, node: NodeId) -> Vec<(u32, bool)> {- self.graph- .node(node)- .frame_state- .map(|frame_state| {- // NB: Only the compiled function's own frame, the outermost- // one, keeps an arguments object virtual.- let root = self- .graph- .frame_state_chain(frame_state)- .last()- .expect("the chain is not empty");- self.graph- .frame_state(root)- .values- .iter()- .filter_map(|(slot, value)| {- let bits = self.graph.constant_value(*value)?;- value::virtual_arguments_kind(bits).map(|mapped| (*slot, mapped))- })- .collect()- })- .unwrap_or_default()+ /// Makes `leave_arguments` the slots of the compiled function's frame,+ /// as the frame state of `node` describes it, that hold the arguments+ /// object the code never created, and whether it is a mapped one.+ fn find_virtual_arguments_slots(&mut self, node: NodeId) {+ self.leave_arguments.clear();+ let Some(frame_state) = self.graph.node(node).frame_state else {+ return;+ };+ // NB: Only the compiled function's own frame, the outermost+ // one, keeps an arguments object virtual.+ let root = self+ .graph+ .frame_state_chain(frame_state)+ .last()+ .expect("the chain is not empty");+ let graph = self.graph;+ self.leave_arguments+ .extend(graph.frame_state(root).values.iter().filter_map(|(slot, value)| {+ let bits = graph.constant_value(*value)?;+ value::virtual_arguments_kind(bits).map(|mapped| (*slot, mapped))+ }));}fn emit_has_in_prototype_chain(&mut self, node: NodeId) {@@ -2374,7 +2444,8 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let layout = self.snapshot.executables[0].layout;let slots = self.runtime.offsets.execution_context_slots;let first = crate::bytecode::RESERVED_REGISTER_COUNT;- let mut fields: Vec<call::ConstantField> = Vec::new();+ let mut fields = self.spare_fields.take();+ fields.clear();let unrolled = layout.registers_and_locals_count.saturating_sub(first) <= UNROLLED_SLOTS;if !unrolled {self.masm.move_imm64(value, value::EMPTY);@@ -2396,7 +2467,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {fields.push((slots + 8 * (layout.constants_base() + index), 8, *constant));}fields.push((self.runtime.offsets.execution_context_frame_initialized, 1, 1));- self.emit_constant_fields_with_vector(self.pinned.frame, value, &mut fields, Some(vector), &[])+ self.emit_constant_fields_with_vector(self.pinned.frame, value, &mut fields, Some(vector), &[])?;+ self.spare_fields = fields;+ Ok(())}/// Initializes the frame for slow paths, whose caller-saved general@@ -2639,11 +2712,10 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.move_imm64(dst, value::EMPTY);return Ok(());}- if let Some(values) = &self.slow_path_values- && let Some(&index) = values.input_of_operand.get(&operand)+ if let Some(values) = self.slow_path_values+ && let Some(&index) = self.input_of_operand.get(&operand){- let (node, registers) = (values.node, values.registers.clone());- self.load_input(dst, node, index, ®isters);+ self.load_input(dst, values.node, index, &values.registers);return Ok(());}let address = self.slot_address(operand)?;@@ -2653,17 +2725,17 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {/// Runs the slow path of the instruction at `pc` of `executable`, with/// its operands in their frame slots or, while `slow_path_values` is- /// set, in the node's inputs. Returns where the outputs that are SSA- /// values are, in layout order.+ /// set, in the node's inputs. Returns where the first of the outputs+ /// that are SSA values is, in layout order.fn emit_generic(&mut self,opcode: crate::bytecode::OpCode,executable: u32,pc: u32,- ) -> Result<Vec<OutputSource>, CompileFailure> {+ ) -> Result<Option<OutputSource>, CompileFailure> {if opcode == crate::bytecode::OpCode::Call && self.makes_dynamic_calls() {self.emit_generic_js_call(executable, pc)?;- return Ok(Vec::new());+ return Ok(None);}if matches!(opcode,@@ -2673,7 +2745,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {) && self.runtime.construct_stub != 0{self.emit_generic_construct(executable, pc)?;- return Ok(Vec::new());+ return Ok(None);}let decoded = self.decoded(executable, pc)?;let next_pc = decoded.next_pc();@@ -2689,7 +2761,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let program_counter = self.frame_field(self.runtime.offsets.execution_context_program_counter);self.masm.store_imm32(&program_counter, pc);let arguments = M::ARGUMENT_GPRS;- let mut ssa_outputs = Vec::new();+ let mut ssa_output = None;match call {SlowPathCall::JitCall => {self.emit_frame_runtime_call(address, pc);@@ -2697,12 +2769,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}SlowPathCall::BinaryValues => {let (dst, lhs, rhs) = binary_operands(&decoded.instruction).expect("binary slow path operands");- let into_record = self- .slow_path_values- .as_ref()- .is_some_and(|values| values.ssa_outputs.contains(&dst.raw()));+ let into_record = self.slow_path_values.is_some() && self.slow_path_ssa_outputs.contains(&dst.raw());let destination = if into_record {- ssa_outputs.push(OutputSource::Record(self.locals.record));+ ssa_output = Some(OutputSource::Record(self.locals.record));self.local_address(self.locals.record)} else {self.slot_address(dst.raw())?@@ -2729,23 +2798,26 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.emit_jump_target_check(pc, true_target, false_target);}SlowPathCall::Record => {- ssa_outputs = self.emit_record_call(opcode, executable, pc, next_pc, address, None)?;+ ssa_output = self.emit_record_call(opcode, executable, pc, next_pc, address, None)?;}}- Ok(ssa_outputs)+ Ok(ssa_output)}- /// The operands a slow path call of the instruction at `pc` reads, in- /// the order of the node's inputs, and the outputs it writes that are SSA- /// values.+ /// Makes `operands` the operands a slow path call of the instruction at+ /// `pc` reads, in the order of the node's inputs, and `ssa_outputs` the+ /// outputs it writes that are SSA values.fn slow_path_call_operands(- &self,+ &mut self,opcode: crate::bytecode::OpCode,executable: u32,pc: u32,- ) -> Result<(Vec<u32>, Vec<u32>), CompileFailure> {- let mut operands = Vec::new();- let mut outputs = Vec::new();+ operands: &mut ZoneVec<'_, u32>,+ ssa_outputs: &mut ZoneVec<'_, u32>,+ ) -> Result<(), CompileFailure> {+ operands.clear();+ ssa_outputs.clear();+ let outputs = ssa_outputs;let is_js_call = slow_path_call(opcode) == Some(SlowPathCall::JitCall);if is_js_call {let decoded = self.decoded(executable, pc)?;@@ -2770,13 +2842,22 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}}let frame_layout = self.snapshot.executables[executable as usize].layout;- let ssa_outputs = outputs- .into_iter()- .filter(|operand| {- crate::builder::is_ssa_slow_path_output(&frame_layout, crate::bytecode::Operand::from_raw(*operand))- })- .collect::<Vec<_>>();- Ok((operands, ssa_outputs))+ outputs.retain(|operand| {+ crate::builder::is_ssa_slow_path_output(&frame_layout, crate::bytecode::Operand::from_raw(*operand))+ });+ Ok(())+ }++ /// Makes `slow_path_values` the operands of the slow path of `node`, in+ /// the node's inputs: `operands` are those of the inputs, in input order.+ fn set_slow_path_values(&mut self, node: NodeId, operands: &[u32], registers: InputRegisters) {+ // NB: Looking up each operand in a list would take time quadratic in the operand count of instructions like+ // NewArray of a large array literal.+ self.input_of_operand.clear();+ for (index, operand) in operands.iter().enumerate() {+ self.input_of_operand.entry(*operand).or_insert(index);+ }+ self.slow_path_values = Some(SlowPathValues { node, registers });}/// A `CallSlowPath` node that is a call: runs the slow path of its@@ -2791,7 +2872,8 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {pc: u32,) -> Result<(), CompileFailure> {let is_js_call = slow_path_call(opcode) == Some(SlowPathCall::JitCall);- let (operands, ssa_outputs) = self.slow_path_call_operands(opcode, executable, pc)?;+ let (mut operands, mut ssa_outputs) = (self.spare_operands.take(), self.slow_path_ssa_outputs.take());+ self.slow_path_call_operands(opcode, executable, pc, &mut operands, &mut ssa_outputs)?;// NB: In an inlined callee, the slow path runs in the frames of the// inlined calls, which compiled code pops again if it continues.let (registers, published) = self.emit_publish_frames_or_save_inputs(node)?;@@ -2809,20 +2891,23 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {for _ in 0..published {self.emit_pop_inline_frame();}+ (self.spare_operands, self.slow_path_ssa_outputs) = (operands, ssa_outputs);return Ok(());}- self.slow_path_values = Some(SlowPathValues::new(node, &operands, registers, ssa_outputs));- let sources = self.emit_generic(opcode, executable, pc);+ self.set_slow_path_values(node, &operands, registers);+ self.slow_path_ssa_outputs = ssa_outputs;+ self.spare_operands = operands;+ let source = self.emit_generic(opcode, executable, pc);self.slow_path_values = None;- let sources = sources?;+ let source = source?;// NB: The value of a conditional jump is the control word, which is// in the output register already.- if let (Some(source), Some(Location::Register(output))) = (sources.first(), self.allocation.node(node).output) {+ if let (Some(source), Some(Location::Register(output))) = (source, self.allocation.node(node).output) {let output = Gpr(output);match source {- OutputSource::Register(register) => self.masm.move64(output, *register),+ OutputSource::Register(register) => self.masm.move64(output, register),OutputSource::Record(offset) => {- let record = self.local_address(*offset);+ let record = self.local_address(offset);self.masm.load64(output, &record);}}@@ -2837,9 +2922,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {/// that calls clobber in the saves area, and returns them: marshalling/// operands into argument registers and publishing frames clobbers them,/// so the call reads those inputs from there.- fn save_input_registers(&mut self, node: NodeId) -> Vec<Gpr> {+ fn save_input_registers(&mut self, node: NodeId) -> RegisterList<Gpr> {let clobbered = slow_path_calls::slow_path_saved_registers::<M>();- let mut saved = Vec::new();+ let mut saved = RegisterList::new();for location in self.allocation.node(node).inputs {if let Location::Register(register) = *location&& let Register::General(register) = register_of(register)@@ -2866,7 +2951,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {// clobbers anyway.let saved = slow_path_calls::slow_path_saved_registers::<M>().iter()- .collect::<Vec<_>>();+ .collect::<RegisterList<_>>();self.emit_save_registers(&saved);let (published, registers) = self.emit_publish_frames(node, &saved)?;Ok((registers, published))@@ -2902,7 +2987,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {&mut self,node: NodeId,registers: &InputRegisters,- ) -> Result<Vec<OutputSource>, CompileFailure> {+ ) -> Result<Option<OutputSource>, CompileFailure> {let Op::CallSlowPath {opcode, executable, pc, ..} = self.graph.node(node).op@@ -2912,25 +2997,30 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {// NB: Slow paths that take their operands by value run like those of// calls, with the saves area for the inputs in saved registers.if slow_path_call(opcode) != Some(SlowPathCall::Record) {- let (operands, ssa_outputs) = self.slow_path_call_operands(opcode, executable, pc)?;+ let (mut operands, mut ssa_outputs) = (self.spare_operands.take(), self.slow_path_ssa_outputs.take());+ self.slow_path_call_operands(opcode, executable, pc, &mut operands, &mut ssa_outputs)?;// NB: The runtime's call helper and the call stub read the// operands of calls from the frame, and calls leave their// result there.if slow_path_call(opcode) == Some(SlowPathCall::JitCall) {self.emit_store_operand_inputs(node, &operands, registers)?;self.emit_generic(opcode, executable, pc)?;- let Some(destination) = ssa_outputs.first() else {- return Ok(Vec::new());+ let destination = ssa_outputs.first().copied();+ (self.spare_operands, self.slow_path_ssa_outputs) = (operands, ssa_outputs);+ let Some(destination) = destination else {+ return Ok(None);};let result = M::RETURN_GPRS[0];- let address = self.slot_address(*destination)?;+ let address = self.slot_address(destination)?;self.masm.load64(result, &address);- return Ok(vec![OutputSource::Register(result)]);+ return Ok(Some(OutputSource::Register(result)));}- self.slow_path_values = Some(SlowPathValues::new(node, &operands, registers.clone(), ssa_outputs));- let sources = self.emit_generic(opcode, executable, pc);+ self.set_slow_path_values(node, &operands, *registers);+ self.slow_path_ssa_outputs = ssa_outputs;+ self.spare_operands = operands;+ let source = self.emit_generic(opcode, executable, pc);self.slow_path_values = None;- return sources;+ return source;}let decoded = self.decoded(executable, pc)?;let address = self.runtime.slow_paths.get(opcode as usize).copied().unwrap_or(0);@@ -3005,39 +3095,21 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {next_pc: u32,address: u64,inputs: Option<(NodeId, &InputRegisters)>,- ) -> Result<Vec<OutputSource>, CompileFailure> {+ ) -> Result<Option<OutputSource>, CompileFailure> {let layout = slow_path_layout(opcode);let arguments = M::ARGUMENT_GPRS;let scratch = self.pinned.scratch;- let operands = layout- .fields- .iter()- .map(|field| self.read_operand(executable, pc, field.instruction_offset))- .collect::<Result<Vec<_>, _>>()?;+ let mut operands = self.spare_operands.take();+ operands.clear();+ for field in layout.fields {+ operands.push(self.read_operand(executable, pc, field.instruction_offset)?);+ }// Inputs passed by value: in the remaining argument registers, then on the stack.- let (by_value, first_register) = match layout.abi {- SlowPathAbi::Scalar => (- layout- .fields- .iter()- .zip(&operands)- .filter(|(field, _)| field.role == OperandRole::In)- .map(|(_, operand)| *operand)- .collect::<Vec<_>>(),- 3,- ),- SlowPathAbi::ScalarInputs => (- layout- .fields- .iter()- .zip(&operands)- .filter(|(field, _)| field.role != OperandRole::Out)- .map(|(_, operand)| *operand)- .collect(),- 4,- ),- SlowPathAbi::Record => (Vec::new(), 4),+ let (is_by_value, first_register): (fn(&crate::bytecode::SlowPathField) -> bool, usize) = match layout.abi {+ SlowPathAbi::Scalar => (|field| field.role == OperandRole::In, 3),+ SlowPathAbi::ScalarInputs => (|field| field.role != OperandRole::Out, 4),+ SlowPathAbi::Record => (|_| false, 4),};// NB: The inputs of a slow path call are the operands of the fields// that are not outputs, then the array's.@@ -3047,17 +3119,6 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {.filter(|field| field.role != OperandRole::Out).count()};- let by_value_fields = layout- .fields- .iter()- .enumerate()- .filter(|(_, field)| match layout.abi {- SlowPathAbi::Scalar => field.role == OperandRole::In,- SlowPathAbi::ScalarInputs => field.role != OperandRole::Out,- SlowPathAbi::Record => false,- })- .map(|(index, _)| index)- .collect::<Vec<_>>();let load = |codegen: &mut Self, dst: Gpr, operand: u32, input: usize| match inputs {Some((node, registers)) => {codegen.load_input(dst, node, input, registers);@@ -3065,12 +3126,13 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}None => codegen.load_raw_operand(dst, operand),};- for (index, operand) in by_value.iter().enumerate() {- let input = input_index(by_value_fields[index]);+ let by_value_fields = (0..layout.fields.len()).filter(|index| is_by_value(&layout.fields[*index]));+ for (index, field) in by_value_fields.enumerate() {+ let (operand, input) = (operands[field], input_index(field));match arguments.get(first_register + index) {- Some(register) => load(self, *register, *operand, input)?,+ Some(register) => load(self, *register, operand, input)?,None => {- load(self, scratch, *operand, input)?;+ load(self, scratch, operand, input)?;let stack_index = (first_register + index - arguments.len()) as u32;let address = self.local_address(8 * stack_index);self.masm.store64(&address, scratch);@@ -3080,7 +3142,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {// The record of every operand value; inputs are filled in here.if layout.abi == SlowPathAbi::Record {- for (index, (field, operand)) in layout.fields.iter().zip(&operands).enumerate() {+ for (index, (field, operand)) in layout.fields.iter().zip(operands.iter()).enumerate() {if field.role != OperandRole::Out {load(self, scratch, *operand, input_index(index))?;let address = self.local_address(self.locals.record + 8 * index as u32);@@ -3116,36 +3178,47 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.call_absolute(address);// Outputs come back in the second return register (scalar) or in the record.- let mut outputs = Vec::new();- let mut input_outputs = Vec::new();- for (index, (field, operand)) in layout.fields.iter().zip(&operands).enumerate() {- if field.role == OperandRole::In || *operand == crate::bytecode::Operand::INVALID {- continue;- }- let source = match layout.abi {- SlowPathAbi::Scalar => OutputSource::Register(M::RETURN_GPRS[1]),- _ => OutputSource::Record(self.locals.record + 8 * index as u32),- };- outputs.push((source, *operand));- if field.role == OperandRole::InOut {- input_outputs.push((source, *operand));- }- }+ let source_of = |codegen: &Self, index: usize| match layout.abi {+ SlowPathAbi::Scalar => OutputSource::Register(M::RETURN_GPRS[1]),+ _ => OutputSource::Record(codegen.locals.record + 8 * index as u32),+ };+ let outputs = (0..layout.fields.len()).filter(|index| {+ layout.fields[*index].role != OperandRole::In && operands[*index] != crate::bytecode::Operand::INVALID+ });if inputs.is_some() {+ let first = outputs.clone().next().map(|index| source_of(self, index));+ self.spare_operands = operands;self.emit_continuation_check(next_pc, &[]);- return Ok(outputs.into_iter().map(|(source, _)| source).collect());+ return Ok(first);}// NB: Outputs that are SSA values stay where the slow path left them.- let ssa_outputs = self- .slow_path_values- .as_ref()- .map(|values| values.ssa_outputs.clone())- .unwrap_or_default();- let (ssa_outputs, frame_outputs): (Vec<_>, Vec<_>) = outputs- .into_iter()- .partition(|(_, operand)| ssa_outputs.contains(operand));- self.emit_continuation_check_with_outputs(next_pc, &frame_outputs, &input_outputs)?;- Ok(ssa_outputs.into_iter().map(|(source, _)| source).collect())+ let is_ssa = |codegen: &Self, operand: u32| {+ codegen.slow_path_values.is_some() && codegen.slow_path_ssa_outputs.contains(&operand)+ };+ let first_ssa_output = outputs+ .clone()+ .find(|index| is_ssa(self, operands[*index]))+ .map(|index| source_of(self, index));+ // NB: The frame outputs, then the outputs that are also inputs.+ let mut stored = self.spare_outputs.take();+ stored.clear();+ stored.extend(+ outputs+ .clone()+ .filter(|index| !is_ssa(self, operands[*index]))+ .map(|index| (source_of(self, index), operands[index])),+ );+ let frame_output_count = stored.len();+ stored.extend(+ outputs+ .filter(|index| layout.fields[*index].role == OperandRole::InOut)+ .map(|index| (source_of(self, index), operands[index])),+ );+ self.spare_operands = operands;+ let (frame_outputs, input_outputs) = stored.split_at(frame_output_count);+ self.emit_continuation_check_with_outputs(next_pc, frame_outputs, input_outputs)?;+ self.spare_outputs = stored;+ Ok(first_ssa_output)}/// Stores slow path outputs to their frame slots.@@ -3192,9 +3265,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {);self.leave_stubs.push(LeaveStub {label,- leave_frame: self.leave_frame.clone(),- input_outputs: input_outputs.to_vec(),- leave_arguments: self.leave_arguments.clone(),+ leave_frame: self.leave_frame,+ input_outputs: self.work.alloc_slice_copy(input_outputs),+ leave_arguments: self.work.alloc_slice_copy(&self.leave_arguments),});self.store_outputs(outputs)}@@ -3218,11 +3291,11 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}/// The out of line code of a slow path call that did not continue.- fn emit_leave_stub(&mut self, stub: LeaveStub) -> Result<(), CompileFailure> {+ fn emit_leave_stub(&mut self, stub: LeaveStub<'a>) -> Result<(), CompileFailure> {self.masm.bind(stub.label);if let Some(leave_frame) = stub.leave_frame {if !stub.input_outputs.is_empty() {- self.emit_store_input_outputs(&stub.input_outputs)?;+ self.emit_store_input_outputs(stub.input_outputs)?;}// NB: Nothing runs the frame again once the interpreter is to// exit, which needs no frame state.@@ -3234,7 +3307,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {}let control = self.local_address(self.locals.leave_control);self.masm.store64(&control, M::RETURN_GPRS[0]);- for (register, offset) in &leave_frame.restore {+ for (register, offset) in leave_frame.restore.iter() {let address = self.local_address(*offset);self.masm.load64(*register, &address);}@@ -3247,9 +3320,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {return Ok(());}if !stub.input_outputs.is_empty() {- self.emit_store_input_outputs(&stub.input_outputs)?;+ self.emit_store_input_outputs(stub.input_outputs)?;}- self.leave_arguments = stub.leave_arguments;+ self.leave_arguments.assign(stub.leave_arguments);self.emit_leave_after_slow_path();Ok(())}@@ -3271,7 +3344,10 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let Some((handler_pc, exception_dst, entry_pc, entry)) = self.catch_entry_of(leave_frame.node)? else {return Ok(());};- let values = self.with_site_source(leave_frame.node, SiteKind::Leave, |site| site.root_frame_values());+ let mut values = self.spare_frame_values.take();+ self.with_site_source(leave_frame.node, SiteKind::Leave, |site| {+ site.root_frame_values(&mut values);+ });let writable = |location: &ValueLocation| {!matches!(location,@@ -3282,6 +3358,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {.iter().all(|(slot, location)| *slot != CALLEE_SLOT && writable(location)){+ self.spare_frame_values = values;return Ok(());}let leave = self.masm.new_label();@@ -3310,7 +3387,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.branch64_imm(Condition::Equal, scratch, value::EMPTY as i64, leave);self.masm.move64(self.pinned.frame, root_frame);- for (register, offset) in &leave_frame.restore {+ for (register, offset) in leave_frame.restore.iter() {let address = self.local_address(*offset);self.masm.load64(*register, &address);}@@ -3326,7 +3403,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.bind(initialized);let value = M::RETURN_GPRS[0];let number = M::ARGUMENT_FPRS[0];- for (slot, location) in &values {+ for (slot, location) in &*values {match *location {ValueLocation::Constant(bits) => self.masm.move_imm64(value, bits),ValueLocation::Register(register, Repr::Float64) => {@@ -3373,13 +3450,14 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let entry = self.label(entry);self.masm.jump(entry);self.masm.bind(leave);+ self.spare_frame_values = values;Ok(())}/// The pc of the handler that catches exceptions thrown at `node` in the/// compiled function's frame, the slot its `Catch` stores the exception/// in, and the pc and block of its catch entry, if it has one.- fn catch_entry_of(&self, node: NodeId) -> Result<Option<(u32, u32, u32, BlockId)>, CompileFailure> {+ fn catch_entry_of(&mut self, node: NodeId) -> Result<Option<(u32, u32, u32, BlockId)>, CompileFailure> {let frame_state = self.graph.node(node).frame_state.expect("leaves have a frame state");let root = self.graph@@ -3448,9 +3526,9 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {let stub = self.masm.new_label();self.leave_stubs.push(LeaveStub {label: stub,- leave_frame: self.leave_frame.clone(),- input_outputs: Vec::new(),- leave_arguments: Vec::new(),+ leave_frame: self.leave_frame,+ input_outputs: &[],+ leave_arguments: &[],});self.masm.jump(stub);} else {@@ -3481,7 +3559,8 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {self.masm.move_imm32(arguments[2], u32::from(mapped));self.masm.call_absolute(self.runtime.create_arguments);self.masm.load64(arguments[1], &root_frame);- for (slot, _) in self.leave_arguments.clone() {+ for index in 0..self.leave_arguments.len() {+ let slot = self.leave_arguments[index].0;let offset = u64::from(self.runtime.offsets.execution_context_slots) + 8 * u64::from(slot);let address = Address::new(arguments[1],diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rsindex 7a4965a6917..7ba2511ccc4 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs@@ -20,6 +20,7 @@//! cell, and on empty free lists.use super::Codegen;+use super::RegisterList;use super::probes::CacheRegisters;use super::slow_path_calls::slow_path_saved_registers;use crate::asm::Address;@@ -53,9 +54,9 @@ pub(super) struct DeferredStorageGrowth {shape: Gpr,}-impl<M: PortableMacroAssembler> Codegen<'_, M> {- fn growth_registers() -> Option<Vec<Gpr>> {- let registers = slow_path_saved_registers::<M>().iter().collect::<Vec<_>>();+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {+ fn growth_registers() -> Option<RegisterList<Gpr>> {+ let registers = slow_path_saved_registers::<M>().iter().collect::<RegisterList<_>>();(registers.len() >= WORK_REGISTER_COUNT + 2).then_some(registers)}@@ -106,7 +107,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}pub(super) fn emit_deferred_storage_growths(&mut self) {- let growths = std::mem::take(&mut self.deferred_storage_growths);+ let growths = self.deferred_storage_growths.take();if growths.is_empty() {return;}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes.rsindex 6c6d88194b6..e5f785d29ad 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs@@ -24,7 +24,7 @@ use crate::asm::Gpr;use crate::asm::Label;use crate::asm::PortableMacroAssembler;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Branches to `miss` unless the dictionary generation of the shape in/// `shape` is the one a cache recorded at `expected`. Loads the two into/// `temps`, the first of which may be `shape`.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rsindex 5119a0d7268..96c0019e143 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs@@ -35,7 +35,7 @@ pub(in crate::codegen) enum KeyName {Identity(u64),}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Looks up the own data property that the string `key` names on the/// object in `base` in the VM's keyed property lookup cache, like the/// runtime's keyed get does when the access's own cache has nothing for@@ -380,7 +380,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Where a cache probe branches when it finds nothing: the target of the/// branch on its result that follows it, if code generation fused them,/// or a new label. Returns whether it is fused.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/megamorphic.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/megamorphic.rsindex aa9660d92cf..b13f5099be5 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/megamorphic.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/megamorphic.rs@@ -28,7 +28,7 @@ pub(super) enum MegamorphicKey {Keyed { key: Gpr },}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Branches to `found` if cache entry `candidate` applies to objects of/// the shape in `shape`.pub(super) fn branch_if_entry_shape(&mut self, candidate: Gpr, shape: Gpr, found: Label) {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rsindex 9b8447c87b2..9e7458e509e 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs@@ -10,6 +10,7 @@//! entries out of line by the runtime's cache probe.use super::super::Codegen;+use super::super::RegisterList;use super::super::checked_i32;use super::super::slow_path_calls::slow_path_saved_registers;use super::keyed::KeyName;@@ -105,7 +106,7 @@ pub(super) struct AdditionEntryFields {pub property_offset: i32,}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {fn cache_registers(&self, node: NodeId) -> CacheRegisters {CacheRegisters {object: self.temp(node, 0),@@ -372,24 +373,22 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {(value::INT32_TAG, snapshot.number_prototype),(value::BOOLEAN_TAG, snapshot.boolean_prototype),]- .into_iter()- .filter_map(|(tag, prototype)| Some((tag, prototype?, self.masm.new_label())))- .collect::<Vec<_>>();+ .map(|(tag, prototype)| Some((tag, prototype?, self.masm.new_label())));let (is_object, have_object) = (self.masm.new_label(), self.masm.new_label());self.masm.branch32_imm(Condition::Equal, scratch, i32::from(value::OBJECT_TAG), is_object);- for (tag, _, label) in &prototypes {+ for (tag, _, label) in prototypes.iter().flatten() {self.masm.branch32_imm(Condition::Equal, scratch, i32::from(*tag), *label);}// Doubles are numbers too.- if let Some((_, _, number)) = prototypes.iter().find(|(tag, ..)| *tag == value::INT32_TAG) {+ if let Some((_, _, number)) = prototypes.iter().flatten().find(|(tag, ..)| *tag == value::INT32_TAG) {self.masm.and32_imm(scratch, scratch, u32::from(value::BASE_TAG));self.masm.branch32_imm(Condition::NotEqual, scratch, i32::from(value::BASE_TAG), *number);}self.masm.jump(fail);- for (_, prototype, label) in prototypes {+ for (_, prototype, label) in prototypes.into_iter().flatten() {self.masm.bind(label);self.masm.move_imm64(object, prototype.0);self.masm.jump(have_object);@@ -804,7 +803,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// The probes of the VM's keyed caches of megamorphic named accesses, out/// of line.pub(in crate::codegen) fn emit_deferred_vm_cache_probes(&mut self) -> Result<(), CompileFailure> {- for deferred in std::mem::take(&mut self.deferred_vm_cache_probes) {+ for deferred in self.deferred_vm_cache_probes.take() {self.emitting = Some(deferred.node);self.masm.bind(deferred.entry);let registers = self.cache_registers(deferred.node);@@ -886,7 +885,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {);let arguments = M::ARGUMENT_GPRS;- let saved = slow_path_saved_registers::<M>().iter().collect::<Vec<_>>();+ let saved = slow_path_saved_registers::<M>().iter().collect::<RegisterList<_>>();self.emit_save_registers(&saved);let base = self.input(node, 0);if base != arguments[1] {@@ -903,7 +902,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// The runtime probes of the cache probe nodes, out of line.pub(in crate::codegen) fn emit_deferred_cache_probes(&mut self) -> Result<(), CompileFailure> {- for deferred in std::mem::take(&mut self.deferred_cache_probes) {+ for deferred in self.deferred_cache_probes.take() {self.emitting = Some(deferred.node);self.masm.bind(deferred.entry);let pc = self.graph.node(deferred.node).pc;@@ -941,7 +940,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {if let Some(output) = output {saved = saved.without(output);}- let saved = saved.iter().collect::<Vec<_>>();+ let saved = saved.iter().collect::<RegisterList<_>>();self.emit_save_registers(&saved);let hit = self.masm.new_label();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs b/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rsindex e650751cc74..29a5fa04c8c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs@@ -18,7 +18,7 @@ use crate::asm::PortableMacroAssembler;use crate::asm::Scale;use crate::ir::NodeId;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Jumps to `yes` if the property iterator cache `keys` still holds the/// keys of the object `receiver`: the cache has a fast path, the/// receiver has the shape (and for dictionaries, its generation) thediff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rsindex 5842a580a27..15bffe50d32 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs@@ -7,8 +7,8 @@//! The sites of compiled code (see `artifact::SiteView`): where the translator finds the values of a node's frame//! state, from the register allocation.-use ak::Column;use ak::Zone;+use ak::ZoneVec;use crate::CompileFailure;use crate::artifact::ArtifactWriter;@@ -30,43 +30,32 @@ use crate::regalloc::Location;/// In place of the record of a frame state: it has none.const NO_RECORD: u32 = u32::MAX;-/// What the sites of a compile are written with. Its memory serves the next compile.-pub(crate) struct SiteScratch {+/// What the sites of a compile are written with, in the work zone.+pub(crate) struct SiteScratch<'a> {/// The record of each frame state of the graph in the tables of the code, by the index of the frame state.- frame_records: Column<u32>,+ frame_records: &'a mut [u32],/// The frame states of a chain that have no record.- pending: Column<u32>,+ pending: ZoneVec<'a, u32>,/// The values of a frame at a site, as the slot in the high half and the word of the location in the low half.- values: Column<u64>,+ values: ZoneVec<'a, u64>,}-impl SiteScratch {+impl<'a> SiteScratch<'a> {// NB: A compile whose graph has more frame states, or a frame state with more values or callers, fails.const MAX_FRAME_STATES: usize = 1 << 24;const MAX_FRAME_VALUES: usize = 1 << 22;const MAX_FRAME_DEPTH: usize = 1 << 16;- pub(crate) fn new() -> Self {- Self {- frame_records: Column::new(Self::MAX_FRAME_STATES, c"JIT frame state records"),- pending: Column::new(Self::MAX_FRAME_DEPTH, c"JIT frame state chain"),- values: Column::new(Self::MAX_FRAME_VALUES, c"JIT frame values"),+ /// What the sites of the code of `graph` are written with, which knows no records yet.+ pub(crate) fn new_in(graph: &Graph, work: &'a Zone) -> Result<Self, CompileFailure> {+ if graph.frame_states.len() > Self::MAX_FRAME_STATES {+ return Err(CompileFailure::TooLarge);}- }-- pub(crate) fn release_memory(&mut self) {- self.frame_records.clear();- self.frame_records.trim(0);- self.pending.clear();- self.pending.trim(0);- self.values.clear();- self.values.trim(0);- }-- /// Starts the sites of the code of `graph`, in tables that hold nothing.- pub(crate) fn begin(&mut self, graph: &Graph) -> Result<(), CompileFailure> {- self.frame_records.clear();- Ok(self.frame_records.try_resize(graph.frame_states.len(), NO_RECORD)?)+ Ok(Self {+ frame_records: work.alloc_slice_fill(graph.frame_states.len(), NO_RECORD),+ pending: ZoneVec::new_in(work),+ values: ZoneVec::new_in(work),+ })}/// The record of `frame_state`, which gets one with its callers if it has none.@@ -74,7 +63,7 @@ impl SiteScratch {&mut self,graph: &Graph,frame_state: FrameStateId,- artifact: &mut ArtifactWriter,+ artifact: &mut ArtifactWriter<'_>,) -> Result<u32, CompileFailure> {self.pending.clear();let mut parent = None;@@ -85,7 +74,10 @@ impl SiteScratch {parent = Some(record);break;}- self.pending.try_push(id.0)?;+ if self.pending.len() == Self::MAX_FRAME_DEPTH {+ return Err(CompileFailure::TooLarge);+ }+ self.pending.push(id.0);next = graph.frame_state(id).parent;}// NB: The record of a frame names that of its caller, so callers come first.@@ -186,7 +178,11 @@ pub(crate) struct SiteSource<'a> {impl SiteSource<'_> {/// Adds the site to the tables of the code, as the next site.- pub(crate) fn write(&self, scratch: &mut SiteScratch, artifact: &mut ArtifactWriter) -> Result<(), CompileFailure> {+ pub(crate) fn write(+ &self,+ scratch: &mut SiteScratch<'_>,+ artifact: &mut ArtifactWriter<'_>,+ ) -> Result<(), CompileFailure> {let graph = self.graph;let frame_state = graph.node(self.node).frame_state.expect("the node has a frame state");let frame = scratch.frame_record(graph, frame_state, artifact)?;@@ -214,11 +210,14 @@ impl SiteSource<'_> {for (_, value) in &state.values {let (slot, location) = locations.next(*value);let word = artifact.location(location)?;- scratch.values.try_push(u64::from(slot) << 32 | u64::from(word))?;+ if scratch.values.len() == SiteScratch::MAX_FRAME_VALUES {+ return Err(CompileFailure::TooLarge);+ }+ scratch.values.push(u64::from(slot) << 32 | u64::from(word));}// NB: The locations of a frame are in the order of its slots, which are in the high halves.scratch.values.sort_unstable();- for value in scratch.values.iter() {+ for value in &*scratch.values {artifact.add_location(*value as u32)?;}next = state.parent;@@ -244,8 +243,9 @@ impl SiteSource<'_> {Ok(())}- /// The slots of the values of the compiled function's frame at the site and where the values are, in slot order.- pub(crate) fn root_frame_values(&self) -> Vec<(u32, ValueLocation)> {+ /// Makes `values` the slots of the values of the compiled function's frame at the site and where the values are,+ /// in slot order.+ pub(crate) fn root_frame_values(&self, values: &mut ZoneVec<'_, (u32, ValueLocation)>) {let frame_state = self.graph.node(self.node)@@ -253,7 +253,7 @@ impl SiteSource<'_> {.expect("the node has a frame state");let objects = self.graph.virtual_objects(frame_state, self.work);let mut locations = self.locations(&objects);- let mut values = Vec::new();+ values.clear();let mut next = Some(frame_state);while let Some(id) = next {let state = self.graph.frame_state(id);@@ -262,7 +262,6 @@ impl SiteSource<'_> {next = state.parent;}values.sort_unstable_by_key(|(slot, _)| *slot);- values}fn locations<'a>(&'a self, objects: &'a [NodeId]) -> Locations<'a> {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex b7ac02196a8..5343abdb325 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -9,6 +9,7 @@//! code of nodes.use super::Codegen;+use super::RegisterList;use super::lowering_info::lowering_info;use crate::CompileFailure;use crate::asm::Address;@@ -41,7 +42,7 @@ pub(super) fn slow_path_saved_registers<M: PortableMacroAssembler>() -> GprSet {/// the order of their words in the saves area: those that may hold values,/// except its output register, which is last if an input is there too, since/// passing the other inputs to the slow path may clobber it.-pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocation: NodeAllocation) -> Vec<Gpr> {+pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocation: NodeAllocation) -> RegisterList<Gpr> {let output = match allocation.output {Some(Location::Register(register)) => Some(Gpr(register)),_ => None,@@ -50,7 +51,7 @@ pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocationif let Some(output) = output {saved = saved.without(output);}- let mut saved = saved.iter().collect::<Vec<_>>();+ let mut saved = saved.iter().collect::<RegisterList<_>>();if let Some(output) = output&& slow_path_saved_registers::<M>().contains(output)&& allocation.inputs.contains(&Location::Register(output.0))@@ -60,7 +61,7 @@ pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocationsaved}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// The out of line code of nodes, after the last block.pub(super) fn emit_deferred_code(&mut self) -> Result<(), CompileFailure> {self.emit_deferred_vm_cache_probes()?;@@ -81,20 +82,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {saved: &[Gpr],) -> Result<(usize, super::InputRegisters), CompileFailure> {if !self.publishes_frames(node) {- return Ok((0, super::InputRegisters::Saved(saved.to_vec())));+ return Ok((0, super::InputRegisters::Saved(saved.iter().copied().collect())));}let frame_state = self.graph.node(node).frame_state.expect("publishing nodes have a frame state");- let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();- let pushed = chain.len() - 1;+ let pushed = self.graph.frame_state_chain(frame_state).count() - 1;// NB: Compiled code writes the headers itself, unless a value they// need is one it cannot write (a virtual object).let compiled_code_writes_headers = saved.len() >= 5- && chain[..pushed].iter().all(|id| {- let frame_state = self.graph.frame_state(*id);+ && self.graph.frame_state_chain(frame_state).take(pushed).all(|id| {+ let frame_state = self.graph.frame_state(id);let arguments_base = self.snapshot.executables[frame_state.executable as usize].layout.arguments_base();@@ -109,7 +109,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {});if compiled_code_writes_headers {self.emit_published_frames(node, saved)?;- return Ok((pushed, super::InputRegisters::Saved(saved.to_vec())));+ return Ok((pushed, super::InputRegisters::Saved(saved.iter().copied().collect())));}let index = u32::try_from(self.sites.len()).expect("site count fits in u32");self.sites.push((node, SiteKind::Publish));@@ -182,16 +182,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {crate::bytecode::SlowPathAbi::Scalar,"slow paths with several outputs return them in the record");- let mut outputs = Vec::new();+ let mut outputs = 0;+ let mut output_field = None;for (field_index, field) in layout.fields.iter().enumerate() {if field.role == crate::bytecode::OperandRole::In {continue;}if self.read_operand(executable, pc, field.instruction_offset)? != crate::bytecode::Operand::INVALID {- outputs.push(field_index as u32);+ if outputs == usize::from(index) {+ output_field = Some(field_index as u32);+ }+ outputs += 1;}}- let field_index = outputs[usize::from(index)];+ let field_index = output_field.expect("the slow path has the output");let record = self.local_address(self.locals.record + 8 * field_index);self.masm.load64(self.output(node), &record);Ok(())@@ -268,29 +272,37 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.frame_state.expect("fast paths have a frame state");// NB: Frame state values are listed innermost frame first.- let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();- let mut locations = self.allocation.node(node).exit_values.iter().copied();- let mut frames = Vec::new();- for id in &chain {- let frame = self.graph.frame_state(*id);- let values = frame- .values- .iter()- .map(|(slot, value)| {- let (_, location) = locations.next().expect("every frame state value has a location");- let repr = self.graph.node(*value).repr.unwrap_or(Repr::Tagged);- (*slot, location, repr)- })- .collect::<Vec<_>>();- frames.push((frame, values));- }+ let graph = self.graph;+ let locations = self.allocation.node(node).exit_values;+ let depth = graph.frame_state_chain(frame_state).count();+ // The frame state at `level` of the chain, with its values: their slots, locations and representations.+ let frame_at = |level: usize| {+ let start: usize = graph+ .frame_state_chain(frame_state)+ .take(level)+ .map(|id| graph.frame_state(id).values.len())+ .sum();+ let id = graph+ .frame_state_chain(frame_state)+ .nth(level)+ .expect("the level is in the chain");+ let frame = graph.frame_state(id);+ let values = frame.values.iter().enumerate().map(move |(index, (slot, value))| {+ let (_, location) = *locations+ .get(start + index)+ .expect("every frame state value has a location");+ let repr = graph.node(*value).repr.unwrap_or(Repr::Tagged);+ (*slot, location, repr)+ });+ (frame, values)+ };let mut clobbered = false;// NB: The new target of the frame of the level above.let mut new_target = None;- for level in (0..frames.len()).rev() {- if level + 1 < frames.len() {- let (caller, _) = &frames[level + 1];- let (callee, values) = &frames[level];+ for level in (0..depth).rev() {+ if level + 1 < depth {+ let (caller, _) = frame_at(level + 1);+ let (callee, mut values) = frame_at(level);let call = self.decoded(caller.executable, caller.pc)?;let callee_function = self.snapshot.executables[callee.executable as usize].function@@ -339,20 +351,17 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// from the saves area, which holds all of them.// NB: A frame of an inlined closure runs the closure that was// called.- let closure = match values.iter().find(|(slot, _, _)| *slot == crate::ir::CALLEE_SLOT) {+ let closure = match values.clone().find(|(slot, _, _)| *slot == crate::ir::CALLEE_SLOT) {Some((_, location, repr)) => {let closure = saved[4];- self.emit_frame_value(closure, *location, *repr, saved, true);+ self.emit_frame_value(closure, location, repr, saved, true);self.emit_unbox_cell(closure, closure);Some(closure)}None => None,};- match values- .iter()- .find(|(slot, _, _)| *slot == crate::bytecode::THIS_VALUE_REGISTER)- {- Some((_, location, repr)) => self.emit_frame_value(this, *location, *repr, saved, true),+ match values.find(|(slot, _, _)| *slot == crate::bytecode::THIS_VALUE_REGISTER) {+ Some((_, location, repr)) => self.emit_frame_value(this, location, repr, saved, true),None => self.masm.move_imm64(this, value::EMPTY),}self.emit_push_inline_frame(@@ -368,13 +377,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {)?;clobbered = true;}- if level + 1 == frames.len() {+ if level + 1 == depth {continue;}- let arguments_base = self.snapshot.executables[frames[level].0.executable as usize]+ let (frame, values) = frame_at(level);+ let arguments_base = self.snapshot.executables[frame.executable as usize].layout.arguments_base();- for &(slot, location, repr) in &frames[level].1 {+ for (slot, location, repr) in values {if slot == crate::ir::CALLEE_SLOT {continue;}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rsindex 7046a3a7397..7ce75bc7264 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs@@ -38,7 +38,7 @@ pub(super) fn int32_condition(comparison: Comparison) -> Condition {}}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {pub(super) fn emit_check_int32(&mut self, node: NodeId) {let exit = self.exit_site(node);let (input, output, scratch) = (self.input(node, 0), self.output(node), self.pinned.scratch);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/strings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/strings.rsindex 244bf4e6c7d..ca9f6910555 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/strings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/strings.rs@@ -19,7 +19,7 @@ use crate::ir::NodeId;use crate::ir::TypeofKind;use crate::ir::value;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// `StringsEqual`: strings with the same bits are equal. Others are not/// if both are interned (two interned strings are equal only if they are/// the same string, like the interpreter's `string_compare`) or if theirdiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/values.rs b/Libraries/LibJS/JIT/Rust/src/codegen/values.rsindex f488a193ad1..c85a00a945c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/values.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/values.rs@@ -22,7 +22,7 @@ use crate::ir::value;/// `Codegen::lowering_fpr()`).pub const LOWERING_FPRS: usize = 3;-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {/// Floating point register `index` (below `LOWERING_FPRS`), which/// lowerings may clobber: the register allocator puts no values there.pub(super) fn lowering_fpr(index: usize) -> Fpr {diff --git a/Libraries/LibJS/JIT/Rust/src/fast_hash.rs b/Libraries/LibJS/JIT/Rust/src/fast_hash.rsdeleted file mode 100644index a01bb7b49ef..00000000000--- a/Libraries/LibJS/JIT/Rust/src/fast_hash.rs+++ /dev/null@@ -1,14 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Hash maps and sets with a fast hasher (see `ak::FastHasher`), for the compiler's keys.--use std::hash::BuildHasherDefault;--use ak::FastHasher;--pub type HashMap<K, V> = std::collections::HashMap<K, V, BuildHasherDefault<FastHasher>>;-pub type HashSet<K> = std::collections::HashSet<K, BuildHasherDefault<FastHasher>>;diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 37611294bd0..77bf5ac61ab 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -16,24 +16,17 @@// NB: A module with `allow(clippy::disallowed_types)` still uses containers of the heap (see clippy.toml). It loses// the `allow` when its data is in zones.-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod artifact;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod asm;pub mod builder;pub mod bytecode;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod code;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod codegen;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod compile_pool;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod coverage;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]-pub mod fast_hash;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]-pub mod inline_vec;pub mod ir;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod options;@@ -50,6 +43,7 @@ compile_error!("the tests of the JIT run on Windows on x86-64 only");use ak::Zone;use artifact::Artifact;+use artifact::ArtifactWriter;use artifact::Tail;use bytecode::OpCode;use code::CompiledCode;@@ -161,12 +155,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(if !snapshot.is_complete() {return Err(CompileFailure::TooLarge);}- let Scratch {- zone,- work,- steps,- tables,- } = scratch;+ let Scratch { zone, work, steps } = scratch;// NB: Nothing of the compile before this one is in use (see `Scratch`).work.reset();let mut graph = {@@ -210,10 +199,18 @@ fn run_stages<M: asm::PortableMacroAssembler>(regalloc::dump_allocation(&graph, &allocation));}- let mut generated =- codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, tables, &allocation, work)?;+ let mut artifact = ArtifactWriter::new_in(work);+ let mut generated = codegen::generate::<M>(+ &graph,+ snapshot,+ snapshot.options.verify_ir,+ &mut artifact,+ &allocation,+ &mut compiled.code,+ work,+ )?;generated.osr_entries.sort_unstable();- let layout = tables.artifact.finish(+ let layout = artifact.finish(&Tail {osr_entries: &generated.osr_entries,osr_loop_back_edges: &graph.osr_loop_back_edges,@@ -225,7 +222,6 @@ fn run_stages<M: asm::PortableMacroAssembler>(},&mut compiled.words,)?;- compiled.code.try_extend_from_slice(&generated.code)?;let mut dump = None;if snapshot.options.dump_ir || snapshot.options.dump_asm || pass_dumps.is_some() {@@ -240,6 +236,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(executable,&snapshot.runtime,M::ARCHITECTURE,+ &compiled.code,&generated,Artifact::new(&compiled.words, &layout),));diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 9d4f5c72c7a..70acc323ebe 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -693,8 +693,9 @@ fn exits_find_constants_registers_and_spilled_values() {let graph = build_with_layout(&program, test_layout(), &[2]);let allocation = allocate_and_verify(&graph);let exit = find_node(&graph, |node| matches!(node.op, Op::Exit { .. }));- let mut scratch = crate::scratch::Scratch::new();- scratch.tables.sites.begin(&graph).unwrap();+ let work = crate::test_work();+ let mut sites = crate::codegen::sites::SiteScratch::new_in(&graph, &work).unwrap();+ let mut artifact = crate::artifact::ArtifactWriter::new_in(&work);SiteSource {graph: &graph,allocation: &allocation,@@ -704,10 +705,10 @@ fn exits_find_constants_registers_and_spilled_values() {saves: &[],work: crate::test_zone(),}- .write(&mut scratch.tables.sites, &mut scratch.tables.artifact)+ .write(&mut sites, &mut artifact).unwrap();let mut words = ak::Column::new(crate::artifact::MAX_WORDS, c"test");- let layout = scratch.tables.artifact.finish(&Tail::default(), &mut words).unwrap();+ let layout = artifact.finish(&Tail::default(), &mut words).unwrap();let artifact = Artifact::new(&words, &layout);let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });let Some(Location::Register(argument_register)) = allocation.node(argument).output else {diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rsindex 727685fc788..75828993dae 100644--- a/Libraries/LibJS/JIT/Rust/src/scratch.rs+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs@@ -8,12 +8,9 @@use ak::Zone;-use crate::artifact::ArtifactWriter;-use crate::codegen::sites::SiteScratch;-/// What a compile keeps its data in, apart from what the heap still holds of it. A thread that compiles has one, and/// every compile of the thread uses it: a compile leaves nothing in it that the next one reads, only the memory.-/// The memory is in a few ranges of address space that are the scratch's own, so all of it can go back to the system+/// The memory is in four ranges of address space that are the scratch's own, so all of it can go back to the system/// at any time between two compiles (see `release_memory()`), whatever else the process allocated since.pub struct Scratch {/// Where the graph of a compile is, with all the lists of its nodes, blocks and frame states. A compile starts@@ -21,7 +18,8 @@ pub struct Scratch {pub(crate) zone: Zone,/// Where the stages of a compile keep the data that only they use. The driver drops the data of the builder,/// and of each pass, when it ends. The register allocator keeps the allocation here, with its own work data,- /// for the code generator, so those stay until the compile ends.+ /// for the code generator, so those stay until the compile ends, with the data of the code generator and of the+ /// tables of the code.pub(crate) work: Zone,/// Where a stage that repeats a step keeps the data of one step, which the step drops when it ends. A stage/// keeps what lasts from one step to the next in `work`. So a stage whose steps each make data as large as the@@ -30,14 +28,6 @@ pub struct Scratch {/// stage moves the data in use to the other zone and resets the first (see `check_elimination`). The driver/// empties both after each stage.pub(crate) steps: [Zone; 2],- pub(crate) tables: Tables,-}--/// The tables of the code generator and of the artifact writer, which are not in the zones. Each is its own range of-/// address space.-pub struct Tables {- pub(crate) artifact: ArtifactWriter,- pub(crate) sites: SiteScratch,}impl Default for Scratch {@@ -57,10 +47,6 @@ impl Scratch {zone: Zone::new(ZONE_LIMIT, c"JIT graph"),work: Zone::new(ZONE_LIMIT, c"JIT work"),steps: [Zone::new(ZONE_LIMIT, c"JIT step"), Zone::new(ZONE_LIMIT, c"JIT step 2")],- tables: Tables {- artifact: ArtifactWriter::new(),- sites: SiteScratch::new(),- },}}@@ -81,7 +67,5 @@ impl Scratch {zone.reset();zone.trim(0);}- self.tables.artifact.release_memory();- self.tables.sites.release_memory();}}diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex 636324c78b2..f53e466b2d4 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -440,14 +440,10 @@ impl JitState {let allocator = Rc::new(RefCell::new(CodeAllocator::default()));#[cfg(not(windows))]let allocator = Rc::clone(&self.code_allocator);- let memory = ExecutableMemory::allocate(- &allocator,- &[code.as_slice()],- &["entry trampoline"],- self.options.perf_map,- )- .pop()- .expect("one code was allocated");+ let memory =+ ExecutableMemory::allocate(&allocator, &[&code[..]], &["entry trampoline"], self.options.perf_map)+ .pop()+ .expect("one code was allocated");// SAFETY: The code is the entry trampoline, with its calling convention.let trampoline = unsafe { core::mem::transmute::<*const u8, EntryTrampoline>(memory.address()) };(memory, trampoline)@@ -463,7 +459,7 @@ impl JitState {.expect("the call stub compiles")?;ExecutableMemory::allocate(&self.code_allocator,- &[code.as_slice()],+ &[&code[..]],&["call stub"],self.options.perf_map,)@@ -481,7 +477,7 @@ impl JitState {.expect("the construct stub compiles")?;ExecutableMemory::allocate(&self.code_allocator,- &[code.as_slice()],+ &[&code[..]],&["construct stub"],self.options.perf_map,)diff --git a/Libraries/LibWasm/JIT/Cargo.toml b/Libraries/LibWasm/JIT/Cargo.tomlindex 5d38632bb55..78e0782e7ee 100644--- a/Libraries/LibWasm/JIT/Cargo.toml+++ b/Libraries/LibWasm/JIT/Cargo.toml@@ -9,6 +9,7 @@ crate-type = ["rlib"]# After changing dependencies, regenerate the Flatpak sources:# python3 Meta/CMake/flatpak/generate-cargo-sources.py[dependencies]+ak = { path = "../../../AK/Rust" }libjs_runtime_macros = { path = "../../LibJS/Rust/macros" }libwasm_module = { path = "../Module" }diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rsindex 537400cf97f..f0f0539715b 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs@@ -148,7 +148,7 @@ pub struct CodeGenerator<'a> {func: &'a Func,allocation: &'a Allocation,runtime: &'a RuntimeInfo,- asm: Assembler,+ asm: Assembler<'a>,block_labels: Vec<Label>,trap_labels: Vec<Option<Label>>,/// The trap with the code in x0, for the runtime's functions that return one.@@ -162,13 +162,18 @@ pub struct CodeGenerator<'a> {}impl<'a> CodeGenerator<'a> {- pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo) -> Self {+ pub fn new(+ func: &'a Func,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ memory: &'a mut crate::CodeMemory,+ ) -> Self {let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;Self {func,allocation,runtime,- asm: Assembler::new(),+ asm: Assembler::new(&mut memory.code, &memory.work),block_labels: Vec::new(),trap_labels: vec![None; 32],dynamic_trap: None,@@ -217,7 +222,11 @@ impl<'a> CodeGenerator<'a> {}}self.out_of_line();- let code = self.asm.finish().map_err(|_| crate::CompileFailure::CodeGeneration)?;+ let code = self+ .asm+ .finish()+ .map_err(|_| crate::CompileFailure::CodeGeneration)?+ .to_vec();Ok(Generated {code,frame_size: self.frame_size,@@ -782,7 +791,8 @@ pub fn generate(allocation: &Allocation,runtime: &RuntimeInfo,_stack_limit: u64,+ memory: &mut crate::CodeMemory,) -> Result<Generated, crate::CompileFailure> {let _ = (NONE, Shift::Lsl);- CodeGenerator::new(func, allocation, runtime).generate()+ CodeGenerator::new(func, allocation, runtime, memory).generate()}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rsindex bbaa008da98..d00a262b861 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs@@ -97,7 +97,7 @@ pub struct CodeGenerator<'a> {allocation: &'a Allocation,runtime: &'a RuntimeInfo,stack_limit: u64,- asm: Assembler,+ asm: Assembler<'a>,block_labels: Vec<Label>,trap_labels: Vec<Option<Label>>,/// The trap with the code in eax, for the runtime's functions that return one.@@ -113,21 +113,27 @@ pub struct CodeGenerator<'a> {exception_sites: Vec<u32>,}-impl BranchGroups for CodeGenerator<'_> {- fn branch_assembler(&mut self) -> &mut Assembler {+impl<'a> BranchGroups<'a> for CodeGenerator<'a> {+ fn branch_assembler(&mut self) -> &mut Assembler<'a> {&mut self.asm}}impl<'a> CodeGenerator<'a> {- pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo, stack_limit: u64) -> Self {+ pub fn new(+ func: &'a Func,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ stack_limit: u64,+ memory: &'a mut crate::CodeMemory,+ ) -> Self {let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;Self {func,allocation,runtime,stack_limit,- asm: Assembler::for_host(),+ asm: Assembler::for_host(&mut memory.code, &memory.work),block_labels: Vec::new(),trap_labels: vec![None; 32],dynamic_trap: None,@@ -181,7 +187,11 @@ impl<'a> CodeGenerator<'a> {}}self.out_of_line();- let code = self.asm.finish().map_err(|_| crate::CompileFailure::CodeGeneration)?;+ let code = self+ .asm+ .finish()+ .map_err(|_| crate::CompileFailure::CodeGeneration)?+ .to_vec();Ok(Generated {code,frame_size: self.frame_size,@@ -769,7 +779,8 @@ pub fn generate(allocation: &Allocation,runtime: &RuntimeInfo,stack_limit: u64,+ memory: &mut crate::CodeMemory,) -> Result<Generated, crate::CompileFailure> {let _ = NONE;- CodeGenerator::new(func, allocation, runtime, stack_limit).generate()+ CodeGenerator::new(func, allocation, runtime, stack_limit, memory).generate()}diff --git a/Libraries/LibJS/JIT/Rust/src/inline_vec.rs b/Libraries/LibWasm/JIT/src/inline_vec.rssimilarity index 95%rename from Libraries/LibJS/JIT/Rust/src/inline_vec.rsrename to Libraries/LibWasm/JIT/src/inline_vec.rsindex b11ea621795..372a6392b5f 100644--- a/Libraries/LibJS/JIT/Rust/src/inline_vec.rs+++ b/Libraries/LibWasm/JIT/src/inline_vec.rs@@ -4,9 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! A vector of copyable values that keeps up to `N` of them inline, for the-//! small per-node lists the register allocator makes for most nodes (their-//! input locations, temps and the like), so that those need no heap+//! A vector of copyable values that keeps up to `N` of them inline, for small lists that mostly need no heap//! allocation./// Up to `N` values inline; more spill to the heap.diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsindex ae0951c0596..94905d56804 100644--- a/Libraries/LibWasm/JIT/src/lib.rs+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -10,18 +10,17 @@//! the runtime needs to install and run it. It touches no heap and no store, so it runs on any thread. See//! `ARCHITECTURE.md` for how it works.-// NB: The assemblers and the small data structures are libjs_jit's, until both JITs share them from a crate of-// their own. The test helpers of the assemblers' own tests are for libjs_jit's tests.+// NB: The assemblers are libjs_jit's, until both JITs share them from a crate of their own. The test helpers of the+// assemblers' own tests are for libjs_jit's tests.#[cfg_attr(test, allow(dead_code))]#[path = "../../../LibJS/JIT/Rust/src/asm/mod.rs"]pub mod asm;-#[path = "../../../LibJS/JIT/Rust/src/inline_vec.rs"]-pub mod inline_vec;pub mod builder;pub mod codegen;pub mod convention;pub mod decode;+pub mod inline_vec;pub mod ir;pub mod passes;pub mod regalloc;@@ -118,6 +117,42 @@ pub struct CompileContext {scheduler: passes::schedule::Scheduler,allocator: regalloc::Allocator,pub allocation: regalloc::Allocation,+ code_memory: CodeMemory,+}++/// The memory that an assembler works in: the column that it writes the code to, and the zone of its labels and+/// fixups.+pub struct CodeMemory {+ pub code: ak::Column<u8>,+ pub work: ak::Zone,+}++impl CodeMemory {+ /// The most code that one function or stub can have.+ const MAX_CODE_BYTES: usize = 1 << 30;+ /// The most bytes that the work data of the assembler can take. It is address space, which costs nothing before+ /// it is used, and it is far above what the largest function body that the parser accepts (7,654,321 bytes) takes,+ /// even one that is all `br_table` targets.+ const MAX_WORK_BYTES: usize = 1 << 34;++ pub fn new() -> Self {+ Self {+ code: ak::Column::new(Self::MAX_CODE_BYTES, c"Wasm JIT code"),+ work: ak::Zone::new(Self::MAX_WORK_BYTES, c"Wasm JIT assembler"),+ }+ }++ /// Drops the code and the data of the assembler that wrote it, and keeps the memory for the next code.+ pub fn clear(&mut self) {+ self.code.clear();+ self.work.reset();+ }+}++impl Default for CodeMemory {+ fn default() -> Self {+ Self::new()+ }}/// The phases of a compile, as `Stats::ticks` counts them.@@ -250,11 +285,13 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Resultregalloc::verify::dump(&context.func, &context.allocation));}+ context.code_memory.clear();let generated = codegen::target::generate(&context.func,&context.allocation,&request.runtime,request.stack_limit,+ &mut context.code_memory,)?;lap(4, &mut stats);stats.nodes = context.func.nodes.len() as u32;@@ -280,9 +317,9 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result} else {asm::Architecture::X86_64};- for line in asm::disassembler::listing(architecture, &compiled.code) {+ asm::disassembler::for_each_instruction(architecture, &compiled.code, compiled.code.len(), |line| {text.push_str(&format!("{:6x} {}\n", line.offset, line.text));- }+ });}compiled.dump = Some(text);}diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rsindex 946d8bbe077..5f5bbae4809 100644--- a/Libraries/LibWasm/JIT/src/stubs.rs+++ b/Libraries/LibWasm/JIT/src/stubs.rs@@ -74,7 +74,8 @@ fn copy(asm: &mut Assembler, ty: Type, from: Address, to: Address) {/// The host stub for functions with these parameter and result types.pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let parameter_slots = convention::slots(params) as i32;let result_slots = convention::slots(results) as i32;let buffer_slots = parameter_slots.max(result_slots);@@ -182,7 +183,7 @@ pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Veasm.mov_ri(SCRATCH, runtime.trap_exit);asm.jmp_r(SCRATCH);}- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}/// What the entry trampoline calls compiled code with, and what it returns.@@ -230,7 +231,8 @@ fn field(offset: usize) -> i32 {/// The trap exit: stores the code in edi as the context's first argument, and the context in the frame that/// trapped, and continues at the interpreter's TrapFromNative handler at `handler`.pub fn trap_exit(handler: u64) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let context = gpr(convention::RAX);asm.mov_rm(Width::W64, context, &Address::new(FP, convention::FRAME_INSTANCE));asm.mov_rm(@@ -246,7 +248,7 @@ pub fn trap_exit(handler: u64) -> Vec<u8> {);asm.mov_ri(SCRATCH, handler);asm.jmp_r(SCRATCH);- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}/// Continues where the `resume` of the context in `context` says, as the runtime set it after unwinding an@@ -277,7 +279,8 @@ fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {/// The entry trampoline, a System V `fn(*mut NativeCall)`, and the offset of the address its call of compiled code/// returns to, where an exception the compiled code does not handle continues (see `RuntimeInfo::throw`).pub fn entry_trampoline() -> (Vec<u8>, usize) {- let mut asm = Assembler::for_host();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let record = gpr(convention::R11);let (rax, rcx, rdx, rsi, rdi) = (gpr(convention::RAX),@@ -375,7 +378,10 @@ pub fn entry_trampoline() -> (Vec<u8>, usize) {}asm.pop(FP);asm.ret();- (asm.finish().expect("stubs have no unbound labels"), return_offset)+ (+ asm.finish().expect("stubs have no unbound labels").to_vec(),+ return_offset,+ )}/// What the runtime function of the adapter returns when the call threw an exception, which the runtime unwound: the@@ -386,7 +392,8 @@ pub const ADAPTER_RESUME: u64 = u64::MAX;/// the callee's header, the save area and fp as the context's first three arguments. A nonzero result is a trap code,/// or `ADAPTER_RESUME`.pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let instance = gpr(convention::INSTANCE_REGISTER);// Below the frame header, the save area at rsp.let frame_size = (convention::FRAME_HEADER_SIZE as usize + ADAPTER_SAVE_AREA).next_multiple_of(16) as i32;@@ -446,5 +453,5 @@ pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {&Address::new(context, field(offset_of!(InstanceData, context))),);resume(&mut asm, context);- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}diff --git a/Libraries/LibWasm/JIT/src/stubs_aarch64.rs b/Libraries/LibWasm/JIT/src/stubs_aarch64.rsindex f6bfc49f4d7..29227214eda 100644--- a/Libraries/LibWasm/JIT/src/stubs_aarch64.rs+++ b/Libraries/LibWasm/JIT/src/stubs_aarch64.rs@@ -103,7 +103,8 @@ fn leave(asm: &mut Assembler) {/// The host stub for functions with these parameter and result types.pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);let parameter_slots = convention::slots(params) as i32;let result_slots = convention::slots(results) as i32;let buffer_slots = parameter_slots.max(result_slots);@@ -198,7 +199,7 @@ pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Veasm.bind(label);trap(&mut asm, code, runtime);}- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}/// What the entry trampoline calls compiled code with, and what it returns.@@ -238,7 +239,8 @@ pub const ADAPTER_SAVE_AREA: usize = 8 * 8 + 8 * 16;/// The trap exit: stores the code in w0 as the context's first argument, and the context in the frame that trapped/// (fp), and continues at the interpreter's TrapFromNative handler at `handler`.pub fn trap_exit(handler: u64) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);let context = SCRATCH;asm.ldr(Width::W64, context, MemOperand::Offset(FP, convention::FRAME_INSTANCE));asm.ldr(@@ -255,7 +257,7 @@ pub fn trap_exit(handler: u64) -> Vec<u8> {);asm.mov_imm(Width::W64, X17, handler);asm.br(X17);- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}/// Continues where the `resume` of the context in `context` says, as the runtime set it after unwinding an@@ -287,7 +289,8 @@ fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {/// the record in x19, which compiled code never uses, and saves nothing else: compiled code uses only the registers/// the host ABI does not preserve (see `convention`).pub fn entry_trampoline() -> (Vec<u8>, usize) {- let mut asm = Assembler::new();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);let record = Gpr(19);let call_field = |offset: usize| field(offset);asm.stp(FP, LR, PairOperand::PreIndex(SP, -32));@@ -403,7 +406,10 @@ pub fn entry_trampoline() -> (Vec<u8>, usize) {asm.ldp(record, Gpr(20), PairOperand::Offset(SP, 16));asm.ldp(FP, LR, PairOperand::PostIndex(SP, 32));asm.ret();- (asm.finish().expect("stubs have no unbound labels"), return_offset)+ (+ asm.finish().expect("stubs have no unbound labels").to_vec(),+ return_offset,+ )}/// What the runtime function of the adapter returns when the call threw an exception, which the runtime unwound: the@@ -414,7 +420,8 @@ pub const ADAPTER_RESUME: u64 = u64::MAX;/// with the callee's header, the save area and fp as the context's first three arguments. A nonzero result is a/// trap code, or `ADAPTER_RESUME`.pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = crate::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);let instance = x(convention::INSTANCE_REGISTER);// Below the frame header, the save area at sp.let frame_size = (convention::FRAME_HEADER_SIZE as usize + ADAPTER_SAVE_AREA).next_multiple_of(16) as i32;@@ -483,5 +490,5 @@ pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {MemOperand::Offset(context, field(offset_of!(InstanceData, context))),);resume(&mut asm, context);- asm.finish().expect("stubs have no unbound labels")+ asm.finish().expect("stubs have no unbound labels").to_vec()}diff --git a/Libraries/LibWasm/JIT/tests/harness/aarch64.rs b/Libraries/LibWasm/JIT/tests/harness/aarch64.rsindex b0e7463f163..4a6a9dc7fda 100644--- a/Libraries/LibWasm/JIT/tests/harness/aarch64.rs+++ b/Libraries/LibWasm/JIT/tests/harness/aarch64.rs@@ -36,13 +36,14 @@ fn operand(asm: &mut Assembler, base: Gpr, offset: i32, size_log2: u32) -> MemOp/// The trap exit, entered with the trap code in w0: returns 1 from the trampoline.pub(super) fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);asm.mov_imm(Width::W64, X16, state as u64);asm.str(Width::W32, Gpr(0), MemOperand::Offset(X16, TRAP_OFFSET));asm.ldr(Width::W64, X17, MemOperand::Offset(X16, ENTRY_SP_OFFSET));asm.mov_sp(SP, X17);restore_and_return(&mut asm, 1);- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}/// The code of functions the JIT did not compile.@@ -52,11 +53,12 @@ pub(super) fn not_compiled_code(trap_exit: u64) -> Vec<u8> {/// Code that traps with `code`.pub(super) fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);asm.mov_imm(Width::W32, Gpr(0), u64::from(code));asm.mov_imm(Width::W64, X16, trap_exit);asm.br(X16);- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}/// Restores what the trampoline saved, from sp at its entry_sp, and returns `status`.@@ -111,7 +113,8 @@ fn copy(asm: &mut Assembler, ty: Type, from: (Gpr, i32), to: (Gpr, i32)) {/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::new();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::new(&mut memory.code, &memory.work);asm.stp(FP, LR, PairOperand::PreIndex(SP, -SAVE_AREA));asm.mov_sp(FP, SP);for (index, pair) in [(19, 20), (21, 22), (23, 24), (25, 26), (27, 28)].iter().enumerate() {@@ -185,5 +188,5 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Ses}asm.add_any(SP, SP, outgoing, X17);restore_and_return(&mut asm, 0);- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}diff --git a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs b/Libraries/LibWasm/JIT/tests/harness/x86_64.rsindex 6a32e88fc51..98302ad5c64 100644--- a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs+++ b/Libraries/LibWasm/JIT/tests/harness/x86_64.rs@@ -19,14 +19,15 @@ const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F,/// The trap exit, entered with the trap code in edi: returns 1 from the trampoline.pub(super) fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let rax = Gpr(convention::RAX);let sp = Gpr(convention::RSP);asm.mov_ri(rax, state as u64);asm.mov_mr(Width::W32, &Address::new(rax, TRAP_OFFSET), Gpr(convention::RDI));asm.mov_rm(Width::W64, sp, &Address::new(rax, ENTRY_SP_OFFSET));restore_and_return(&mut asm, 1);- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}/// The code of functions the JIT did not compile.@@ -36,11 +37,12 @@ pub(super) fn not_compiled_code(trap_exit: u64) -> Vec<u8> {/// Code that traps with `code`.pub(super) fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);asm.mov_ri32(Gpr(convention::RDI), code);asm.mov_ri(Gpr(convention::R11), trap_exit);asm.jmp_r(Gpr(convention::R11));- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}fn restore_and_return(asm: &mut Assembler, status: u32) {@@ -62,7 +64,8 @@ fn restore_and_return(asm: &mut Assembler, status: u32) {/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {- let mut asm = Assembler::for_host();+ let mut memory = libwasm_jit::CodeMemory::new();+ let mut asm = Assembler::for_host(&mut memory.code, &memory.work);let g = Gpr;let (rdi, rsi, rdx, rcx) = (g(convention::RDI),@@ -186,5 +189,5 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Sesasm.add_ri(Width::W64, sp, outgoing);}restore_and_return(&mut asm, 0);- asm.finish().unwrap()+ asm.finish().unwrap().to_vec()}