Truly independent web browser
LibJS: Keep decoded instruction arrays and builder lists in a zone
Andreas Kling1e3153f0bc69
diff --git a/Libraries/LibJS/Flap/src/rust_bytecode.rs b/Libraries/LibJS/Flap/src/rust_bytecode.rsindex 53107df78de..eb254cc6ef0 100644--- a/Libraries/LibJS/Flap/src/rust_bytecode.rs+++ b/Libraries/LibJS/Flap/src/rust_bytecode.rs@@ -265,14 +265,31 @@ pub fn generate_instruction_length_from_bytes(Ok(())}+/// How the `Instruction` enum holds the trailing array of an instruction.+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum ArrayFields {+ /// A `Vec` of the elements: `Instruction` owns them.+ Owned,+ /// A slice of the elements: `Instruction<'a>` borrows them for `'a`.+ Borrowed,+}+/// Emit the `Instruction` enum with one variant per opcode. `derives` is the/// list of traits to derive, for example `"Debug, Clone"`.-pub fn generate_instruction_enum(mut w: impl Write, ops: &[InstructionDefinition], derives: &str) -> GeneratorResult {+pub fn generate_instruction_enum(+ mut w: impl Write,+ ops: &[InstructionDefinition],+ derives: &str,+ arrays: ArrayFields,+) -> GeneratorResult {writeln!(w, "/// A bytecode instruction with typed fields.")?;writeln!(w, "///")?;writeln!(w, "/// Each variant corresponds to one instruction definition.")?;writeln!(w, "#[derive({derives})]")?;- writeln!(w, "pub enum Instruction {{")?;+ match arrays {+ ArrayFields::Owned => writeln!(w, "pub enum Instruction {{")?,+ ArrayFields::Borrowed => writeln!(w, "pub enum Instruction<'a> {{")?,+ }for op in ops {let fields = user_fields(op);if fields.is_empty() {@@ -282,8 +299,10 @@ pub fn generate_instruction_enum(mut w: impl Write, ops: &[InstructionDefinitionfor f in &fields {let info = field_type_info(&f.ty);let r_name = rust_field_name(&f.name);- if f.is_array {+ if f.is_array && arrays == ArrayFields::Owned {writeln!(w, " {}: Vec<{}>,", r_name, info.rust_type)?;+ } else if f.is_array {+ writeln!(w, " {}: &'a [{}],", r_name, info.rust_type)?;} else {writeln!(w, " {}: {},", r_name, info.rust_type)?;}@@ -439,6 +458,7 @@ pub fn generate_encode_method(ops: &[InstructionDefinition],method_name: &str,encoder_type: &str,+ arrays: ArrayFields,) -> GeneratorResult {writeln!(w,@@ -461,6 +481,12 @@ pub fn generate_encode_method(op.name,bindings.join(", "))?;+ if arrays == ArrayFields::Borrowed {+ for f in fields.iter().filter(|f| f.is_array) {+ let name = rust_field_name(&f.name);+ writeln!(w, " let {name} = *{name};")?;+ }+ }}generate_encode_body(&mut w, op)?;diff --git a/Libraries/LibJS/JIT/Rust/build.rs b/Libraries/LibJS/JIT/Rust/build.rsindex 6a869d0aa55..4381f2e900a 100644--- a/Libraries/LibJS/JIT/Rust/build.rs+++ b/Libraries/LibJS/JIT/Rust/build.rs@@ -18,6 +18,7 @@ use flapc::metadata::SlowPathAbi as FlapSlowPathAbi;use flapc::metadata::SlowPathLayout;use flapc::metadata::field_type_info;use flapc::metadata::user_fields;+use flapc::rust_bytecode::ArrayFields;use flapc::rust_bytecode::InstructionSet;use flapc::rust_bytecode::count_field_name;use flapc::rust_bytecode::generate_encode_method;@@ -127,12 +128,12 @@ fn generate_decode_function(mut w: impl Write, ops: &[InstructionDefinition]) ->)?;writeln!(w,- "/// The caller has checked that the whole instruction lies within `bytes`."+ "/// The caller has checked that the whole instruction lies within `bytes`. The arrays of the instruction are in `zone`.")?;writeln!(w, "#[allow(unused_variables)]")?;writeln!(w,- "fn decode_fields(opcode: u8, bytes: &[u8], at: usize, length: usize) -> Result<Instruction, DecodeErrorKind> {{"+ "fn decode_fields<'a>(opcode: u8, bytes: &[u8], at: usize, length: usize, zone: &'a Zone) -> Result<Instruction<'a>, DecodeErrorKind> {{")?;writeln!(w, " match opcode {{")?;for (i, op) in ops.iter().enumerate() {@@ -159,7 +160,7 @@ fn generate_decode_function(mut w: impl Write, ops: &[InstructionDefinition]) ->);writeln!(w,- " let {name} = (0..{name}_len).map(|index| {element}).collect::<Vec<_>>();"+ " let {name} = &*zone.alloc_slice_from_iter((0..{name}_len).map(|index| {element}));")?;}if fields.is_empty() {@@ -227,7 +228,7 @@ fn generate_for_each_operand_method(mut w: impl Write, ops: &[InstructionDefinit)?,(true, false) => writeln!(w,- " for operand in {name} {{ visitor(*operand, {role}); }}"+ " for operand in *{name} {{ visitor(*operand, {role}); }}")?,(false, true) => writeln!(w,@@ -276,7 +277,7 @@ fn generate_for_each_jump_target_method(mut w: impl Write, ops: &[InstructionDefw," for label in {name}.iter().flatten() {{ visitor(*label); }}")?,- (true, false) => writeln!(w, " for label in {name} {{ visitor(*label); }}")?,+ (true, false) => writeln!(w, " for label in *{name} {{ visitor(*label); }}")?,(false, true) => writeln!(w, " if let Some(label) = {name} {{ visitor(*label); }}")?,(false, false) => writeln!(w, " visitor(*{name});")?,}@@ -345,14 +346,16 @@ fn generate_slow_path_layout_function(Ok(())}+/// The field types that name a feedback slot, with the field of `FeedbackSlots` for each.+const FEEDBACK_KINDS: [(&str, &str); 5] = [+ ("ArithFeedbackIndex", "arith"),+ ("ValueFeedbackIndex", "value"),+ ("CallFeedbackIndex", "call"),+ ("KeyedFeedbackIndex", "keyed"),+ ("ProfiledPropertyLookupCacheIndex", "cache_value"),+];+fn generate_feedback_slots_method(mut w: impl Write, ops: &[InstructionDefinition]) -> GeneratorResult {- const KINDS: [(&str, &str); 5] = [- ("ArithFeedbackIndex", "arith"),- ("ValueFeedbackIndex", "value"),- ("CallFeedbackIndex", "call"),- ("KeyedFeedbackIndex", "keyed"),- ("ProfiledPropertyLookupCacheIndex", "cache_value"),- ];writeln!(w," /// The interpreter feedback slots this instruction records into."@@ -363,7 +366,7 @@ fn generate_feedback_slots_method(mut w: impl Write, ops: &[InstructionDefinitiolet feedback_fields = user_fields(op).into_iter().filter_map(|field| {- KINDS+ FEEDBACK_KINDS.iter().find(|(ty, _)| *ty == field.ty).map(|(_, kind)| (rust_field_name(&field.name), *kind))@@ -399,6 +402,53 @@ fn generate_feedback_slots_method(mut w: impl Write, ops: &[InstructionDefinitioOk(())}+fn generate_feedback_slots_from_bytes_function(mut w: impl Write, ops: &[InstructionDefinition]) -> GeneratorResult {+ writeln!(+ w,+ "/// The interpreter feedback slots that the instruction with `opcode` at `bytes[at..]` records into. Reads"+ )?;+ writeln!(+ w,+ "/// nothing else of the instruction. The caller has checked that the whole instruction lies within `bytes`."+ )?;+ writeln!(+ w,+ "fn feedback_slots_from_bytes(opcode: u8, bytes: &[u8], at: usize) -> FeedbackSlots {{"+ )?;+ writeln!(w, " match opcode {{")?;+ for (i, op) in ops.iter().enumerate() {+ // NB: Every kind of feedback slot index, cache indices too, takes two bytes in the bytecode.+ let slots = user_fields(op)+ .into_iter()+ .filter_map(|field| {+ FEEDBACK_KINDS.iter().find(|(ty, _)| *ty == field.ty).map(|(_, kind)| {+ assert_eq!(+ field_type_info(&field.ty).size,+ 2,+ "feedback slot indices take two bytes"+ );+ let offset = op.layout.field_offsets[&field.name];+ format!("{kind}: Some({READER}read_u16(bytes, at + {offset}))")+ })+ })+ .collect::<Vec<_>>();+ if slots.is_empty() {+ continue;+ }+ writeln!(+ w,+ " {i} => FeedbackSlots {{ {}, ..FeedbackSlots::default() }}, // {}",+ slots.join(", "),+ op.name+ )?;+ }+ writeln!(w, " _ => FeedbackSlots::default(),")?;+ writeln!(w, " }}")?;+ writeln!(w, "}}")?;+ writeln!(w)?;+ Ok(())+}+fn generate_rust_code(mut w: impl Write, ops: &[InstructionDefinition], record_form_only: bool) -> GeneratorResult {writeln!(w, "// @generated from Libraries/LibJS/Interpreter/interpreter.flap")?;writeln!(w, "// Do not edit manually.")?;@@ -407,12 +457,13 @@ fn generate_rust_code(mut w: impl Write, ops: &[InstructionDefinition], record_fgenerate_opcode_enum(&mut w, ops)?;generate_num_opcodes_const(&mut w, ops)?;generate_opcode_impl(&mut w, ops)?;- generate_instruction_enum(&mut w, ops, "Debug, Clone, PartialEq, Eq")?;+ generate_instruction_enum(&mut w, ops, "Debug, Clone, Copy, PartialEq, Eq", ArrayFields::Borrowed)?;generate_instruction_length_from_bytes(&mut w, ops, "DecodeErrorKind")?;generate_decode_function(&mut w, ops)?;+ generate_feedback_slots_from_bytes_function(&mut w, ops)?;generate_slow_path_layout_function(&mut w, ops, record_form_only)?;- writeln!(w, "impl Instruction {{")?;+ writeln!(w, "impl Instruction<'_> {{")?;generate_opcode_method(&mut w, ops)?;generate_is_terminator_method(&mut w, ops)?;generate_for_each_operand_method(&mut w, ops)?;@@ -424,8 +475,8 @@ fn generate_rust_code(mut w: impl Write, ops: &[InstructionDefinition], record_f// The encoder lets the unit tests build instruction streams from typed instructions.writeln!(w, "#[cfg(test)]")?;writeln!(w, "#[allow(dead_code)]")?;- writeln!(w, "impl Instruction {{")?;- generate_encode_method(&mut w, ops, "encode_with", "TestEncoder<'_>")?;+ writeln!(w, "impl Instruction<'_> {{")?;+ generate_encode_method(&mut w, ops, "encode_with", "TestEncoder<'_>", ArrayFields::Borrowed)?;generate_encoded_size_method(&mut w, ops)?;writeln!(w,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rsindex ffff67e142c..1b26ab630cf 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs@@ -136,18 +136,19 @@ impl GraphBuilder<'_, '_> {if !self.can_allocate_array(elements.len()) {return Ok(false);}- let values = elements- .iter()- .map(|element| match element {- ArrayElement::Operand(operand) => self.read(*operand),- ArrayElement::Constant(bits) => Ok(self.constant(*bits)),- })- .collect::<Result<Vec<_>, _>>()?;+ let mut values = self.node_list();+ for element in elements {+ values.push(match element {+ ArrayElement::Operand(operand) => self.read(*operand)?,+ ArrayElement::Constant(bits) => self.constant(*bits),+ });+ }// NB: Holes (the empty value) make the elements holey, not packed.if values.iter().any(|value| self.graph.constant_value(*value) == Some(crate::ir::value::EMPTY)){+ self.release_node_list(values);return Ok(false);}let shape = self.runtime.array_allocation.shape;@@ -156,9 +157,10 @@ impl GraphBuilder<'_, '_> {}let count = u32::try_from(values.len()).expect("array literals have fewer than 2^32 elements");let array = self.emit(Op::AllocateArray { count }, &[], Some(Repr::Tagged));- for (index, value) in (0u32..).zip(values) {+ for (index, value) in (0u32..).zip(values.iter().copied()) {self.emit(Op::InitializeElement { index }, &[array, value], None);}+ self.release_node_list(values);self.write(dst, array)?;Ok(true)}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rsindex edfbb279c4b..9078638e4a3 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs@@ -350,7 +350,7 @@ impl<'a> GraphBuilder<'a, '_> {else {return Ok(None);};- let (forwarded, start) = match arguments.as_slice() {+ let (forwarded, start) = match *arguments {[forwarded] => (*forwarded, None),[forwarded, start] => (*forwarded, Some(*start)),_ => return Ok(None),@@ -399,7 +399,7 @@ impl<'a> GraphBuilder<'a, '_> {let Instruction::Call { callee, arguments, .. } = instruction else {return None;};- let [_, forwarded] = arguments.as_slice() else {+ let [_, forwarded] = *arguments else {return None;};// NB: CallForwardingArguments reads the running frame, which is not an@@ -440,7 +440,7 @@ impl<'a> GraphBuilder<'a, '_> {return Ok(None);};let call_pc = call.pc;- let call_instruction = call.instruction.clone();+ let call_instruction = call.instruction;let block = self.function.cfg.block_for_pc(self.function.pc);let in_one_block = block.is_some()&& block == self.function.cfg.block_for_pc(append.pc)diff --git a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rsindex 0ac437d94c9..38babe58453 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs@@ -25,7 +25,7 @@ use crate::ir::value;/// The `hint` of a `GetIterator` for synchronous iteration.const SYNC_HINT: u8 = 0;-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// The builtin `%ArrayIteratorPrototype%.next` of the realm of the/// compiled code, if `%ArrayIteratorPrototype%` held it when the/// snapshot was taken.@@ -79,26 +79,26 @@ impl GraphBuilder<'_, '_> {self.branch_to_next_case(&mut slow_paths,BranchCondition::HoldsValidWatchpointSet,- vec![watchpoint_set_address],+ &[watchpoint_set_address],true,);}- let array = self.branch_to_next_case(&mut slow_paths, BranchCondition::Object, vec![iterable], true);+ let array = self.branch_to_next_case(&mut slow_paths, BranchCondition::Object, &[iterable], true);let address = self.cell_address(array);self.embed(self.runtime.array_prototype);self.branch_to_next_case(&mut slow_paths,BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties,- vec![address],+ &[address],true,);- self.end_hot_path(&mut slow_paths, vec![first_index, array, not_done]);+ self.end_hot_path(&mut slow_paths, &[first_index, array, not_done]);let started = self.start_next_case(&mut slow_paths);debug_assert!(started, "values that fail the checks go on to the next case");let array = self.emit(Op::OpenArrayIteration, &[iterable], Some(Repr::Tagged));let array = self.branch_if_empty(&mut slow_paths, array);- let outputs = self.join_paths(slow_paths, vec![first_index, array, not_done], |_, outputs| outputs);+ let outputs = self.join_paths(slow_paths, &[first_index, array, not_done], |_, _| {});self.write(dst_iterator_object, outputs[0])?;self.write(dst_iterator_next, outputs[1])?;self.write(dst_iterator_done, outputs[2])?;@@ -139,40 +139,40 @@ impl GraphBuilder<'_, '_> {let kind = ElementsKind::Holey;// Fast array mode. NB: Iterations that are done take the slow path.- let index = self.branch_to_next_case(&mut slow_paths, BranchCondition::NonNegativeInt32, vec![iterator], true);+ let index = self.branch_to_next_case(&mut slow_paths, BranchCondition::NonNegativeInt32, &[iterator], true);self.branch_to_slow_path(&mut slow_paths,BranchCondition::TaggedEquals { equal: true },- vec![iterator_is_done, not_done],+ &[iterator_is_done, not_done],true,);- let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![next], true);- let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), vec![array], true);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[next], true);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), &[array], true);let array = self.cell_address(array);- let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, vec![array], true);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, &[array], true);let index = self.emit(Op::UnboxInt32, &[index], Some(Repr::Int32));let length = self.emit(Op::LoadElementsLength, &[array], Some(Repr::Int32));- let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, vec![index, length]);+ let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, &[index, length]);// NB: The done operand keeps the iteration done, also if the array// grows.self.block = outside;- self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);+ self.end_hot_path(&mut slow_paths, &[undefined, done, iterator, done]);self.block = inside;- let index = self.refine(BranchCondition::IndexInBounds, true, vec![index, length]);+ let index = self.refine(BranchCondition::IndexInBounds, true, &[index, length]);let element = self.load_array_iteration_element(&mut slow_paths, kind, array, index);// NB: The index is below the capacity, so the next one is an int32 too.let one = self.int32_constant(1);let next_index = self.emit_checked(Op::Int32Binary { op: BinaryOp::Add }, &[index, one], Some(Repr::Int32));let next_index = self.emit(Op::BoxInt32, &[next_index], Some(Repr::Tagged));- self.end_hot_path(&mut slow_paths, vec![element, not_done, next_index, iterator_is_done]);+ self.end_hot_path(&mut slow_paths, &[element, not_done, next_index, iterator_is_done]);// Array iterators. NB: Without them, the other values take the slow// path.let Some(builtin_next) = self.array_iterator_next() else {- let outputs = self.join_hot_paths_with(slow_paths, |_, outputs| outputs);- self.write_iterator_next_unpack_outputs(&outputs, dst_value, dst_done, iterator_object, iterator_done)?;+ let outputs = self.join_hot_paths_with(slow_paths, |_, _| {});+ self.write_iterator_next_unpack_outputs(outputs, dst_value, dst_done, iterator_object, iterator_done)?;return Ok(Some(Flow::Continue));};let started = self.start_next_case(&mut slow_paths);@@ -180,47 +180,43 @@ impl GraphBuilder<'_, '_> {self.branch_to_slow_path(&mut slow_paths,BranchCondition::TaggedEquals { equal: true },- vec![next, builtin_next],+ &[next, builtin_next],true,);- let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![iterator], true);+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[iterator], true);let object = self.cell_address(object);- let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ArrayIterator, vec![object], true);+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ArrayIterator, &[object], true);// NB: Done iterators no longer have an array.let array = self.emit(Op::LoadArrayIteratorArray, &[object], Some(Repr::Tagged));- let (exhausted, live) = self.branch_both_ways(BranchCondition::Undefined, vec![array]);+ let (exhausted, live) = self.branch_both_ways(BranchCondition::Undefined, &[array]);self.block = exhausted;- self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);+ self.end_hot_path(&mut slow_paths, &[undefined, done, iterator, done]);self.block = live;- let array = self.refine(BranchCondition::Undefined, false, vec![array]);- let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), vec![array], true);+ let array = self.refine(BranchCondition::Undefined, false, &[array]);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), &[array], true);let array = self.cell_address(array);// NB: Array iterators iterate array-likes up to their `length`,// which only arrays keep as the size of their elements.- let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, vec![array], true);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, &[array], true);let index = self.emit(Op::LoadArrayIteratorIndex, &[object], Some(Repr::Int32));let length = self.emit(Op::LoadElementsLength, &[array], Some(Repr::Int32));- let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, vec![index, length]);+ let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, &[index, length]);// NB: The array has no element at the index, so the iterator is done.self.block = outside;self.emit(Op::FinishArrayIterator, &[object], None);- self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);+ self.end_hot_path(&mut slow_paths, &[undefined, done, iterator, done]);self.block = inside;- let index = self.refine(BranchCondition::IndexInBounds, true, vec![index, length]);+ let index = self.refine(BranchCondition::IndexInBounds, true, &[index, length]);let element = self.load_array_iteration_element(&mut slow_paths, kind, array, index);let one = self.int32_constant(1);let next_index = self.emit_checked(Op::Int32Binary { op: BinaryOp::Add }, &[index, one], Some(Repr::Int32));self.emit(Op::StoreArrayIteratorIndex, &[object, next_index], None);- let outputs = self.join_paths(- slow_paths,- vec![element, not_done, iterator, iterator_is_done],- |_, outputs| outputs,- );- self.write_iterator_next_unpack_outputs(&outputs, dst_value, dst_done, iterator_object, iterator_done)?;+ let outputs = self.join_paths(slow_paths, &[element, not_done, iterator, iterator_is_done], |_, _| {});+ self.write_iterator_next_unpack_outputs(outputs, dst_value, dst_done, iterator_object, iterator_done)?;Ok(Some(Flow::Continue))}@@ -228,7 +224,7 @@ impl GraphBuilder<'_, '_> {/// take the slow path.fn load_array_iteration_element(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,kind: ElementsKind,array: NodeId,index: NodeId,@@ -237,7 +233,7 @@ impl GraphBuilder<'_, '_> {// Elements are accessed through the array (see// `element_storage_and_bound()`).let capacity = self.emit(Op::LoadElementsCapacity, &[array], Some(Repr::Int32));- let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, capacity], true);+ let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, &[index, capacity], true);let element = self.load_element(kind, array, index);self.branch_if_empty(slow_paths, element)}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rsindex 91905009f4a..f66c1770382 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs@@ -32,6 +32,7 @@ use crate::snapshot::Intrinsic;use crate::snapshot::PropertyCacheEntrySnapshot;use crate::snapshot::PropertyCacheEntryType;use crate::snapshot::PropertyCacheKind;+use ak::ZoneVec;/// Where the property an entry describes is.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -231,11 +232,11 @@ impl CacheEntry {}}-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// The entries of property lookup cache `cache` in their guard and/// action form, if the cache is monomorphic or polymorphic and compiled/// code can apply every entry.- pub(super) fn cache_entries(&self, cache: u32) -> Option<Vec<CacheEntry>> {+ pub(super) fn cache_entries(&self, cache: u32) -> Option<&'a [CacheEntry]> {let cache = self.snapshot[self.function.executable.property_caches].get(cache as usize)?;if !matches!(cache.kind,@@ -244,13 +245,18 @@ impl GraphBuilder<'_, '_> {{return None;}- self.snapshot[cache.entries].iter().map(CacheEntry::of).collect()+ let snapshots = &self.snapshot[cache.entries];+ let mut entries = ZoneVec::with_capacity_in(snapshots.len(), self.work);+ for entry in snapshots {+ entries.push(CacheEntry::of(entry)?);+ }+ Some(entries.into_slice())}/// The entry of megamorphic property lookup cache `cache` for the shape/// the code knows the object in `object` has (see/// `AbstractFrame::fresh_shapes`), if the snapshot captured one.- pub(super) fn megamorphic_entries_for_known_shape(&self, cache: u32, object: Operand) -> Option<Vec<CacheEntry>> {+ pub(super) fn megamorphic_entries_for_known_shape(&self, cache: u32, object: Operand) -> Option<&'a [CacheEntry]> {let cache = self.snapshot[self.function.executable.property_caches].get(cache as usize)?;if cache.kind != PropertyCacheKind::Megamorphic {return None;@@ -260,7 +266,7 @@ impl GraphBuilder<'_, '_> {.iter().filter_map(CacheEntry::of).find(|entry| entry.shape.shape == shape)?;- Some(vec![entry])+ Some(self.work.alloc_slice_copy(&[entry]))}/// The shape guard of an entry. Records whether the shape was stable,@@ -284,7 +290,8 @@ impl GraphBuilder<'_, '_> {apply: impl FnMut(&mut Self, &CacheEntry, NodeId) -> Option<NodeId>,) -> Option<NodeId> {let entries = self.entries_for_known_shape(object, entries);- let shapes = entries.iter().map(|entry| self.shape_guard(entry)).collect::<Vec<_>>();+ let work = self.work;+ let shapes = ZoneVec::from_iter_in(entries.iter().map(|entry| self.shape_guard(entry)), work);// NB: The action applies the first entry's, so entries that differ in whether the property holds data do not// share one.let one_action = entries.iter().all(|entry| {@@ -341,7 +348,7 @@ impl GraphBuilder<'_, '_> {let source = self.block;let frame = self.frame.clone();let frame_state = self.eager_frame_state();- let mut cases = Vec::with_capacity(shapes.len());+ let mut cases = ZoneVec::with_capacity_in(shapes.len(), self.work);for shape in shapes {let block = self.graph.add_block(Block {predecessors: self.graph.list(&[source]),@@ -363,13 +370,17 @@ impl GraphBuilder<'_, '_> {self.graph.nodes[switch.index()].frame_state = Some(frame_state);let join = self.graph.add_block(self.graph.new_block());- let mut results = Vec::new();- let mut case_shapes = Vec::with_capacity(cases.len());+ let mut results = ZoneVec::with_capacity_in(cases.len(), self.work);+ let mut every_case_has_a_result = true;+ let mut case_shapes = ZoneVec::with_capacity_in(cases.len(), self.work);for (index, (shape, block)) in cases.iter().enumerate() {self.block = *block;- self.frame = frame.clone();- let refined = self.refine(BranchCondition::Shape(*shape), true, vec![object, address]);- results.push(case(self, index, refined));+ self.frame.clone_from(&frame);+ let refined = self.refine(BranchCondition::Shape(*shape), true, &[object, address]);+ match case(self, index, refined) {+ Some(result) => results.push(result),+ None => every_case_has_a_result = false,+ }debug_assert_eq!(self.frame.slots, frame.slots, "cases do not change frame slots");self.set_control(Op::Jump { target: join }, &[]);self.graph.blocks[join.index()].predecessors.push(self.block);@@ -382,7 +393,9 @@ impl GraphBuilder<'_, '_> {self.frame.set_common_fresh_shapes(case_shapes.iter().map(|shapes| shapes.as_slice()));- let results = results.into_iter().collect::<Option<Vec<_>>>()?;+ if !every_case_has_a_result {+ return None;+ }if results.iter().all(|result| *result == results[0]) {return Some(results[0]);}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex 0ffca2b56ff..3e6c79ea7a8 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -29,8 +29,9 @@ use crate::ir::FrameStateId;use crate::ir::NodeId;use crate::ir::Op;use crate::ir::value;+use ak::ZoneVec;-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// Builds an instruction whose handling is `Handling::Expanded`.pub(super) fn build_expanded(&mut self,@@ -63,11 +64,11 @@ impl GraphBuilder<'_, '_> {}Instruction::ThrowIfNotObject { src } => {let value = self.read(src)?;- self.build_throwing_check(BranchCondition::Object, vec![value], false)+ self.build_throwing_check(BranchCondition::Object, &[value], false)}Instruction::ThrowIfNullish { src } => {let value = self.read(src)?;- self.build_throwing_check(BranchCondition::Nullish, vec![value], true)+ self.build_throwing_check(BranchCondition::Nullish, &[value], true)}Instruction::ToObject { dst, value } => self.build_conversion(BranchCondition::Object, true, dst, value),Instruction::ToLength { dst, value } => {@@ -146,14 +147,15 @@ impl GraphBuilder<'_, '_> {pub(super) fn build_throwing_check(&mut self,condition: BranchCondition,- inputs: Vec<NodeId>,+ inputs: &[NodeId],throws_when: bool,) -> Result<Flow, CompileFailure> {let frame_state = self.eager_frame_state();let slow_path_inputs = self.slow_path_inputs()?;let (next, cold) = self.branch_with_cold_side(condition, inputs, !throws_when);self.block = cold;- self.emit_call_slow_path(slow_path_inputs, frame_state, None);+ self.emit_call_slow_path(&slow_path_inputs, frame_state, None);+ self.release_node_list(slow_path_inputs);self.set_control(Op::Unreachable, &[]);self.block = next;Ok(Flow::Continue)@@ -169,8 +171,8 @@ impl GraphBuilder<'_, '_> {}let empty = self.constant(value::EMPTY);let condition = BranchCondition::TaggedEquals { equal: true };- self.build_throwing_check(condition, vec![value, empty], true)?;- Ok(self.refine(condition, false, vec![value, empty]))+ self.build_throwing_check(condition, &[value, empty], true)?;+ Ok(self.refine(condition, false, &[value, empty]))}/// Writes `src` to `dst` where `condition` of it is `unchanged_when`, and@@ -185,10 +187,11 @@ impl GraphBuilder<'_, '_> {let frame_state = self.eager_frame_state();let value = self.read(src)?;let slow_path_inputs = self.slow_path_inputs()?;- let (hot, cold) = self.branch_with_cold_side(condition, vec![value], unchanged_when);+ let (hot, cold) = self.branch_with_cold_side(condition, &[value], unchanged_when);self.block = cold;- let converted = self.emit_call_slow_path(slow_path_inputs, frame_state, Some(Repr::Tagged));- self.join_blocks(vec![hot, cold]);+ let converted = self.emit_call_slow_path(&slow_path_inputs, frame_state, Some(Repr::Tagged));+ self.release_node_list(slow_path_inputs);+ self.join_blocks(&[hot, cold]);let result = self.add_phi(&[value, converted]);self.write(dst, result)?;Ok(Flow::Continue)@@ -220,13 +223,13 @@ impl GraphBuilder<'_, '_> {let empty = self.constant(value::EMPTY);let (hot, cold) = self.branch_with_cold_side(BranchCondition::TaggedEquals { equal: true },- vec![this_value, empty],+ &[this_value, empty],false,);self.block = cold;// NB: The slow path's value is the this value it resolved.- let resolved = self.emit_call_slow_path(Vec::new(), frame_state, Some(Repr::Tagged));- self.join_blocks(vec![hot, cold]);+ let resolved = self.emit_call_slow_path(&[], frame_state, Some(Repr::Tagged));+ self.join_blocks(&[hot, cold]);let result = self.add_phi(&[this_value, resolved]);self.frame.slots[slot] = SlotState { node: result, in_sync };Ok(Flow::Continue)@@ -249,9 +252,9 @@ impl GraphBuilder<'_, '_> {/// Ends `predecessors` with jumps to a new block, in which building/// continues. Phis of the new block take their inputs in the order of/// `predecessors`.- pub(super) fn join_blocks(&mut self, predecessors: Vec<BlockId>) -> BlockId {- let join = self.start_new_block(&predecessors);- for block in predecessors {+ pub(super) fn join_blocks(&mut self, predecessors: &[BlockId]) -> BlockId {+ let join = self.start_new_block(predecessors);+ for &block in predecessors {self.block = block;self.set_control(Op::Jump { target: join }, &[]);}@@ -264,16 +267,10 @@ impl GraphBuilder<'_, '_> {/// `bytecode::slow_path_layout()`), with the empty value for absent/// ones: the inputs of its `CallSlowPath` node. Read before the/// instruction branches, so that the values are in the abstract frame- /// on every path.- pub(super) fn slow_path_inputs(&mut self) -> Result<Vec<NodeId>, CompileFailure> {- self.slow_path_operands()?- .inputs- .into_iter()- .map(|operand| match operand {- Operand::INVALID => Ok(self.constant(value::EMPTY)),- raw => self.read(Operand::from_raw(raw)),- })- .collect()+ /// on every path. The list is to give back with `release_node_list()`.+ pub(super) fn slow_path_inputs(&mut self) -> Result<ZoneVec<'a, NodeId>, CompileFailure> {+ let operands = self.slow_path_operands()?;+ self.read_slow_path_inputs(operands)}fn opcode(&self) -> OpCode {@@ -286,7 +283,7 @@ impl GraphBuilder<'_, '_> {/// instruction's eager frame state.pub(super) fn emit_call_slow_path(&mut self,- inputs: Vec<NodeId>,+ inputs: &[NodeId],frame_state: FrameStateId,repr: Option<Repr>,) -> NodeId {@@ -297,7 +294,7 @@ impl GraphBuilder<'_, '_> {pc: self.function.pc,saves_registers: true,},- &inputs,+ inputs,repr,);self.graph.nodes[node.index()].frame_state = Some(frame_state);@@ -309,13 +306,14 @@ impl GraphBuilder<'_, '_> {/// `repr` if the instruction writes one: the frame state and the/// operands of the slow path are the instruction's, before any of it/// ran.- pub(super) fn start_slow_paths(&mut self, repr: Option<Repr>) -> Result<SlowPaths, CompileFailure> {+ pub(super) fn start_slow_paths(&mut self, repr: Option<Repr>) -> Result<SlowPaths<'a>, CompileFailure> {let frame_state = self.eager_frame_state();- let inputs = self.slow_path_inputs()?;+ let operands = self.slow_path_operands()?;+ let inputs = self.read_slow_path_inputs(operands)?;// NB: The value of a conditional jump's slow path is the pc it// jumps to.let output_count = if repr.is_some() {- self.slow_path_operands()?.outputs.len().max(1)+ operands.output_count().max(1)} else {0};@@ -324,9 +322,9 @@ impl GraphBuilder<'_, '_> {inputs,repr,output_count,- hot: Vec::new(),- cold: Vec::new(),- next_case: Vec::new(),+ hot: ZoneVec::new_in(self.work),+ cold: ZoneVec::new_in(self.work),+ next_case: ZoneVec::new_in(self.work),exits: None,})}@@ -336,14 +334,14 @@ impl GraphBuilder<'_, '_> {/// before. The code after the instruction then joins no path that ran/// other code, so it keeps what it knew before the instruction. For/// instructions whose slow path only handles rare cases.- pub(super) fn exit_instead_of_slow_path(&mut self, slow_paths: &mut SlowPaths) {+ pub(super) fn exit_instead_of_slow_path(&mut self, slow_paths: &mut SlowPaths<'a>) {self.exit_with_instead_of_slow_path(slow_paths, ExitKind::SlowPath);}/// Like `exit_instead_of_slow_path()`, exiting with `kind`, for/// instructions whose other speculations exit with `ExitKind::SlowPath`/// and should not go once such an exit was taken.- pub(super) fn exit_with_instead_of_slow_path(&mut self, slow_paths: &mut SlowPaths, kind: ExitKind) {+ pub(super) fn exit_with_instead_of_slow_path(&mut self, slow_paths: &mut SlowPaths<'a>, kind: ExitKind) {slow_paths.exits = self.may_speculate(kind).then_some(kind);}@@ -354,12 +352,12 @@ impl GraphBuilder<'_, '_> {/// input in the new block, for the nodes that rely on the condition.pub(super) fn branch_to_slow_path(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,condition: BranchCondition,- inputs: Vec<NodeId>,+ inputs: &[NodeId],continue_when: bool,) -> NodeId {- let (hot, cold) = self.branch_with_cold_side(condition, inputs.clone(), continue_when);+ let (hot, cold) = self.branch_with_cold_side(condition, inputs, continue_when);slow_paths.cold.push(cold);self.block = hot;self.refine(condition, continue_when, inputs)@@ -370,12 +368,12 @@ impl GraphBuilder<'_, '_> {/// `start_next_case()`) instead, or to the slow path if there is none.pub(super) fn branch_to_next_case(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,condition: BranchCondition,- inputs: Vec<NodeId>,+ inputs: &[NodeId],continue_when: bool,) -> NodeId {- let (if_true, if_false) = self.branch_both_ways(condition, inputs.clone());+ let (if_true, if_false) = self.branch_both_ways(condition, inputs);let (hot, edge) = if continue_when {(if_true, if_false)} else {@@ -389,8 +387,8 @@ impl GraphBuilder<'_, '_> {/// Starts a block where the values that `branch_to_next_case()` sent on/// continue, in which building continues. Returns false, and starts/// nothing, if none did.- pub(super) fn start_next_case(&mut self, slow_paths: &mut SlowPaths) -> bool {- let edges = std::mem::take(&mut slow_paths.next_case);+ pub(super) fn start_next_case(&mut self, slow_paths: &mut SlowPaths<'a>) -> bool {+ let edges = slow_paths.next_case.take();match edges.as_slice() {[] => return false,// NB: A single edge is the case's block itself.@@ -400,24 +398,24 @@ impl GraphBuilder<'_, '_> {}_ => {}}- self.join_blocks(edges);+ self.join_blocks(&edges);true}/// The refinement of the first of `inputs`, at the head of the current/// block, which only the edge of a branch on `condition` of `inputs`/// where it is `holds` reaches (see `Op::Refine`).- pub(super) fn refine(&mut self, condition: BranchCondition, holds: bool, inputs: Vec<NodeId>) -> NodeId {+ pub(super) fn refine(&mut self, condition: BranchCondition, holds: bool, inputs: &[NodeId]) -> NodeId {let repr = self.graph.node(inputs[0]).repr;- self.emit(Op::Refine { condition, holds }, &inputs, repr)+ self.emit(Op::Refine { condition, holds }, inputs, repr)}/// Ends the current block as one of several paths that completed the/// instruction, with `values` like `join_paths()`/// takes them, to be joined with the others there. Building continues/// in another block.- pub(super) fn end_hot_path(&mut self, slow_paths: &mut SlowPaths, values: Vec<NodeId>) {- slow_paths.hot.push((self.block, values));+ pub(super) fn end_hot_path(&mut self, slow_paths: &mut SlowPaths<'a>, values: &[NodeId]) {+ slow_paths.hot.push((self.block, self.work.alloc_slice_copy(values)));}/// Ends the current block with a branch on `condition` of `inputs` to a@@ -426,7 +424,7 @@ impl GraphBuilder<'_, '_> {pub(super) fn branch_with_cold_side(&mut self,condition: BranchCondition,- inputs: Vec<NodeId>,+ inputs: &[NodeId],continue_when: bool,) -> (BlockId, BlockId) {let source = self.block;@@ -439,14 +437,14 @@ impl GraphBuilder<'_, '_> {if_true,if_false,},- &inputs,+ inputs,);(hot, cold)}/// Ends the current block with a branch on `condition` of `inputs` to/// two new blocks, and returns them: where it holds, and where not.- pub(super) fn branch_both_ways(&mut self, condition: BranchCondition, inputs: Vec<NodeId>) -> (BlockId, BlockId) {+ pub(super) fn branch_both_ways(&mut self, condition: BranchCondition, inputs: &[NodeId]) -> (BlockId, BlockId) {let source = self.block;let if_true = self.add_block_after(source);let if_false = self.add_block_after(source);@@ -456,7 +454,7 @@ impl GraphBuilder<'_, '_> {if_true,if_false,},- &inputs,+ inputs,);(if_true, if_false)}@@ -468,21 +466,21 @@ impl GraphBuilder<'_, '_> {/// take a slow path otherwise.pub(super) fn branch_on_cases(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,value: NodeId,conditions: &[BranchCondition],others: bool,- mut build: impl FnMut(&mut Self, &mut SlowPaths, usize, NodeId),+ mut build: impl FnMut(&mut Self, &mut SlowPaths<'a>, usize, NodeId),) {for (index, condition) in conditions.iter().enumerate() {if index + 1 == conditions.len() && !others {- let refined = self.branch_to_slow_path(slow_paths, *condition, vec![value], true);+ let refined = self.branch_to_slow_path(slow_paths, *condition, &[value], true);build(self, slow_paths, index, refined);return;}- let (matched, other) = self.branch_both_ways(*condition, vec![value]);+ let (matched, other) = self.branch_both_ways(*condition, &[value]);self.block = matched;- let refined = self.refine(*condition, true, vec![value]);+ let refined = self.refine(*condition, true, &[value]);build(self, slow_paths, index, refined);self.block = other;}@@ -494,42 +492,40 @@ impl GraphBuilder<'_, '_> {let empty = self.constant(value::EMPTY);let condition = BranchCondition::TaggedEquals { equal: true };let frame_state = self.eager_frame_state();- let (hot, cold) = self.branch_with_cold_side(condition, vec![value, empty], false);+ let (hot, cold) = self.branch_with_cold_side(condition, &[value, empty], false);self.block = cold;let exit = self.set_control(Op::Exit { kind }, &[]);self.graph.nodes[exit.index()].frame_state = Some(frame_state);self.block = hot;- self.refine(condition, false, vec![value, empty])+ self.refine(condition, false, &[value, empty])}/// `value`, refined to not be the empty value (a hole, or nothing found/// by a cache probe), taking a slow path where it is.- pub(super) fn branch_if_empty(&mut self, slow_paths: &mut SlowPaths, value: NodeId) -> NodeId {+ pub(super) fn branch_if_empty(&mut self, slow_paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {let empty = self.constant(value::EMPTY);self.branch_to_slow_path(slow_paths,BranchCondition::TaggedEquals { equal: true },- vec![value, empty],+ &[value, empty],false,)}/// Joins the paths that `end_hot_path()` ended with the slow paths, and/// returns the instruction's value, if it has one.- pub(super) fn join_hot_paths(&mut self, slow_paths: SlowPaths) -> Option<NodeId> {- self.join_hot_paths_with(slow_paths, |_, outputs| outputs)- .into_iter()- .next()+ pub(super) fn join_hot_paths(&mut self, slow_paths: SlowPaths<'a>) -> Option<NodeId> {+ self.join_hot_paths_with(slow_paths, |_, _| {}).first().copied()}/// Like `join_hot_paths()`, for instructions that write several/// operands, where `values` makes their values of the outputs of the- /// slow path, in the slow path's block.+ /// slow path, in the slow path's block, in place of the outputs.pub(super) fn join_hot_paths_with(&mut self,- mut slow_paths: SlowPaths,- values: impl FnOnce(&mut Self, Vec<NodeId>) -> Vec<NodeId>,- ) -> Vec<NodeId> {+ mut slow_paths: SlowPaths<'a>,+ values: impl FnOnce(&mut Self, &mut ZoneVec<'a, NodeId>),+ ) -> &'a [NodeId] {let (block, hot_values) = slow_paths.take_last_hot_path();self.block = block;self.join_paths(slow_paths, hot_values, values)@@ -540,65 +536,66 @@ impl GraphBuilder<'_, '_> {/// continues. Returns the/// instruction's value there: the phi of `value`, its value in the/// current block, and the slow paths' values.- pub(super) fn join_slow_paths(&mut self, slow_paths: SlowPaths, value: Option<NodeId>) -> Option<NodeId> {- self.join_paths(slow_paths, value.into_iter().collect(), |_, outputs| outputs)- .into_iter()- .next()+ pub(super) fn join_slow_paths(&mut self, slow_paths: SlowPaths<'a>, value: Option<NodeId>) -> Option<NodeId> {+ self.join_paths(slow_paths, value.as_slice(), |_, _| {})+ .first()+ .copied()}/// Like `join_slow_paths()`, for an instruction that writes several/// operands: `values` are their values in the current block, in the/// order of the slow path's outputs, `slow_values` makes them of the- /// outputs of the slow path, in its block, and this returns their phis.+ /// outputs of the slow path, in its block, in place of the outputs, and+ /// this returns their phis.pub(super) fn join_paths(&mut self,- mut slow_paths: SlowPaths,- values: Vec<NodeId>,- slow_values: impl FnOnce(&mut Self, Vec<NodeId>) -> Vec<NodeId>,- ) -> Vec<NodeId> {- let mut predecessors = slow_paths.hot.iter().map(|(block, _)| *block).collect::<Vec<_>>();+ mut slow_paths: SlowPaths<'a>,+ values: &[NodeId],+ slow_values: impl FnOnce(&mut Self, &mut ZoneVec<'a, NodeId>),+ ) -> &'a [NodeId] {+ let mut predecessors = ZoneVec::with_capacity_in(slow_paths.hot.len() + 2, self.work);+ predecessors.extend(slow_paths.hot.iter().map(|(block, _)| *block));predecessors.push(self.block);// NB: Values that no case took take the slow path.- for edge in std::mem::take(&mut slow_paths.next_case) {+ for edge in slow_paths.next_case.take() {self.graph.blocks[edge.index()].is_cold = true;slow_paths.cold.push(edge);}- let slow = self.build_slow_path(&slow_paths).map(|(_, outputs)| {- let values = slow_values(self, outputs);- (self.block, values)+ let slow = self.build_slow_path(&slow_paths).map(|mut outputs| {+ slow_values(self, &mut outputs);+ (self.block, outputs)});predecessors.extend(slow.as_ref().map(|(block, _)| *block));- self.join_blocks(predecessors);+ self.join_blocks(&predecessors);assert!(values.is_empty() || values.len() == slow_paths.output_count,"the slow path writes the same operands");- values- .into_iter()- .enumerate()- .map(|(index, value)| {- let mut inputs = slow_paths- .hot- .iter()- .map(|(_, values)| values[index])- .collect::<Vec<_>>();- inputs.push(value);- inputs.extend(slow.as_ref().map(|(_, outputs)| outputs[index]));- if inputs.iter().all(|input| *input == inputs[0]) {- return inputs[0];- }- let repr = self.graph.node(value).repr;- let phi = self.add_phi(&inputs);- self.graph.nodes[phi.index()].repr = repr;- phi- })- .collect()+ let mut inputs = self.node_list();+ let mut phis = ZoneVec::with_capacity_in(values.len(), self.work);+ for (index, &value) in values.iter().enumerate() {+ inputs.clear();+ inputs.extend(slow_paths.hot.iter().map(|(_, values)| values[index]));+ inputs.push(value);+ inputs.extend(slow.as_ref().map(|(_, outputs)| outputs[index]));+ if inputs.iter().all(|input| *input == inputs[0]) {+ phis.push(inputs[0]);+ continue;+ }+ let repr = self.graph.node(value).repr;+ let phi = self.add_phi(&inputs);+ self.graph.nodes[phi.index()].repr = repr;+ phis.push(phi);+ }+ self.release_node_list(inputs);+ self.release_node_list(slow_paths.inputs);+ phis.into_slice()}/// The block running the slow path of `slow_paths`, which every cold/// edge they took jumps to, with the operands the slow path wrote, if- /// any edge was taken.- fn build_slow_path(&mut self, slow_paths: &SlowPaths) -> Option<(BlockId, Vec<NodeId>)> {+ /// any edge was taken. The current block is that block.+ fn build_slow_path(&mut self, slow_paths: &SlowPaths<'a>) -> Option<ZoneVec<'a, NodeId>> {if let Some(kind) = slow_paths.exits {for edge in &slow_paths.cold {self.block = *edge;@@ -611,49 +608,50 @@ impl GraphBuilder<'_, '_> {[] => return None,[edge] => *edge,edges => {- let slow = self.join_blocks(edges.to_vec());+ let slow = self.join_blocks(edges);self.graph.blocks[slow.index()].is_cold = true;slow}};self.block = slow;- let call = self.emit_call_slow_path(slow_paths.inputs.clone(), slow_paths.frame_state, slow_paths.repr);- let mut outputs = vec![call];+ let call = self.emit_call_slow_path(&slow_paths.inputs, slow_paths.frame_state, slow_paths.repr);+ let mut outputs = ZoneVec::with_capacity_in(slow_paths.output_count.max(1), self.work);+ outputs.push(call);for index in 1..slow_paths.output_count {let index = u8::try_from(index).expect("slow paths have few outputs");outputs.push(self.emit(Op::SlowPathOutput { index }, &[call], Some(Repr::Tagged)));}- Some((slow, outputs))+ Some(outputs)}}/// The paths of an instruction built as IR so far: the cold edges to its/// slow path, the other paths that completed it, and what the slow path/// takes (see `GraphBuilder::start_slow_paths()`).-pub(in crate::builder) struct SlowPaths {+pub(in crate::builder) struct SlowPaths<'a> {frame_state: FrameStateId,- inputs: Vec<NodeId>,+ inputs: ZoneVec<'a, NodeId>,repr: Option<Repr>,/// How many operands the slow path writes.output_count: usize,/// The other blocks that completed the instruction (see/// `GraphBuilder::end_hot_path()`), with their values.- hot: Vec<(BlockId, Vec<NodeId>)>,+ hot: ZoneVec<'a, (BlockId, &'a [NodeId])>,/// The cold edges taken so far, which all jump to one block running the/// slow path (see `GraphBuilder::build_slow_path()`).- cold: Vec<BlockId>,+ cold: ZoneVec<'a, BlockId>,/// The edges that `GraphBuilder::branch_to_next_case()` took since the/// last case started.- next_case: Vec<BlockId>,+ next_case: ZoneVec<'a, BlockId>,/// The kind of exit the cold edges take instead, if they exit (see/// `GraphBuilder::exit_instead_of_slow_path()`).exits: Option<ExitKind>,}-impl SlowPaths {+impl<'a> SlowPaths<'a> {/// The last path that `GraphBuilder::end_hot_path()` ended, which no/// longer is one of them.- pub(in crate::builder) fn take_last_hot_path(&mut self) -> (BlockId, Vec<NodeId>) {+ pub(in crate::builder) fn take_last_hot_path(&mut self) -> (BlockId, &'a [NodeId]) {self.hot.pop().expect("a path completed the instruction")}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/elements.rs b/Libraries/LibJS/JIT/Rust/src/builder/elements.rsindex f8f6f24a0e4..1e87b718ca2 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/elements.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/elements.rs@@ -43,11 +43,10 @@ impl GraphBuilder<'_, '_> {}/// The typed array element kinds keyed feedback `bits` saw.- pub(super) fn typed_array_elements_seen(&self, bits: u32) -> Vec<TypedArrayElement> {- TypedArrayElement::ALL- .into_iter()- .filter(|element| bits & (1 << (TYPED_ARRAY_SHIFT + u32::from(self.typed_array_kind_value(*element)))) != 0)- .collect()+ pub(super) fn typed_array_elements_seen(&self, bits: u32) -> impl Iterator<Item = TypedArrayElement> + '_ {+ TypedArrayElement::ALL.into_iter().filter(move |element| {+ bits & (1 << (TYPED_ARRAY_SHIFT + u32::from(self.typed_array_kind_value(*element)))) != 0+ })}/// The elements kind the keyed feedback of `instruction` saw, if it saw@@ -57,12 +56,13 @@ impl GraphBuilder<'_, '_> {if bits & KEY_KINDS_MASK != INT32_INDEX || bits & (OTHER_ELEMENTS | OUT_OF_BOUNDS) != 0 {return None;}- let typed_arrays = self.typed_array_elements_seen(bits);- let kind = match (bits & (PACKED | HOLEY), typed_arrays.as_slice()) {- (PACKED, []) => ElementsKind::Packed,+ let mut typed_arrays = self.typed_array_elements_seen(bits);+ let (first_typed_array, more_typed_arrays) = (typed_arrays.next(), typed_arrays.next().is_some());+ let kind = match (bits & (PACKED | HOLEY), first_typed_array, more_typed_arrays) {+ (PACKED, None, _) => ElementsKind::Packed,// NB: Holey accesses take packed elements too.- (HOLEY | PACKED_AND_HOLEY, []) => ElementsKind::Holey,- (0, [element]) => ElementsKind::TypedArray(*element),+ (HOLEY | PACKED_AND_HOLEY, None, _) => ElementsKind::Holey,+ (0, Some(element), false) => ElementsKind::TypedArray(element),_ => return None,};let gates = [ExitKind::BadElements, ExitKind::OutOfBounds, ExitKind::NotInt32];diff --git a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs b/Libraries/LibJS/JIT/Rust/src/builder/environments.rsindex 210b45c7952..c776248ecc1 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/environments.rs@@ -210,7 +210,7 @@ impl GraphBuilder<'_, '_> {BranchCondition::BindingMutable {index: coordinate.index,},- vec![environment],+ &[environment],true,);}@@ -225,7 +225,7 @@ impl GraphBuilder<'_, '_> {self.branch_to_slow_path(&mut slow_paths,BranchCondition::TaggedEquals { equal: false },- vec![binding, empty],+ &[binding, empty],true,);self.emit(@@ -275,7 +275,7 @@ impl GraphBuilder<'_, '_> {self.branch_to_slow_path(&mut slow_paths,BranchCondition::NextBindingOfShape { name, flags },- vec![environment],+ &[environment],true,);self.emit(Op::AppendEnvironmentBinding, &[environment], None);diff --git a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs b/Libraries/LibJS/JIT/Rust/src/builder/globals.rsindex 83facd06b6a..f9b32e5ac45 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/globals.rs@@ -260,7 +260,7 @@ impl GraphBuilder<'_, '_> {&[value, realm, executable],Some(Repr::Bool),);- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, vec![stored], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, &[stored], true);self.join_slow_paths(slow_paths, None);Ok(Flow::Continue)}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex af61f15612b..b3cc02d13ed 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -1057,7 +1057,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {}}Forwarding::Apply => {- let [this, forwarded_arguments] = arguments.as_slice() else {+ let [this, forwarded_arguments] = *arguments else {return Ok(None);};if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeApply)@@ -1147,7 +1147,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {};// NB: An inlined callee forwards what its call passed it.if self.constant_intrinsic(*callee) == Some(Intrinsic::FunctionPrototypeApply)- && let [this, forwarded_arguments] = arguments.as_slice()+ && let [this, forwarded_arguments] = *arguments&& self.holds_virtual_arguments(*forwarded_arguments)&& let Some((arguments, count)) = self.inlined_call_arguments(){@@ -1361,10 +1361,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {// no branch.(None, Some(callee_value)) if case + 1 < cases.len() => {let expected = self.constant(*bits);- let (if_true, if_false) = self.branch_both_ways(- BranchCondition::TaggedEquals { equal: true },- vec![callee_value, expected],- );+ let (if_true, if_false) =+ self.branch_both_ways(BranchCondition::TaggedEquals { equal: true }, &[callee_value, expected]);self.block = if_true;next_case = Some(if_false);}@@ -1410,7 +1408,10 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {if results.is_empty() {return Ok(Some(Flow::Ended));}- self.join_blocks(results.iter().map(|(block, _, _)| *block).collect());+ self.join_blocks(&ZoneVec::from_iter_in(+ results.iter().map(|(block, _, _)| *block),+ self.work,+ ));if edges.is_some() {// NB: The callee's phi no longer reaches here.let mut functions = ZoneVec::with_capacity_in(results.len(), self.work);@@ -1628,7 +1629,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {let Some(executable) = self.snapshot.executables.get(index as usize) else {return true;};- let Ok(decoded) = super::decoded_function(self.snapshot, executable, &self.decoded[index as usize]) else {+ let Ok(decoded) = super::decoded_function(self.snapshot, executable, &self.decoded[index as usize], self.work)+ else {return true;};let exit_sites = &self.snapshot[executable.exit_sites];@@ -2151,8 +2153,12 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {if callee_executable.builtin {return true;}- let Ok(decoded) = super::decoded_function(self.snapshot, callee_executable, &self.decoded[index as usize])- else {+ let Ok(decoded) = super::decoded_function(+ self.snapshot,+ callee_executable,+ &self.decoded[index as usize],+ self.work,+ ) else {return false;};self.inlined_instructions + decoded.instructions.len()@@ -2185,12 +2191,13 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {if !may_inline {return None;}- let decoded = super::decoded_function(snapshot, callee_executable, &self.decoded[index as usize]).ok()?;+ let decoded =+ super::decoded_function(snapshot, callee_executable, &self.decoded[index as usize], self.work).ok()?;let instruction_count = decoded.instructions.len();let limits = snapshot.options.inlining;// NB: Builtins are always inlined (see the snapshot's inlining rules).let within_budget = callee_executable.builtin- || crate::bytecode::inlining_size(&decoded.instructions) <= limits.always_inlined_instructions as usize+ || crate::bytecode::inlining_size(decoded.instructions) <= limits.always_inlined_instructions as usize|| (kind != InlinedCallKind::Call && instruction_count <= limits.max_construct_instructions as usize)|| (instruction_count <= limits.max_instructions as usize&& self.inlined_instructions + instruction_count <= limits.budget_instructions as usize);diff --git a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rsindex d238c80cc55..127084e7978 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs@@ -28,6 +28,7 @@ use crate::snapshot::HelperOperand;use crate::snapshot::HelperResult;use crate::snapshot::Intrinsic;use crate::snapshot::value_feedback;+use ak::ZoneVec;/// What a call of a string builtin that reads a character returns.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -48,7 +49,7 @@ const MAX_INLINE_SPLICED_VALUES: usize = crate::codegen::DIRECT_CALL_MAX_INPUTS/// How many arguments `try_build_math_min_max()` compares inline at most.const MAX_MIN_MAX_ARGUMENTS: usize = 8;-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// Calls the packed-array splice helper without a native frame. It/// declines before doing anything observable for receivers or species/// constructors that require the ordinary call.@@ -89,7 +90,8 @@ impl GraphBuilder<'_, '_> {}let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;let receiver = self.read(*this_value)?;- let mut inputs = vec![receiver];+ let mut inputs = self.node_list();+ inputs.push(receiver);for (index, argument) in arguments.iter().enumerate() {let value = self.read(*argument)?;inputs.push(if index < 2 {@@ -99,6 +101,7 @@ impl GraphBuilder<'_, '_> {});}let result = self.emit(Op::CallArraySplice, &inputs, Some(Repr::Tagged));+ self.release_node_list(inputs);let result = self.branch_if_empty(&mut slow_paths, result);let result = self.join_slow_paths(slow_paths, Some(result))@@ -117,7 +120,7 @@ impl GraphBuilder<'_, '_> {dst,callee,this_value,- ref arguments,+ arguments,..} = *instructionelse {@@ -223,7 +226,7 @@ impl GraphBuilder<'_, '_> {let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;self.exit_instead_of_slow_path(&mut slow_paths);if target.is_none() {- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), vec![callee], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), &[callee], true);}let result = if let Some(integer) = self.int32_value_of(argument) {self.build_int32_math_function(&mut slow_paths, op, integer)@@ -232,21 +235,21 @@ impl GraphBuilder<'_, '_> {self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged))} else {// NB: Int32 arguments, then doubles.- let (int32, other) = self.branch_both_ways(BranchCondition::Int32Value, vec![argument]);+ let (int32, other) = self.branch_both_ways(BranchCondition::Int32Value, &[argument]);self.block = other;- let double = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Double, vec![argument], true);+ let double = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Double, &[argument], true);let double = self.emit(Op::UnboxDouble, &[double], Some(Repr::Float64));let result = self.emit(Op::Float64Unary { op }, &[double], Some(Repr::Float64));let double_result = self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged));let double = self.block;self.block = int32;- let integer = self.refine(BranchCondition::Int32Value, true, vec![argument]);+ let integer = self.refine(BranchCondition::Int32Value, true, &[argument]);let integer = self.emit(Op::UnboxInt32, &[integer], Some(Repr::Int32));let int32_result = self.build_int32_math_function(&mut slow_paths, op, integer);let int32 = self.block;- self.join_blocks(vec![int32, double]);+ self.join_blocks(&[int32, double]);self.add_phi(&[int32_result, double_result])};let result = self@@ -285,20 +288,22 @@ impl GraphBuilder<'_, '_> {self.check_callee(callee, target)?;}let callee = self.read(callee)?;- let arguments = arguments- .iter()- .map(|argument| self.read(*argument))- .collect::<Result<Vec<_>, _>>()?;+ let mut values = self.node_list();+ for argument in arguments {+ values.push(self.read(*argument)?);+ }let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;self.exit_instead_of_slow_path(&mut slow_paths);if target.is_none() {- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), vec![callee], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), &[callee], true);+ }+ let mut numbers = self.node_list();+ for &value in &values {+ numbers.push(self.float64_of_number(&mut slow_paths, value));}- let numbers = arguments- .into_iter()- .map(|argument| self.float64_of_number(&mut slow_paths, argument))- .collect::<Vec<_>>();let result = self.emit(Op::CallFloat64Function { function }, &numbers, Some(Repr::Float64));+ self.release_node_list(numbers);+ self.release_node_list(values);let result = self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged));let result = self.join_slow_paths(slow_paths, Some(result))@@ -339,7 +344,7 @@ impl GraphBuilder<'_, '_> {/// `value` as a `Repr::Float64`, where it is a number, taking a slow/// path of `slow_paths` otherwise.- pub(super) fn float64_of_number(&mut self, slow_paths: &mut SlowPaths, value: NodeId) -> NodeId {+ pub(super) fn float64_of_number(&mut self, slow_paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {self.float64_of(value, |builder, condition, inputs| {builder.branch_to_slow_path(slow_paths, condition, inputs, true)})@@ -347,12 +352,12 @@ impl GraphBuilder<'_, '_> {/// `value` as a `Repr::Int32`, where it is an int32, taking a slow path/// of `slow_paths` otherwise.- pub(super) fn int32_or_slow_path(&mut self, slow_paths: &mut SlowPaths, value: NodeId) -> NodeId {+ pub(super) fn int32_or_slow_path(&mut self, slow_paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {if let Some(integer) = self.int32_value_of(value) {return integer;}let value = self.tagged(value);- let refined = self.branch_to_slow_path(slow_paths, BranchCondition::Int32Value, vec![value], true);+ let refined = self.branch_to_slow_path(slow_paths, BranchCondition::Int32Value, &[value], true);self.emit(Op::UnboxInt32, &[refined], Some(Repr::Int32))}@@ -368,7 +373,7 @@ impl GraphBuilder<'_, '_> {repr: Repr,int32: fn(&mut Self, NodeId) -> NodeId,double: fn(&mut Self, NodeId) -> NodeId,- otherwise: impl FnOnce(&mut Self, BranchCondition, Vec<NodeId>) -> NodeId,+ otherwise: impl FnOnce(&mut Self, BranchCondition, &[NodeId]) -> NodeId,) -> NodeId {self.on_integer_or_double(BranchCondition::Int32Value, value, repr, int32, double, otherwise)}@@ -383,22 +388,22 @@ impl GraphBuilder<'_, '_> {repr: Repr,int32: fn(&mut Self, NodeId) -> NodeId,double: fn(&mut Self, NodeId) -> NodeId,- otherwise: impl FnOnce(&mut Self, BranchCondition, Vec<NodeId>) -> NodeId,+ otherwise: impl FnOnce(&mut Self, BranchCondition, &[NodeId]) -> NodeId,) -> NodeId {- let (int32_block, other) = self.branch_both_ways(integer, vec![value]);+ let (int32_block, other) = self.branch_both_ways(integer, &[value]);self.block = int32_block;- let refined = self.refine(integer, true, vec![value]);+ let refined = self.refine(integer, true, &[value]);let integer = self.emit(Op::UnboxInt32, &[refined], Some(Repr::Int32));let int32_value = int32(self, integer);let int32_end = self.block;self.block = other;- let refined = otherwise(self, BranchCondition::Double, vec![value]);+ let refined = otherwise(self, BranchCondition::Double, &[value]);let number = self.emit(Op::UnboxDouble, &[refined], Some(Repr::Float64));let double_value = double(self, number);let double_end = self.block;- self.join_blocks(vec![int32_end, double_end]);+ self.join_blocks(&[int32_end, double_end]);let phi = self.add_phi(&[int32_value, double_value]);self.graph.nodes[phi.index()].repr = Some(repr);phi@@ -408,7 +413,12 @@ impl GraphBuilder<'_, '_> {/// `integer`: itself for the functions that round, and the absolute/// value but for the smallest int32, whose absolute value is no int32/// and goes to a slow path of `slow_paths`.- fn build_int32_math_function(&mut self, slow_paths: &mut SlowPaths, op: Float64UnaryOp, integer: NodeId) -> NodeId {+ fn build_int32_math_function(+ &mut self,+ slow_paths: &mut SlowPaths<'a>,+ op: Float64UnaryOp,+ integer: NodeId,+ ) -> NodeId {match op {Float64UnaryOp::Floor | Float64UnaryOp::Ceil | Float64UnaryOp::Round => self.tagged(integer),// NB: Negating the smallest int32 overflows, and exits.@@ -423,7 +433,7 @@ impl GraphBuilder<'_, '_> {let integer = self.branch_to_slow_path(slow_paths,BranchCondition::Int32(Comparison::StrictlyEquals),- vec![integer, smallest],+ &[integer, smallest],false,);let result = self.emit(Op::Int32Abs, &[integer], Some(Repr::Int32));@@ -460,7 +470,7 @@ impl GraphBuilder<'_, '_> {let string = self.read(this_value)?;let index = self.read(argument)?;let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), vec![callee], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), &[callee], true);let index = self.int32_or_slow_path(&mut slow_paths, index);let code_unit = self.string_code_unit(&mut slow_paths, string, index);let result = match character {@@ -477,23 +487,23 @@ impl GraphBuilder<'_, '_> {/// The code unit at `index`, a `Repr::Int32`, of the tagged `string`,/// taking a slow path of `slow_paths` unless it is a string whose/// characters can be read and the index is in its bounds.- pub(super) fn string_code_unit(&mut self, slow_paths: &mut SlowPaths, string: NodeId, index: NodeId) -> NodeId {- let string = self.branch_to_slow_path(slow_paths, BranchCondition::String, vec![string], true);+ pub(super) fn string_code_unit(&mut self, slow_paths: &mut SlowPaths<'a>, string: NodeId, index: NodeId) -> NodeId {+ let string = self.branch_to_slow_path(slow_paths, BranchCondition::String, &[string], true);let address = self.emit(Op::StringAddress, &[string], Some(Repr::Pointer));- let readable = self.branch_to_slow_path(slow_paths, BranchCondition::ResolvedString, vec![address], true);+ let readable = self.branch_to_slow_path(slow_paths, BranchCondition::ResolvedString, &[address], true);let length = self.emit(Op::StringLength, &[address], Some(Repr::Int32));- let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, length], true);+ let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, &[index, length], true);self.emit(Op::LoadStringCodeUnit, &[readable, index], Some(Repr::Int32))}/// The VM's string of `code_unit`, taking a slow path of `slow_paths`/// unless it is ASCII.- pub(super) fn ascii_character_string(&mut self, slow_paths: &mut SlowPaths, code_unit: NodeId) -> NodeId {+ pub(super) fn ascii_character_string(&mut self, slow_paths: &mut SlowPaths<'a>, code_unit: NodeId) -> NodeId {let limit = self.int32_constant(0x80);let code_unit = self.branch_to_slow_path(slow_paths,BranchCondition::Int32(Comparison::LessThan),- vec![code_unit, limit],+ &[code_unit, limit],true,);self.emit(Op::SingleCharacterString, &[code_unit], Some(Repr::Tagged))@@ -531,10 +541,10 @@ impl GraphBuilder<'_, '_> {return Ok(None);}let receiver = self.read(*this_value)?;- let values = arguments- .iter()- .map(|value| self.read(*value))- .collect::<Result<Vec<_>, _>>()?;+ let mut values = self.node_list();+ for value in *arguments {+ values.push(self.read(*value)?);+ }self.embed(self.runtime.array_prototype);self.embed(self.runtime.object_prototype);let receiver = self.emit_checked(Op::CheckAppendableArray, &[receiver], Some(Repr::Tagged));@@ -546,7 +556,7 @@ impl GraphBuilder<'_, '_> {// values) never fit. More values need that much room between// them, which only overflows for such lengths, and exits for them.let (room_condition, room_inputs) = if values.len() == 1 {- (BranchCondition::IndexInBounds, vec![length, capacity])+ (BranchCondition::IndexInBounds, &[length, capacity])} else {let room = self.emit_checked(Op::Int32Binary { op: BinaryOp::Sub },@@ -554,9 +564,9 @@ impl GraphBuilder<'_, '_> {Some(Repr::Int32),);let count = self.int32_constant(values.len() as i32);- (BranchCondition::Int32(Comparison::GreaterThanEquals), vec![room, count])+ (BranchCondition::Int32(Comparison::GreaterThanEquals), &[room, count])};- let (hot, cold) = self.branch_with_cold_side(room_condition, room_inputs.clone(), true);+ let (hot, cold) = self.branch_with_cold_side(room_condition, room_inputs, true);self.block = cold;let mut pushed = None;for value in &values {@@ -570,12 +580,13 @@ impl GraphBuilder<'_, '_> {} else {length};- for value in values {+ for &value in &values {new_length = self.emit(Op::AppendElement, &[array, new_length, value], Some(Repr::Int32));}+ self.release_node_list(values);let new_length = self.emit(Op::BoxInt32, &[new_length], Some(Repr::Tagged));let hot = self.block;- self.join_blocks(vec![hot, cold]);+ self.join_blocks(&[hot, cold]);let length = self.add_phi(&[new_length, pushed]);self.write(*dst, length)?;Ok(Some(Flow::Continue))@@ -593,7 +604,7 @@ impl GraphBuilder<'_, '_> {call_feedback,dst,callee,- ref arguments,+ arguments,..} = *instructionelse {@@ -619,10 +630,10 @@ impl GraphBuilder<'_, '_> {if !self.may_speculate(ExitKind::BadCallTarget) {return Ok(None);}- let values = arguments- .iter()- .map(|operand| self.read_value(*operand))- .collect::<Result<Vec<_>, _>>()?;+ let mut values = self.node_list();+ for operand in arguments {+ values.push(self.read_value(*operand)?);+ }// NB: Int32 results do not prove int32 arguments (Math.min(1, 2.5)// is 1). Arguments that are no int32 values exit, and code compiled// after the exit computes with doubles. The results are numbers@@ -631,30 +642,35 @@ impl GraphBuilder<'_, '_> {&& self.may_speculate(ExitKind::NotInt32)&& self.may_be_int32(&values);if !int32 && !self.may_speculate(ExitKind::BadType) {+ self.release_node_list(values);return Ok(None);}self.check_callee(callee, target)?;+ // NB: All the arguments are converted before the first of the operations on them.let result = if int32 {let op = if max { Op::Int32Max } else { Op::Int32Min };+ for value in &mut values {+ *value = self.int32(*value);+ }let result = values- .into_iter()- .map(|value| self.int32(value))- .collect::<Vec<_>>()- .into_iter()+ .iter()+ .copied().reduce(|result, value| self.emit(op.clone(), &[result, value], Some(Repr::Int32))).expect("there are arguments");self.emit(Op::BoxInt32, &[result], Some(Repr::Tagged))} else {let op = if max { Op::Float64Max } else { Op::Float64Min };+ for value in &mut values {+ *value = self.number(*value);+ }let result = values- .into_iter()- .map(|value| self.number(value))- .collect::<Vec<_>>()- .into_iter()+ .iter()+ .copied().reduce(|result, number| self.emit(op.clone(), &[result, number], Some(Repr::Float64))).expect("there are arguments");self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged))};+ self.release_node_list(values);self.write(dst, result)?;Ok(Some(Flow::Continue))}@@ -667,7 +683,7 @@ impl GraphBuilder<'_, '_> {call_feedback,dst,callee,- ref arguments,+ arguments,..} = *instructionelse {@@ -763,7 +779,7 @@ impl GraphBuilder<'_, '_> {// NB: Other numbers are lengths that throw, and other// values elements.let length =- self.branch_to_slow_path(&mut slow_paths, BranchCondition::NonNegativeInt32, vec![length], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::NonNegativeInt32, &[length], true);self.emit(Op::UnboxInt32, &[length], Some(Repr::Int32))}None => self.int32_constant(0),@@ -808,7 +824,7 @@ impl GraphBuilder<'_, '_> {if arguments.iter().any(|operand| self.holds_virtual_arguments(*operand)) {return Ok(None);}- if let [length] = arguments.as_slice() {+ if let [length] = *arguments {if self.checked_intrinsic_callee(*call_feedback, *callee)?.is_none() {return Ok(None);}@@ -821,11 +837,10 @@ impl GraphBuilder<'_, '_> {{return Ok(None);}- let elements = arguments- .iter()- .copied()- .map(super::allocation::ArrayElement::Operand)- .collect::<Vec<_>>();+ let elements = ZoneVec::from_iter_in(+ arguments.iter().copied().map(super::allocation::ArrayElement::Operand),+ self.work,+ );// NB: Arrays with holes are left to the generic construct, which reading the operands does not affect.if !self.try_build_new_array(*dst, &elements)? {return Ok(None);@@ -895,42 +910,42 @@ impl GraphBuilder<'_, '_> {let value = self.read(*argument)?;let result = if constructor == Intrinsic::StringConstructor {// 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value- let (string, other) = self.branch_both_ways(BranchCondition::String, vec![value]);+ let (string, other) = self.branch_both_ways(BranchCondition::String, &[value]);self.block = string;- let string = self.refine(BranchCondition::String, true, vec![value]);- self.end_hot_path(&mut slow_paths, vec![string]);+ let string = self.refine(BranchCondition::String, true, &[value]);+ self.end_hot_path(&mut slow_paths, &[string]);// NB: The VM has the strings of small integers.self.block = other;- let (int32, other) = self.branch_both_ways(BranchCondition::Int32Value, vec![value]);+ let (int32, other) = self.branch_both_ways(BranchCondition::Int32Value, &[value]);self.block = int32;- let integer = self.refine(BranchCondition::Int32Value, true, vec![value]);+ let integer = self.refine(BranchCondition::Int32Value, true, &[value]);let unboxed = self.emit(Op::UnboxInt32, &[integer], Some(Repr::Int32));let cached = self.emit(Op::IntegerToString, &[unboxed], Some(Repr::Tagged));let empty = self.constant(crate::ir::value::EMPTY);let missing = BranchCondition::TaggedEquals { equal: true };- let (miss, hit) = self.branch_both_ways(missing, vec![cached, empty]);+ let (miss, hit) = self.branch_both_ways(missing, &[cached, empty]);self.block = hit;- let cached = self.refine(missing, false, vec![cached, empty]);- self.end_hot_path(&mut slow_paths, vec![cached]);+ let cached = self.refine(missing, false, &[cached, empty]);+ self.end_hot_path(&mut slow_paths, &[cached]);self.block = miss;let string = self.emit(Op::PrimitiveToString, &[integer], Some(Repr::Tagged));- self.end_hot_path(&mut slow_paths, vec![string]);+ self.end_hot_path(&mut slow_paths, &[string]);self.block = other;- let primitive = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![value], false);+ let primitive = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[value], false);self.emit(Op::PrimitiveToString, &[primitive], Some(Repr::Tagged))} else {// 20.1.1.1 Object ( [ value ] ), https://tc39.es/ecma262/#sec-object-value- let (object, other) = self.branch_both_ways(BranchCondition::Object, vec![value]);+ let (object, other) = self.branch_both_ways(BranchCondition::Object, &[value]);self.block = object;- let object = self.refine(BranchCondition::Object, true, vec![value]);- self.end_hot_path(&mut slow_paths, vec![object]);+ let object = self.refine(BranchCondition::Object, true, &[value]);+ self.end_hot_path(&mut slow_paths, &[object]);self.block = other;- let primitive = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Nullish, vec![value], false);+ let primitive = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Nullish, &[value], false);let function = self.read(*callee)?;let object = self.emit(Op::ToObject, &[primitive, function], Some(Repr::Tagged));self.branch_if_empty(&mut slow_paths, object)};- self.end_hot_path(&mut slow_paths, vec![result]);+ self.end_hot_path(&mut slow_paths, &[result]);let result = self.join_hot_paths(slow_paths).expect("calls have a value");self.write(*dst, result)?;Ok(Some(Flow::Continue))@@ -993,7 +1008,7 @@ impl GraphBuilder<'_, '_> {return Ok(None);}let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;- let mut inputs = Vec::with_capacity(1 + call.arguments.len());+ let mut inputs = self.node_list();let operands = std::iter::once(Some(*this_value)).chain((0..call.arguments.len()).map(|index| arguments.get(index).copied()));for (operand, kind) in operands.zip(std::iter::once(call.receiver).chain(call.arguments.iter().copied())) {@@ -1001,7 +1016,7 @@ impl GraphBuilder<'_, '_> {(Some(operand), HelperOperand::Value) => self.read(operand)?,(Some(operand), HelperOperand::String) => {let value = self.read(operand)?;- self.branch_to_slow_path(&mut slow_paths, BranchCondition::String, vec![value], true)+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::String, &[value], true)}(Some(operand), HelperOperand::Int32 { .. }) => {let value = self.read(operand)?;@@ -1013,6 +1028,7 @@ impl GraphBuilder<'_, '_> {inputs.push(input);}let result = self.emit(Op::CallIntrinsic { intrinsic }, &inputs, Some(call.result.repr()));+ self.release_node_list(inputs);let result = match call.result {HelperResult::Int32 => self.emit(Op::BoxInt32, &[result], Some(Repr::Tagged)),HelperResult::Bool => self.emit(Op::BoxBool, &[result], Some(Repr::Tagged)),@@ -1058,7 +1074,7 @@ impl GraphBuilder<'_, '_> {let code_unit = self.branch_to_slow_path(&mut slow_paths,BranchCondition::Int32(Comparison::LessThan),- vec![code_unit, ascii_limit],+ &[code_unit, ascii_limit],true,);let string = self.emit(Op::SingleCharacterString, &[code_unit], Some(Repr::Tagged));@@ -1103,7 +1119,7 @@ impl GraphBuilder<'_, '_> {let key = self.read_value(property)?;let value = self.read(value)?;let index = self.int32_or_slow_path(&mut slow_paths, key);- let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![object], true);+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[object], true);let kinds = [ElementsKind::Packed, ElementsKind::Holey];let conditions = kinds.map(BranchCondition::ElementsKind);self.branch_on_cases(@@ -1120,7 +1136,7 @@ impl GraphBuilder<'_, '_> {// NB: Filling a hole defines a new element, which takes an// extensible object. Filling the last one may make the// elements packed, which the slow path does.- builder.branch_to_slow_path(slow_paths, BranchCondition::Extensible, vec![address], true);+ builder.branch_to_slow_path(slow_paths, BranchCondition::Extensible, &[address], true);let (_, index) = builder.element_index_in_bounds(slow_paths, kind, address, index);let length = builder.emit(Op::LoadElementsLength, &[address], Some(Repr::Int32));let one = builder.int32_constant(1);@@ -1128,12 +1144,12 @@ impl GraphBuilder<'_, '_> {builder.branch_to_slow_path(slow_paths,BranchCondition::Int32(Comparison::LessThan),- vec![index, last],+ &[index, last],true,)};builder.emit(Op::StoreElementAt { kind }, &[address, index, value], None);- builder.end_hot_path(slow_paths, Vec::new());+ builder.end_hot_path(slow_paths, &[]);},);self.join_hot_paths(slow_paths);diff --git a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rsindex 23711bb1c28..e15fab2bbdd 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs@@ -49,6 +49,7 @@ use crate::snapshot::keyed_feedback_bits::PACKED;use crate::snapshot::keyed_feedback_bits::STRING_KEY;use crate::snapshot::keyed_feedback_bits::SYMBOL_KEY;use crate::snapshot::keyed_feedback_bits::TYPED_ARRAY_SHIFT;+use ak::ZoneVec;/// What a site is built for without keyed feedback: every key and every/// elements kind, like the interpreter handles them inline.@@ -63,7 +64,7 @@ struct KeyPaths {named: Option<(BlockId, NodeId)>,}-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// What the keyed feedback of `instruction` saw, or everything if it saw/// nothing.fn keyed_access_bits(&self, instruction: &Instruction) -> u32 {@@ -74,19 +75,15 @@ impl GraphBuilder<'_, '_> {}/// The elements kinds keyed feedback `bits` saw for int32 keys.- fn elements_kinds_seen(&self, bits: u32) -> Vec<ElementsKind> {- let mut kinds = Vec::new();+ fn elements_kinds_seen(&self, bits: u32) -> ZoneVec<'a, ElementsKind> {+ let mut kinds = ZoneVec::new_in(self.work);if bits & INT32_INDEX != 0 && bits & PACKED != 0 {kinds.push(ElementsKind::Packed);}if bits & INT32_INDEX != 0 && bits & HOLEY != 0 {kinds.push(ElementsKind::Holey);}- kinds.extend(- self.typed_array_elements_seen(bits)- .into_iter()- .map(ElementsKind::TypedArray),- );+ kinds.extend(self.typed_array_elements_seen(bits).map(ElementsKind::TypedArray));kinds}@@ -95,7 +92,13 @@ impl GraphBuilder<'_, '_> {/// with the key, each in a block of its own if a key may be either. Keys/// of kinds the feedback never saw take a slow path. Returns `None`,/// having built nothing, if keys like `key` take no path.- fn split_key(&mut self, slow_paths: &mut SlowPaths, key: NodeId, indexed: bool, named: bool) -> Option<KeyPaths> {+ fn split_key(+ &mut self,+ slow_paths: &mut SlowPaths<'a>,+ key: NodeId,+ indexed: bool,+ named: bool,+ ) -> Option<KeyPaths> {if !indexed && !named {return None;}@@ -114,12 +117,12 @@ impl GraphBuilder<'_, '_> {return named.then_some(paths);}let integer = if !named {- self.branch_to_slow_path(slow_paths, BranchCondition::Int32Value, vec![key], true)+ self.branch_to_slow_path(slow_paths, BranchCondition::Int32Value, &[key], true)} else if indexed {- let (integer, other) = self.branch_both_ways(BranchCondition::Int32Value, vec![key]);+ let (integer, other) = self.branch_both_ways(BranchCondition::Int32Value, &[key]);paths.named = Some((other, key));self.block = integer;- self.refine(BranchCondition::Int32Value, true, vec![key])+ self.refine(BranchCondition::Int32Value, true, &[key])} else {// NB: The cache lookup misses for int32 keys.paths.named = Some((self.block, key));@@ -135,13 +138,13 @@ impl GraphBuilder<'_, '_> {/// bounds, taking a slow path where it is not.pub(super) fn element_index_in_bounds(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,kind: ElementsKind,address: NodeId,index: NodeId,) -> (NodeId, NodeId) {let (storage, bound) = self.element_storage_and_bound(kind, address);- let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, bound], true);+ let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, &[index, bound], true);(storage, index)}@@ -152,17 +155,17 @@ impl GraphBuilder<'_, '_> {/// the elements where they have no room for it, and the access is done.pub(super) fn element_index_or_append(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,object: NodeId,address: NodeId,index: NodeId,value: NodeId,) -> NodeId {let length = self.emit(Op::LoadElementsLength, &[address], Some(Repr::Int32));- let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, vec![index, length]);+ let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, &[index, length]);self.block = outside;let next = BranchCondition::Int32(Comparison::StrictlyEquals);- let next_index = self.branch_to_slow_path(slow_paths, next, vec![index, length], true);+ let next_index = self.branch_to_slow_path(slow_paths, next, &[index, length], true);let array = self.emit_checked(Op::CheckAppendableArray, &[object], None);let array_address = self.cell_address(array);let capacity = self.emit(Op::LoadElementsCapacity, &[array_address], Some(Repr::Int32));@@ -172,42 +175,37 @@ impl GraphBuilder<'_, '_> {// which runs no code either, but at such lengths, whose keys are// no indices, which the slow path stores.let room = BranchCondition::IndexInBounds;- let (hot, cold) = self.branch_with_cold_side(room, vec![next_index, capacity], true);+ let (hot, cold) = self.branch_with_cold_side(room, &[next_index, capacity], true);self.block = cold;let zero = self.int32_constant(0);let nonnegative = BranchCondition::Int32(Comparison::GreaterThanEquals);- self.branch_to_slow_path(slow_paths, nonnegative, vec![next_index, zero], true);+ self.branch_to_slow_path(slow_paths, nonnegative, &[next_index, zero], true);self.graph.blocks[self.block.index()].is_cold = true;self.emit(Op::CallArrayPush, &[array, value], Some(Repr::Tagged));- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);self.block = hot;- let next_index = self.refine(room, true, vec![next_index, capacity]);+ let next_index = self.refine(room, true, &[next_index, capacity]);self.emit(Op::AppendElement,&[array_address, next_index, value],Some(Repr::Int32),);- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);self.block = inside;- let index = self.refine(BranchCondition::IndexInBounds, true, vec![index, length]);+ let index = self.refine(BranchCondition::IndexInBounds, true, &[index, length]);let capacity = self.emit(Op::LoadElementsCapacity, &[address], Some(Repr::Int32));- self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, capacity], true)+ self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, &[index, capacity], true)}/// Ends the current block, where the object at `address` has no element/// at a non-negative index, as a path that read undefined, if its/// prototype chain has no indexed properties. Takes the slow path/// otherwise.- fn read_missing_element(&mut self, slow_paths: &mut SlowPaths, address: NodeId) {- self.branch_to_slow_path(- slow_paths,- BranchCondition::PlainArrayPrototypeChain,- vec![address],- true,- );+ fn read_missing_element(&mut self, slow_paths: &mut SlowPaths<'a>, address: NodeId) {+ self.branch_to_slow_path(slow_paths, BranchCondition::PlainArrayPrototypeChain, &[address], true);let undefined = self.constant(value::UNDEFINED);- self.end_hot_path(slow_paths, vec![undefined]);+ self.end_hot_path(slow_paths, &[undefined]);}/// Builds `GetByValue` (`Handling::Expanded`) for the keys and elements@@ -249,11 +247,7 @@ impl GraphBuilder<'_, '_> {if let Some((block, index)) = paths.indexed {self.block = block;- let conditions = kinds- .iter()- .copied()- .map(BranchCondition::ElementsKind)- .collect::<Vec<_>>();+ let conditions = ZoneVec::from_iter_in(kinds.iter().copied().map(BranchCondition::ElementsKind), self.work);self.branch_on_cases(&mut slow_paths,object,@@ -269,40 +263,36 @@ impl GraphBuilder<'_, '_> {if kind == ElementsKind::Holey {element = builder.branch_if_empty(slow_paths, element);}- builder.end_hot_path(slow_paths, vec![element]);+ builder.end_hot_path(slow_paths, &[element]);return;}let (storage, bound) = builder.element_storage_and_bound(kind, address);- let (inside, outside) =- builder.branch_both_ways(BranchCondition::IndexInBounds, vec![index, bound]);+ let (inside, outside) = builder.branch_both_ways(BranchCondition::IndexInBounds, &[index, bound]);builder.block = outside;let zero = builder.int32_constant(0);builder.branch_to_slow_path(slow_paths,BranchCondition::Int32(Comparison::GreaterThanEquals),- vec![index, zero],+ &[index, zero],true,);builder.read_missing_element(slow_paths, address);builder.block = inside;- let index = builder.refine(BranchCondition::IndexInBounds, true, vec![index, bound]);+ let index = builder.refine(BranchCondition::IndexInBounds, true, &[index, bound]);let element = builder.load_element(kind, storage, index);let element = builder.tagged(element);if kind == ElementsKind::Holey {let empty = builder.constant(value::EMPTY);- let (hole, present) = builder- .branch_both_ways(BranchCondition::TaggedEquals { equal: true }, vec![element, empty]);+ let (hole, present) =+ builder.branch_both_ways(BranchCondition::TaggedEquals { equal: true }, &[element, empty]);builder.block = hole;builder.read_missing_element(slow_paths, address);builder.block = present;- let element = builder.refine(- BranchCondition::TaggedEquals { equal: true },- false,- vec![element, empty],- );- builder.end_hot_path(slow_paths, vec![element]);+ let element =+ builder.refine(BranchCondition::TaggedEquals { equal: true }, false, &[element, empty]);+ builder.end_hot_path(slow_paths, &[element]);} else {- builder.end_hot_path(slow_paths, vec![element]);+ builder.end_hot_path(slow_paths, &[element]);}},);@@ -310,7 +300,7 @@ impl GraphBuilder<'_, '_> {if strings {let code_unit = self.string_code_unit(&mut slow_paths, object, index);let character = self.ascii_character_string(&mut slow_paths, code_unit);- self.end_hot_path(&mut slow_paths, vec![character]);+ self.end_hot_path(&mut slow_paths, &[character]);}}if let Some((block, key)) = paths.named {@@ -322,7 +312,7 @@ impl GraphBuilder<'_, '_> {Some(Repr::Tagged),);let value = self.branch_if_empty(&mut slow_paths, value);- self.end_hot_path(&mut slow_paths, vec![value]);+ self.end_hot_path(&mut slow_paths, &[value]);}let result = self.join_hot_paths(slow_paths);self.write(dst, result.expect("GetByValue has a value"))?;@@ -358,7 +348,8 @@ impl GraphBuilder<'_, '_> {// which go once their check of the array exits with `ExitKind::SlowPath`. Where that happened, appends// take the slow path, which they would otherwise exit at too.let appends = self.may_speculate(ExitKind::SlowPath);- let out_of_bounds_typed_arrays = !self.typed_array_elements_seen(bits).is_empty() && bits & OUT_OF_BOUNDS != 0;+ let out_of_bounds_typed_arrays =+ self.typed_array_elements_seen(bits).next().is_some() && bits & OUT_OF_BOUNDS != 0;if appends&& bits & KEY_KINDS_MASK == INT32_INDEX&& bits & OTHER_ELEMENTS == 0@@ -383,11 +374,7 @@ impl GraphBuilder<'_, '_> {}if let Some((block, index)) = paths.indexed {self.block = block;- let conditions = kinds- .iter()- .copied()- .map(BranchCondition::ElementsKind)- .collect::<Vec<_>>();+ let conditions = ZoneVec::from_iter_in(kinds.iter().copied().map(BranchCondition::ElementsKind), self.work);self.branch_on_cases(&mut slow_paths,object,@@ -408,7 +395,7 @@ impl GraphBuilder<'_, '_> {builder.element_index_in_bounds(slow_paths, kind, address, index)};builder.store_element(kind, storage, index, stored);- builder.end_hot_path(slow_paths, Vec::new());+ builder.end_hot_path(slow_paths, &[]);},);}@@ -420,8 +407,8 @@ impl GraphBuilder<'_, '_> {&[object, key, value],Some(Repr::Bool),);- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, vec![stored], true);- self.end_hot_path(&mut slow_paths, Vec::new());+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, &[stored], true);+ self.end_hot_path(&mut slow_paths, &[]);}self.join_hot_paths(slow_paths);Ok(Flow::Continue)@@ -433,33 +420,33 @@ impl GraphBuilder<'_, '_> {/// which runs no code where the object is an array with a plain prototype/// chain (see `BranchCondition::HoleFillableArray`); other holes take a/// slow path.- fn store_holey_element(&mut self, slow_paths: &mut SlowPaths, address: NodeId, index: NodeId, value: NodeId) {+ fn store_holey_element(&mut self, slow_paths: &mut SlowPaths<'a>, address: NodeId, index: NodeId, value: NodeId) {let kind = ElementsKind::Holey;let in_bounds = BranchCondition::IndexInBounds;let length = self.emit(Op::LoadElementsLength, &[address], Some(Repr::Int32));- let index = self.branch_to_slow_path(slow_paths, in_bounds, vec![index, length], true);+ let index = self.branch_to_slow_path(slow_paths, in_bounds, &[index, length], true);// NB: Elements made with a length, like `new Array(length)`, have no room yet, and grow as they get filled.let capacity = self.emit(Op::LoadElementsCapacity, &[address], Some(Repr::Int32));- let (room, no_room) = self.branch_with_cold_side(in_bounds, vec![index, capacity], true);+ let (room, no_room) = self.branch_with_cold_side(in_bounds, &[index, capacity], true);self.block = no_room;// NB: Lengths above i32::MAX let negative int32 keys, which are no indices, pass as below the length.let zero = self.int32_constant(0);let nonnegative = BranchCondition::Int32(Comparison::GreaterThanEquals);- let element_index = self.branch_to_slow_path(slow_paths, nonnegative, vec![index, zero], true);+ let element_index = self.branch_to_slow_path(slow_paths, nonnegative, &[index, zero], true);self.graph.blocks[self.block.index()].is_cold = true;- let array = self.branch_to_slow_path(slow_paths, BranchCondition::HoleFillableArray, vec![address], true);+ let array = self.branch_to_slow_path(slow_paths, BranchCondition::HoleFillableArray, &[address], true);self.graph.blocks[self.block.index()].is_cold = true;self.emit(Op::CallStoreHoleyElement, &[array, element_index, value], None);- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);self.block = room;- let index = self.refine(in_bounds, true, vec![index, capacity]);+ let index = self.refine(in_bounds, true, &[index, capacity]);let old = self.emit(Op::LoadElementAt { kind }, &[address, index], Some(Repr::Tagged));let empty = self.constant(value::EMPTY);- let (hole, element) = self.branch_both_ways(BranchCondition::TaggedEquals { equal: true }, vec![old, empty]);+ let (hole, element) = self.branch_both_ways(BranchCondition::TaggedEquals { equal: true }, &[old, empty]);self.block = hole;- let array = self.branch_to_slow_path(slow_paths, BranchCondition::HoleFillableArray, vec![address], true);+ let array = self.branch_to_slow_path(slow_paths, BranchCondition::HoleFillableArray, &[address], true);// NB: A store to the last index may make the elements packed, which// the runtime does. The index is below the length, so the length// is not 0.@@ -469,23 +456,23 @@ impl GraphBuilder<'_, '_> {&[length, one],Some(Repr::Int32),);- let (before_last, at_last) = self.branch_with_cold_side(in_bounds, vec![index, last], true);+ let (before_last, at_last) = self.branch_with_cold_side(in_bounds, &[index, last], true);self.block = at_last;self.emit(Op::CallStoreHoleyElement, &[array, index, value], None);- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);self.block = before_last;- let index_before_last = self.refine(in_bounds, true, vec![index, last]);+ let index_before_last = self.refine(in_bounds, true, &[index, last]);self.store_element(kind, address, index_before_last, value);- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);self.block = element;self.store_element(kind, address, index, value);- self.end_hot_path(slow_paths, Vec::new());+ self.end_hot_path(slow_paths, &[]);}/// `value` as elements of `kind` store it, taking a slow path for/// values of typed arrays that are no numbers.- fn stored_element(&mut self, slow_paths: &mut SlowPaths, kind: ElementsKind, value: NodeId) -> NodeId {+ fn stored_element(&mut self, slow_paths: &mut SlowPaths<'a>, kind: ElementsKind, value: NodeId) -> NodeId {let int32 = self.int32_value_of(value);match (kind.stored_repr(), int32) {(Repr::Int32, Some(int32)) => int32,@@ -518,7 +505,7 @@ impl GraphBuilder<'_, '_> {dst,callee,this_value,- ref arguments,+ arguments,..} = *instructionelse {@@ -536,7 +523,7 @@ impl GraphBuilder<'_, '_> {let Some(feedback) = self.call_feedback(call_feedback) else {return Ok(None);};- let (object, key) = match (arguments.as_slice(), feedback.monomorphic_intrinsic()) {+ let (object, key) = match (arguments, feedback.monomorphic_intrinsic()) {([key], Some((target, Intrinsic::ObjectPrototypeHasOwnProperty))) => {self.check_callee(callee, target)?;(this_value, *key)diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 154c16ac03a..01275050a92 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -118,7 +118,7 @@ pub fn build_graph_with_feedback<'z>(has_run: &dyn Fn(u32) -> bool,zone: &'z Zone,) -> Result<Graph<'z>, CompileFailure> {- let attempts = Attempts::new(snapshot, has_run, zone);+ let mut attempts = Attempts::new(snapshot, has_run, zone);loop {if let Some(graph) = attempts.build(zone)? {return Ok(graph);@@ -131,10 +131,9 @@ pub fn build_graph_with_feedback<'z>(/// of its slots recorded something. Instructions without feedback count as/// having run. Instructions that never ran are compiled as unconditional exits.pub fn has_run(snapshot: &Snapshot, executable: &ExecutableSnapshot, pc: u32) -> bool {- let Ok(instruction) = crate::bytecode::decode_instruction(&snapshot[executable.bytecode], pc) else {+ let Some(slots) = crate::bytecode::feedback_slots_at(&snapshot[executable.bytecode], pc) else {return true;};- let slots = instruction.instruction.feedback_slots();let feedback = &executable.feedback;let slot = |slot: Option<u16>| slot.map(usize::from);let recorded = [@@ -169,9 +168,9 @@ pub struct Attempts<'a> {has_run: &'a dyn Fn(u32) -> bool,/// Where the builds keep their own data. It holds the data of all the builds until its owner resets it.work: &'a Zone,- decoded: Vec<OnceCell<Result<DecodedFunction<'a>, CompileFailure>>>,- virtualized_inlined_arguments: Cell<bool>,- next: Cell<Attempt>,+ decoded: &'a [OnceCell<Result<DecodedFunction<'a>, CompileFailure>>],+ virtualized_inlined_arguments: &'a Cell<bool>,+ next: Attempt,}/// What a build of `Attempts` does differently from the first one.@@ -189,25 +188,25 @@ impl<'a> Attempts<'a> {snapshot,has_run,work,- decoded: (0..snapshot.executables.len()).map(|_| OnceCell::new()).collect(),- virtualized_inlined_arguments: Cell::new(false),- next: Cell::new(Attempt::First),+ decoded: work.alloc_slice_from_iter((0..snapshot.executables.len()).map(|_| OnceCell::new())),+ virtualized_inlined_arguments: work.alloc(Cell::new(false)),+ next: Attempt::First,}}/// Builds a graph in `zone`. Returns `None` for a graph that cannot be used: the caller then drops what is in- /// `zone` and calls this again, which builds the graph in another way. The builds keep the decoded functions, whose- /// analyses are in the work zone, borrowed for as long as the attempts live.- pub fn build<'z>(&'a self, zone: &'z Zone) -> Result<Option<Graph<'z>>, CompileFailure> {+ /// `zone` and calls this again, which builds the graph in another way. The builds keep the decoded functions and+ /// their analyses, which are in the work zone.+ pub fn build<'z>(&mut self, zone: &'z Zone) -> Result<Option<Graph<'z>>, CompileFailure> {let build = |virtualize_arguments, virtualize_inlined_arguments, build_osr_entries| {GraphBuilder::new(self.snapshot,self.has_run,- &self.decoded,+ self.decoded,ArgumentsVirtualization {compiled_function: virtualize_arguments,inlined_callees: virtualize_inlined_arguments,- inlined_callees_virtualized: &self.virtualized_inlined_arguments,+ inlined_callees_virtualized: self.virtualized_inlined_arguments,},build_osr_entries,zone,@@ -215,11 +214,11 @@ impl<'a> Attempts<'a> {)?.build()};- let graph = match self.next.get() {+ let graph = match self.next {Attempt::First => match build(true, true, true) {Ok(graph) if !arguments::uses_virtual_arguments(&graph) => return Ok(Some(graph)),_ if self.virtualized_inlined_arguments.get() => {- self.next.set(Attempt::WithoutVirtualArgumentsOfInlinedCallees);+ self.next = Attempt::WithoutVirtualArgumentsOfInlinedCallees;return Ok(None);}result => result?,@@ -237,18 +236,18 @@ impl<'a> Attempts<'a> {return Ok(Some(graph));}// Something needs the arguments object itself.- self.next.set(Attempt::WithoutVirtualArguments);+ self.next = Attempt::WithoutVirtualArguments;return Ok(None);}Attempt::WithoutVirtualArguments => return build(false, false, true).map(Some),};// NB: The graph uses the virtual arguments object of the compiled function.- self.next.set(if graph.osr_entries.is_empty() {+ self.next = if graph.osr_entries.is_empty() {// Something needs the arguments object itself.Attempt::WithoutVirtualArguments} else {Attempt::WithoutOsrEntries- });+ };Ok(None)}}@@ -445,7 +444,7 @@ fn loop_phi_slots<'w>(cfg: &Cfg<'w>, work: &'w Zone) -> ZoneVec<'w, ZoneBitSet<'/// Analyses are lazy: an inlining budget rejection only needs decoding./// The analyses are in the work zone of the builds.struct DecodedFunction<'w> {- instructions: Vec<DecodedInstruction>,+ instructions: &'w [DecodedInstruction<'w>],analysis: OnceCell<Result<FunctionAnalysis<'w>, CompileFailure>>,}@@ -453,11 +452,12 @@ fn decoded_function<'c, 'w>(snapshot: &Snapshot,executable: &ExecutableSnapshot,cache: &'c OnceCell<Result<DecodedFunction<'w>, CompileFailure>>,+ work: &'w Zone,) -> Result<&'c DecodedFunction<'w>, CompileFailure> {cache.get_or_init(|| {let bytecode = &snapshot[executable.bytecode];- let instructions = decode_all(bytecode).map_err(|error| CompileFailure::InvalidBytecode {+ let instructions = decode_all(bytecode, work).map_err(|error| CompileFailure::InvalidBytecode {pc: error.pc,reason: "undecodable instruction",})?;@@ -495,7 +495,7 @@ struct Function<'a> {index: u32,executable: &'a ExecutableSnapshot,layout: FrameLayout,- instructions: &'a [DecodedInstruction],+ instructions: &'a [DecodedInstruction<'a>],cfg: &'a Cfg<'a>,liveness: &'a Liveness<'a>,// NB: The lists of the walk below have an element for each bytecode block once the walk starts (see@@ -550,7 +550,7 @@ impl<'a> Function<'a> {) -> Result<Self, CompileFailure> {let executable = &snapshot.executables[index as usize];let layout = executable.layout;- let instructions = decoded.instructions.as_slice();+ let instructions = decoded.instructions;let analysis = decoded.analysis.get_or_init(|| {@@ -678,6 +678,8 @@ struct GraphBuilder<'a, 'z> {free_slot_sets: ZoneVec<'a, ZoneBitSet<'a>>,/// Lists of slots that are free to use again (see `slot_list()`).free_slot_lists: ZoneVec<'a, ZoneVec<'a, usize>>,+ /// Lists of nodes that are free to use again (see `node_list()`).+ free_node_lists: ZoneVec<'a, ZoneVec<'a, NodeId>>,}impl<'a, 'z> GraphBuilder<'a, 'z> {@@ -694,7 +696,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {pc: 0,reason: "no executable",})?;- let decoded_root = decoded_function(snapshot, executable, &decoded[0])?;+ let decoded_root = decoded_function(snapshot, executable, &decoded[0], work)?;// NB: `GetArgument` reads the argument slots from frame memory, which only the slots it keeps live hold the// current values of: a dead slot may be in sync with `undefined` instead (see `dead_frame()`). Inlined// callees that read their passed arguments keep them live the same way (see `inlinable_callee()`).@@ -736,6 +738,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {has_instance: ZoneMap::new_in(work),free_slot_sets: ZoneVec::new_in(work),free_slot_lists: ZoneVec::new_in(work),+ free_node_lists: ZoneVec::new_in(work),})}@@ -882,6 +885,18 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {self.free_slot_lists.push(list);}+ /// An empty list of nodes, to give back with `release_node_list()` once it is not needed any more.+ fn node_list(&mut self) -> ZoneVec<'a, NodeId> {+ let mut list = self.free_node_lists.pop().unwrap_or_else(|| ZoneVec::new_in(self.work));+ list.clear();+ list+ }++ /// Gives back a list that `node_list()` gave, for it to use again.+ fn release_node_list(&mut self, list: ZoneVec<'a, NodeId>) {+ self.free_node_lists.push(list);+ }+/// Loads a slot from frame memory, which then holds its value in sync.fn load_slot(&mut self, slot: usize) -> NodeId {let operand = self.function.layout.operand_for_tracked_index(slot);@@ -1680,7 +1695,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {return Ok(None);}}- Instruction::NewArray { dst, ref elements, .. } => {+ Instruction::NewArray { dst, elements, .. } => {if elements.is_empty()&& let Some(flow) = self.try_build_spread_forwarding(dst)?{@@ -1715,7 +1730,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {return Ok(None);}}- Instruction::NewPrimitiveArray { dst, ref elements, .. } => {+ Instruction::NewPrimitiveArray { dst, elements, .. } => {let elements = ZoneVec::from_iter_in(elements.iter().copied().map(allocation::ArrayElement::Constant),self.work,@@ -2003,13 +2018,13 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {) -> Result<Flow, CompileFailure> {let source = self.read(completion)?;let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;- let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![source], true);+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[source], true);let object = self.cell_address(object);- let generator = self.branch_to_slow_path(&mut slow_paths, BranchCondition::GeneratorObject, vec![object], true);+ let generator = self.branch_to_slow_path(&mut slow_paths, BranchCondition::GeneratorObject, &[object], true);let completion_type = self.emit(Op::LoadGeneratorCompletionType, &[generator], Some(Repr::Int32));let completion_type = self.emit(Op::BoxInt32, &[completion_type], Some(Repr::Tagged));let value = self.emit(Op::LoadGeneratorCompletionValue, &[generator], Some(Repr::Tagged));- let outputs = self.join_paths(slow_paths, vec![completion_type, value], |_, outputs| outputs);+ let outputs = self.join_paths(slow_paths, &[completion_type, value], |_, _| {});self.write(type_dst, outputs[0])?;self.write(value_dst, outputs[1])?;Ok(Flow::Continue)@@ -2126,8 +2141,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {self.block = fallback;let boolean = self.emit(Op::ToBoolean, &[value], Some(Repr::Bool));- let (fallback_true_block, fallback_false_block) = self.branch_both_ways(BranchCondition::Bool, vec![boolean]);- self.join_blocks(vec![true_block, false_block, fallback_true_block, fallback_false_block]);+ let (fallback_true_block, fallback_false_block) = self.branch_both_ways(BranchCondition::Bool, &[boolean]);+ self.join_blocks(&[true_block, false_block, fallback_true_block, fallback_false_block]);self.frame = frame;let (truthy, falsy) = if negate {diff --git a/Libraries/LibJS/JIT/Rust/src/builder/named.rs b/Libraries/LibJS/JIT/Rust/src/builder/named.rsindex ac0ee07c3c5..278bc99501d 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/named.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/named.rs@@ -25,7 +25,7 @@ use crate::ir::Comparison;use crate::ir::NodeId;use crate::ir::Op;-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// Builds `GetById` (`Handling::Expanded`): the property the cache has/// for the value (see `Op::ProbePropertyCache`).pub(super) fn build_get_by_id(&mut self, instruction: &Instruction) -> Result<Flow, CompileFailure> {@@ -74,7 +74,7 @@ impl GraphBuilder<'_, '_> {&[object, value],Some(Repr::Bool),);- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, vec![stored], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Bool, &[stored], true);self.join_slow_paths(slow_paths, None);Ok(Flow::Continue)}@@ -98,16 +98,16 @@ impl GraphBuilder<'_, '_> {// set of the realm tells if array iterators have a return method.if let Some(return_watchpoint_set) = self.runtime.array_iterator_return_watchpoint_set {let (fast_array_mode, iterator_object) =- self.branch_both_ways(BranchCondition::NonNegativeInt32, vec![iterator]);+ self.branch_both_ways(BranchCondition::NonNegativeInt32, &[iterator]);self.block = fast_array_mode;self.embed(return_watchpoint_set);self.assume(Dependency::WatchpointSetValid(return_watchpoint_set));- self.end_hot_path(&mut slow_paths, Vec::new());+ self.end_hot_path(&mut slow_paths, &[]);self.block = iterator_object;}let return_method = self.probe_property_cache(&mut slow_paths, iterator, cache, u32::MAX);- self.branch_to_slow_path(&mut slow_paths, BranchCondition::Nullish, vec![return_method], true);+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Nullish, &[return_method], true);self.join_slow_paths(slow_paths, None);Ok(Flow::Continue)}@@ -118,7 +118,7 @@ impl GraphBuilder<'_, '_> {/// `Op::ProbePropertyCache`).fn probe_property_cache(&mut self,- slow_paths: &mut SlowPaths,+ slow_paths: &mut SlowPaths<'a>,object: NodeId,cache: u32,property: u32,@@ -165,14 +165,14 @@ impl GraphBuilder<'_, '_> {|builder, slow_paths, case, value| {if case == 0 {let address = builder.cell_address(value);- let (magical, named) = builder.branch_both_ways(BranchCondition::MagicalLength, vec![address]);+ let (magical, named) = builder.branch_both_ways(BranchCondition::MagicalLength, &[address]);builder.block = magical;- let array = builder.refine(BranchCondition::MagicalLength, true, vec![address]);+ let array = builder.refine(BranchCondition::MagicalLength, true, &[address]);let length = builder.emit(Op::LoadElementsLength, &[array], Some(Repr::Int32));builder.end_with_length(slow_paths, length);builder.block = named;let length = builder.probe_property_cache(slow_paths, value, cache, u32::MAX);- builder.end_hot_path(slow_paths, vec![length]);+ builder.end_hot_path(slow_paths, &[length]);} else {let address = builder.emit(Op::StringAddress, &[value], Some(Repr::Pointer));let length = builder.emit(Op::StringLength, &[address], Some(Repr::Int32));@@ -188,15 +188,15 @@ impl GraphBuilder<'_, '_> {/// Ends a path of `GetLength` with the `Repr::Int32` `length`, which/// takes a slow path where it is no int32, an unsigned length above/// `i32::MAX`.- fn end_with_length(&mut self, slow_paths: &mut SlowPaths, length: NodeId) {+ fn end_with_length(&mut self, slow_paths: &mut SlowPaths<'a>, length: NodeId) {let zero = self.int32_constant(0);let length = self.branch_to_slow_path(slow_paths,BranchCondition::Int32(Comparison::GreaterThanEquals),- vec![length, zero],+ &[length, zero],true,);let length = self.emit(Op::BoxInt32, &[length], Some(Repr::Tagged));- self.end_hot_path(slow_paths, vec![length]);+ self.end_hot_path(slow_paths, &[length]);}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rsindex e6966d274e8..5c27498cf1a 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs@@ -50,6 +50,7 @@ use crate::snapshot::CellId;use crate::snapshot::Intrinsic;use crate::snapshot::NativeCallTarget;use crate::snapshot::keyed_feedback_bits;+use ak::ZoneVec;/// A check that a key is the one a keyed access speculates on: `key` must/// be `expected`, the encoded key cell `cell`.@@ -61,9 +62,9 @@ pub(super) struct KeyCheck {}/// Cache entries of a keyed access for one key, and the check of the key.-type KeyedEntries = (Vec<CacheEntry>, Option<KeyCheck>);+type KeyedEntries<'a> = (&'a [CacheEntry], Option<KeyCheck>);-impl<'z> GraphBuilder<'_, 'z> {+impl<'a, 'z> GraphBuilder<'a, 'z> {/// The speculation gate: whether the current instruction may speculate/// in a way that exits with `kind`. A speculation that already failed at/// the same place is never made again.@@ -304,7 +305,7 @@ impl<'z> GraphBuilder<'_, 'z> {if !same_cached_getter || !gates.into_iter().all(|kind| self.may_speculate(kind)) {return Ok(false);}- let (object, getter) = self.check_accessor_call(base, &entries, AccessorPart::Getter)?;+ let (object, getter) = self.check_accessor_call(base, entries, AccessorPart::Getter)?;debug_assert!(getter.is_none(), "all entries have the same checked getter");let value = self.load_named(object, offset);self.write(dst, value)?;@@ -380,7 +381,7 @@ impl<'z> GraphBuilder<'_, 'z> {// NB: Exiting instead of running the slow path keeps loops bounded by the length free of code that may// change what they read.self.exit_instead_of_slow_path(&mut slow_paths);- let (object, checked_getter) = self.check_accessor_call(base, &entries, AccessorPart::Getter)?;+ let (object, checked_getter) = self.check_accessor_call(base, entries, AccessorPart::Getter)?;debug_assert!(checked_getter.is_none(), "all entries have the same checked getter");let typed_array = self.emit_checked(Op::CheckTypedArray, &[object], Some(Repr::Tagged));let address = self.cell_address(typed_array);@@ -389,7 +390,7 @@ impl<'z> GraphBuilder<'_, 'z> {let length = self.branch_to_slow_path(&mut slow_paths,BranchCondition::Int32(Comparison::GreaterThan),- vec![length, zero],+ &[length, zero],true,);let length = self.emit(Op::BoxInt32, &[length], Some(Repr::Tagged));@@ -402,7 +403,7 @@ impl<'z> GraphBuilder<'_, 'z> {/// `part` of the same accessor property with functions of the same/// executable (see `try_inline_getter()`), with the index of that/// executable in the snapshot.- fn accessor_call_entries(&self, cache: u32, part: AccessorPart) -> Option<(Vec<CacheEntry>, u32)> {+ fn accessor_call_entries(&self, cache: u32, part: AccessorPart) -> Option<(&'a [CacheEntry], u32)> {let entries = self.cache_entries(cache)?;let first = entries[0];let executable_of = |entry: &CacheEntry| {@@ -425,7 +426,7 @@ impl<'z> GraphBuilder<'_, 'z> {/// `part` of the same accessor property (at one offset of the receiver,/// or of one prototype) with the same raw native function, with the/// target through which JIT code calls it (see `try_build_native_getter()`).- fn native_accessor_entries(&self, cache: u32, part: AccessorPart) -> Option<(Vec<CacheEntry>, NativeCallTarget)> {+ fn native_accessor_entries(&self, cache: u32, part: AccessorPart) -> Option<(&'a [CacheEntry], NativeCallTarget)> {// NB: Calls in inlined callees need their inlined frames, which these calls do not build.if self.function.is_virtual() {return None;@@ -464,7 +465,7 @@ impl<'z> GraphBuilder<'_, 'z> {&mut self,part: AccessorPart,target: NativeCallTarget,- inputs: Vec<NodeId>,+ inputs: &[NodeId],dst: u32,) -> NodeId {let argument_count = inputs.len() as u64 - 1;@@ -477,7 +478,7 @@ impl<'z> GraphBuilder<'_, 'z> {part,target,};- let node = self.emit(op, &inputs, Some(Repr::Tagged));+ let node = self.emit(op, inputs, Some(Repr::Tagged));let frame_state = self.resume_after_frame_state(dst);self.graph.nodes[node.index()].frame_state = Some(frame_state);node@@ -497,9 +498,9 @@ impl<'z> GraphBuilder<'_, 'z> {let Some((entries, target)) = self.native_accessor_entries(cache, AccessorPart::Getter) else {return Ok(false);};- let (object, getter) = self.check_accessor_call(base, &entries, AccessorPart::Getter)?;+ let (object, getter) = self.check_accessor_call(base, entries, AccessorPart::Getter)?;debug_assert!(getter.is_none(), "all entries have the same checked getter");- let value = self.emit_native_accessor_call(AccessorPart::Getter, target, vec![object], dst.raw());+ let value = self.emit_native_accessor_call(AccessorPart::Getter, target, &[object], dst.raw());self.write(dst, value)?;Ok(true)}@@ -517,9 +518,9 @@ impl<'z> GraphBuilder<'_, 'z> {return Ok(false);};let value = self.read(src)?;- let (object, setter) = self.check_accessor_call(base, &entries, AccessorPart::Setter)?;+ let (object, setter) = self.check_accessor_call(base, entries, AccessorPart::Setter)?;debug_assert!(setter.is_none(), "all entries have the same checked setter");- self.emit_native_accessor_call(AccessorPart::Setter, target, vec![object, value], Operand::INVALID);+ self.emit_native_accessor_call(AccessorPart::Setter, target, &[object, value], Operand::INVALID);Ok(true)}@@ -546,14 +547,15 @@ impl<'z> GraphBuilder<'_, 'z> {let first = entries[0];let object = self.read(base)?;let object = self.check_object(object);- let shapes = entries.iter().map(|entry| self.shape_guard(entry)).collect::<Vec<_>>();+ let work = self.work;+ let shapes = ZoneVec::from_iter_in(entries.iter().map(|entry| self.shape_guard(entry)), work);let object = self.check_shapes(object, &shapes);let (Action::Get { holder, offset } | Action::Set { holder, offset }) = first.action else {unreachable!("accessor calls get or set");};let holder = match holder {Holder::Prototype { prototype, .. } => {- let mut checked_validities = Vec::new();+ let mut checked_validities = ZoneVec::new_in(self.work);for entry in entries {let (Action::Get {holder: Holder::Prototype { validity, valid, .. },@@ -616,7 +618,7 @@ impl<'z> GraphBuilder<'_, 'z> {let Some((entries, index)) = self.accessor_call_entries(cache, AccessorPart::Getter) else {return Ok(None);};- let (_, getter) = self.check_accessor_call(base, &entries, AccessorPart::Getter)?;+ let (_, getter) = self.check_accessor_call(base, entries, AccessorPart::Getter)?;self.try_inline_getter_call(index, getter, base, dst)}@@ -636,7 +638,7 @@ impl<'z> GraphBuilder<'_, 'z> {let Some(dst) = self.dead_register(&[base, src]) else {return Ok(None);};- let (_, setter) = self.check_accessor_call(base, &entries, AccessorPart::Setter)?;+ let (_, setter) = self.check_accessor_call(base, entries, AccessorPart::Setter)?;self.try_inline_setter_call(index, setter, base, src, dst)}@@ -688,28 +690,34 @@ impl<'z> GraphBuilder<'_, 'z> {/// own if it is a constant, or those of the only key the cache saw, with/// the key check to make (see `check_key()`). Returns nothing for other/// keys.- fn keyed_cache_entries(&mut self, cache: u32, key: Operand) -> Result<Option<KeyedEntries>, CompileFailure> {+ fn keyed_cache_entries(&mut self, cache: u32, key: Operand) -> Result<Option<KeyedEntries<'a>>, CompileFailure> {let Some(entries) = self.cache_entries(cache) else {return Ok(None);};- let Some(keys) = entries.iter().map(|entry| entry.key).collect::<Option<Vec<_>>>() else {+ if entries.iter().any(|entry| entry.key.is_none()) {return Ok(None);- };+ }+ let key_of = |entry: &CacheEntry| entry.key.map(|(value, _)| value);let key = self.read(key)?;let key_value = match self.graph.constant_value(key) {Some(bits) => bits,None => {- let (first, _) = keys[0];- if !keys.iter().all(|(value, _)| *value == first) || !self.may_speculate(ExitKind::UnexpectedValue) {+ let first = key_of(&entries[0]);+ if !entries.iter().all(|entry| key_of(entry) == first) || !self.may_speculate(ExitKind::UnexpectedValue)+ {return Ok(None);}- first+ first.expect("every entry has a key")}};- let entries = entries- .into_iter()- .filter(|entry| entry.key.is_some_and(|(value, _)| value == key_value))- .collect::<Vec<_>>();+ let entries = ZoneVec::from_iter_in(+ entries+ .iter()+ .copied()+ .filter(|entry| entry.key.is_some_and(|(value, _)| value == key_value)),+ self.work,+ )+ .into_slice();let Some((_, cell)) = entries.first().and_then(|entry| entry.key) else {return Ok(None);};@@ -742,7 +750,7 @@ impl<'z> GraphBuilder<'_, 'z> {&mut self,dst: Operand,base: Operand,- entries: Vec<CacheEntry>,+ entries: &[CacheEntry],key_check: Option<KeyCheck>,) -> Result<bool, CompileFailure> {// NB: Loads of properties that hold accessors exit, so these are left to the instruction's handling, which@@ -758,7 +766,7 @@ impl<'z> GraphBuilder<'_, 'z> {let object = self.read(base)?;let object = self.check_object(object);let result = self- .translate_entries(object, &entries, |builder, entry, object| {+ .translate_entries(object, entries, |builder, entry, object| {Some(builder.load_entry(object, entry))}).expect("every case loads a value");@@ -785,7 +793,7 @@ impl<'z> GraphBuilder<'_, 'z> {&mut self,base: Operand,src: Operand,- entries: Vec<CacheEntry>,+ entries: &[CacheEntry],key_check: Option<KeyCheck>,) -> Result<bool, CompileFailure> {let speculatable = entries@@ -799,7 +807,7 @@ impl<'z> GraphBuilder<'_, 'z> {let object = self.read(base)?;let value = self.read(src)?;let object = self.check_object(object);- self.translate_entries(object, &entries, |builder, entry, object| {+ self.translate_entries(object, entries, |builder, entry, object| {let Action::Set { offset, .. } = entry.action else {unreachable!("only sets store");};diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rsindex 32f1b61f720..2c20d9a98a5 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs@@ -26,6 +26,7 @@ use crate::CompileFailure;use crate::bytecode::Operand;use crate::code::ExitKind;use crate::ir::Op;+use ak::ZoneVec;impl GraphBuilder<'_, '_> {/// Builds `base.property = src` as `AddNamed` and `StoreNamed` nodes, if@@ -85,8 +86,8 @@ impl GraphBuilder<'_, '_> {}let value = self.read(src)?;- let entries = self.entries_for_known_shape(object, &entries);- let shapes = entries.iter().map(|entry| entry.shape).collect::<Vec<_>>();+ let entries = self.entries_for_known_shape(object, entries);+ let shapes = ZoneVec::from_iter_in(entries.iter().map(|entry| entry.shape), self.work);self.dispatch_on_shapes(object,entries,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rsindex 178d7334a0d..fcbe098e62b 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs@@ -43,25 +43,25 @@ impl GraphBuilder<'_, '_> {// rare. Exiting there, until an exit was taken, makes the key the cache's key wherever the loop's body// reads it, which keyed accesses of the key rely on to read the property at its known place.self.exit_instead_of_slow_path(&mut slow_paths);- let receiver = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![receiver], true);+ let receiver = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, &[receiver], true);self.branch_to_slow_path(&mut slow_paths,BranchCondition::PropertyIteratorCacheValid,- vec![receiver, keys],+ &[receiver, keys],true,);let cursor_index = self.branch_to_slow_path(&mut slow_paths,BranchCondition::NonNegativeInt32,- vec![cursor_value],+ &[cursor_value],true,);let index = self.emit(Op::UnboxInt32, &[cursor_index], Some(Repr::Int32));let count = self.emit(Op::LoadPropertyIteratorKeyCount, &[keys], Some(Repr::Int32));- let (more, finished) = self.branch_both_ways(BranchCondition::Int32(Comparison::LessThan), vec![index, count]);+ let (more, finished) = self.branch_both_ways(BranchCondition::Int32(Comparison::LessThan), &[index, count]);self.block = more;- let index = self.refine(BranchCondition::Int32(Comparison::LessThan), true, vec![index, count]);+ let index = self.refine(BranchCondition::Int32(Comparison::LessThan), true, &[index, count]);let key = self.emit(Op::LoadPropertyIteratorKey, &[keys, index], Some(Repr::Tagged));// NB: The index is below the count, so the next one is an int32 too.let one = self.int32_constant(1);@@ -70,12 +70,12 @@ impl GraphBuilder<'_, '_> {let not_done = self.constant(value::FALSE);let done = self.constant(value::TRUE);- self.join_blocks(vec![more, finished]);+ self.join_blocks(&[more, finished]);let value = self.add_phi(&[key, old_value]);let is_done = self.add_phi(&[not_done, done]);let new_cursor = self.add_phi(&[next, cursor_value]);- let outputs = self.join_paths(slow_paths, vec![value, is_done, new_cursor], |_, outputs| outputs);+ let outputs = self.join_paths(slow_paths, &[value, is_done, new_cursor], |_, _| {});self.write(dst_value, outputs[0])?;self.write(dst_done, outputs[1])?;self.write(cursor, outputs[2])?;diff --git a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rsindex 1bdd257ee55..a9cc6d95dc2 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs@@ -17,21 +17,98 @@ use crate::bytecode::FrameLayout;use crate::bytecode::Instruction;use crate::bytecode::Operand;use crate::bytecode::OperandRole;+use crate::bytecode::SlowPathLayout;use crate::bytecode::slow_path_layout;use crate::code::Repr;use crate::codegen::slow_path_call;+use crate::ir::NodeId;use crate::ir::Op;use crate::ir::value;+use ak::ZoneVec;/// The operands of a slow path, as raw operands of its instruction.-pub(crate) struct SlowPathOperands {- /// The operands it reads, in the order of its layout (see- /// `bytecode::slow_path_layout()`): the fields that are not outputs,- /// then the array's elements. `Operand::INVALID` for absent ones.- pub(crate) inputs: Vec<u32>,- /// The operands it writes, with the index of their layout field, in- /// layout order.- pub(crate) outputs: Vec<(u32, u32)>,+#[derive(Clone, Copy)]+pub(crate) enum SlowPathOperands<'a> {+ /// The operands of the instruction at `at` of `bytecode` in the layout of its slow path (see+ /// `bytecode::slow_path_layout()`), all of whose operand fields lie within the bytecode.+ Layout {+ bytecode: &'a [u8],+ at: usize,+ layout: SlowPathLayout,+ array_length: u32,+ },+ /// The operands of a JS call instruction (see `js_call_operands()`).+ JsCall(Instruction<'a>),+}++impl SlowPathOperands<'_> {+ /// Calls `visit` with the operands the slow path reads, in the order of its layout (see+ /// `bytecode::slow_path_layout()`): the fields that are not outputs, then the array's elements.+ /// `Operand::INVALID` for absent ones.+ pub(crate) fn for_each_input(&self, mut visit: impl FnMut(u32)) {+ match self {+ SlowPathOperands::Layout {+ bytecode,+ at,+ layout,+ array_length,+ } => {+ let read_operand = |offset: u32| Operand::raw_from_byte(bytecode[at + offset as usize]);+ for field in layout.fields {+ if field.role != OperandRole::Out {+ visit(read_operand(field.instruction_offset));+ }+ }+ if let Some(array) = layout.array {+ for element in 0..*array_length {+ visit(read_operand(array.instruction_offset + element));+ }+ }+ }+ SlowPathOperands::JsCall(instruction) => instruction.for_each_operand(|operand, role| {+ if role.is_read() {+ visit(operand.raw());+ }+ }),+ }+ }++ /// Calls `visit` with the operands the slow path writes, with the index of their layout field, in layout order.+ pub(crate) fn for_each_output(&self, mut visit: impl FnMut(u32, u32)) {+ match self {+ SlowPathOperands::Layout {+ bytecode, at, layout, ..+ } => {+ for (index, field) in layout.fields.iter().enumerate() {+ let operand = Operand::raw_from_byte(bytecode[at + field.instruction_offset as usize]);+ if field.role != OperandRole::In && operand != Operand::INVALID {+ visit(u32::try_from(index).expect("layouts have few fields"), operand);+ }+ }+ }+ SlowPathOperands::JsCall(instruction) => instruction.for_each_operand(|operand, role| {+ if role.is_written() {+ visit(0, operand.raw());+ }+ }),+ }+ }++ /// How many operands the slow path writes.+ pub(crate) fn output_count(&self) -> usize {+ let mut count = 0;+ self.for_each_output(|_, _| count += 1);+ count+ }++ /// The first operand the slow path writes, if it writes one.+ fn first_output(&self) -> Option<u32> {+ let mut first = None;+ self.for_each_output(|_, operand| {+ first.get_or_insert(operand);+ });+ first+ }}/// Whether `operand`, an output of a slow path in a frame of `layout`, becomes an SSA value: any slot but a@@ -43,55 +120,68 @@ pub(crate) fn is_ssa_slow_path_output(layout: &FrameLayout, operand: Operand) ->/// The operands of a JS call instruction, whose slow path is the runtime's/// call helper (`SlowPathCall::JitCall`): the operands it reads, in the order/// the instruction lists them, and its destination.-pub(crate) fn js_call_operands(instruction: &Instruction) -> SlowPathOperands {- let mut inputs = Vec::new();- let mut outputs = Vec::new();- instruction.for_each_operand(|operand, role| {- if role.is_read() {- inputs.push(operand.raw());- }- if role.is_written() {- outputs.push((0, operand.raw()));- }- });- SlowPathOperands { inputs, outputs }+pub(crate) fn js_call_operands(instruction: Instruction<'_>) -> SlowPathOperands<'_> {+ SlowPathOperands::JsCall(instruction)}-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// The operands of the slow path of the instruction being built.- pub(super) fn slow_path_operands(&self) -> Result<SlowPathOperands, CompileFailure> {+ pub(super) fn slow_path_operands(&self) -> Result<SlowPathOperands<'a>, CompileFailure> {let opcode = self.function.instructions[self.function.instruction_index].instruction.opcode();let layout = slow_path_layout(opcode);- let bytes_at = |offset: u32, size: usize| -> Result<&[u8], CompileFailure> {- let at = (self.function.pc + offset) as usize;- self.snapshot[self.function.executable.bytecode]- .get(at..at + size)+ let bytecode = &self.snapshot[self.function.executable.bytecode];+ let at = self.function.pc as usize;+ let byte_at = |offset: u32| -> Result<u8, CompileFailure> {+ bytecode+ .get(at + offset as usize)+ .copied().ok_or(CompileFailure::InvalidBytecode {pc: self.function.pc,reason: "operand field outside the bytecode",})};- let read_operand =- |offset: u32| -> Result<u32, CompileFailure> { Ok(Operand::raw_from_byte(bytes_at(offset, 1)?[0])) };- let mut inputs = Vec::new();- let mut outputs = Vec::new();- for (index, field) in layout.fields.iter().enumerate() {- let operand = read_operand(field.instruction_offset)?;- if field.role != OperandRole::Out {- inputs.push(operand);- }- if field.role != OperandRole::In && operand != Operand::INVALID {- outputs.push((u32::try_from(index).expect("layouts have few fields"), operand));- }+ for field in layout.fields {+ byte_at(field.instruction_offset)?;}+ let mut array_length = 0;if let Some(array) = layout.array {- for element in 0..u32::from(bytes_at(array.count_offset, 1)?[0]) {- inputs.push(read_operand(array.instruction_offset + element)?);+ array_length = u32::from(byte_at(array.count_offset)?);+ for element in 0..array_length {+ byte_at(array.instruction_offset + element)?;}}- Ok(SlowPathOperands { inputs, outputs })+ Ok(SlowPathOperands::Layout {+ bytecode,+ at,+ layout,+ array_length,+ })+ }++ /// The values of the operands that `operands` reads, with the empty value for absent ones, in a list to give back+ /// with `release_node_list()`.+ pub(super) fn read_slow_path_inputs(+ &mut self,+ operands: SlowPathOperands<'_>,+ ) -> Result<ZoneVec<'a, NodeId>, CompileFailure> {+ let mut inputs = self.node_list();+ let mut result = Ok(());+ operands.for_each_input(|operand| {+ if result.is_err() {+ return;+ }+ match operand {+ Operand::INVALID => inputs.push(self.constant(value::EMPTY)),+ raw => match self.read(Operand::from_raw(raw)) {+ Ok(value) => inputs.push(value),+ Err(error) => result = Err(error),+ },+ }+ });+ result?;+ Ok(inputs)}/// Builds an instruction as a call of its slow path on SSA values (see@@ -119,18 +209,11 @@ impl GraphBuilder<'_, '_> {return Ok(None);}let operands = if info.is_js_call {- js_call_operands(instruction)+ js_call_operands(*instruction)} else {self.slow_path_operands()?};- let inputs = operands- .inputs- .iter()- .map(|operand| match *operand {- Operand::INVALID => Ok(self.constant(value::EMPTY)),- raw => self.read(Operand::from_raw(raw)),- })- .collect::<Result<Vec<_>, _>>()?;+ let inputs = self.read_slow_path_inputs(operands)?;let mut destination = None;instruction.for_each_operand(|operand, role| {@@ -139,14 +222,13 @@ impl GraphBuilder<'_, '_> {}});- let mut targets = Vec::new();- instruction.for_each_jump_target(|label| targets.push(label));- let repr = if !targets.is_empty() {+ let mut jumps = false;+ instruction.for_each_jump_target(|_| jumps = true);+ let repr = if jumps {Some(Repr::Int32)} else if operands- .outputs- .first()- .is_some_and(|(_, operand)| is_ssa_slow_path_output(&self.function.layout, Operand::from_raw(*operand)))+ .first_output()+ .is_some_and(|operand| is_ssa_slow_path_output(&self.function.layout, Operand::from_raw(operand))){Some(Repr::Tagged)} else {@@ -162,6 +244,7 @@ impl GraphBuilder<'_, '_> {&inputs,repr,);+ self.release_node_list(inputs);// NB: Where the slow path does not continue with the next// instruction, it threw or runs a callee in the interpreter. The@@ -169,33 +252,40 @@ impl GraphBuilder<'_, '_> {// of the outputs the slow path did not write, except that it// writes back the outputs it reads (as the interpreter does on// exceptions): the frame state lists those as held by the frame.- let input_outputs = operands- .outputs- .iter()- .filter(|(field, _)| {- !info.is_js_call && slow_path_layout(opcode).fields[*field as usize].role == OperandRole::InOut- })- .filter_map(|(_, operand)| self.function.layout.tracked_index(Operand::from_raw(*operand)))- .collect::<Vec<_>>();+ let mut input_outputs = self.slot_list();+ operands.for_each_output(|field, operand| {+ if !info.is_js_call+ && slow_path_layout(opcode).fields[field as usize].role == OperandRole::InOut+ && let Some(slot) = self.function.layout.tracked_index(Operand::from_raw(operand))+ {+ input_outputs.push(slot);+ }+ });let frame_state = self.resume_after_frame_state_with_outputs_in_frame(destination.map_or(Operand::INVALID, Operand::raw),&input_outputs,);+ self.release_slot_list(input_outputs);self.graph.nodes[node.index()].frame_state = Some(frame_state);- for (index, (_, operand)) in operands.outputs.iter().enumerate() {- let operand = Operand::from_raw(*operand);- if !is_ssa_slow_path_output(&self.function.layout, operand) {- continue;+ let mut index = 0;+ let mut result = Ok(());+ operands.for_each_output(|_, operand| {+ let output = index;+ index += 1;+ let operand = Operand::from_raw(operand);+ if result.is_err() || !is_ssa_slow_path_output(&self.function.layout, operand) {+ return;}- let value = if index == 0 {+ let value = if output == 0 {node} else {- let index = u8::try_from(index).expect("slow paths have few outputs");- self.emit(Op::SlowPathOutput { index }, &[node], Some(Repr::Tagged))+ let output = u8::try_from(output).expect("slow paths have few outputs");+ self.emit(Op::SlowPathOutput { index: output }, &[node], Some(Repr::Tagged))};- self.write(operand, value)?;- }+ result = self.write(operand, value);+ });+ result?;self.end_generic_instruction(instruction, node).map(Some)}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rsindex 1e7da9d8739..fa8f29ebbab 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs@@ -47,6 +47,7 @@ use crate::ir::Op;use crate::ir::TypeofKind;use crate::ir::value;use crate::snapshot::arith_feedback;+use ak::ZoneVec;#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum UnaryOp {@@ -235,7 +236,7 @@ impl Operation {}}-impl GraphBuilder<'_, '_> {+impl<'a> GraphBuilder<'a, '_> {/// The arithmetic feedback of the instruction being built.fn arith_feedback(&self, instruction: &Instruction) -> Option<u8> {let slot = instruction.feedback_slots().arith?;@@ -283,7 +284,7 @@ impl GraphBuilder<'_, '_> {};let numbers = numbers && !op.is_bitwise();let [result] = self.join_hot_paths_with(paths, |builder, outputs| {- builder.slow_path_numbers(numbers, outputs, &[dst])+ builder.slow_path_numbers(numbers, outputs, &[dst]);})[..] else {unreachable!("binary operations have one value")};@@ -296,7 +297,7 @@ impl GraphBuilder<'_, '_> {};let numbers = numbers && matches!(op, UnaryOp::Plus | UnaryOp::Minus);let [result] = self.join_hot_paths_with(paths, |builder, outputs| {- builder.slow_path_numbers(numbers, outputs, &[dst])+ builder.slow_path_numbers(numbers, outputs, &[dst]);})[..] else {unreachable!("unary operations have one value")};@@ -307,11 +308,14 @@ impl GraphBuilder<'_, '_> {let Some(paths) = self.build_update_paths(op, value, old_value.is_some(), feedback)? else {return self.build_generic(instruction, info);};- let destinations = old_value.into_iter().chain([src]).collect::<Vec<_>>();+ let destinations = match old_value {+ Some(old_value) => &[old_value, src][..],+ None => &[src][..],+ };let values = self.join_hot_paths_with(paths, |builder, outputs| {- builder.slow_path_numbers(numbers, outputs, &destinations)+ builder.slow_path_numbers(numbers, outputs, destinations);});- match (values.as_slice(), old_value) {+ match (values, old_value) {([new_value], None) => self.write(src, *new_value)?,([old, new_value], Some(dst)) => {self.write(dst, *old)?;@@ -340,7 +344,8 @@ impl GraphBuilder<'_, '_> {Outcome::Value(_) => {let [result] = self.join_hot_paths_with(paths, |builder, outputs| {let truth = builder.constant(value::TRUE);- vec![builder.emit(Op::TaggedEquals { equal: true }, &[outputs[0], truth], Some(Repr::Bool))]+ outputs[0] =+ builder.emit(Op::TaggedEquals { equal: true }, &[outputs[0], truth], Some(Repr::Bool));})[..] else {unreachable!("comparisons have one value")};@@ -349,13 +354,13 @@ impl GraphBuilder<'_, '_> {Outcome::Jump(true_target, _) => {let [result] = self.join_hot_paths_with(paths, |builder, outputs| {let true_pc = builder.int32_constant(true_target.0.cast_signed());- vec![builder.emit(+ outputs[0] = builder.emit(Op::Int32Compare {comparison: Comparison::StrictlyEquals,},&[outputs[0], true_pc],Some(Repr::Bool),- )]+ );})[..] else {unreachable!("comparisons have one value")};@@ -372,27 +377,24 @@ impl GraphBuilder<'_, '_> {/// `destinations`, `outputs`, as the numbers its other paths make/// (boxed doubles) if `numbers`: the code exits after the instruction/// where they are no numbers (like bigints).- fn slow_path_numbers(&mut self, numbers: bool, outputs: Vec<NodeId>, destinations: &[Operand]) -> Vec<NodeId> {+ fn slow_path_numbers(&mut self, numbers: bool, outputs: &mut ZoneVec<'a, NodeId>, destinations: &[Operand]) {if !numbers {- return outputs;+ return;}// NB: The exit continues after the instruction, which wrote the// outputs.let frame = self.frame.clone();- for (destination, output) in destinations.iter().zip(&outputs) {+ for (destination, output) in destinations.iter().zip(outputs.iter()) {self.write(*destination, *output).expect("the instruction's destinations are in the frame");}let frame_state = self.resume_after_frame_state(Operand::INVALID);self.frame = frame;- outputs- .into_iter()- .map(|output| {- let number = self.emit(Op::CheckNumber, &[output], Some(Repr::Float64));- self.graph.nodes[number.index()].frame_state = Some(frame_state);- self.emit(Op::BoxFloat64, &[number], Some(Repr::Tagged))- })- .collect()+ for output in outputs.iter_mut() {+ let number = self.emit(Op::CheckNumber, &[*output], Some(Repr::Float64));+ self.graph.nodes[number.index()].frame_state = Some(frame_state);+ *output = self.emit(Op::BoxFloat64, &[number], Some(Repr::Tagged));+ }}fn box_number_result(&mut self, value: NodeId) -> NodeId {@@ -826,20 +828,20 @@ impl GraphBuilder<'_, '_> {/// `value` as a `Repr::Int32`, where it is an int32: a test sends other/// values on.- fn int32_on_path(&mut self, paths: &mut SlowPaths, value: NodeId) -> NodeId {+ fn int32_on_path(&mut self, paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {if let Some(integer) = self.int32_value_of(value) {return integer;}if let Some(integer) = self.int32_constant_of(value) {return self.int32_constant(integer);}- let refined = self.branch_to_next_case(paths, BranchCondition::Int32Value, vec![value], true);+ let refined = self.branch_to_next_case(paths, BranchCondition::Int32Value, &[value], true);self.emit(Op::UnboxInt32, &[refined], Some(Repr::Int32))}/// `value` as a `Repr::Float64`, where it is a number: tests send other/// values on.- fn float64_on_path(&mut self, paths: &mut SlowPaths, value: NodeId) -> NodeId {+ fn float64_on_path(&mut self, paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {self.float64_of(value, |builder, condition, inputs| {builder.branch_to_next_case(paths, condition, inputs, true)})@@ -850,7 +852,7 @@ impl GraphBuilder<'_, '_> {pub(super) fn float64_of(&mut self,value: NodeId,- otherwise: impl FnOnce(&mut Self, BranchCondition, Vec<NodeId>) -> NodeId,+ otherwise: impl FnOnce(&mut Self, BranchCondition, &[NodeId]) -> NodeId,) -> NodeId {if let Some(double) = self.float64_value_of(value) {return double;@@ -878,7 +880,7 @@ impl GraphBuilder<'_, '_> {/// values on.fn int32_of_operand_on_path(&mut self,- paths: &mut SlowPaths,+ paths: &mut SlowPaths<'a>,value: NodeId,doubles: bool,booleans: bool,@@ -892,7 +894,7 @@ impl GraphBuilder<'_, '_> {BranchCondition::Int32Value};if !doubles {- let refined = self.branch_to_next_case(paths, integer, vec![value], true);+ let refined = self.branch_to_next_case(paths, integer, &[value], true);return self.emit(Op::UnboxInt32, &[refined], Some(Repr::Int32));}self.on_integer_or_double(@@ -910,7 +912,7 @@ impl GraphBuilder<'_, '_> {/// numbers and booleans: the slow path then only handles operands that/// never came, and running it would make the code after the operation/// forget what it knew (see `exit_instead_of_slow_path()`).- fn exit_for_rare_bitwise_operands(&mut self, paths: &mut SlowPaths, feedback: u8) {+ fn exit_for_rare_bitwise_operands(&mut self, paths: &mut SlowPaths<'a>, feedback: u8) {if feedback & (arith_feedback::STRING | arith_feedback::BIG_INT | arith_feedback::OTHER) == 0 {self.exit_instead_of_slow_path(paths);}@@ -956,7 +958,7 @@ impl GraphBuilder<'_, '_> {lhs: NodeId,rhs: NodeId,feedback: u8,- ) -> Result<Option<SlowPaths>, CompileFailure> {+ ) -> Result<Option<SlowPaths<'a>>, CompileFailure> {let int32_results =self.may_speculate_int32_results(feedback) && op != BinaryOp::Div && self.may_be_int32(&[lhs, rhs]);if op.is_bitwise() {@@ -988,7 +990,7 @@ impl GraphBuilder<'_, '_> {let result = self.int32_binary(op, lhs, rhs);self.tagged(result)};- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);return Ok(Some(paths));}if op == BinaryOp::Mod {@@ -999,7 +1001,7 @@ impl GraphBuilder<'_, '_> {let (lhs, rhs) = (self.int32_on_path(&mut paths, lhs), self.int32_on_path(&mut paths, rhs));let result = self.int32_binary(op, lhs, rhs);let result = self.tagged(result);- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);return Ok(Some(paths));}let numbers = (feedback & (arith_feedback::DOUBLE | arith_feedback::INT32_OVERFLOW) != 0@@ -1017,7 +1019,7 @@ impl GraphBuilder<'_, '_> {let (lhs, rhs) = (self.int32_on_path(&mut paths, lhs), self.int32_on_path(&mut paths, rhs));let result = self.int32_binary(op, lhs, rhs);let result = self.tagged(result);- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);started = true;}if numbers && (!started || self.start_next_case(&mut paths)) {@@ -1027,7 +1029,7 @@ impl GraphBuilder<'_, '_> {);let result = self.emit(Op::Float64Binary { op }, &[lhs, rhs], Some(Repr::Float64));let result = self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged));- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);started = true;}if strings && (!started || self.start_next_case(&mut paths)) {@@ -1039,13 +1041,13 @@ impl GraphBuilder<'_, '_> {/// The paths of an `Add` of strings: two strings, and if `integers`, a/// string and an integer whose string the VM has.- fn build_concatenation_paths(&mut self, paths: &mut SlowPaths, lhs: NodeId, rhs: NodeId, integers: bool) {+ fn build_concatenation_paths(&mut self, paths: &mut SlowPaths<'a>, lhs: NodeId, rhs: NodeId, integers: bool) {let (lhs, rhs) = (self.tagged(lhs), self.tagged(rhs));- let string = self.branch_to_next_case(paths, BranchCondition::String, vec![lhs], true);+ let string = self.branch_to_next_case(paths, BranchCondition::String, &[lhs], true);let other = self.string_on_path(paths, rhs, integers);self.finish_concatenation(paths, string, other);if integers && self.start_next_case(paths) {- let string = self.branch_to_next_case(paths, BranchCondition::String, vec![rhs], true);+ let string = self.branch_to_next_case(paths, BranchCondition::String, &[rhs], true);let other = self.string_on_path(paths, lhs, true);self.finish_concatenation(paths, other, string);}@@ -1066,7 +1068,7 @@ impl GraphBuilder<'_, '_> {let (lhs, rhs) = (self.read(dst)?, self.read(src)?);let mut paths = self.start_slow_paths(Some(Repr::Tagged))?;let (lhs, rhs) = (self.tagged(lhs), self.tagged(rhs));- let string = self.branch_to_next_case(&mut paths, BranchCondition::String, vec![lhs], true);+ let string = self.branch_to_next_case(&mut paths, BranchCondition::String, &[lhs], true);let integers = self.runtime.layout.numeric_string_cache != 0;let other = self.string_on_path(&mut paths, rhs, integers);self.finish_concatenation(&mut paths, string, other);@@ -1077,13 +1079,13 @@ impl GraphBuilder<'_, '_> {/// The string `value` is, or if `integers`, the string of the integer/// it is, where the VM has that: tests send other values on.- fn string_on_path(&mut self, paths: &mut SlowPaths, value: NodeId, integers: bool) -> NodeId {+ fn string_on_path(&mut self, paths: &mut SlowPaths<'a>, value: NodeId, integers: bool) -> NodeId {if !integers {- return self.branch_to_next_case(paths, BranchCondition::String, vec![value], true);+ return self.branch_to_next_case(paths, BranchCondition::String, &[value], true);}- let (string_block, other) = self.branch_both_ways(BranchCondition::String, vec![value]);+ let (string_block, other) = self.branch_both_ways(BranchCondition::String, &[value]);self.block = string_block;- let string = self.refine(BranchCondition::String, true, vec![value]);+ let string = self.refine(BranchCondition::String, true, &[value]);let string_end = self.block;self.block = other;@@ -1092,26 +1094,26 @@ impl GraphBuilder<'_, '_> {let converted = self.test_not_empty(paths, converted);let converted_end = self.block;- self.join_blocks(vec![string_end, converted_end]);+ self.join_blocks(&[string_end, converted_end]);self.add_phi(&[string, converted])}/// `value`, which is the empty value where only the slow path can make/// it: a test sends that on.- fn test_not_empty(&mut self, paths: &mut SlowPaths, value: NodeId) -> NodeId {+ fn test_not_empty(&mut self, paths: &mut SlowPaths<'a>, value: NodeId) -> NodeId {let empty = self.constant(value::EMPTY);self.branch_to_next_case(paths,BranchCondition::TaggedEquals { equal: false },- vec![value, empty],+ &[value, empty],true,)}- fn finish_concatenation(&mut self, paths: &mut SlowPaths, lhs: NodeId, rhs: NodeId) {+ fn finish_concatenation(&mut self, paths: &mut SlowPaths<'a>, lhs: NodeId, rhs: NodeId) {let result = self.emit(Op::ConcatenateStrings { key: false }, &[lhs, rhs], Some(Repr::Tagged));let result = self.test_not_empty(paths, result);- self.end_hot_path(paths, vec![result]);+ self.end_hot_path(paths, &[result]);}fn build_unary_paths(@@ -1119,7 +1121,7 @@ impl GraphBuilder<'_, '_> {op: UnaryOp,value: NodeId,feedback: u8,- ) -> Result<Option<SlowPaths>, CompileFailure> {+ ) -> Result<Option<SlowPaths<'a>>, CompileFailure> {let int32s = feedback & arith_feedback::SAW_INT32 != 0;let doubles = feedback & arith_feedback::DOUBLE != 0;// NB: ToInt32 of a boolean is 0 or 1 (see `build_binary_paths()`).@@ -1136,7 +1138,7 @@ impl GraphBuilder<'_, '_> {// NB: ToNumber of a number is the number itself.if self.int32_value_of(value).is_some() || self.graph.node(value).repr == Some(Repr::Float64) {let result = self.tagged(value);- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);return Ok(Some(paths));}let mut started = false;@@ -1145,8 +1147,8 @@ impl GraphBuilder<'_, '_> {(doubles, BranchCondition::Double),] {if seen && (!started || self.start_next_case(&mut paths)) {- let number = self.branch_to_next_case(&mut paths, condition, vec![value], true);- self.end_hot_path(&mut paths, vec![number]);+ let number = self.branch_to_next_case(&mut paths, condition, &[value], true);+ self.end_hot_path(&mut paths, &[number]);started = true;}}@@ -1159,7 +1161,7 @@ impl GraphBuilder<'_, '_> {let minus_one = self.int32_constant(-1);let result = self.int32_binary(BinaryOp::Mul, integer, minus_one);let result = self.tagged(result);- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);}if doubles || !int32_results {if int32_results && !self.start_next_case(&mut paths) {@@ -1174,7 +1176,7 @@ impl GraphBuilder<'_, '_> {Some(Repr::Float64),);let result = self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged));- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);}}UnaryOp::BitwiseNot | UnaryOp::ToInt32 => {@@ -1186,7 +1188,7 @@ impl GraphBuilder<'_, '_> {integer};let result = self.tagged(result);- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);}}Ok(Some(paths))@@ -1200,7 +1202,7 @@ impl GraphBuilder<'_, '_> {value: NodeId,postfix: bool,feedback: u8,- ) -> Result<Option<SlowPaths>, CompileFailure> {+ ) -> Result<Option<SlowPaths<'a>>, CompileFailure> {let int32_results = self.may_speculate_int32_results(feedback);let numbers = feedback & (arith_feedback::DOUBLE | arith_feedback::INT32_OVERFLOW) != 0|| (feedback & arith_feedback::INT32 != 0 && !int32_results);@@ -1209,19 +1211,15 @@ impl GraphBuilder<'_, '_> {}// NB: ToNumeric of a number is the number itself.let old_value = self.tagged(value);- let values = |new_value| {- if postfix {- vec![old_value, new_value]- } else {- vec![new_value]- }- };+ // NB: The values are the old value, if `postfix`, and the new value.+ let first_value = usize::from(!postfix);+ let values = |new_value| [old_value, new_value];let mut paths = self.start_slow_paths(Some(Repr::Tagged))?;if int32_results {let integer = self.int32_on_path(&mut paths, value);let result = self.int32_update(op, integer);let result = self.tagged(result);- self.end_hot_path(&mut paths, values(result));+ self.end_hot_path(&mut paths, &values(result)[first_value..]);}if numbers && (!int32_results || self.start_next_case(&mut paths)) {let number = self.float64_on_path(&mut paths, value);@@ -1232,7 +1230,7 @@ impl GraphBuilder<'_, '_> {Some(Repr::Float64),);let result = self.emit(Op::BoxFloat64, &[result], Some(Repr::Tagged));- self.end_hot_path(&mut paths, values(result));+ self.end_hot_path(&mut paths, &values(result)[first_value..]);}Ok(Some(paths))}@@ -1245,7 +1243,7 @@ impl GraphBuilder<'_, '_> {rhs: NodeId,feedback: u8,slow_repr: Repr,- ) -> Result<Option<SlowPaths>, CompileFailure> {+ ) -> Result<Option<SlowPaths<'a>>, CompileFailure> {let equality = comparison.equality();// NB: `x == null`: undefined, null and [[IsHTMLDDA]] objects are loosely// equal to undefined and null, and nothing else is.@@ -1270,12 +1268,12 @@ impl GraphBuilder<'_, '_> {self.assume_no_htmldda_objects();let other = self.tagged(other);let mut paths = self.start_slow_paths(Some(slow_repr))?;- self.branch_to_next_case(&mut paths, BranchCondition::Nullish, vec![other], true);+ self.branch_to_next_case(&mut paths, BranchCondition::Nullish, &[other], true);let truth = self.typed_constant(u64::from(equal), Repr::Bool);- self.end_hot_path(&mut paths, vec![truth]);+ self.end_hot_path(&mut paths, &[truth]);self.start_next_case(&mut paths);let truth = self.typed_constant(u64::from(!equal), Repr::Bool);- self.end_hot_path(&mut paths, vec![truth]);+ self.end_hot_path(&mut paths, &[truth]);return Ok(Some(paths));}}@@ -1296,7 +1294,7 @@ impl GraphBuilder<'_, '_> {if int32s || strict_with_int32 {let (lhs, rhs) = (self.int32_on_path(&mut paths, lhs), self.int32_on_path(&mut paths, rhs));let result = self.emit(Op::Int32Compare { comparison }, &[lhs, rhs], Some(Repr::Bool));- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);started = true;}if (doubles || strict_with_int32) && (!started || self.start_next_case(&mut paths)) {@@ -1305,7 +1303,7 @@ impl GraphBuilder<'_, '_> {self.float64_on_path(&mut paths, rhs),);let result = self.emit(Op::Float64Compare { comparison }, &[lhs, rhs], Some(Repr::Bool));- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);started = true;}if let Some(equal) = equality@@ -1313,17 +1311,17 @@ impl GraphBuilder<'_, '_> {&& (!started || self.start_next_case(&mut paths)){let (lhs, rhs) = (self.tagged(lhs), self.tagged(rhs));- let lhs = self.branch_to_next_case(&mut paths, BranchCondition::String, vec![lhs], true);- let rhs = self.branch_to_next_case(&mut paths, BranchCondition::String, vec![rhs], true);+ let lhs = self.branch_to_next_case(&mut paths, BranchCondition::String, &[lhs], true);+ let rhs = self.branch_to_next_case(&mut paths, BranchCondition::String, &[rhs], true);let result = self.emit(Op::StringsEqual, &[lhs, rhs], Some(Repr::Tagged));let result = self.test_not_empty(&mut paths, result);let truth = self.constant(value::TRUE);let result = self.emit(Op::TaggedEquals { equal }, &[result, truth], Some(Repr::Bool));- self.end_hot_path(&mut paths, vec![result]);+ self.end_hot_path(&mut paths, &[result]);}if strict_with_int32 && self.start_next_case(&mut paths) {let truth = self.typed_constant(u64::from(equality == Some(false)), Repr::Bool);- self.end_hot_path(&mut paths, vec![truth]);+ self.end_hot_path(&mut paths, &[truth]);}Ok(Some(paths))}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 56e1cef7172..5ee1633a311 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -84,11 +84,11 @@ fn executable_analyses_are_lazy_and_borrowed_by_independent_walks() {let snapshot = snapshot_for(&program, test_layout());let executable = &snapshot.executables[0];let cache = OnceCell::new();- let decoded = decoded_function(&snapshot, executable, &cache).unwrap();+ let decoded = decoded_function(&snapshot, executable, &cache, crate::test_zone()).unwrap();assert!(decoded.analysis.get().is_none());assert!(std::ptr::eq(decoded,- decoded_function(&snapshot, executable, &cache).unwrap()+ decoded_function(&snapshot, executable, &cache, crate::test_zone()).unwrap()));let mut first = Function::new(&snapshot, 0, decoded, false, crate::test_zone()).unwrap();first.start_walk();@@ -109,7 +109,7 @@ fn cached_liveness_keeps_legacy_arguments_only_for_inlined_walks() {let snapshot = snapshot_for(&program, layout);let executable = &snapshot.executables[0];let cache = OnceCell::new();- let decoded = decoded_function(&snapshot, executable, &cache).unwrap();+ let decoded = decoded_function(&snapshot, executable, &cache, crate::test_zone()).unwrap();let first = Function::new(&snapshot, 0, decoded, first_mode, crate::test_zone()).unwrap();let second = Function::new(&snapshot, 0, decoded, !first_mode, crate::test_zone()).unwrap();let live_in = |function: &Function<'_>, slot| {@@ -759,7 +759,7 @@ fn calls_write_back_their_arguments_and_values_survive_them() {callee: r(5),this_value: r(5),argument_count: 1,- arguments: vec![r(6)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6)]),},Instruction::Mov { dst: l(0), src: r(7) },Instruction::Return { value: r(6) },@@ -865,7 +865,7 @@ pub(crate) mod property_access {use crate::snapshot::PropertyCacheKind;use crate::snapshot::PropertyCacheSnapshot;- pub(crate) fn get_by_id(dst: Operand, base: Operand, cache: u32) -> Instruction {+ pub(crate) fn get_by_id(dst: Operand, base: Operand, cache: u32) -> Instruction<'static> {Instruction::GetById {dst,base,@@ -874,7 +874,7 @@ pub(crate) mod property_access {}}- pub(crate) fn put_by_id(base: Operand, src: Operand, cache: u32) -> Instruction {+ pub(crate) fn put_by_id(base: Operand, src: Operand, cache: u32) -> Instruction<'static> {Instruction::PutById {base,property: PropertyKeyTableIndex(0),@@ -1355,7 +1355,7 @@ pub(crate) mod property_access {assert!(!text.contains("CheckValue"), "{text}");}- fn get_by_value(dst: Operand, base: Operand, property: Operand) -> Instruction {+ fn get_by_value(dst: Operand, base: Operand, property: Operand) -> Instruction<'static> {Instruction::GetByValue {keyed_feedback: 0,dst,@@ -1707,14 +1707,19 @@ pub(crate) mod inlining {pub(crate) const REALM: u64 = 0x8000;pub(crate) const ENVIRONMENT: u64 = 0x9000;- pub(crate) fn call(dst: Operand, callee: Operand, this_value: Operand, arguments: Vec<Operand>) -> Instruction {+ pub(crate) fn call(+ dst: Operand,+ callee: Operand,+ this_value: Operand,+ arguments: Vec<Operand>,+ ) -> Instruction<'static> {Instruction::Call {call_feedback: 0,dst,callee,this_value,argument_count: u32::try_from(arguments.len()).unwrap(),- arguments,+ arguments: crate::test_zone().alloc_slice_copy(&arguments),}}@@ -2592,7 +2597,7 @@ mod arguments {use crate::snapshot::Intrinsic;use crate::snapshot::PropertyCacheEntryType;- fn create_arguments(mapped: bool) -> Instruction {+ fn create_arguments(mapped: bool) -> Instruction<'static> {Instruction::CreateArguments {dst: Some(l(0)),kind: u8::from(!mapped),@@ -2685,7 +2690,7 @@ mod arguments {Instruction::NewArray {dst: r(7),element_count: 0,- elements: Vec::new(),+ elements: &[],},Instruction::ArrayAppend {dst: r(7),diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rsindex 9619196177b..c8748fef7d4 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs@@ -559,7 +559,7 @@ mod tests {Instruction::Return { value: r(5) },]});- let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();+ let instructions = crate::bytecode::decode_all(&program.bytes, crate::test_zone()).unwrap();let error = Cfg::new(&instructions, &[], &test_layout(), crate::test_zone()).unwrap_err();assert!(matches!(error, CfgError::InvalidJumpTarget { pc: 0, .. }));}diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rsindex 5832850cc92..705d88ed595 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs@@ -11,6 +11,9 @@//! interpreter.flap. The input is the exact byte stream the interpreter//! executes: operands are flat slot indices, labels are absolute byte offsets.+use ak::Zone;+use ak::ZoneVec;+include!(concat!(env!("OUT_DIR"), "/decoder_generated.rs"));/// A frame slot, as a flat index into the interpreter's@@ -176,13 +179,13 @@ pub struct FeedbackSlots {}/// One decoded instruction and where it lives in the bytecode.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct DecodedInstruction {+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DecodedInstruction<'a> {/// Byte offset of the instruction.pub pc: u32,/// Encoded length in bytes; the next instruction starts at `pc + length`.pub length: u32,- pub instruction: Instruction,+ pub instruction: Instruction<'a>,}impl OpCode {@@ -203,7 +206,7 @@ pub fn inlining_size(instructions: &[DecodedInstruction]) -> usize {.count()}-impl Instruction {+impl Instruction<'_> {/// The property lookup cache whose entries compiled code speculates on/// for this instruction, as shape checks that exit with/// `ExitKind::BadShape`.@@ -219,7 +222,7 @@ impl Instruction {}}-impl DecodedInstruction {+impl DecodedInstruction<'_> {pub fn next_pc(&self) -> u32 {self.pc + self.length}@@ -277,8 +280,9 @@ fn read_u64(bytes: &[u8], at: usize) -> u64 {u64::from_ne_bytes(bytes[at..at + 8].try_into().unwrap())}-/// Decodes the instruction starting at byte offset `pc`.-pub fn decode_instruction(bytes: &[u8], pc: u32) -> Result<DecodedInstruction, DecodeError> {+/// The opcode and the encoded length of the instruction starting at byte offset `pc`, after a check that the whole+/// instruction lies within `bytes`.+fn opcode_and_length(bytes: &[u8], pc: u32) -> Result<(u8, usize), DecodeError> {let error = |kind| DecodeError { pc, kind };let at = pc as usize;if at >= bytes.len() {@@ -289,8 +293,17 @@ pub fn decode_instruction(bytes: &[u8], pc: u32) -> Result<DecodedInstruction, Dif length == 0 || at + length > bytes.len() {return Err(error(DecodeErrorKind::TruncatedInstruction));}- let length_u32 = u32::try_from(length).map_err(|_| error(DecodeErrorKind::InvalidLength))?;- let instruction = match decode_fields(opcode, bytes, at, length).map_err(error)? {+ if u32::try_from(length).is_err() {+ return Err(error(DecodeErrorKind::InvalidLength));+ }+ Ok((opcode, length))+}++/// Decodes the instruction starting at byte offset `pc`. Its array, if it has one, is in `zone`.+pub fn decode_instruction<'a>(bytes: &[u8], pc: u32, zone: &'a Zone) -> Result<DecodedInstruction<'a>, DecodeError> {+ let error = |kind| DecodeError { pc, kind };+ let (opcode, length) = opcode_and_length(bytes, pc)?;+ let instruction = match decode_fields(opcode, bytes, pc as usize, length, zone).map_err(error)? {// NB: The rest of the compiler has no reason to care how far up the frame a move reaches.Instruction::MovWide { dst_slot, src_slot } => Instruction::Mov {dst: Operand::from_raw(dst_slot),@@ -300,25 +313,40 @@ pub fn decode_instruction(bytes: &[u8], pc: u32) -> Result<DecodedInstruction, D};Ok(DecodedInstruction {pc,- length: length_u32,+ length: length as u32,instruction,})}-/// Decodes a whole instruction stream.-pub fn decode_all(bytes: &[u8]) -> Result<Vec<DecodedInstruction>, DecodeError> {+/// The feedback slots of the instruction starting at byte offset `pc`, or `None` if it cannot be decoded.+pub fn feedback_slots_at(bytes: &[u8], pc: u32) -> Option<FeedbackSlots> {+ let (opcode, _) = opcode_and_length(bytes, pc).ok()?;+ Some(feedback_slots_from_bytes(opcode, bytes, pc as usize))+}++/// Decodes a whole instruction stream into `zone`.+pub fn decode_all<'a>(bytes: &[u8], zone: &'a Zone) -> Result<&'a [DecodedInstruction<'a>], DecodeError> {let end = u32::try_from(bytes.len()).map_err(|_| DecodeError {pc: 0,kind: DecodeErrorKind::InvalidLength,})?;- let mut instructions = Vec::new();+ // NB: The list gets its size before the first instruction is decoded, so the arrays that the zone gives out+ // after it never make it move.+ let mut count = 0;+ let mut pc = 0;+ while pc < end {+ let (_, length) = opcode_and_length(bytes, pc)?;+ pc += length as u32;+ count += 1;+ }+ let mut instructions = ZoneVec::with_capacity_in(count, zone);let mut pc = 0;while pc < end {- let instruction = decode_instruction(bytes, pc)?;+ let instruction = decode_instruction(bytes, pc, zone)?;pc = instruction.next_pc();instructions.push(instruction);}- Ok(instructions)+ Ok(instructions.into_slice())}#[cfg(test)]@@ -347,7 +375,7 @@ mod tests {bytes.push(7); // dstbytes.push(12); // src- let decoded = decode_instruction(&bytes, 0).unwrap();+ let decoded = decode_instruction(&bytes, 0, crate::test_zone()).unwrap();assert_eq!(decoded.pc, 0);assert_eq!(decoded.length, 3);assert_eq!(@@ -375,7 +403,7 @@ mod tests {jump.extend(48u32.to_ne_bytes()); // false_targetbytes.extend(jump);- let decoded = decode_instruction(&bytes, 16).unwrap();+ let decoded = decode_instruction(&bytes, 16, crate::test_zone()).unwrap();assert_eq!(decoded.pc, 16);assert_eq!(decoded.length, 10);assert_eq!(decoded.next_pc(), 26);@@ -405,12 +433,12 @@ mod tests {callee: operand(6),this_value: operand(7),argument_count: 3,- arguments: vec![operand(8), operand(20), operand(21)],+ arguments: crate::test_zone().alloc_slice_copy(&[operand(8), operand(20), operand(21)]),};let mut bytes = Vec::new();call.encode(&mut bytes);- let decoded = decode_instruction(&bytes, 0).unwrap();+ let decoded = decode_instruction(&bytes, 0, crate::test_zone()).unwrap();assert_eq!(decoded.length as usize, bytes.len());assert_eq!(decoded.length as usize, call.encoded_size());assert_eq!(decoded.instruction, call);@@ -435,7 +463,7 @@ mod tests {Instruction::NewPrimitiveArray {dst: operand(5),element_count: 2,- elements: vec![0x7ff8_0000_0000_0001, 42],+ elements: crate::test_zone().alloc_slice_copy(&[0x7ff8_0000_0000_0001, 42]),},Instruction::NewClass {element_keys_are_in_array: false,@@ -447,7 +475,7 @@ mod tests {lhs_name: Some(IdentifierTableIndex(4)),computed_name: None,element_keys_count: 3,- element_keys: vec![Some(operand(8)), None, Some(operand(9))],+ element_keys: crate::test_zone().alloc_slice_copy(&[Some(operand(8)), None, Some(operand(9))]),},Instruction::GetBinding {value_feedback: 0,@@ -490,7 +518,7 @@ mod tests {instruction.encode(&mut bytes);}- let decoded = decode_all(&bytes).unwrap();+ let decoded = decode_all(&bytes, crate::test_zone()).unwrap();assert_eq!(decoded.len(), instructions.len());let mut pc = 0;for (decoded, instruction) in decoded.iter().zip(&instructions) {@@ -524,7 +552,7 @@ mod tests {#[test]fn rejects_malformed_instructions() {- let error = |bytes: &[u8]| decode_instruction(bytes, 0).unwrap_err().kind;+ let error = |bytes: &[u8]| decode_instruction(bytes, 0, crate::test_zone()).unwrap_err().kind;assert_eq!(error(&[]), DecodeErrorKind::TruncatedInstruction);assert_eq!(error(&[u8::MAX, 0]), DecodeErrorKind::UnknownOpcode);@@ -544,7 +572,7 @@ mod tests {callee: operand(6),this_value: operand(7),argument_count: 1,- arguments: vec![operand(8)],+ arguments: crate::test_zone().alloc_slice_copy(&[operand(8)]),}.encode(&mut call);// Call's layout: header, call feedback slot, dst, callee, this_value, argument_count at 6.@@ -556,7 +584,7 @@ mod tests {let mut stream = mov.clone();stream.extend(&mov[..2]);assert_eq!(- decode_all(&stream).unwrap_err(),+ decode_all(&stream, crate::test_zone()).unwrap_err(),DecodeError {pc: 3,kind: DecodeErrorKind::TruncatedInstructiondiff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rsindex c3e689a3d6f..e7483e96f4c 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs@@ -165,25 +165,25 @@ pub(crate) mod test_support {}impl Program {- pub fn instructions(&self) -> Vec<DecodedInstruction> {- decode_all(&self.bytes).unwrap()+ pub fn instructions(&self) -> &'static [DecodedInstruction<'static>] {+ decode_all(&self.bytes, crate::test_zone()).unwrap()}pub fn cfg(&self) -> Cfg<'static> {- Cfg::new(&self.instructions(), &self.handlers, &test_layout(), crate::test_zone()).unwrap()+ Cfg::new(self.instructions(), &self.handlers, &test_layout(), crate::test_zone()).unwrap()}}/// Encodes the instructions returned by `build`, which receives a function/// that turns an instruction index into a label pointing at that instruction.- pub fn assemble(build: impl Fn(&dyn Fn(usize) -> Label) -> Vec<Instruction>) -> Program {+ pub fn assemble(build: impl Fn(&dyn Fn(usize) -> Label) -> Vec<Instruction<'static>>) -> Program {assemble_with_handlers(build, &[])}/// Like `assemble()`, with exception handlers given as instruction indices/// `(start, end, handler)`, where `end` is exclusive.pub fn assemble_with_handlers(- build: impl Fn(&dyn Fn(usize) -> Label) -> Vec<Instruction>,+ build: impl Fn(&dyn Fn(usize) -> Label) -> Vec<Instruction<'static>>,handlers: &[(usize, usize, usize)],) -> Program {let mut offsets = Vec::new();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex d9937ba1df1..2eeb0731ee5 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -78,14 +78,14 @@ enum CallOperand {/// What `emit_js_call()` worked out about a `Call` instruction before/// emitting it.-struct JsCall {+struct JsCall<'a> {executable: u32,pc: u32,next_pc: u32,dst: Operand,callee: Operand,this_value: Operand,- arguments: Vec<Operand>,+ arguments: &'a [Operand],/// The registers of the operands, for a `CallDirect` node that has them/// as inputs.input_registers: Option<Vec<Gpr>>,@@ -189,7 +189,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}).ok_or(invalid("direct call without a target"))?;if self.stores_operands(node) {- let operands = crate::builder::js_call_operands(&decoded.instruction).inputs;+ let mut operands = Vec::new();+ crate::builder::js_call_operands(decoded.instruction).for_each_input(|operand| operands.push(operand));self.emit_store_operand_inputs(node, &operands, registers)?;}self.emit_js_call(executable, pc, Some((target, node)), None)@@ -268,29 +269,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let next_pc = decoded.next_pc();let (dst, callee, new_target, arguments) = match decoded.instruction {Instruction::CallConstruct {- dst,- callee,- ref arguments,- ..- } => (- dst,- CallOperand::Slot(callee),- CallOperand::Slot(callee),- arguments.clone(),- ),+ dst, callee, arguments, ..+ } => (dst, CallOperand::Slot(callee), CallOperand::Slot(callee), arguments),Instruction::SuperCall {dst,super_constructor,- ref arguments,+ arguments,..- } => (- dst,- CallOperand::Slot(super_constructor),- CallOperand::Empty,- arguments.clone(),- ),+ } => (dst, CallOperand::Slot(super_constructor), CallOperand::Empty, arguments),Instruction::SuperCallWithForwardedArguments { dst, .. } => {- (dst, CallOperand::Undefined, CallOperand::Empty, Vec::new())+ (dst, CallOperand::Undefined, CallOperand::Empty, &[][..])}_ => {return Err(CompileFailure::InvalidBytecode {@@ -299,7 +287,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {});}};- let arguments = arguments.into_iter().map(CallOperand::Slot).collect::<Vec<_>>();+ let arguments = arguments.iter().copied().map(CallOperand::Slot).collect::<Vec<_>>();self.emit_call_stub_call(callee,new_target,@@ -1142,7 +1130,8 @@ 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 stored_operands = crate::builder::js_call_operands(&decoded.instruction).inputs;+ 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,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 13d4cf4e2cd..9640d09c669 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -117,6 +117,7 @@ fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bograph: &graph,allocation: &allocation,snapshot: &snapshot,+ work: &zone,runtime,stress: crate::snapshot::StressOptions::default(),pinned,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 0222f4d747a..687ce3bf9cb 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -116,6 +116,7 @@ use crate::snapshot::ExecutableSnapshot;use crate::snapshot::RuntimeInfo;use crate::snapshot::Snapshot;use crate::snapshot::StressOptions;+use ak::Zone;use sites::SiteSource;/// Bit 32 of a slow path control word marks a continuation in the same frame.@@ -274,6 +275,8 @@ struct Codegen<'a, M: PortableMacroAssembler> {allocation: &'a Allocation,/// 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.+ work: &'a Zone,/// The runtime info of the snapshot.runtime: &'a RuntimeInfo,stress: StressOptions,@@ -425,6 +428,7 @@ pub fn generate<M: PortableMacroAssembler>(snapshot: &Snapshot,verify: bool,tables: &mut Tables,+ work: &Zone,) -> Result<GeneratedCode, CompileFailure> {let Tables {artifact,@@ -450,6 +454,7 @@ pub fn generate<M: PortableMacroAssembler>(graph,allocation,snapshot,+ work,runtime: &snapshot.runtime,stress: snapshot.options.stress,pinned,@@ -703,7 +708,7 @@ fn checked_i32(value: u64) -> Result<i32, CompileFailure> {i32::try_from(value).map_err(|_| CompileFailure::CodeGeneration)}-impl<M: PortableMacroAssembler> Codegen<'_, M> {+impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {// Frame layout./// Sizes the locals area and decides which callee-saved registers to save.@@ -936,9 +941,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}/// The instruction at `pc` of executable `executable`.- fn decoded(&self, executable: u32, pc: u32) -> Result<DecodedInstruction, CompileFailure> {+ fn decoded(&self, executable: u32, pc: u32) -> Result<DecodedInstruction<'a>, CompileFailure> {let bytecode = &self.snapshot[self.snapshot.executables[executable as usize].bytecode];- decode_instruction(bytecode, pc).map_err(|_| CompileFailure::InvalidBytecode {+ decode_instruction(bytecode, pc, self.work).map_err(|_| CompileFailure::InvalidBytecode {pc,reason: "undecodable instruction",})@@ -2748,9 +2753,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let is_js_call = slow_path_call(opcode) == Some(SlowPathCall::JitCall);if is_js_call {let decoded = self.decoded(executable, pc)?;- let call_operands = crate::builder::js_call_operands(&decoded.instruction);- operands = call_operands.inputs;- outputs = call_operands.outputs.into_iter().map(|(_, operand)| operand).collect();+ let call_operands = crate::builder::js_call_operands(decoded.instruction);+ call_operands.for_each_input(|operand| operands.push(operand));+ call_operands.for_each_output(|_, operand| outputs.push(operand));} else {let layout = slow_path_layout(opcode);for field in layout.fields {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex b0eccd402c4..699f8e50f01 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -181,16 +181,20 @@ fn continuation_after(vm: *mut u64, pc: u32) -> i64 {{return control;}- let next_pc = decode_instruction(&state.bytecodes[running_executable(vm)], pc)+ let next_pc = decode_instruction(&state.bytecodes[running_executable(vm)], pc, crate::test_zone()).unwrap().next_pc();(CONTINUATION_BIT | u64::from(next_pc)) as i64}-fn decoded(vm: *mut u64, pc: u32) -> Instruction {- decode_instruction(&test_state(vm).borrow().bytecodes[running_executable(vm)], pc)- .unwrap()- .instruction+fn decoded(vm: *mut u64, pc: u32) -> Instruction<'static> {+ decode_instruction(+ &test_state(vm).borrow().bytecodes[running_executable(vm)],+ pc,+ crate::test_zone(),+ )+ .unwrap()+ .instruction}fn int(value: u64) -> i32 {@@ -203,7 +207,7 @@ fn is_int32(bits: u64) -> bool {}#[cfg(target_arch = "x86_64")]-fn add(dst: Operand, lhs: Operand, rhs: Operand) -> Instruction {+fn add(dst: Operand, lhs: Operand, rhs: Operand) -> Instruction<'static> {Instruction::Add {arith_feedback: 0,dst,@@ -247,9 +251,13 @@ struct SlowPathResult {#[jit_abi]extern "C" fn add_values(vm: *mut u64, pc: u32, dst: *mut u64, lhs: u64, rhs: u64, length: u32) -> i64 {- let next_pc = decode_instruction(&test_state(vm).borrow().bytecodes[running_executable(vm)], pc)- .unwrap()- .next_pc();+ let next_pc = decode_instruction(+ &test_state(vm).borrow().bytecodes[running_executable(vm)],+ pc,+ crate::test_zone(),+ )+ .unwrap()+ .next_pc();assert_eq!(pc + length, next_pc);let control = continuation_after(vm, pc);if control >= 0 && control as u64 & CONTINUATION_BIT != 0 {@@ -384,7 +392,7 @@ extern "C" fn jit_call(vm: *mut u64, frame: *mut u64, pc: u32) -> i64 {// SAFETY: The frame is the fake frame of the running test.unsafe {let mut result = int(*frame.add(slot(callee)));- for argument in arguments {+ for &argument in arguments {result = result.wrapping_add(int(*frame.add(slot(argument))));}*frame.add(slot(dst)) = value::int32(result);@@ -1004,7 +1012,7 @@ fn compile_program_with(/// The pc of the (only) loop back edge of `program`, which on-stack/// replacement entries start at.fn back_edge_pc(program: &Program) -> u32 {- crate::bytecode::decode_all(&program.bytes)+ crate::bytecode::decode_all(&program.bytes, crate::test_zone()).unwrap().iter().find(|decoded| crate::builder::is_loop_back_edge(decoded.instruction.opcode()))@@ -1046,7 +1054,7 @@ mod execution {use super::*;/// A generic instruction whose fake slow path adds.- fn add(dst: Operand, lhs: Operand, rhs: Operand) -> Instruction {+ fn add(dst: Operand, lhs: Operand, rhs: Operand) -> Instruction<'static> {Instruction::Exp {arith_feedback: 0,dst,@@ -1472,7 +1480,7 @@ mod execution {callee: c(1),this_value: c(0),argument_count: 2,- arguments: vec![r(6), c(1)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6), c(1)]),},// r6 still holds the argument, which lived across the call.Instruction::IsCallable { dst: l(1), value: r(6) },@@ -1495,7 +1503,7 @@ mod execution {Instruction::NewArray {dst: r(6),element_count: 3,- elements: vec![r(5), c(1), a(0)],+ elements: crate::test_zone().alloc_slice_copy(&[r(5), c(1), a(0)]),},Instruction::Return { value: r(6) },]@@ -1705,7 +1713,7 @@ mod execution {instructions.push(Instruction::NewArray {dst: register(15),element_count: 10,- elements: (5..15).map(register).collect(),+ elements: crate::test_zone().alloc_slice_from_iter((5..15).map(register)),});instructions.push(Instruction::Return { value: register(15) });instructions@@ -1830,7 +1838,7 @@ mod execution {if never_ran.contains(&pc) {return ReferenceEnd::Exited { pc, slots };}- let decoded = decode_instruction(&program.bytes, pc).unwrap();+ let decoded = decode_instruction(&program.bytes, pc, crate::test_zone()).unwrap();let read = |slots: &[u64], operand: Operand| slots[operand.raw() as usize];let mut next_pc = decoded.next_pc();match decoded.instruction {@@ -1878,7 +1886,7 @@ mod execution {dst, callee, arguments, ..} => {let mut result = int(read(&slots, callee));- for argument in arguments {+ for &argument in arguments {result = result.wrapping_add(int(read(&slots, argument)));}slots[dst.raw() as usize] = value::int32(result);@@ -2004,7 +2012,7 @@ mod execution {assert_eq!(result.status, RESUME, "seed {seed}");assert_eq!(machine.program_counter(), pc, "seed {seed}");// Every slot the interpreter can still read must be right.- let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();+ let instructions = crate::bytecode::decode_all(&program.bytes, crate::test_zone()).unwrap();let work = crate::test_work();let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();let liveness =@@ -2177,7 +2185,7 @@ mod execution {},) => {assert_eq!(resumed_pc, *pc, "seed {seed}: resumed exit");- let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();+ let instructions = crate::bytecode::decode_all(&program.bytes, crate::test_zone()).unwrap();let work = crate::test_work();let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();let liveness =@@ -2209,7 +2217,7 @@ mod execution {exits += 1;assert_eq!(result.status, RESUME, "seed {seed}");assert_eq!(machine.program_counter(), pc, "seed {seed}");- let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();+ let instructions = crate::bytecode::decode_all(&program.bytes, crate::test_zone()).unwrap();let work = crate::test_work();let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();let liveness =@@ -2388,7 +2396,7 @@ fn aarch64_code_disassembles() {Instruction::NewArray {dst: r(6),element_count: 2,- elements: vec![l(0), a(0)],+ elements: crate::test_zone().alloc_slice_copy(&[l(0), a(0)]),},Instruction::JumpIf {condition: r(6),@@ -2898,7 +2906,7 @@ mod property_access {callee: r(6),this_value: a(0),argument_count: 1,- arguments: vec![c(1)],+ arguments: crate::test_zone().alloc_slice_copy(&[c(1)]),},Instruction::Return { value: r(5) },]@@ -3017,7 +3025,7 @@ mod property_access {callee: c(0),this_value: c(0),argument_count: 0,- arguments: Vec::new(),+ arguments: &[],},get_by_id(r(7), a(0), 1),add(l(0), r(5), r(7)),@@ -3283,7 +3291,7 @@ mod inlining {}/// `function plus(v) { return v + other; }`, with `other` from `src`.- fn plus(src: Instruction) -> Program {+ fn plus(src: Instruction<'static>) -> Program {assemble(|_| {vec![Instruction::Enter,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex f439e90fcca..80021cbd641 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -374,18 +374,18 @@ fn run_compiled_program(}/// Runs `instruction`, which writes `r(5)` from the arguments, and returns `r(5)`.-fn run_instruction(instruction: Instruction, arguments: &[u64]) -> u64 {+fn run_instruction(instruction: Instruction<'static>, arguments: &[u64]) -> u64 {run_instruction_with(GENERAL_FEEDBACK, instruction, arguments).0}/// Like `run_instruction()`, with arithmetic feedback `feedback`, and/// `EXITED` if the code exits. Also returns the number of calls of the/// fake comparison and jump slow paths.-fn run_instruction_with(feedback: u8, instruction: Instruction, arguments: &[u64]) -> (u64, u64) {+fn run_instruction_with(feedback: u8, instruction: Instruction<'static>, arguments: &[u64]) -> (u64, u64) {compile_instruction(feedback, instruction)(arguments)}-fn compile_instruction(feedback: u8, instruction: Instruction) -> impl Fn(&[u64]) -> (u64, u64) {+fn compile_instruction(feedback: u8, instruction: Instruction<'static>) -> impl Fn(&[u64]) -> (u64, u64) {let program = assemble(|_| {vec![Instruction::Enter,@@ -585,7 +585,7 @@ fn double_operation(op: BinaryOp, lhs: f64, rhs: f64) -> f64 {}}-fn binary_instruction(op: BinaryOp, lhs: OperationInput, rhs: OperationInput) -> Instruction {+fn binary_instruction(op: BinaryOp, lhs: OperationInput, rhs: OperationInput) -> Instruction<'static> {use OperationInput::Int32;use OperationInput::Operand as Slot;let dst = r(5);@@ -959,7 +959,7 @@ fn slow_paths_preserve_registers() {Instruction::NewArray {dst: l(0),element_count: 3,- elements: vec![r(5), r(6), r(7)],+ elements: crate::test_zone().alloc_slice_copy(&[r(5), r(6), r(7)]),},Instruction::Return { value: l(0) },]@@ -1037,7 +1037,12 @@ const COMPARISONS: [Comparison; 8] = [Comparison::LooselyInequals,];-fn compare_instruction(comparison: Comparison, dst: Operand, lhs: Operand, rhs: OperationInput) -> Instruction {+fn compare_instruction(+ comparison: Comparison,+ dst: Operand,+ lhs: Operand,+ rhs: OperationInput,+) -> Instruction<'static> {use OperationInput::Int32;use OperationInput::Operand as Slot;macro_rules! pick {@@ -1081,7 +1086,7 @@ fn compare_jump_instruction(is_loop: bool,true_target: crate::bytecode::Label,false_target: crate::bytecode::Label,-) -> Instruction {+) -> Instruction<'static> {use OperationInput::Int32;use OperationInput::Operand as Slot;macro_rules! pick {@@ -1185,11 +1190,12 @@ fn boolean(result: Option<bool>) -> u64 {#[test]fn comparisons() {let values = values();- let check = |(result, slow_calls), instruction: &Instruction, lhs: u64, rhs: u64, expected: Option<bool>| {- let context = format!("{instruction:?} {lhs:#x} {rhs:#x}: got {result:#x}");- assert_eq!(result, boolean(expected), "{context}");- assert_eq!(slow_calls, u64::from(expected.is_none()), "{context}");- };+ let check =+ |(result, slow_calls), instruction: &Instruction<'static>, lhs: u64, rhs: u64, expected: Option<bool>| {+ let context = format!("{instruction:?} {lhs:#x} {rhs:#x}: got {result:#x}");+ assert_eq!(result, boolean(expected), "{context}");+ assert_eq!(slow_calls, u64::from(expected.is_none()), "{context}");+ };for comparison in COMPARISONS {let instruction = compare_instruction(comparison, r(5), argument(0), OperationInput::Operand(argument(1)));let run = compile_instruction(GENERAL_FEEDBACK, instruction.clone());@@ -2064,7 +2070,7 @@ impl FakeEnvironment {/// returns the result and how often a slow path that counts ran. `exits` are/// the exits taken before, by the index of their instruction.fn run_with_environments(- instructions: Vec<Instruction>,+ instructions: Vec<Instruction<'static>>,arguments: &[u64],lexical: &FakeEnvironment,variable: &FakeEnvironment,@@ -2374,7 +2380,7 @@ impl FakeGlobals {}}- fn run(&self, instruction: Instruction, arguments: &[u64]) -> (JitResult, u64) {+ fn run(&self, instruction: Instruction<'static>, arguments: &[u64]) -> (JitResult, u64) {let program = assemble(|_| {vec![Instruction::Enter,@@ -2466,7 +2472,7 @@ fn global_variables() {/// environment has the serial number `serial`.fn run_with_global_cache(globals: &FakeGlobals,- instruction: &Instruction,+ instruction: &Instruction<'static>,arguments: &[u64],cache: crate::snapshot::GlobalCacheSnapshot,serial: u64,@@ -2787,7 +2793,7 @@ fn modulo_of_random_int32_values() {#[test]fn checks_take_the_slow_path_only_when_they_fail() {let object = u64::from(value::OBJECT_TAG) << 48 | 0x1000;- let slow_paths = |instruction: Instruction, argument: u64| {+ let slow_paths = |instruction: Instruction<'static>, argument: u64| {let program = assemble(|_| {vec![Instruction::Enter,@@ -3079,13 +3085,13 @@ impl FakeCachedObject {self.entry[2] = new_shape.as_ptr() as u64;}- fn run(&self, instruction: Instruction, arguments: &[u64]) -> (JitResult, u64) {+ fn run(&self, instruction: Instruction<'static>, arguments: &[u64]) -> (JitResult, u64) {self.run_with_prototypes(instruction, arguments, PrimitivePrototypes::default())}fn run_with_prototypes(&self,- instruction: Instruction,+ instruction: Instruction<'static>,arguments: &[u64],prototypes: PrimitivePrototypes,) -> (JitResult, u64) {@@ -3641,14 +3647,14 @@ fn get_by_value_of_string_characters() {/// A `Call` of the callee in `argument(0)` with `this_value` and/// `arguments`, into `r(5)`.-fn builtin_call(this_value: Operand, arguments: Vec<Operand>) -> Instruction {+fn builtin_call(this_value: Operand, arguments: Vec<Operand>) -> Instruction<'static> {Instruction::Call {call_feedback: 0,dst: r(5),callee: argument(0),this_value,argument_count: arguments.len() as u32,- arguments,+ arguments: crate::test_zone().alloc_slice_copy(&arguments),}}diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 6772246d04b..bfbf8ea9968 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -144,7 +144,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(// NB: Nothing of the compile before this one is in use (see `Scratch`).work.reset();let mut graph = {- let attempts = builder::Attempts::new(snapshot, has_run, work);+ let mut attempts = builder::Attempts::new(snapshot, has_run, work);loop {// NB: This drops the graph of the compile before this one, and a graph that the builder gave up.zone.reset();@@ -187,7 +187,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(regalloc::dump_allocation(&graph, &tables.regalloc.allocation));}- let mut generated = codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, tables)?;+ let mut generated = codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, tables, work)?;generated.osr_entries.sort_unstable();let layout = tables.artifact.finish(&Tail {diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 048f5a97c9c..6ca6df2dddf 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -117,7 +117,7 @@ fn values_live_across_calls_are_spilled_at_their_definition() {callee: r(5),this_value: r(5),argument_count: 1,- arguments: vec![r(6)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6)]),},Instruction::Mov { dst: a(0), src: r(7) },Instruction::Return { value: r(6) },@@ -155,7 +155,7 @@ fn values_loaded_from_unwritten_slots_are_reloaded_from_the_frame() {callee: r(5),this_value: r(5),argument_count: 1,- arguments: vec![r(6)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6)]),},Instruction::Return { value: r(6) },]@@ -468,7 +468,7 @@ fn loops_leave_the_values_they_only_carry_through_in_their_stack_slots() {callee: r(15),this_value: r(15),argument_count: 0,- arguments: vec![],+ arguments: &[],},xor(5, r(10), r(5), r(6)),xor(6, r(12), r(7), r(11)),@@ -762,7 +762,7 @@ fn the_verifier_finds_values_in_the_wrong_place() {callee: r(5),this_value: r(5),argument_count: 1,- arguments: vec![r(6)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6)]),},Instruction::Mov { dst: a(0), src: r(7) },Instruction::Return { value: r(6) },@@ -800,7 +800,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {callee: r(5),this_value: r(5),argument_count: 1,- arguments: vec![r(6)],+ arguments: crate::test_zone().alloc_slice_copy(&[r(6)]),},Instruction::Return { value: r(6) },]@@ -872,7 +872,7 @@ impl Random {/// An instruction whose jump targets are instruction indices.#[derive(Clone)]enum Item {- Plain(Instruction),+ Plain(Instruction<'static>),Jump(usize),JumpIf(Operand, usize, usize),JumpTrue(Operand, usize),@@ -925,7 +925,7 @@ impl ProgramGenerator {}}- fn plain(&mut self) -> Instruction {+ fn plain(&mut self) -> Instruction<'static> {if self.property_access && self.random.chance(30) {let cache = u32::try_from(self.random.below(2)).unwrap();return if self.random.chance(60) {@@ -981,7 +981,7 @@ impl ProgramGenerator {callee: self.readable(),this_value: self.readable(),argument_count: u32::try_from(argument_count).unwrap(),- arguments: (0..argument_count).map(|_| self.readable()).collect(),+ arguments: crate::test_zone().alloc_slice_from_iter((0..argument_count).map(|_| self.readable())),}}_ => Instruction::ToBoolean {@@ -1227,7 +1227,7 @@ fn float64_values_get_floating_point_registers() {callee: r(6),this_value: r(7),argument_count: 1,- arguments: vec![a(0)],+ arguments: crate::test_zone().alloc_slice_copy(&[a(0)]),},Instruction::Return { value: r(5) },]diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 6249ad305ef..0b2cb0896e2 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -19,7 +19,7 @@use core::marker::PhantomData;use core::ops::{Deref, DerefMut, Index, IndexMut};-use ak::{Column, RowBlock};+use ak::{Column, RowBlock, Zone};use std::sync::Arc;use crate::ir::Float64Function;@@ -1785,6 +1785,10 @@ pub trait Row: Copy + Send + Sync + 'static {/// How many bytes of rows a list that is written row by row holds at most.const MAX_OPEN_LIST_BYTES: usize = 16 * 1024 * 1024;+/// The most bytes that the scratch zone of a capture gives out. It is address space, which costs nothing before it+/// is used.+const MAX_CAPTURE_SCRATCH_BYTES: usize = 1 << 30;+macro_rules! rows {($($name:ident: $row:ty,)*) => {#[allow(non_camel_case_types)]@@ -1805,6 +1809,9 @@ macro_rules! rows {$($name: Column<$row>,)*/// Whether a list of each type is being written.open: [bool; ROW_TYPE_COUNT],+ /// Where a step of a capture keeps data that only it reads, like the array of the instruction that a+ /// walk over bytecode is at. It holds nothing from one step to the next.+ scratch: Zone,}impl OpenLists {@@ -1812,6 +1819,7 @@ macro_rules! rows {Self {$($name: Column::new(MAX_OPEN_LIST_BYTES / size_of::<$row>(), c"JIT snapshot open lists"),)*open: [false; ROW_TYPE_COUNT],+ scratch: Zone::new(MAX_CAPTURE_SCRATCH_BYTES, c"JIT snapshot scratch"),}}@@ -1819,6 +1827,7 @@ macro_rules! rows {fn reset(&mut self) {$(self.$name.clear();)*self.open = [false; ROW_TYPE_COUNT];+ self.scratch.reset();}}@@ -1986,6 +1995,12 @@ impl SnapshotWriter {(self.snapshot, self.lists)}+ /// A zone for data that one step of the capture reads and then drops (see `Zone::scope()`). Its memory serves+ /// capture after capture, like that of the lists that are written row by row.+ pub fn scratch(&mut self) -> &mut Zone {+ &mut self.lists.scratch+ }+/// Starts a list, which gets the rows that `push()` adds until `end()`. Only one list of a type of row can be/// written at a time.pub fn begin<T: Row>(&mut self) -> ListStart<T> {diff --git a/Libraries/LibJS/Rust/generate/instructions.rs b/Libraries/LibJS/Rust/generate/instructions.rsindex 60026dec915..8345ead749e 100644--- a/Libraries/LibJS/Rust/generate/instructions.rs+++ b/Libraries/LibJS/Rust/generate/instructions.rs@@ -18,6 +18,7 @@ use flapc::metadata::SpecializedParameterBinding;use flapc::metadata::compute_layouts;use flapc::metadata::field_type_info;use flapc::metadata::user_fields;+use flapc::rust_bytecode::ArrayFields;use flapc::rust_bytecode::InstructionSet;use flapc::rust_bytecode::count_field_name;use flapc::rust_bytecode::generate_encode_method;@@ -52,7 +53,7 @@ fn generate_rust_code(generate_opcode_enum(&mut w, ops)?;generate_num_opcodes_const(&mut w, ops)?;- generate_instruction_enum(&mut w, ops, "Debug, Clone")?;+ generate_instruction_enum(&mut w, ops, "Debug, Clone", ArrayFields::Owned)?;generate_instruction_impl(&mut w, ops)?;generate_instruction_length_from_bytes(&mut w, ops, "super::operand::InstructionLengthError")?;generate_instruction_name_from_opcode(&mut w, ops)?;@@ -602,6 +603,7 @@ fn generate_instruction_impl(ops,"encode_into_block","crate::bytecode::codegen::emitter::BlockEncoder<'_>",+ ArrayFields::Owned,)?;generate_visit_labels_method(&mut w, ops)?;writeln!(w, " }}")?;diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 8f4ffa910d5..f11d1ee71cb 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -11,6 +11,7 @@ use core::ffi::c_void;use core::ops::ControlFlow;use std::collections::HashMap;+use ak::Zone;use libjs_jit::artifact::{Artifact, FrameView, Layout, Patch, SiteView};use libjs_jit::bytecode::{EnvironmentCoordinate, decode_instruction};use libjs_jit::code::ExitKind;@@ -131,6 +132,21 @@ pub fn speculated_cache_size(cache: &PropertyLookupCache) -> u8 {u8::try_from(entries).expect("caches that are not megamorphic have few entries")}+/// The property lookup cache that the instruction at `pc` of `bytecode` speculates on (see+/// `Instruction::speculated_property_lookup_cache()`), if it has one.+fn speculated_property_lookup_cache_index(bytecode: &[u8], pc: u32) -> Option<u32> {+ // NB: A zone takes no memory before it gives some out, and it gives out memory only for the array of an+ // instruction, which no instruction that speculates on a property lookup cache has.+ let zone = Zone::new(DECODED_ARRAY_LIMIT, c"LibJS decoded instruction");+ decode_instruction(bytecode, pc, &zone)+ .ok()?+ .instruction+ .speculated_property_lookup_cache()+}++/// The most memory the array of one decoded instruction takes.+const DECODED_ARRAY_LIMIT: usize = 1 << 30;+/// The function object of an inlined executable, which its materialized frames run.#[derive(Clone, Copy, PartialEq, Eq, Hash, Trace)]pub enum InlinedFunction {@@ -593,8 +609,7 @@ impl Executable {/// The property lookup cache that the instruction at `pc` speculates on (see/// `Instruction::speculated_property_lookup_cache()`), if it has one.fn speculated_property_lookup_cache(&self, pc: u32) -> Option<&PropertyLookupCache> {- let decoded = decode_instruction(self.bytecode(), pc).ok()?;- let index = decoded.instruction.speculated_property_lookup_cache()?;+ let index = speculated_property_lookup_cache_index(self.bytecode(), pc)?;self.property_lookup_caches().get(index as usize)}@@ -602,9 +617,7 @@ impl Executable {/// `ExitKind::BadShape` at `pc`. Returns whether that code speculated on more shapes there than the code that/// exited there before, so that a recompile learns from the exit.pub fn note_jit_shape_exit(&self, pc: u32, cache_sizes: &[u8]) -> bool {- let Some(size) = decode_instruction(self.bytecode(), pc)- .ok()- .and_then(|decoded| decoded.instruction.speculated_property_lookup_cache())+ let Some(size) = speculated_property_lookup_cache_index(self.bytecode(), pc).and_then(|index| cache_sizes.get(index as usize).copied())else {return false;diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex f6ccc8cdd21..13d98af70f2 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -7,6 +7,7 @@//! Snapshots of executables for compile jobs, captured on the main thread straight from the runtime's structures.//! A snapshot refers to cells only by address; the cells it captured are kept alive by whoever owns the job.+use ak::Zone;use core::num::NonZeroU64;use libjs_abi::Builtin;use std::collections::HashMap;@@ -1415,7 +1416,7 @@ impl SnapshotBuilder<'_> {let loads = &executable.jit_state().captured_binding_accesses- .get_or_init(|| captured_binding_accesses(&executable))+ .get_or_init(|| captured_binding_accesses(&executable, self.snapshot.scratch())).loads;let exit_sites = executable.jit_exit_sites();let changed: Vec<EnvironmentCoordinate> = loads@@ -1473,7 +1474,7 @@ fn mutable_bindings(let stores = &executable.jit_state().captured_binding_accesses- .get_or_init(|| captured_binding_accesses(&executable))+ .get_or_init(|| captured_binding_accesses(&executable, snapshot.scratch())).stores;let bindings = snapshot.begin();for &coordinate in stores {@@ -1498,8 +1499,8 @@ fn mutable_bindings(}/// The loads and stores of bindings of environments in `executable`, or none if its code may change its lexical-/// environment, so that they are not the environments of its closure.-fn captured_binding_accesses(executable: &Executable) -> CapturedBindingAccesses {+/// environment, so that they are not the environments of its closure. `zone` holds nothing after this.+fn captured_binding_accesses(executable: &Executable, zone: &mut Zone) -> CapturedBindingAccesses {let bytecode = executable.bytecode();let Ok(end) = u32::try_from(bytecode.len()) else {return CapturedBindingAccesses::default();@@ -1507,35 +1508,41 @@ fn captured_binding_accesses(executable: &Executable) -> CapturedBindingAccesseslet mut loads = Vec::new();let mut stores = Vec::new();let mut pc = 0;- // NB: This reads the instructions one at a time: a list of all of them would be a large block of the heap.+ // NB: This reads the instructions one at a time: a list of all of them would be a large block of the heap. The+ // arrays of the instructions go in the zone, which drops each one when the next instruction is read. The+ // zone is one that captures share: a zone of its own would take memory from the system for each walk.while pc < end {- let Ok(decoded) = decode_instruction(bytecode, pc) else {+ let next_pc = zone.scope(|zone| {+ let decoded = decode_instruction(bytecode, pc, zone).ok()?;+ let changes_environment = matches!(+ decoded.instruction.opcode(),+ OpCode::SetLexicalEnvironment+ | OpCode::CreateLexicalEnvironment+ | OpCode::CreateVariableEnvironment+ | OpCode::EnterObjectEnvironment+ | OpCode::NewClass+ | OpCode::CallDirectEval+ | OpCode::CallDirectEvalWithArgumentArray+ | OpCode::Debugger+ );+ if changes_environment {+ return None;+ }+ match decoded.instruction {+ Instruction::GetBinding { cache: coordinate, .. }+ | Instruction::GetInitializedBinding { cache: coordinate, .. }+ | Instruction::GetCalleeAndThisFromEnvironment { cache: coordinate, .. } => {+ loads.push((coordinate, decoded.pc));+ }+ Instruction::SetLexicalBinding { cache: coordinate, .. } => stores.push(coordinate),+ _ => {}+ }+ Some(decoded.next_pc())+ });+ let Some(next_pc) = next_pc else {return CapturedBindingAccesses::default();};- pc = decoded.next_pc();- let changes_environment = matches!(- decoded.instruction.opcode(),- OpCode::SetLexicalEnvironment- | OpCode::CreateLexicalEnvironment- | OpCode::CreateVariableEnvironment- | OpCode::EnterObjectEnvironment- | OpCode::NewClass- | OpCode::CallDirectEval- | OpCode::CallDirectEvalWithArgumentArray- | OpCode::Debugger- );- if changes_environment {- return CapturedBindingAccesses::default();- }- match decoded.instruction {- Instruction::GetBinding { cache: coordinate, .. }- | Instruction::GetInitializedBinding { cache: coordinate, .. }- | Instruction::GetCalleeAndThisFromEnvironment { cache: coordinate, .. } => {- loads.push((coordinate, decoded.pc));- }- Instruction::SetLexicalBinding { cache: coordinate, .. } => stores.push(coordinate),- _ => {}- }+ pc = next_pc;}CapturedBindingAccesses {loads: loads.into_boxed_slice(),