Truly independent web browser
LibJS: Shrink the struct of compiled code from 192 to 136 bytes
Andreas Klingd0547f83bdde
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rsindex 028ebe8654e..bd2a82d3739 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs@@ -17,7 +17,7 @@ pub struct AssembledBytecode {pub bytecode: BlockSlice<u8>,pub strict_ranges: Box<[StrictRange]>,pub source_map: BlockSlice<u8>,- pub exception_handlers: BlockSlice<ExceptionHandler>,+ pub exception_handlers: Box<[ExceptionHandler]>,pub number_of_registers: u32,/// One past the highest `Operand::argument` index referenced by any/// instruction, or 0 if the bytecode never reads an argument.diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rsindex 19ad9087295..7a9384deabb 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs@@ -419,7 +419,6 @@ impl NameTables {/// How much of a block the tables that stay with the code take.pub(super) fn room_for_tables(&self) -> usize {SliceBlock::room_for::<Utf16FlyString>(self.identifiers.entries.len())- + SliceBlock::room_for::<Utf16FlyString>(self.strings.entries.len())}/// How much of a block the table that only linking reads takes.@@ -427,8 +426,8 @@ impl NameTables {SliceBlock::room_for::<Utf16FlyString>(self.property_keys.entries.len())}- /// Hands out the tables, as an executable keeps them: identifiers and strings from `block`, and property keys from- /// `link_block`.+ /// Hands out the tables, as an executable keeps them: identifiers from `block`, property keys from `link_block`, and+ /// strings, which few executables have, on their own.pub(super) fn take_tables(&mut self,tree: &SyntaxTree,@@ -437,7 +436,7 @@ impl NameTables {) -> (BlockSlice<Utf16FlyString>,BlockSlice<Utf16FlyString>,- BlockSlice<Utf16FlyString>,+ Box<[Utf16FlyString]>,) {let script_names = &mut self.script_names;let mut fly_string_of = |entry: &TableEntry| match entry {@@ -447,7 +446,7 @@ impl NameTables {(block.slice(self.identifiers.entries.iter().map(&mut fly_string_of)),link_block.slice(self.property_keys.entries.iter().map(&mut fly_string_of)),- block.slice(self.strings.entries.iter().map(&mut fly_string_of)),+ self.strings.entries.iter().map(&mut fly_string_of).collect(),)}}diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rsindex 085105ffbed..002849b1a56 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs@@ -2006,28 +2006,29 @@ impl Generator<'_> {} else {Box::default()};- let executable = ExecutableData {- bytecode: assembled.bytecode,- exception_handlers: assembled.exception_handlers,- strict_ranges: assembled.strict_ranges,- source_map: assembled.source_map,- number_of_registers: assembled.number_of_registers,- number_of_arguments: assembled.number_of_arguments,- is_strict: self.strict,- cache_counts: self.cache_counts(),+ let class_blueprints = link_block.slice(std::mem::take(&mut self.class_blueprints).into_iter());+ let executable = ExecutableData::new(+ assembled.bytecode,+ assembled.source_map,+ assembled.exception_handlers,+ assembled.strict_ranges,+ assembled.number_of_registers,+ assembled.number_of_arguments,+ self.strict,+ self.cache_counts(),identifier_table,string_table,variable_names,local_variable_metadata,- length_identifier: self.length_identifier,+ self.length_identifier,property_key_table,constants,shared_function_data,- class_blueprints: link_block.slice(std::mem::take(&mut self.class_blueprints).into_iter()),- position_source: script.positions.clone(),- tables: block.finish(),- link_tables: link_block.finish(),- };+ class_blueprints,+ script.positions.clone(),+ block.finish(),+ link_block.finish(),+ );let this_from_environment = this_comes_from_environment(flags);PrecompiledFunction {executable: Arc::new(executable),diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rsindex d82c49f9574..25e5c63eac1 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs@@ -4216,7 +4216,6 @@ impl Generator<'_> {SliceBlock::builder(SliceBlock::room_for::<u8>(head.bytes.len() + segment.bytes.len())+ SliceBlock::room_for::<u8>(source_map_bytes.len())- + SliceBlock::room_for::<ExceptionHandler>(exception_handlers.len())+ other_tables_size,)};@@ -4254,7 +4253,7 @@ impl Generator<'_> {bytecode,strict_ranges,source_map,- exception_handlers: block.slice(exception_handlers.into_iter()),+ exception_handlers: exception_handlers.into_boxed_slice(),number_of_registers: frame.register_count,number_of_arguments: stream.number_of_arguments,};diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex af0a2c48e00..2aaab16bd80 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -1373,7 +1373,7 @@ impl Executable {/// The string that `index`, a field of an instruction of this executable, refers to.pub fn get_string(&self, index: &StringTableIndex) -> &Utf16FlyString {- &self.code.string_table[index.index_in(self.bytecode())]+ &self.code.string_table()[index.index_in(self.bytecode())]}/// Forgets the cells the inline caches remember that died in this collection.@@ -1413,7 +1413,7 @@ impl Executable {shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,_defer_gc: &DeferGc<'_>,) -> Self {- let cache_counts = &code.cache_counts;+ let cache_counts = &code.cache_counts();let property_lookup_caches = tables.slice((0..cache_counts.property_lookup).map(|index| {if index == UNCACHED_SITE {PropertyLookupCache::new_uncacheable()@@ -1465,7 +1465,7 @@ impl Executable {number_of_registers: code.number_of_registers,number_of_arguments: code.number_of_arguments,length_identifier: code- .length_identifier+ .length_identifier().map(|index| core::num::NonZeroU32::new(index.0 + 1).expect("the index plus one is not zero")),interpreter_tier: Cell::new(InterpreterTier::Plain),has_dumped_feedback: Cell::new(false),@@ -1537,7 +1537,7 @@ impl Executable {/// The bytes of the tables that an executable of `code` has from the start.fn size_of_tables(code: &ExecutableData) -> usize {- let cache_counts = &code.cache_counts;+ let cache_counts = &code.cache_counts();SliceBlock::room_for::<Gc<SharedFunctionInstanceData>>(code.shared_function_data.len())+ SliceBlock::room_for::<PropertyKey>(code.property_key_table.len())+ SliceBlock::room_for::<Value>(code.constants.len())@@ -1566,10 +1566,10 @@ impl Executable {None => tables.slice(data.property_key_table.iter().cloned().map(PropertyKey::from)),};let constants = tables.slice(data.constants.iter().map(|constant| constant_value(vm, constant)));- let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = (0..data.cache_counts.template_object)+ let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = (0..data.cache_counts().template_object).map(|_| TemplateObjectCache::create(vm)).collect();- let object_property_iterator_caches = data.cache_counts.object_property_iterator;+ let object_property_iterator_caches = data.cache_counts().object_property_iterator;let mut executable =Self::new_with_code(data, tables, constants, property_keys, shared_function_data, defer_gc);@@ -1716,11 +1716,11 @@ impl Executable {}pub fn string_table(&self) -> &[Utf16FlyString] {- &self.code.string_table+ self.code.string_table()}pub fn exception_handlers(&self) -> &[ExceptionHandler] {- &self.code.exception_handlers+ self.code.exception_handlers()}pub fn source_positions(&self) -> impl Iterator<Item = SourceMapEntry> + '_ {@@ -1766,7 +1766,7 @@ impl Executable {if self.is_strict_mode {return true;}- let ranges = &self.code.strict_ranges;+ let ranges = self.code.strict_ranges();let index = ranges.partition_point(|range| range.end_offset <= pc);ranges.get(index).is_some_and(|range| range.start_offset <= pc)}diff --git a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs b/Libraries/LibJS/Rust/src/bytecode/executable_data.rsindex 091545ffac2..169e8a741bb 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs@@ -6,6 +6,7 @@//! Compiled bytecode together with everything needed to run it, as owned Rust values.+use core::num::NonZeroU32;use std::sync::Arc;use ak::Utf16String;@@ -201,23 +202,20 @@ impl StrictRange {/// [`Executable`]: super::executable::Executablepub struct ExecutableData {pub bytecode: BlockSlice<u8>,- /// Sorted by start offset, and not overlapping.- pub exception_handlers: BlockSlice<ExceptionHandler>,/// Sorted by bytecode offset: where in the source code the instructions from each offset on came from.pub source_map: BlockSlice<u8>,pub number_of_registers: u32,pub number_of_arguments: u32,pub is_strict: bool,- /// Sorted by start offset. Where a class body makes the code strict, if the function is not.- pub strict_ranges: Box<[StrictRange]>,- pub cache_counts: ExecutableCacheCounts,+ cache_slot_counts: CacheSlotCounts,+ /// The index of the length in the property key table, plus one.+ length_identifier: Option<NonZeroU32>,pub identifier_table: BlockSlice<ak::Utf16FlyString>,- pub string_table: BlockSlice<ak::Utf16FlyString>,/// The names of the local variables, then the names of the arguments.pub variable_names: BlockSlice<ak::Utf16FlyString>,/// One for each of the local variables.pub local_variable_metadata: BlockSlice<LocalVariableMetadata>,- pub length_identifier: Option<PropertyKeyTableIndex>,+ rare_data: Option<Box<RareExecutableData>>,/// What linking reads, and nothing after it (see [`ExecutableData::release_link_inputs()`]).pub property_key_table: BlockSlice<ak::Utf16FlyString>,pub constants: BlockSlice<ConstantValue>,@@ -231,6 +229,55 @@ pub struct ExecutableData {pub link_tables: SliceBlock,}+// NB: Every compiled function has these bytes.+const _: () = assert!(size_of::<ExecutableData>() == 136);++/// The parts of code that few codes have.+#[derive(Default)]+struct RareExecutableData {+ /// Sorted by start offset, and not overlapping.+ exception_handlers: Box<[ExceptionHandler]>,+ /// Sorted by start offset. Where a class body makes the code strict, if the function is not.+ strict_ranges: Box<[StrictRange]>,+ string_table: Box<[ak::Utf16FlyString]>,+ template_object_caches: u32,+ object_property_iterator_caches: u32,+ environment_shape_caches: u32,+}++/// The counts of the kinds of cache and feedback slots whose sites past the last slot index share it, so that each is+/// at most 65536, kept in two bytes as `u16::MAX`. Code with exactly 65535 slots of a kind gets one more, which no+/// site uses.+#[derive(Clone, Copy)]+struct CacheSlotCounts {+ property_lookup: u16,+ global_variable: u16,+ environment_coordinate: u16,+ object_shape: u16,+ arith_feedback: u16,+ value_feedback: u16,+ call_feedback: u16,+ keyed_feedback: u16,+}++impl CacheSlotCounts {+ fn compact(count: u32) -> u16 {+ assert!(+ count <= u32::from(u16::MAX) + 1,+ "sites past the last slot index share it"+ );+ u16::try_from(count).unwrap_or(u16::MAX)+ }++ fn expand(count: u16) -> u32 {+ if count == u16::MAX {+ u32::from(u16::MAX) + 1+ } else {+ u32::from(count)+ }+ }+}+fn constant_memory_size(constant: &ConstantValue) -> usize {match constant {ConstantValue::String(string) => utf16_string_memory_size(string),@@ -245,6 +292,119 @@ fn constant_memory_size(constant: &ConstantValue) -> usize {unsafe impl crate::gc::lint_markers::HoldsNoCells for ExecutableData {}impl ExecutableData {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ bytecode: BlockSlice<u8>,+ source_map: BlockSlice<u8>,+ exception_handlers: Box<[ExceptionHandler]>,+ strict_ranges: Box<[StrictRange]>,+ number_of_registers: u32,+ number_of_arguments: u32,+ is_strict: bool,+ cache_counts: ExecutableCacheCounts,+ identifier_table: BlockSlice<ak::Utf16FlyString>,+ string_table: Box<[ak::Utf16FlyString]>,+ variable_names: BlockSlice<ak::Utf16FlyString>,+ local_variable_metadata: BlockSlice<LocalVariableMetadata>,+ length_identifier: Option<PropertyKeyTableIndex>,+ property_key_table: BlockSlice<ak::Utf16FlyString>,+ constants: BlockSlice<ConstantValue>,+ shared_function_data: BlockSlice<PendingSharedFunctionData>,+ class_blueprints: BlockSlice<PendingClassBlueprint>,+ position_source: Arc<crate::parser::SourcePositions>,+ tables: SliceBlock,+ link_tables: SliceBlock,+ ) -> Self {+ let rare_data = RareExecutableData {+ exception_handlers,+ strict_ranges,+ string_table,+ template_object_caches: cache_counts.template_object,+ object_property_iterator_caches: cache_counts.object_property_iterator,+ environment_shape_caches: cache_counts.environment_shape,+ };+ let has_rare_data = !rare_data.exception_handlers.is_empty()+ || !rare_data.strict_ranges.is_empty()+ || !rare_data.string_table.is_empty()+ || rare_data.template_object_caches != 0+ || rare_data.object_property_iterator_caches != 0+ || rare_data.environment_shape_caches != 0;+ Self {+ bytecode,+ source_map,+ number_of_registers,+ number_of_arguments,+ is_strict,+ cache_slot_counts: CacheSlotCounts {+ property_lookup: CacheSlotCounts::compact(cache_counts.property_lookup),+ global_variable: CacheSlotCounts::compact(cache_counts.global_variable),+ environment_coordinate: CacheSlotCounts::compact(cache_counts.environment_coordinate),+ object_shape: CacheSlotCounts::compact(cache_counts.object_shape),+ arith_feedback: CacheSlotCounts::compact(cache_counts.arith_feedback),+ value_feedback: CacheSlotCounts::compact(cache_counts.value_feedback),+ call_feedback: CacheSlotCounts::compact(cache_counts.call_feedback),+ keyed_feedback: CacheSlotCounts::compact(cache_counts.keyed_feedback),+ },+ length_identifier: length_identifier+ .map(|index| NonZeroU32::new(index.0 + 1).expect("the index plus one is not zero")),+ identifier_table,+ variable_names,+ local_variable_metadata,+ rare_data: has_rare_data.then(|| Box::new(rare_data)),+ property_key_table,+ constants,+ shared_function_data,+ class_blueprints,+ position_source,+ tables,+ link_tables,+ }+ }++ /// How many inline cache and feedback slots of each kind the bytecode indexes into.+ pub fn cache_counts(&self) -> ExecutableCacheCounts {+ let counts = &self.cache_slot_counts;+ let rare_data = self.rare_data.as_deref();+ ExecutableCacheCounts {+ property_lookup: CacheSlotCounts::expand(counts.property_lookup),+ global_variable: CacheSlotCounts::expand(counts.global_variable),+ environment_coordinate: CacheSlotCounts::expand(counts.environment_coordinate),+ template_object: rare_data.map_or(0, |rare_data| rare_data.template_object_caches),+ object_shape: CacheSlotCounts::expand(counts.object_shape),+ object_property_iterator: rare_data.map_or(0, |rare_data| rare_data.object_property_iterator_caches),+ environment_shape: rare_data.map_or(0, |rare_data| rare_data.environment_shape_caches),+ arith_feedback: CacheSlotCounts::expand(counts.arith_feedback),+ value_feedback: CacheSlotCounts::expand(counts.value_feedback),+ call_feedback: CacheSlotCounts::expand(counts.call_feedback),+ keyed_feedback: CacheSlotCounts::expand(counts.keyed_feedback),+ }+ }++ pub fn length_identifier(&self) -> Option<PropertyKeyTableIndex> {+ self.length_identifier+ .map(|index| PropertyKeyTableIndex(index.get() - 1))+ }++ /// Sorted by start offset, and not overlapping.+ pub fn exception_handlers(&self) -> &[ExceptionHandler] {+ self.rare_data+ .as_deref()+ .map_or(&[], |rare_data| &rare_data.exception_handlers)+ }++ /// Sorted by start offset. Where a class body makes the code strict, if the function is not.+ pub fn strict_ranges(&self) -> &[StrictRange] {+ self.rare_data+ .as_deref()+ .map_or(&[], |rare_data| &rare_data.strict_ranges)+ }++ pub fn string_table(&self) -> &[ak::Utf16FlyString] {+ self.rare_data+ .as_deref()+ .map_or(&[], |rare_data| &rare_data.string_table)+ }+/// The entries of the source map, with the lines and columns that they stand for, which get worked out when something/// asks.pub fn source_positions(&self) -> impl Iterator<Item = crate::bytecode::source_map::SourceMapEntry> + '_ {@@ -271,11 +431,14 @@ impl ExecutableData {pub fn memory_size(&self) -> usize {size_of::<Self>()+ size_of_val(&*self.bytecode)- + size_of_val(&*self.exception_handlers)+ + self.rare_data.as_ref().map_or(0, |rare_data| {+ size_of::<RareExecutableData>()+ + size_of_val(&*rare_data.exception_handlers)+ + size_of_val(&*rare_data.strict_ranges)+ + size_of_val(&*rare_data.string_table)+ })+ size_of_val(&*self.source_map)- + size_of_val(&*self.strict_ranges)+ size_of_val(&*self.identifier_table)- + size_of_val(&*self.string_table)+ size_of_val(&*self.variable_names)+ size_of_val(&*self.local_variable_metadata)+ size_of_val(&*self.property_key_table)