Truly independent web browser
LibJS: Shrink Array and EcmascriptFunctionObject to 32 bytes
Andreas Klingc7e6dd659486
diff --git a/Libraries/LibJS/Flap/tests/interpreter-layout.conf b/Libraries/LibJS/Flap/tests/interpreter-layout.confindex 2b35cf5f6d1..525cbf757b1 100644--- a/Libraries/LibJS/Flap/tests/interpreter-layout.conf+++ b/Libraries/LibJS/Flap/tests/interpreter-layout.conf@@ -20,8 +20,8 @@ field Accessor.getter FunctionObject ACCESSOR_GETTER nullable compressed# Object flagsconst OBJECT_FLAGS = 12field Object.flags u16 OBJECT_FLAGS nullable scalar-const OBJECT_FUNCTION_BITS = 15-field Object.function_bits u8 OBJECT_FUNCTION_BITS nullable scalar+const OBJECT_CLASS_BITS = 15+field Object.class_bits u8 OBJECT_CLASS_BITS nullable scalarconst OBJECT_FLAG_HAS_MAGICAL_LENGTH = 4const OBJECT_FLAG_MAY_INTERFERE = 16const OBJECT_FLAG_IS_TYPED_ARRAY = 8diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flapindex 52ace514f12..9854bb88273 100644--- a/Libraries/LibJS/Interpreter/interpreter.flap+++ b/Libraries/LibJS/Interpreter/interpreter.flap@@ -3908,8 +3908,8 @@ handler Call(frame.lexical_environment = lexical_environment;frame.variable_environment = lexical_environment;frame.private_environment = null;- let function_bits = function.function_bits;- if function_bits has ECMASCRIPT_FUNCTION_FLAG_HAS_RARE_DATA {+ let class_bits = function.class_bits;+ if class_bits has ECMASCRIPT_FUNCTION_FLAG_HAS_RARE_DATA {frame.private_environment = ecmascript_function.private_environment;}frame.this_value = receiver;diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rsindex 02f4914adf5..a4484eb2bf7 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs@@ -56,8 +56,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.unbox_object_or_branch(array, receiver, exit);self.branch_unless_plain_array(array, prototype, exit);self.masm- .load8(scratch, &Address::new(array, layout.array_length_writable as i32));- self.masm.branch_test32(Condition::Zero, scratch, 0xFF, exit);+ .load8(scratch, &Address::new(array, layout.array_flags as i32));+ self.masm.branch_test32(+ Condition::NonZero,+ scratch,+ u32::from(layout.array_flag_length_not_writable),+ exit,+ );// Packed indexed storage, or none yet.let known_kind = self.masm.new_label();self.masm@@ -94,8 +99,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.branch32_imm(Condition::NotEqual, scratch, i32::from(flags), fail);self.masm- .load8(scratch, &Address::new(array, layout.array_is_proxy_target as i32));- self.masm.branch_test32(Condition::NonZero, scratch, 0xFF, fail);+ .load8(scratch, &Address::new(array, layout.array_flags as i32));+ self.masm.branch_test32(+ Condition::NonZero,+ scratch,+ u32::from(layout.array_flag_is_proxy_target),+ fail,+ );// NB: %Object.prototype% is an immutable prototype exotic object,// so the chain ends there.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 0d69a839343..fefeace6d6f 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -2163,7 +2163,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let offsets = self.runtime.offsets;let done = self.masm.new_label();self.masm- .load8(dst, &Address::new(function, offsets.object_function_bits as i32));+ .load8(dst, &Address::new(function, offsets.object_class_bits as i32));self.masm.and32_imm(dst, dst, offsets.ecmascript_function_flag_has_rare_data);self.masm.branch_test32(Condition::Zero, dst, u32::MAX, done);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex 0d6663572a7..0b25f40b29a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -72,7 +72,7 @@ fn offsets() -> RuntimeOffsets {ecmascript_function_environment: 0,ecmascript_function_private_environment: 8,shared_function_script_or_module: 24,- object_function_bits: 40,+ object_class_bits: 40,ecmascript_function_flag_has_rare_data: 8,vm_execution_generation: 8 * VM_EXECUTION_GENERATION_WORD as u32,}@@ -2503,7 +2503,7 @@ mod property_access {/// `Array.prototype.push` against fake arrays: `[shape, flags, named/// property storage, elements, storage kind (byte 0) and size (bytes- /// 4-7), length writable (byte 0) and proxy target (byte 1)]`, with+ /// 4-7), array flags (length not writable: 1, proxy target: 2)]`, with/// shapes `[dictionary generation, compressed prototype]`.mod array_push {use super::*;@@ -2532,7 +2532,7 @@ mod property_access {0,elements.as_ptr() as u64,PACKED | u64::from(size) << 32,- 1,+ 0,]))}@@ -2617,8 +2617,9 @@ mod property_access {object_flag_is_extensible: EXTENSIBLE as u16,object_flag_has_magical_length: MAGICAL_LENGTH as u16,object_flag_may_interfere: MAY_INTERFERE,- array_length_writable: 40,- array_is_proxy_target: 41,+ array_flags: 40,+ array_flag_length_not_writable: 1,+ array_flag_is_proxy_target: 2,shape_prototype: 8,..runtime.layout};@@ -2681,8 +2682,8 @@ mod property_access {&|array| array.0[1] = EXTENSIBLE,&|array| array.0[1] |= u64::from(MAY_INTERFERE),&|array| array.0[4] = 2 | 1 << 32,- &|array| array.0[5] = 0,- &|array| array.0[5] = 1 | 1 << 8,+ &|array| array.0[5] = 1,+ &|array| array.0[5] = 2,] {assert_eq!(exits(&world, change), [ExitKind::SlowPath]);}@@ -3802,7 +3803,7 @@ mod direct_calls {fake_heap::use_in(runtime);runtime.offsets.ecmascript_function_environment = 24;runtime.offsets.ecmascript_function_private_environment = 32;- runtime.offsets.object_function_bits = 15;+ runtime.offsets.object_class_bits = 15;runtime.dynamic_calls = crate::snapshot::DynamicCallLayout {object_flag_is_ecmascript_function: ECMASCRIPT_FUNCTION_FLAG,ecmascript_function_shared_data: 16,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 4ef3303ce77..cc4a185a9e8 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1194,8 +1194,9 @@ fn fake_object_layout() -> RuntimeLayout {string_object_class: STRING_OBJECT_CLASS,string_prototype_class: STRING_PROTOTYPE_CLASS,object_flag_may_interfere: FLAG_MAY_INTERFERE,- array_length_writable: 0,- array_is_proxy_target: 0,+ array_flags: 0,+ array_flag_length_not_writable: 1,+ array_flag_is_proxy_target: 2,shape_prototype: 0,object_flag_is_typed_array: FLAG_IS_TYPED_ARRAY,object_flag_is_htmldda: HTMLDDA_FLAG,diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 48a93ae8236..294eb8a2416 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -1545,9 +1545,9 @@ pub struct RuntimeOffsets {pub ecmascript_function_private_environment: u32,/// `SharedFunctionInstanceData::script_or_module` (8 bytes, as in `ExecutionContext`).pub shared_function_script_or_module: u32,- /// `Object::function_bits` (u8).- pub object_function_bits: u32,- /// The bit of `Object::function_bits` of an ECMAScript function that has+ /// `Object::class_bits` (u8).+ pub object_class_bits: u32,+ /// The bit of `Object::class_bits` of an ECMAScript function that has/// a private environment field.pub ecmascript_function_flag_has_rare_data: u32,/// `VmHead::execution_generation` (u32).@@ -1673,9 +1673,11 @@ pub struct RuntimeLayout {pub string_prototype_class: u64,/// `Object::Flag::MayInterfereWithIndexedPropertyAccess`.pub object_flag_may_interfere: u16,- /// `Array::length_writable` and `Array::is_proxy_target` (bools).- pub array_length_writable: u32,- pub array_is_proxy_target: u32,+ /// Where an array keeps its flags (u8), and the bits of them that say that its length is not writable and that it+ /// is the target of a proxy.+ pub array_flags: u32,+ pub array_flag_length_not_writable: u8,+ pub array_flag_is_proxy_target: u8,/// `Shape::prototype`.pub shape_prototype: u32,/// `Object::Flag::IsTypedArray`.@@ -1748,7 +1750,7 @@ pub struct RuntimeLayout {/// The address of the VM's array of the strings of the 128 ASCII/// characters (cell pointers), or 0 for code without one.pub single_ascii_character_strings: u64,- /// `Object::function_bits` (u8): the builtin a function is plus one, if+ /// `Object::class_bits` (u8): the builtin a function is plus one, if/// it is one.pub function_object_builtin: u32,/// `Builtin` values.diff --git a/Libraries/LibJS/Rust/generate/layout_table.rs b/Libraries/LibJS/Rust/generate/layout_table.rsindex 98d28a24caa..ec8682883a4 100644--- a/Libraries/LibJS/Rust/generate/layout_table.rs+++ b/Libraries/LibJS/Rust/generate/layout_table.rs@@ -186,7 +186,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {w.section("Object flags");field!(w, "OBJECT_FLAGS", "Object.flags", "u16", Object, flags, 2, "nullable", "scalar");- field!(w, "OBJECT_FUNCTION_BITS", "Object.function_bits", "u8", Object, function_bits, 1, "nullable", "scalar");+ field!(w, "OBJECT_CLASS_BITS", "Object.class_bits", "u8", Object, class_bits, 1, "nullable", "scalar");w.constant("OBJECT_FLAG_HAS_MAGICAL_LENGTH", object_flag::HAS_MAGICAL_LENGTH_PROPERTY);w.constant("OBJECT_FLAG_MAY_INTERFERE", object_flag::MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS);w.constant("OBJECT_FLAG_IS_TYPED_ARRAY", object_flag::IS_TYPED_ARRAY);@@ -489,8 +489,10 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {field!(w, "DIRECT_GETTER_FUNCTION_IMPLEMENTATION_VALUE_IS_COMPRESSED", "DirectGetterFunction.implementation_value_is_compressed", "u32", DirectGetterFunction, implementation_value_is_compressed, 4, "nullable", "scalar");w.section("ECMAScriptFunctionObject layout");- field!(w, "ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA", "ECMAScriptFunctionObject.shared_data", "SharedFunctionInstanceData", EcmascriptFunctionObject, shared_data, 4, "nonnull", "compressed");- field!(w, "ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT", "ECMAScriptFunctionObject.environment", "Environment", EcmascriptFunctionObject, environment, 4, "nullable", "compressed");+ w.constant("ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA", ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET);+ w.field("ECMAScriptFunctionObject.shared_data", "SharedFunctionInstanceData", "ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA", "nonnull", "compressed");+ w.constant("ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT", ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT_OFFSET);+ w.field("ECMAScriptFunctionObject.environment", "Environment", "ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT", "nullable", "compressed");field!(w, "ECMASCRIPT_FUNCTION_OBJECT_PRIVATE_ENVIRONMENT", "ECMAScriptFunctionObject.private_environment", "PrivateEnvironment", EcmascriptFunctionObjectWithRareData, private_environment, 4, "nullable", "compressed");w.constant("ECMASCRIPT_FUNCTION_FLAG_HAS_RARE_DATA", ecmascript_function_flags::HAS_RARE_DATA);diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 1ab1a3231e8..ff8768de042 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -75,7 +75,7 @@ use crate::runtime::module::{Module, finish_loading_imported_module};use crate::runtime::module_loading::{ImportedModulePayload, ImportedModuleReferrer};use crate::runtime::module_request::ModuleRequest;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;-use crate::runtime::object::IntrinsicAccessor;+use crate::runtime::object::{IndexedDictionary, IntrinsicAccessor};use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::promise::{Promise, PromiseState, RejectionOperation};use crate::runtime::property_key::PropertyKey;@@ -520,6 +520,11 @@ pub struct Vm {native_function_count: Cell<u32>,/// The index of each function in the native function table, by its address and type.native_function_indices: RefCell<HashMap<(usize, u32), u32>>,+ /// The indexed property dictionaries of the ECMAScript function objects that have one, by address. Those objects+ /// have no pointer to their indexed elements (see `EcmascriptFunctionFields`), and hardly any of them has indexed+ /// properties. The objects trace and free their dictionaries.+ pub(crate) function_indexed_dictionaries:+ RefCell<HashMap<usize, *mut IndexedDictionary, foldhash::fast::RandomState>>,roots: RootSet,pub names: CommonPropertyNames,@@ -679,6 +684,7 @@ impl Vm {native_function_table: RefCell::new(native_function_table),native_function_count: Cell::new(0),native_function_indices: RefCell::new(HashMap::new()),+ function_indexed_dictionaries: RefCell::default(),roots: RootSet::default(),names: CommonPropertyNames::new(),no_parameter_names: Rc::from([]),diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex d3461efbaa5..a8eb762f5d2 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -42,13 +42,14 @@ use crate::layout::environment::{use crate::layout::executable::ExecutableHead;use crate::layout::execution_context::ExecutionContext;use crate::layout::function_object::{- CallEnvironmentTemplate, EcmascriptFunctionObject, EcmascriptFunctionObjectWithRareData,- FUNCTION_ENVIRONMENT_WORDS, NATIVE_FUNCTION_TABLE_INDEX_MASK, NativeFunction, NativeFunctionTableEntry,- SharedFunctionInstanceData, asm_call_metadata, ecmascript_function_flags,+ CallEnvironmentTemplate, ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT_OFFSET,+ ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET, EcmascriptFunctionObjectWithRareData, FUNCTION_ENVIRONMENT_WORDS,+ NATIVE_FUNCTION_TABLE_INDEX_MASK, NativeFunction, NativeFunctionTableEntry, SharedFunctionInstanceData,+ asm_call_metadata, ecmascript_function_flags,};use crate::layout::object::{INDEXED_ELEMENTS_HEADER_SIZE, IndexedStorageKind, Object, TYPED_ARRAY_CACHED_DATA_OFFSET_INVALID, TypedArrayBase,- object_flag, typed_array_kind,+ array_flags, object_flag, typed_array_kind,};use crate::layout::primitive_string::{DEFERRED_KIND_MASK, DeferredKind, INTERNED_FLAG, InlineString, PrimitiveString};use crate::layout::property_lookup_cache::{@@ -60,7 +61,6 @@ use crate::layout::realm::Realm;use crate::layout::shape::{Shape, WatchpointSet};use crate::layout::value::Value;use crate::layout::vm::VmHead;-use crate::runtime::array::{ARRAY_IS_PROXY_TARGET_OFFSET, ARRAY_LENGTH_WRITABLE_OFFSET};use crate::runtime::array_iterator::ArrayIterator;use crate::runtime::function_environment::{FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET, FUNCTION_ENVIRONMENT_THIS_VALUE_OFFSET,@@ -163,13 +163,13 @@ fn runtime_offsets() -> RuntimeOffsets {execution_context_argument_count: offset(offset_of!(ExecutionContext, argument_count)),execution_context_returns_to_native_caller: offset(offset_of!(ExecutionContext, returns_to_native_caller)),execution_context_runs_jit_code: offset(offset_of!(ExecutionContext, runs_jit_code)),- ecmascript_function_environment: offset(offset_of!(EcmascriptFunctionObject, environment)),+ ecmascript_function_environment: offset(ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT_OFFSET),ecmascript_function_private_environment: offset(offset_of!(EcmascriptFunctionObjectWithRareData,private_environment)),shared_function_script_or_module: offset(offset_of!(SharedFunctionInstanceData, script_or_module)),- object_function_bits: offset(offset_of!(Object, function_bits)),+ object_class_bits: offset(offset_of!(Object, class_bits)),ecmascript_function_flag_has_rare_data: ecmascript_function_flags::HAS_RARE_DATA.into(),vm_execution_generation: offset(offset_of!(VmHead, execution_generation)),}@@ -191,8 +191,9 @@ fn runtime_layout() -> RuntimeLayout {string_object_class: core::ptr::from_ref(StringObject::CLASS) as u64,string_prototype_class: core::ptr::from_ref(StringPrototype::CLASS) as u64,object_flag_may_interfere: object_flag::MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS,- array_length_writable: offset(ARRAY_LENGTH_WRITABLE_OFFSET),- array_is_proxy_target: offset(ARRAY_IS_PROXY_TARGET_OFFSET),+ array_flags: offset(offset_of!(Object, class_bits)),+ array_flag_length_not_writable: array_flags::LENGTH_NOT_WRITABLE,+ array_flag_is_proxy_target: array_flags::IS_PROXY_TARGET,shape_prototype: offset(offset_of!(Shape, prototype)),object_flag_is_typed_array: object_flag::IS_TYPED_ARRAY,object_flag_is_htmldda: object_flag::IS_HTMLDDA,@@ -231,7 +232,7 @@ fn runtime_layout() -> RuntimeLayout {utf16_string_data_storage: offset(size_of::<ak::Utf16StringDataHeader>()),// NB: Filled in by runtime_info().single_ascii_character_strings: 0,- function_object_builtin: offset(offset_of!(Object, function_bits)),+ function_object_builtin: offset(offset_of!(Object, class_bits)),builtin_string_prototype_char_code_at: Builtin::StringPrototypeCharCodeAt as u8,builtin_string_prototype_char_at: Builtin::StringPrototypeCharAt as u8,builtin_math_abs: Builtin::MathAbs as u8,@@ -571,7 +572,7 @@ fn dynamic_call_layout(vm: &Vm) -> DynamicCallLayout {.expect("the VM has a JIT entry table while the JIT is on");DynamicCallLayout {object_flag_is_ecmascript_function: object_flag::IS_ECMASCRIPT_FUNCTION_OBJECT,- ecmascript_function_shared_data: offset(offset_of!(EcmascriptFunctionObject, shared_data)),+ ecmascript_function_shared_data: offset(ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET),shared_data_executable: offset(offset_of!(SharedFunctionInstanceData, executable)),shared_data_asm_call_metadata: offset(offset_of!(SharedFunctionInstanceData, asm_call_metadata)),executable_jit_entry_slot: offset(offset_of!(ExecutableHead, jit_entry_slot)),diff --git a/Libraries/LibJS/Rust/src/layout/function_object.rs b/Libraries/LibJS/Rust/src/layout/function_object.rsindex 35f0b187300..5d55fca7601 100644--- a/Libraries/LibJS/Rust/src/layout/function_object.rs+++ b/Libraries/LibJS/Rust/src/layout/function_object.rs@@ -85,10 +85,35 @@ pub struct NativeFunctionTableEntry {#[repr(C)]pub struct EcmascriptFunctionObject {pub base: FunctionObject,+}++const _: () = assert!(size_of::<EcmascriptFunctionObject>() == 32);++/// What an ECMAScript function object keeps where other objects have the pointer to their indexed elements. Hardly any+/// function has indexed properties, and those it has stay in a dictionary outside of the cell (see+/// `IndexedStorageKind::Dictionary`), so the indexed storage kind of a function never lets anything read the pointer.+#[repr(C)]+pub struct EcmascriptFunctionFields {pub shared_data: NullableMember<SharedFunctionInstanceData>,pub environment: NullableMember<Environment>,}+const _: () = assert!(size_of::<EcmascriptFunctionFields>() == size_of::<*mut Value>());++pub const ECMASCRIPT_FUNCTION_OBJECT_SHARED_DATA_OFFSET: usize =+ core::mem::offset_of!(Object, indexed_elements) + core::mem::offset_of!(EcmascriptFunctionFields, shared_data);+pub const ECMASCRIPT_FUNCTION_OBJECT_ENVIRONMENT_OFFSET: usize =+ core::mem::offset_of!(Object, indexed_elements) + core::mem::offset_of!(EcmascriptFunctionFields, environment);++impl EcmascriptFunctionObject {+ #[inline(always)]+ pub fn fields(&self) -> &EcmascriptFunctionFields {+ // SAFETY: The fields are as large as the pointer they take the place of, and no more aligned. They are cells,+ // like the pointer, which this kind of object never uses as one.+ unsafe { &*core::ptr::from_ref(&self.base.base.indexed_elements).cast() }+ }+}+/// An ECMAScript function object that needs more than most: a method or a class constructor, or a function of code/// with private names (see ecmascript_function_flags::HAS_RARE_DATA).#[repr(C)]@@ -99,7 +124,7 @@ pub struct EcmascriptFunctionObjectWithRareData {pub storage: EcmascriptFunctionObjectStorage,}-/// The bits of FunctionObject::flags of an ECMAScript function object.+/// The bits of Object::class_bits of an ECMAScript function object.pub mod ecmascript_function_flags {/// Set on all ECMAScript function objects, which keeps their flags from reading as a builtin.pub const IS_ECMASCRIPT_FUNCTION: u8 = 1 << 7;diff --git a/Libraries/LibJS/Rust/src/layout/object.rs b/Libraries/LibJS/Rust/src/layout/object.rsindex 1e7254f20a9..77e7187153c 100644--- a/Libraries/LibJS/Rust/src/layout/object.rs+++ b/Libraries/LibJS/Rust/src/layout/object.rs@@ -43,6 +43,12 @@ pub enum IndexedStorageKind {Dictionary,}+/// The bits of Object::class_bits of an array.+pub mod array_flags {+ pub const LENGTH_NOT_WRITABLE: u8 = 1 << 0;+ pub const IS_PROXY_TARGET: u8 = 1 << 1;+}+/// Packed and holey indexed storage keeps its capacity in a header right in front of the first element.pub const INDEXED_ELEMENTS_HEADER_SIZE: usize = 8;@@ -60,9 +66,10 @@ pub struct Object {/// How many named property values the inline storage holds. It comes right after the object, in the cells of the/// classes that make room for it.pub inline_named_capacity: Cell<u8>,- /// What a function object keeps in the object: its builtin plus one (zero for none), or ecmascript_function_flags- /// for an ECMAScript function object, which have the highest bit set. Zero for other objects.- pub function_bits: Cell<u8>,+ /// What a class keeps in the object: the builtin of a function object plus one (zero for none),+ /// ecmascript_function_flags for an ECMAScript function object, which have the highest bit set, or array_flags for+ /// an array. Zero for other objects.+ pub class_bits: Cell<u8>,/// Points at `inline_named_storage` until the object needs more room.pub named_properties: Cell<*mut Value>,pub indexed_elements: Cell<*mut Value>,diff --git a/Libraries/LibJS/Rust/src/runtime/array.rs b/Libraries/LibJS/Rust/src/runtime/array.rsindex 9ef35047183..8faea5a336c 100644--- a/Libraries/LibJS/Rust/src/runtime/array.rs+++ b/Libraries/LibJS/Rust/src/runtime/array.rs@@ -4,15 +4,13 @@* SPDX-License-Identifier: BSD-2-Clause*/-use core::cell::Cell;-use libjs_runtime_macros::Trace;use crate::gc::class::{Class, GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;-use crate::layout::member::Member;+use crate::layout::object::array_flags;use crate::layout::value::Value;use crate::runtime::abstract_operations::call_function_object;use crate::runtime::array_prototype::array_merge_sort;@@ -38,16 +36,9 @@ use crate::utf16::Utf16View;#[derive(Trace)]pub struct Array {base: Object,- realm: Member<Realm>,- length_writable: Cell<bool>,- is_proxy_target: Cell<bool>,}-const _: () = assert!(size_of::<Array>() == 40);--/// The offsets of the flags JIT code checks before writing elements of an array.-pub const ARRAY_LENGTH_WRITABLE_OFFSET: usize = core::mem::offset_of!(Array, length_writable);-pub const ARRAY_IS_PROXY_TARGET_OFFSET: usize = core::mem::offset_of!(Array, is_proxy_target);+const _: () = assert!(size_of::<Array>() == 32);pub static ARRAY_OBJECT_METHODS: ObjectMethods = ObjectMethods {internal_get_own_property: Array::internal_get_own_property,@@ -100,12 +91,7 @@ impl Array {),None => Object::new_with_prototype(vm, class, prototype, MayInterfereWithIndexedPropertyAccess::No),};- let array = Self {- base,- realm: Member::new(realm),- length_writable: Cell::new(true),- is_proxy_target: Cell::new(false),- };+ let array = Self { base };array.base.set_has_magical_length_property();array}@@ -164,15 +150,20 @@ impl Array {}pub fn length_is_writable(&self) -> bool {- self.length_writable.get()+ self.class_bits.get() & array_flags::LENGTH_NOT_WRITABLE == 0}pub fn is_proxy_target(&self) -> bool {- self.is_proxy_target.get()+ self.class_bits.get() & array_flags::IS_PROXY_TARGET != 0}pub fn set_is_proxy_target(&self, is_proxy_target: bool) {- self.is_proxy_target.set(is_proxy_target);+ let flags = self.class_bits.get();+ self.class_bits.set(if is_proxy_target {+ flags | array_flags::IS_PROXY_TARGET+ } else {+ flags & !array_flags::IS_PROXY_TARGET+ });}// Packed arrays have no holes, so the prototype chain is irrelevant:@@ -241,7 +232,7 @@ impl Array {}// NOTE: Step d. doesn't apply here.// e. Else if current.[[Writable]] is false, then- if !self.length_writable.get() {+ if !self.length_is_writable() {// i. If Desc has a [[Writable]] field and Desc.[[Writable]] is true, return false.if property_descriptor.writable == Some(true) {return Ok(false);@@ -266,7 +257,8 @@ impl Array {// a. Set succeeded to ! OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Writable]]: false }).// b. Assert: succeeded is true.if !new_writable {- self.length_writable.set(false);+ self.class_bits+ .set(self.class_bits.get() | array_flags::LENGTH_NOT_WRITABLE);}// NOTE: Continuation of step #17@@ -281,11 +273,11 @@ impl Array {/// The realm whose intrinsics default_prototype_chain_intact() compares the prototype chain with.pub fn realm(&self) -> Gc<Realm> {- self.realm.get()+ self.shape().realm()}pub fn default_prototype_chain_intact(&self) -> bool {- let realm = self.realm.get();+ let realm = self.realm();let Some(array_prototype) = self.shape().prototype() else {return false;};@@ -338,7 +330,7 @@ impl Array {if property_key.is_string() && property_key.as_string() == vm.names.length.as_string() {return Ok(Some(PropertyDescriptor {value: Some(Value::from_f64(f64::from(array.indexed_array_like_size()))),- writable: Some(array.length_writable.get()),+ writable: Some(array.length_is_writable()),enumerable: Some(false),configurable: Some(false),..Default::default()@@ -373,7 +365,7 @@ impl Array {if !array.is_extensible(vm)? {return Ok(false);}- if index >= array.indexed_array_like_size() && !array.length_writable.get() {+ if index >= array.indexed_array_like_size() && !array.length_is_writable() {return Ok(false);}array.indexed_put(index, value, DEFAULT_ATTRIBUTES);@@ -429,7 +421,7 @@ impl Array {// f. Let index be ! ToUint32(P).// g. If index ≥ oldLen and oldLenDesc.[[Writable]] is false, return false.- if property_key.as_number() >= array.indexed_array_like_size() && !array.length_writable.get() {+ if property_key.as_number() >= array.indexed_array_like_size() && !array.length_is_writable() {return Ok(false);}diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex e7f78b1865f..0cf772526fb 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -68,7 +68,7 @@ pub struct EcmascriptFunctionObjectStorage {}// NB: Every ECMAScript function has these bytes, so keep what only some functions need in the rare data.-const _: () = assert!(size_of::<EcmascriptFunctionObject>() == 40);+const _: () = assert!(size_of::<EcmascriptFunctionObject>() == 32);// SAFETY: Visits the cells of the class data, if there is any.unsafe impl Trace for EcmascriptFunctionObjectStorage {@@ -117,8 +117,8 @@ define_cell!(unsafe impl Trace for EcmascriptFunctionObject {fn trace(&self, visitor: &mut Visitor) {self.base.trace(visitor);- self.environment.trace(visitor);- visitor.visit_nullable_member(&self.shared_data);+ self.fields().environment.trace(visitor);+ visitor.visit_nullable_member(&self.fields().shared_data);}}@@ -298,8 +298,7 @@ impl EcmascriptFunctionObject {let base =FunctionObject::new_with_prototype(vm, Self::CLASS, prototype, MayInterfereWithIndexedPropertyAccess::No);base.set_is_ecmascript_function_object();- base.function_bits- .set(ecmascript_function_flags::IS_ECMASCRIPT_FUNCTION);+ base.class_bits.set(ecmascript_function_flags::IS_ECMASCRIPT_FUNCTION);// OPTIMIZATION: Start from a premade shape: normal and async functions create their properties lazily, and// the other kinds already have theirs in spec order. Arrow functions use the same shape as other@@ -319,11 +318,10 @@ impl EcmascriptFunctionObject {.set(function_shape.create_prototype_transition(vm, Some(prototype)));}- Self {- base,- shared_data: NullableMember::new(Some(shared_data)),- environment: NullableMember::new(parent_environment),- }+ let function = Self { base };+ function.fields().shared_data.set(Some(shared_data));+ function.fields().environment.set(parent_environment);+ function}fn initialize(&self, vm: &Vm, realm: Gc<Realm>) {@@ -888,12 +886,12 @@ impl EcmascriptFunctionObject {}fn has_flag(&self, flag: u8) -> bool {- self.function_bits.get() & flag != 0+ self.class_bits.get() & flag != 0}fn set_flag(&self, flag: u8, value: bool) {- let flags = self.function_bits.get();- self.function_bits.set(if value { flags | flag } else { flags & !flag });+ let flags = self.class_bits.get();+ self.class_bits.set(if value { flags | flag } else { flags & !flag });}fn class_data(&self) -> Option<&GcRefCell<ClassData>> {@@ -949,7 +947,7 @@ impl EcmascriptFunctionObject {pub fn shared_data(&self) -> Gc<SharedFunctionInstanceData> {// SAFETY: An ECMAScript function object gets its shared data when it is created, and keeps it.- unsafe { self.shared_data.get_unchecked() }+ unsafe { self.fields().shared_data.get_unchecked() }}pub fn is_module_wrapper(&self) -> bool {@@ -989,7 +987,7 @@ impl EcmascriptFunctionObject {}pub fn environment(&self) -> Option<Gc<Environment>> {- self.environment.get()+ self.fields().environment.get()}pub fn private_environment(&self) -> Option<Gc<PrivateEnvironment>> {diff --git a/Libraries/LibJS/Rust/src/runtime/function_object.rs b/Libraries/LibJS/Rust/src/runtime/function_object.rsindex 70625bcde48..efcd2d4f88c 100644--- a/Libraries/LibJS/Rust/src/runtime/function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/function_object.rs@@ -94,7 +94,7 @@ impl FunctionObject {}pub fn builtin(&self) -> Option<Builtin> {- let bits = self.function_bits.get();+ let bits = self.class_bits.get();if bits == 0 || bits & ecmascript_function_flags::IS_ECMASCRIPT_FUNCTION != 0 {return None;}@@ -102,7 +102,7 @@ impl FunctionObject {}pub fn set_builtin(&self, builtin: Option<Builtin>) {- self.function_bits.set(builtin.map_or(0, |builtin| builtin as u8 + 1));+ self.class_bits.set(builtin.map_or(0, |builtin| builtin as u8 + 1));}pub fn is_array_prototype_next_builtin(&self) -> bool {diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex 60b41e47ef5..f8e9507ae76 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -349,6 +349,8 @@ unsafe impl Trace for Object {}}+pub(crate) type IndexedDictionary = GcRefCell<GenericIndexedPropertyStorage>;+/// Object::~Object(), which LibGC runs as it sweeps the object, rather than in a finalizer every dead object would/// have to visit while the world is stopped. Property storage in ValueStorage cells is collected with the object, and/// may be swept before it, so only the flags tell what else the object owns.@@ -573,7 +575,7 @@ impl Object {indexed_storage_kind: Cell::new(IndexedStorageKind::None),flags: Cell::new(object_flag::IS_EXTENSIBLE),inline_named_capacity: Cell::new(0),- function_bits: Cell::new(0),+ class_bits: Cell::new(0),named_properties: Cell::new(core::ptr::null_mut()),indexed_elements: Cell::new(core::ptr::null_mut()),inline_named_storage: [],@@ -3772,15 +3774,33 @@ impl Object {self.indexed_array_like_size.get()}- fn indexed_dictionary(&self) -> &GcRefCell<GenericIndexedPropertyStorage> {+ fn indexed_dictionary(&self) -> &IndexedDictionary {assert!(self.indexed_storage_kind() == IndexedStorageKind::Dictionary);- // SAFETY: In dictionary mode the indexed elements pointer is the boxed storage, which the object owns until it- // leaves dictionary mode.- unsafe {- &*self- .indexed_elements- .get()- .cast::<GcRefCell<GenericIndexedPropertyStorage>>()+ // SAFETY: In dictionary mode the pointer is the boxed storage, which the object owns until it leaves dictionary+ // mode.+ unsafe { &*self.indexed_dictionary_pointer() }+ }++ fn indexed_dictionary_pointer(&self) -> *mut IndexedDictionary {+ if self.is_ecmascript_function_object() {+ return *self+ .vm()+ .function_indexed_dictionaries+ .borrow()+ .get(&core::ptr::from_ref(self).addr())+ .expect("a function in dictionary mode has a dictionary");+ }+ self.indexed_elements.get().cast()+ }++ fn set_indexed_dictionary_pointer(&self, dictionary: *mut IndexedDictionary) {+ if self.is_ecmascript_function_object() {+ self.vm()+ .function_indexed_dictionaries+ .borrow_mut()+ .insert(core::ptr::from_ref(self).addr(), dictionary);+ } else {+ self.indexed_elements.set(dictionary.cast());}}@@ -3841,6 +3861,7 @@ impl Object {}fn adopt_indexed_elements(&self, elements: *mut Value) {+ assert!(!self.is_ecmascript_function_object());debug_assert!(self.indexed_elements.get().is_null() && !self.has_flag(object_flag::HAS_MALLOC_INDEXED_STORAGE));self.replace_storage(&self.indexed_elements,@@ -3850,15 +3871,9 @@ impl Object {}fn free_indexed_elements(&self) {+ assert!(!self.is_ecmascript_function_object());if self.indexed_storage_kind() == IndexedStorageKind::Dictionary {- // SAFETY: In dictionary mode the indexed elements pointer came from Box::into_raw in transition_to_dictionary().- drop(unsafe {- Box::from_raw(- self.indexed_elements- .get()- .cast::<GcRefCell<GenericIndexedPropertyStorage>>(),- )- });+ self.free_indexed_elements_dictionary();} else {self.release_indexed_elements();}@@ -3888,6 +3903,7 @@ impl Object {}fn ensure_indexed_elements(&self, needed_capacity: u32) {+ assert!(!self.is_ecmascript_function_object());if !self.indexed_elements.get().is_null() && self.indexed_elements_capacity() >= needed_capacity {return;}@@ -3937,8 +3953,7 @@ impl Object {// Set the array_like_size on the dictionarydictionary.set_array_like_size(self.indexed_array_like_size() as usize);- let dictionary = Box::into_raw(Box::new(GcRefCell::new(dictionary)));- self.indexed_elements.set(dictionary.cast::<Value>());+ self.set_indexed_dictionary_pointer(Box::into_raw(Box::new(GcRefCell::new(dictionary))));self.indexed_storage_kind.set(IndexedStorageKind::Dictionary);});}@@ -3958,15 +3973,19 @@ impl Object {}fn free_indexed_elements_dictionary(&self) {- // SAFETY: In dictionary mode the indexed elements pointer came from Box::into_raw in transition_to_dictionary().- drop(unsafe {- Box::from_raw(- self.indexed_elements- .get()- .cast::<GcRefCell<GenericIndexedPropertyStorage>>(),- )- });- self.indexed_elements.set(core::ptr::null_mut());+ let dictionary = if self.is_ecmascript_function_object() {+ self.vm()+ .function_indexed_dictionaries+ .borrow_mut()+ .remove(&core::ptr::from_ref(self).addr())+ .unwrap_or(core::ptr::null_mut())+ } else {+ self.indexed_elements.replace(core::ptr::null_mut()).cast()+ };+ if !dictionary.is_null() {+ // SAFETY: The pointer came from Box::into_raw in transition_to_dictionary(), and is gone from the object.+ drop(unsafe { Box::from_raw(dictionary) });+ }}pub fn indexed_get(&self, index: u32) -> Option<ValueAndAttributes> {@@ -4009,7 +4028,8 @@ impl Object {// that has non-default attributes.let becoming_dense = !are_dense_enough(old_size, length) && are_dense_enough(dictionary.size(), length);let becoming_packed = old_size < length && dictionary.size() == length;- if (becoming_dense || becoming_packed)+ if !self.is_ecmascript_function_object()+ && (becoming_dense || becoming_packed)&& dictionary.sparse_elements().values()@@ -4072,8 +4092,8 @@ impl Object {return;}- // Non-default attributes require Dictionary mode- if attributes != DEFAULT_ATTRIBUTES {+ // Non-default attributes require Dictionary mode, and functions have nowhere else to keep their elements.+ if attributes != DEFAULT_ATTRIBUTES || self.is_ecmascript_function_object() {self.transition_to_dictionary();self.indexed_put_dictionary_and_update_size(index, value, attributes);return;@@ -4189,6 +4209,7 @@ impl Object {let new_size = u32::try_from(new_size).expect("an array-like size fits in u32");if self.indexed_storage_kind() == IndexedStorageKind::None {+ assert!(!self.is_ecmascript_function_object());if new_size == 0 {return true;}diff --git a/Tests/LibJS/Runtime/array-flags.js b/Tests/LibJS/Runtime/array-flags.jsnew file mode 100644index 00000000000..57c43eb0606--- /dev/null+++ b/Tests/LibJS/Runtime/array-flags.js@@ -0,0 +1,35 @@+test("a length that is not writable sticks", () => {+ const array = [1, 2, 3];+ Object.defineProperty(array, "length", { writable: false });++ expect(Object.getOwnPropertyDescriptor(array, "length").writable).toBeFalse();+ expect(() => array.push(4)).toThrow(TypeError);+ expect(() => array.pop()).toThrow(TypeError);+ expect(array.length).toBe(3);+ array[1] = "two";+ expect(array[1]).toBe("two");+});++test("arrays that are the target of a proxy stay arrays", () => {+ const array = [1, 2, 3];+ const proxy = new Proxy(array, {});++ expect(Array.isArray(proxy)).toBeTrue();+ expect(proxy.length).toBe(3);+ proxy.push(4);+ expect(array.length).toBe(4);+ array.push(5);+ expect(proxy[4]).toBe(5);++ Object.defineProperty(array, "length", { writable: false });+ expect(() => proxy.push(6)).toThrow(TypeError);+});++test("arrays from another realm keep their own intrinsics in mind", () => {+ const array = [1, 2, 3];+ Object.setPrototypeOf(array, Object.prototype);+ expect(array.concat).toBeUndefined();+ Object.setPrototypeOf(array, Array.prototype);+ expect(array.concat([4])).toEqual([1, 2, 3, 4]);+ for (const value of array) expect(value).toBeGreaterThan(0);+});diff --git a/Tests/LibJS/Runtime/functions/function-indexed-properties.js b/Tests/LibJS/Runtime/functions/function-indexed-properties.jsnew file mode 100644index 00000000000..c9758f9e75a--- /dev/null+++ b/Tests/LibJS/Runtime/functions/function-indexed-properties.js@@ -0,0 +1,119 @@+describe("indexed properties of functions", () => {+ test("functions keep working with indexed properties", () => {+ const outer = 42;+ function f(a) {+ return a + outer;+ }++ f[0] = "zero";+ f[1] = "one";+ f[1000000] = "sparse";++ expect(f[0]).toBe("zero");+ expect(f[1]).toBe("one");+ expect(f[1000000]).toBe("sparse");+ expect(f[2]).toBeUndefined();+ expect(f(1)).toBe(43);+ expect(new f(1)).toBeInstanceOf(f);+ });++ test("indexed keys come first, in order", () => {+ function f() {}+ f.named = 1;+ f[2] = "two";+ f[0] = "zero";++ expect(Object.keys(f)).toEqual(["0", "2", "named"]);+ expect(Object.getOwnPropertyNames(f).slice(0, 2)).toEqual(["0", "2"]);+ });++ test("dense fills stay readable", () => {+ function f() {+ return "called";+ }+ for (let i = 0; i < 1000; ++i) f[i] = i * 2;+ let sum = 0;+ for (let i = 0; i < 1000; ++i) sum += f[i];++ expect(sum).toBe(999000);+ expect(f()).toBe("called");+ });++ test("deleting and redefining", () => {+ function f() {}+ f[0] = 1;+ expect(delete f[0]).toBeTrue();+ expect(f[0]).toBeUndefined();+ expect(0 in f).toBeFalse();++ Object.defineProperty(f, 3, { value: "fixed", writable: false, enumerable: false, configurable: false });+ expect(Object.getOwnPropertyDescriptor(f, 3).writable).toBeFalse();+ expect(delete f[3]).toBeFalse();+ expect(f[3]).toBe("fixed");+ });++ test("freezing", () => {+ function f() {}+ f[0] = 1;+ Object.freeze(f);+ expect(Object.isFrozen(f)).toBeTrue();+ expect(() => {+ "use strict";+ f[0] = 2;+ }).toThrow(TypeError);+ expect(f[0]).toBe(1);+ });++ test("array methods applied to functions", () => {+ function f() {}+ f[0] = "a";+ f[1] = "b";+ // NB: Function length is not writable, so the methods that write it throw.+ expect(Array.prototype.join.call(f)).toBe("");+ expect(() => Array.prototype.push.call(f, "c")).toThrow(TypeError);+ expect(f[0]).toBe("c");+ expect(f[1]).toBe("b");+ });++ test("every kind of function, surviving a collection", () => {+ const functions = [+ function () {},+ () => {},+ function* () {},+ async function () {},+ class {},+ class {+ static #x = 1;+ static m() {+ return this.#x;+ }+ },+ ];+ for (const f of functions) {+ f[0] = { value: "kept" };+ f[100000] = { value: "sparse" };+ }+ gc();+ for (const f of functions) {+ expect(f[0].value).toBe("kept");+ expect(f[100000].value).toBe("sparse");+ }+ expect(functions[5].m()).toBe(1);+ });++ test("the prototype chain reads the elements of a function", () => {+ function f() {}+ f[7] = "inherited";+ const object = Object.create(f);+ expect(object[7]).toBe("inherited");+ expect(7 in object).toBeTrue();+ });++ test("many functions with elements, collected", () => {+ for (let i = 0; i < 1000; ++i) {+ const f = function () {};+ f[0] = i;+ }+ gc();+ });+});