Skip to content

Truly independent web browser

LibGC: Add compressed Member and NonnullMember cell field types

Andreas Kling6334948684c6
diff --git a/AK/TypedTransfer.h b/AK/TypedTransfer.h
index a286913a81d..7efb3e11c13 100644
--- a/AK/TypedTransfer.h
+++ b/AK/TypedTransfer.h
@@ -78,7 +78,9 @@ public:
return;
if constexpr (IsTriviallyRelocatable<T>) {
- __builtin_memcpy(destination, source, count * sizeof(T));
+ // NB: A trivially relocatable type may still have a non-trivial assignment, which makes it not trivially
+ // copyable, but relocating it never assigns.
+ __builtin_memcpy(static_cast<void*>(destination), static_cast<void const*>(source), count * sizeof(T));
return;
}
diff --git a/Libraries/LibGC/BlockAllocator.cpp b/Libraries/LibGC/BlockAllocator.cpp
index a193c842934..9cb4ed4d709 100644
--- a/Libraries/LibGC/BlockAllocator.cpp
+++ b/Libraries/LibGC/BlockAllocator.cpp
@@ -84,7 +84,15 @@ public:
m_base = reinterpret_cast<u8*>(aligned_start);
VERIFY(reinterpret_cast<FlatPtr>(m_base) % size == 0);
- js_heap_region_base = reinterpret_cast<FlatPtr>(m_base);
+ publish_base(reinterpret_cast<FlatPtr>(m_base));
+ }
+
+ static void register_base_copy(HeapRegionBaseCopyRegistration& registration)
+ {
+ MutexLocker locker(base_copies_mutex());
+ registration.m_next = exchange(s_base_copies, &registration);
+ if (js_heap_region_base)
+ *registration.m_copy = js_heap_region_base;
}
// This process-global region is shared by every Heap. GC block allocation is single-threaded per process, but the
@@ -134,6 +142,24 @@ public:
private:
static void request_prepared_chunk();
+ static void publish_base(FlatPtr base)
+ {
+ MutexLocker locker(base_copies_mutex());
+ js_heap_region_base = base;
+ for (auto* registration = s_base_copies; registration; registration = registration->m_next)
+ *registration->m_copy = base;
+ }
+
+ // NB: Static initialization registers copies, possibly before that of this file has run, so the list starts out
+ // constant-initialized and its mutex is set up on first use.
+ static Mutex& base_copies_mutex()
+ {
+ static AK::NeverDestroyed<Mutex> mutex;
+ return *mutex;
+ }
+
+ static constinit inline HeapRegionBaseCopyRegistration* s_base_copies { nullptr };
+
// The guards at either end of the region are never committed.
static constexpr size_t FIRST_CHUNK_OFFSET = HEAP_REGION_LOW_GUARD_SIZE;
static constexpr size_t LAST_CHUNK_OFFSET = size - HEAP_REGION_HIGH_GUARD_SIZE - CHUNK_SIZE;
@@ -394,6 +420,12 @@ size_t BlockAllocator::block_count()
return m_blocks.size();
}
+HeapRegionBaseCopyRegistration::HeapRegionBaseCopyRegistration(FlatPtr& copy)
+ : m_copy(&copy)
+{
+ HeapRegion::register_base_copy(*this);
+}
+
FlatPtr BlockAllocator::heap_region_start()
{
return heap_region().start();
diff --git a/Libraries/LibGC/Cell.h b/Libraries/LibGC/Cell.h
index e3cef2c1c9d..eff84d96955 100644
--- a/Libraries/LibGC/Cell.h
+++ b/Libraries/LibGC/Cell.h
@@ -14,6 +14,7 @@
#include <AK/StringView.h>
#include <LibGC/Forward.h>
#include <LibGC/Internals.h>
+#include <LibGC/Member.h>
#include <LibGC/NanBoxedValue.h>
#include <LibGC/Ptr.h>
@@ -125,6 +126,21 @@ public:
visit_impl(*as_cell(const_cast<RemoveConst<T>*>(cell.ptr())));
}
+ // Members are visited through their slot, which a moving collector will update. For now this visits the cell
+ // they point to.
+ template<typename T>
+ void visit(Member<T> const& slot)
+ {
+ if (slot)
+ visit_member_cell(slot.ptr());
+ }
+
+ template<typename T>
+ void visit(NonnullMember<T> const& slot)
+ {
+ visit_member_cell(slot.ptr());
+ }
+
template<typename T>
void visit(ReadonlySpan<T> span)
requires(!IsBaseOf<NanBoxedValue, T> && IsVisitable<T>::value)
@@ -264,6 +280,15 @@ public:
virtual void visit_ephemeron(Cell& key, NanBoxedValue const& value);
protected:
+ template<typename T>
+ ALWAYS_INLINE void visit_member_cell(T* cell)
+ {
+ auto* mutable_cell = as_cell(const_cast<RemoveConst<T>*>(cell));
+ // A compressed pointer must name the start of its cell.
+ ASSERT(static_cast<void const*>(mutable_cell) == static_cast<void const*>(cell));
+ visit_impl(*mutable_cell);
+ }
+
virtual void visit_impl(Cell&) = 0;
virtual void visit_impl(ReadonlySpan<NanBoxedValue>) = 0;
virtual ~Visitor() = default;
diff --git a/Libraries/LibGC/CompressedPointer.h b/Libraries/LibGC/CompressedPointer.h
index 7600fbedb1f..32112f5ca7d 100644
--- a/Libraries/LibGC/CompressedPointer.h
+++ b/Libraries/LibGC/CompressedPointer.h
@@ -21,14 +21,14 @@ static_assert((static_cast<u64>(1) << (32 + COMPRESSED_POINTER_SHIFT)) == HEAP_R
// Every compressed pointer below this decodes into the low guard, so it is never a cell.
static constexpr u32 MIN_COMPRESSED_CELL_POINTER = HEAP_REGION_LOW_GUARD_SIZE >> COMPRESSED_POINTER_SHIFT;
+// OPTIMIZATION: The region is aligned to its size, so the low 32 bits of a cell's address shifted right by 3 are its
+// compressed pointer, which takes no load of the base. Null stays 0.
ALWAYS_INLINE u32 compress(void const* cell)
{
- if (!cell)
- return 0;
- auto offset = reinterpret_cast<FlatPtr>(cell) - js_heap_region_base;
- ASSERT(offset < HEAP_REGION_SIZE);
- ASSERT(offset % (1 << COMPRESSED_POINTER_SHIFT) == 0);
- return static_cast<u32>(offset >> COMPRESSED_POINTER_SHIFT);
+ auto address = reinterpret_cast<FlatPtr>(cell);
+ ASSERT(!cell || address - heap_region_base() < HEAP_REGION_SIZE);
+ ASSERT(address % (1 << COMPRESSED_POINTER_SHIFT) == 0);
+ return static_cast<u32>(address >> COMPRESSED_POINTER_SHIFT);
}
// Decodes a compressed pointer that is not null.
@@ -36,7 +36,7 @@ ALWAYS_INLINE u32 compress(void const* cell)
// Makes the compressed pointer live up to this point, and the decoded address from this point on. The conservative
// stack scan recognizes a cell by its address or by its compressed pointer in either half of a word, but not by its
// unshifted offset, which the compiler could otherwise keep instead while either is held across an allocation.
-ALWAYS_INLINE FlatPtr decompress_nonnull(u32 compressed, FlatPtr heap_region_base = js_heap_region_base)
+ALWAYS_INLINE FlatPtr decompress_nonnull(u32 compressed, FlatPtr heap_region_base = GC::heap_region_base())
{
auto address = heap_region_base + (static_cast<FlatPtr>(compressed) << COMPRESSED_POINTER_SHIFT);
// NB: The assembly is empty. It only has the compiler put the compressed pointer and the address in registers here.
diff --git a/Libraries/LibGC/ConservativeVector.h b/Libraries/LibGC/ConservativeVector.h
index 3e1f96e3753..d36dbf521b8 100644
--- a/Libraries/LibGC/ConservativeVector.h
+++ b/Libraries/LibGC/ConservativeVector.h
@@ -31,7 +31,7 @@ public:
};
template<typename T, size_t inline_capacity>
-requires(!IsSpecializationOf<RemoveCVReference<T>, Ptr> && !IsSpecializationOf<RemoveCVReference<T>, Ref>) class GC_API ConservativeVector final
+requires(!IsPreciselyTracedCellPointer<T>) class GC_API ConservativeVector final
: public ConservativeVectorBase
, public Vector<T, inline_capacity> {
diff --git a/Libraries/LibGC/Forward.h b/Libraries/LibGC/Forward.h
index 759ee6ece2a..9f7a42aebde 100644
--- a/Libraries/LibGC/Forward.h
+++ b/Libraries/LibGC/Forward.h
@@ -44,9 +44,19 @@ class Ref;
template<class T>
class Ptr;
-// Precisely traceable pointers belong in RootVector rather than conservative storage.
+template<class T>
+class Member;
+
+template<class T>
+class NonnullMember;
+
+// The cell pointers that are traced precisely. Ptr and Ref belong in RootVector rather than conservative storage, and
+// members only in cells.
+template<typename T>
+concept IsPreciselyTracedCellPointer = IsSpecializationOf<RemoveCVReference<T>, Ptr> || IsSpecializationOf<RemoveCVReference<T>, Ref> || IsSpecializationOf<RemoveCVReference<T>, Member> || IsSpecializationOf<RemoveCVReference<T>, NonnullMember>;
+
template<class T, size_t inline_capacity = 0>
-requires(!IsSpecializationOf<RemoveCVReference<T>, Ptr> && !IsSpecializationOf<RemoveCVReference<T>, Ref>) class ConservativeVector;
+requires(!IsPreciselyTracedCellPointer<T>) class ConservativeVector;
template<typename K, typename V, typename KeyTraits, typename ValueTraits, bool IsOrdered>
class ConservativeHashMap;
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index ac2f6316eeb..2d77b6d15cc 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -493,6 +493,28 @@ static void add_possible_value(PossiblePointers& possible_pointers, FlatPtr data
possible_pointers.pointers.set(possible_pointer, move(origin));
}
+// Adds the possible values in the captures of a GC::Function. Its captures start 8-byte aligned, but may end with a
+// lone compressed cell pointer, as a capture of nothing but one member does. That one is no half of a whole word, so it
+// is added on its own. A member elsewhere in the captures is either half of one of the whole words.
+static void add_possible_captured_values(PossiblePointers& possible_pointers, ReadonlyBytes bytes, PossiblePointerBounds const& bounds)
+{
+ HeapRoot const origin { .type = HeapRoot::Type::HeapFunctionCapturedPointer };
+ ASSERT(reinterpret_cast<FlatPtr>(bytes.data()) % alignof(FlatPtr) == 0);
+ auto const* words = reinterpret_cast<FlatPtr const*>(bytes.data());
+ auto word_count = bytes.size() / sizeof(FlatPtr);
+ for (size_t i = 0; i < word_count; ++i)
+ add_possible_value(possible_pointers, words[i], origin, bounds);
+
+ // NB: Anything shorter than 4 bytes past the last whole word is too short to be a member, and anything that is a
+ // member is 4-byte aligned.
+ auto tail = bytes.slice(word_count * sizeof(FlatPtr));
+ if (tail.size() >= sizeof(u32)) {
+ u32 compressed;
+ memcpy(&compressed, tail.data(), sizeof(compressed));
+ add_possible_compressed_pointer(possible_pointers, compressed, origin, bounds);
+ }
+}
+
template<typename Callback>
static void for_each_cell_among_possible_pointers(HashTable<HeapBlock*> const& all_live_heap_blocks, PossiblePointers& possible_pointers, Callback callback)
{
@@ -554,9 +576,7 @@ public:
{
PossiblePointers possible_pointers;
- auto* raw_pointer_sized_values = reinterpret_cast<FlatPtr const*>(bytes.data());
- for (size_t i = 0; i < (bytes.size() / sizeof(FlatPtr)); ++i)
- add_possible_value(possible_pointers, raw_pointer_sized_values[i], HeapRoot { .type = HeapRoot::Type::HeapFunctionCapturedPointer }, m_possible_pointer_bounds);
+ add_possible_captured_values(possible_pointers, bytes, m_possible_pointer_bounds);
for_each_cell_among_possible_pointers(m_heap.m_live_heap_blocks, possible_pointers, [&](Cell* cell, auto&, FlatPtr) {
if (cell->state() != Cell::State::Live)
@@ -1383,9 +1403,7 @@ public:
{
PossiblePointers possible_pointers;
- auto* raw_pointer_sized_values = reinterpret_cast<FlatPtr const*>(bytes.data());
- for (size_t i = 0; i < (bytes.size() / sizeof(FlatPtr)); ++i)
- add_possible_value(possible_pointers, raw_pointer_sized_values[i], HeapRoot { .type = HeapRoot::Type::HeapFunctionCapturedPointer }, m_possible_pointer_bounds);
+ add_possible_captured_values(possible_pointers, bytes, m_possible_pointer_bounds);
for (auto* heap : m_domain) {
for_each_cell_among_possible_pointers(heap->m_live_heap_blocks, possible_pointers, [&](Cell* cell, auto&, FlatPtr) {
diff --git a/Libraries/LibGC/HeapRegion.h b/Libraries/LibGC/HeapRegion.h
index 9370c154396..85191682fb5 100644
--- a/Libraries/LibGC/HeapRegion.h
+++ b/Libraries/LibGC/HeapRegion.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Noncopyable.h>
#include <AK/Platform.h>
#include <AK/StdLibExtras.h>
#include <AK/Types.h>
@@ -33,3 +34,55 @@ static constexpr size_t HEAP_REGION_HIGH_GUARD_SIZE = 2ull * MiB;
}
extern "C" GC_API FlatPtr js_heap_region_base;
+
+namespace GC {
+
+// A copy of the heap region base outside LibGC, which LibGC fills in when it reserves the region, or when the copy is
+// registered if that happens later. Either way that is before any cell exists, and the base never changes after that.
+// A registration lasts for the rest of the process, like the shared objects that hold them, which are never unloaded.
+class GC_API HeapRegionBaseCopyRegistration {
+ AK_MAKE_NONCOPYABLE(HeapRegionBaseCopyRegistration);
+ AK_MAKE_NONMOVABLE(HeapRegionBaseCopyRegistration);
+
+public:
+ explicit HeapRegionBaseCopyRegistration(FlatPtr& copy);
+
+private:
+ friend class HeapRegion;
+
+ FlatPtr* m_copy { nullptr };
+ HeapRegionBaseCopyRegistration* m_next { nullptr };
+};
+
+namespace Detail {
+
+// OPTIMIZATION: Every shared object keeps a hidden copy of the base, which a decode reads with one PC-relative load.
+// Reading js_heap_region_base from outside LibGC takes a GOT load first.
+class HeapRegionBaseCopy {
+public:
+ FlatPtr base() const { return m_base; }
+
+private:
+ // NB: Static storage starts out zeroed, so the base is 0 until registering it fills it in, also for anything that
+ // reads it before this is constructed.
+ FlatPtr m_base { 0 };
+ HeapRegionBaseCopyRegistration m_registration { m_base };
+};
+
+// NB: Every translation unit that decodes includes this header, so the copy of its shared object is constructed and
+// registered before the dynamic initialization of anything that it defines after including it. No cell exists
+// before the region does, so the copy holds the base by the time anything decodes a cell pointer.
+#if defined(AK_OS_WINDOWS)
+inline HeapRegionBaseCopy heap_region_base_copy;
+#else
+[[gnu::visibility("hidden")]] inline HeapRegionBaseCopy heap_region_base_copy;
+#endif
+
+}
+
+ALWAYS_INLINE FlatPtr heap_region_base()
+{
+ return Detail::heap_region_base_copy.base();
+}
+
+}
diff --git a/Libraries/LibGC/Member.h b/Libraries/LibGC/Member.h
new file mode 100644
index 00000000000..c9f46b0b546
--- /dev/null
+++ b/Libraries/LibGC/Member.h
@@ -0,0 +1,436 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Format.h>
+#include <AK/StdLibExtras.h>
+#include <AK/Traits.h>
+#include <AK/Types.h>
+#include <LibGC/CompressedPointer.h>
+#include <LibGC/Ptr.h>
+
+namespace GC {
+
+// Member and NonnullMember are the types of cell pointers stored in cells, and in storage that cells visit. They hold a
+// compressed pointer in 32 bits. Locals, parameters and return values keep using the full-width Ptr and Ref, which
+// members convert to implicitly. Like Ptr and Ref, members only hand out a raw pointer through ptr().
+//
+// A member holds the address of the T it points to, so T must start with its cell, which the conservative scanner
+// requires of a compressed pointer it finds on the stack: it only recognizes cell starts.
+
+template<typename T>
+class Member;
+
+template<typename T>
+class NonnullMember;
+
+namespace Detail {
+
+// Every store of a member goes through this hook, where a generational or moving collector will record the slot. It is
+// empty for now, so it compiles to nothing.
+ALWAYS_INLINE void member_write_barrier([[maybe_unused]] void const* slot, [[maybe_unused]] u32 compressed)
+{
+}
+
+template<typename T>
+ALWAYS_INLINE u32 compress_cell(T* cell)
+{
+ return compress(static_cast<void const*>(cell));
+}
+
+template<typename T>
+concept IsMember = IsSpecializationOf<T, Member> || IsSpecializationOf<T, NonnullMember>;
+
+}
+
+template<typename T>
+class Member {
+public:
+ constexpr Member() = default;
+
+ Member(nullptr_t) { }
+
+ Member(T* cell)
+ : m_compressed(Detail::compress_cell(cell))
+ {
+ }
+
+ Member(T& cell)
+ : m_compressed(Detail::compress_cell(&cell))
+ {
+ }
+
+ template<typename U>
+ Member(U* cell)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(cell)))
+ {
+ }
+
+ template<typename U>
+ Member(U& cell)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(&cell)))
+ {
+ }
+
+ template<typename U>
+ Member(Ptr<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ template<typename U>
+ Member(Ref<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ // OPTIMIZATION: Constructing a member from another copies its u32 and nothing else, which also has members passed
+ // and returned in registers. Only stores into existing members go through the write barrier.
+ Member(Member const&) = default;
+ Member(Member&&) = default;
+
+ template<typename U>
+ Member(Member<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ template<typename U>
+ Member(NonnullMember<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ template<typename U>
+ Member(U* foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(foreign_cell)))
+ {
+ }
+
+ template<typename U>
+ Member(U& foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(&foreign_cell)))
+ {
+ }
+
+ template<typename U>
+ Member(Ptr<U> const& foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(foreign_cell.ptr())))
+ {
+ }
+
+ template<typename U>
+ Member(Ref<U> const& foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(foreign_cell.ptr())))
+ {
+ }
+
+ Member& operator=(Member const& other)
+ {
+ set_compressed(other.m_compressed);
+ return *this;
+ }
+
+ template<typename U>
+ Member& operator=(U&& other)
+ requires(requires { Member(forward<U>(other)); })
+ {
+ set_compressed(Member(forward<U>(other)).m_compressed);
+ return *this;
+ }
+
+ T* ptr() const { return reinterpret_cast<T*>(decompress(m_compressed)); }
+
+ RETURNS_NONNULL T* operator->() const
+ {
+ ASSERT(m_compressed);
+ return reinterpret_cast<T*>(decompress_nonnull(m_compressed));
+ }
+
+ [[nodiscard]] T& operator*() const
+ {
+ ASSERT(m_compressed);
+ return *reinterpret_cast<T*>(decompress_nonnull(m_compressed));
+ }
+
+ explicit operator bool() const { return m_compressed != 0; }
+ bool operator!() const { return m_compressed == 0; }
+
+ Ref<T> as_nonnull() const
+ {
+ VERIFY(m_compressed);
+ return *reinterpret_cast<T*>(decompress_nonnull(m_compressed));
+ }
+
+ template<typename U>
+ operator Ptr<U>() const
+ requires(IsConvertible<T*, U*> || IsForeignCellConvertibleToCell<T, U>)
+ {
+ return Ptr<U>(ptr());
+ }
+
+ u32 compressed() const { return m_compressed; }
+
+private:
+ template<typename U>
+ friend class Member;
+
+ ALWAYS_INLINE void set_compressed(u32 compressed)
+ {
+ Detail::member_write_barrier(this, compressed);
+ m_compressed = compressed;
+ }
+
+ u32 m_compressed { 0 };
+};
+
+template<typename T>
+class NonnullMember {
+public:
+ NonnullMember() = delete;
+
+ NonnullMember(T& cell)
+ : m_compressed(Detail::compress_cell(&cell))
+ {
+ }
+
+ template<typename U>
+ NonnullMember(U& cell)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(&cell)))
+ {
+ }
+
+ template<typename U>
+ NonnullMember(Ref<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ NonnullMember(NonnullMember const&) = default;
+ NonnullMember(NonnullMember&&) = default;
+
+ template<typename U>
+ NonnullMember(NonnullMember<U> const& other)
+ requires(IsConvertible<U*, T*>)
+ : m_compressed(Detail::compress_cell(static_cast<T*>(other.ptr())))
+ {
+ }
+
+ template<typename U>
+ NonnullMember(U& foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(&foreign_cell)))
+ {
+ }
+
+ template<typename U>
+ NonnullMember(Ref<U> const& foreign_cell)
+ requires(IsForeignCellConvertibleToCell<U, T>)
+ : m_compressed(Detail::compress_cell(as_cell(foreign_cell.ptr())))
+ {
+ }
+
+ NonnullMember& operator=(NonnullMember const& other)
+ {
+ set_compressed(other.m_compressed);
+ return *this;
+ }
+
+ template<typename U>
+ NonnullMember& operator=(U&& other)
+ requires(requires { NonnullMember(forward<U>(other)); })
+ {
+ set_compressed(NonnullMember(forward<U>(other)).m_compressed);
+ return *this;
+ }
+
+ RETURNS_NONNULL T* ptr() const { return reinterpret_cast<T*>(decompress_nonnull(m_compressed)); }
+
+ RETURNS_NONNULL T* operator->() const { return ptr(); }
+
+ [[nodiscard]] T& operator*() const { return *ptr(); }
+
+ operator T&() const { return *ptr(); }
+
+ template<typename U>
+ operator Ref<U>() const
+ requires(IsConvertible<T*, U*> || IsForeignCellConvertibleToCell<T, U>)
+ {
+ return Ref<U>(*ptr());
+ }
+
+ template<typename U>
+ operator Ptr<U>() const
+ requires(IsConvertible<T*, U*> || IsForeignCellConvertibleToCell<T, U>)
+ {
+ return Ptr<U>(ptr());
+ }
+
+ operator bool() const = delete;
+ bool operator!() const = delete;
+
+ u32 compressed() const { return m_compressed; }
+
+private:
+ template<typename U>
+ friend class NonnullMember;
+
+ ALWAYS_INLINE void set_compressed(u32 compressed)
+ {
+ Detail::member_write_barrier(this, compressed);
+ m_compressed = compressed;
+ }
+
+ u32 m_compressed;
+};
+
+namespace Detail {
+
+// Whether a member of T that holds `compressed` points to `other`, as a comparison of T* with U* would tell.
+template<typename T, typename U>
+ALWAYS_INLINE bool member_points_to(u32 compressed, U const* other)
+{
+ if constexpr (IsConvertible<U*, T const*>) {
+ // OPTIMIZATION: Compressing the other pointer is a shift, where decoding the member would load the base.
+ return compressed == compress(static_cast<T const*>(other));
+ } else if constexpr (IsConvertible<T*, U const*>) {
+ return static_cast<U const*>(reinterpret_cast<T const*>(decompress(compressed))) == other;
+ } else {
+ // A cell compared to a type that names foreign cells, which shares its address.
+ return compressed == compress(other);
+ }
+}
+
+}
+
+// OPTIMIZATION: Two members point to the same cell exactly when their compressed pointers are equal, so comparing them
+// decodes neither.
+template<typename T, typename U>
+requires(Detail::IsMember<T> && Detail::IsMember<U>)
+inline bool operator==(T const& a, U const& b)
+{
+ return a.compressed() == b.compressed();
+}
+
+template<typename T, typename U>
+inline bool operator==(Member<T> const& a, Ptr<U> const& b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b.ptr());
+}
+
+template<typename T, typename U>
+inline bool operator==(Member<T> const& a, Ref<U> const& b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b.ptr());
+}
+
+template<typename T, typename U>
+inline bool operator==(NonnullMember<T> const& a, Ptr<U> const& b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b.ptr());
+}
+
+template<typename T, typename U>
+inline bool operator==(NonnullMember<T> const& a, Ref<U> const& b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b.ptr());
+}
+
+template<typename T, typename U>
+inline bool operator==(Member<T> const& a, U const* b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b);
+}
+
+template<typename T, typename U>
+inline bool operator==(NonnullMember<T> const& a, U const* b)
+{
+ return Detail::member_points_to<T>(a.compressed(), b);
+}
+
+template<typename T>
+inline bool operator==(Member<T> const& member, nullptr_t)
+{
+ return !member;
+}
+
+}
+
+namespace AK {
+
+template<typename T>
+struct Traits<GC::Member<T>> : public DefaultTraits<GC::Member<T>> {
+ static unsigned hash(GC::Member<T> const& value)
+ {
+ return Traits<T*>::hash(value.ptr());
+ }
+ static constexpr bool may_have_slow_equality_check() { return false; }
+};
+
+template<typename T>
+struct Traits<GC::NonnullMember<T>> : public DefaultTraits<GC::NonnullMember<T>> {
+ static unsigned hash(GC::NonnullMember<T> const& value)
+ {
+ return Traits<T*>::hash(value.ptr());
+ }
+ static constexpr bool may_have_slow_equality_check() { return false; }
+};
+
+namespace Detail {
+
+template<typename T>
+inline constexpr bool IsHashCompatible<GC::Member<T>, GC::Ptr<T>> = true;
+
+template<typename T>
+inline constexpr bool IsHashCompatible<GC::Ptr<T>, GC::Member<T>> = true;
+
+template<typename T>
+inline constexpr bool IsHashCompatible<GC::NonnullMember<T>, GC::Ref<T>> = true;
+
+template<typename T>
+inline constexpr bool IsHashCompatible<GC::Ref<T>, GC::NonnullMember<T>> = true;
+
+}
+
+template<typename T>
+struct Formatter<GC::Member<T>> : Formatter<T const*> {
+ ErrorOr<void> format(FormatBuilder& builder, GC::Member<T> const& value)
+ {
+ return Formatter<T const*>::format(builder, value.ptr());
+ }
+};
+
+template<Formattable T>
+struct Formatter<GC::NonnullMember<T>> : Formatter<T> {
+ ErrorOr<void> format(FormatBuilder& builder, GC::NonnullMember<T> const& value)
+ {
+ return Formatter<T>::format(builder, *value);
+ }
+};
+
+template<typename T>
+requires(!HasFormatter<T>)
+struct Formatter<GC::NonnullMember<T>> : Formatter<T const*> {
+ ErrorOr<void> format(FormatBuilder& builder, GC::NonnullMember<T> const& value)
+ {
+ return Formatter<T const*>::format(builder, value.ptr());
+ }
+};
+
+}
diff --git a/Libraries/LibGC/NanBoxedValue.h b/Libraries/LibGC/NanBoxedValue.h
index 1428825d8eb..288af55d28a 100644
--- a/Libraries/LibGC/NanBoxedValue.h
+++ b/Libraries/LibGC/NanBoxedValue.h
@@ -62,13 +62,13 @@ public:
static FlatPtr encode_pointer_bits(void const* pointer)
{
auto pointer_bits = reinterpret_cast<FlatPtr>(pointer);
- ASSERT((pointer_bits & ~HEAP_REGION_OFFSET_MASK) == js_heap_region_base);
+ ASSERT((pointer_bits & ~HEAP_REGION_OFFSET_MASK) == heap_region_base());
return pointer_bits & HEAP_REGION_OFFSET_MASK;
}
static FlatPtr extract_pointer_bits(u64 encoded)
{
- return js_heap_region_base + (encoded & HEAP_REGION_OFFSET_MASK);
+ return heap_region_base() + (encoded & HEAP_REGION_OFFSET_MASK);
}
template<typename PointerType>
diff --git a/Libraries/LibJS/Heap/Cell.cpp b/Libraries/LibJS/Heap/Cell.cpp
index ad142977df8..94021be5201 100644
--- a/Libraries/LibJS/Heap/Cell.cpp
+++ b/Libraries/LibJS/Heap/Cell.cpp
@@ -4,10 +4,18 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGC/HeapRegion.h>
#include <LibJS/Heap/Cell.h>
+// The copy of the heap region base that the Rust half of LibJS decodes with (see layout_forward.rs).
+extern "C" FlatPtr* js_heap_region_base_copy();
+
namespace JS {
+// NB: Nothing in LibJS allocates a cell during static initialization, so this registers the copy before the first cell
+// that the Rust half could decode exists.
+static GC::HeapRegionBaseCopyRegistration s_rust_heap_region_base_copy_registration { *js_heap_region_base_copy() };
+
void Cell::initialize(Realm&)
{
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/feedback.rs b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
index bfdb4dfe4f7..aedca8cdce8 100644
--- a/Libraries/LibJS/Rust/src/bytecode/feedback.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
@@ -16,7 +16,6 @@ use core::cell::Cell;
use core::ptr::NonNull;
use crate::build_configuration::HEAP_REGION_OFFSET_MASK;
-use crate::gc::capi;
use crate::gc::primitive_storage::{OwnedPrimitiveStorage, ZeroFillNewBytes};
use crate::gc::sweep::Sweep;
use crate::layout::cell::{CellHeader, Gc};
@@ -173,8 +172,8 @@ impl ExecutableFeedback {
/// the heap region.
fn decode_weak_reference(reference: &Cell<Option<Gc<CellHeader>>>) -> Option<Gc<CellHeader>> {
let cell = reference.get()?;
- // SAFETY: LibGC fixed the heap region base before any cell existed.
- let base = unsafe { capi::js_heap_region_base } as u64;
+ // NB: The heap region base was fixed before any cell existed.
+ let base = crate::layout_forward::heap_region_base() as u64;
let address = base + (cell.as_ptr() as u64 & HEAP_REGION_OFFSET_MASK);
let address = NonNull::new(core::ptr::with_exposed_provenance_mut::<CellHeader>(address as usize))
.expect("the heap region does not start at null");
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index 8977172ee42..68dc75bd943 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -331,8 +331,7 @@ impl<T: GcCell> crate::layout::cell::Gc<T> {
/// Whether `address` is in the region LibGC allocates every cell in, which has no cells before it is set up.
pub(crate) fn is_in_heap_region(address: usize) -> bool {
- // SAFETY: LibGC sets the base once, when it sets up the region, before any cell exists.
- let base = unsafe { super::capi::js_heap_region_base };
+ let base = crate::layout_forward::heap_region_base();
base != 0 && address.wrapping_sub(base) as u64 <= crate::build_configuration::HEAP_REGION_OFFSET_MASK
}
diff --git a/Libraries/LibJS/Rust/src/layout_forward.rs b/Libraries/LibJS/Rust/src/layout_forward.rs
index 9e1337bed4e..687b54ff825 100644
--- a/Libraries/LibJS/Rust/src/layout_forward.rs
+++ b/Libraries/LibJS/Rust/src/layout_forward.rs
@@ -76,11 +76,31 @@ pub use crate::runtime::shared_function_instance_data::SharedFunctionInstanceDat
pub use crate::runtime::typed_array::TypedArrayBaseStorage;
-/// The base of the heap region, which compressed cell pointers are offsets from.
+/// A copy of LibGC's js_heap_region_base, which LibGC fills in through its registration (see
+/// js_heap_region_base_copy()) before any cell exists, and never changes after that.
+struct HeapRegionBaseCopy(core::cell::UnsafeCell<usize>);
+
+// SAFETY: LibGC writes the copy once, before any cell exists, and every read of it is of a cell that some thread has
+// made since, which it had to synchronize with to get at.
+unsafe impl Sync for HeapRegionBaseCopy {}
+
+// OPTIMIZATION: A copy of the base in this library, which a decode reads with one PC-relative load instead of a load of
+// js_heap_region_base's address from the GOT first. It is a plain load, which the compiler can hoist out
+// of loops, where an atomic one would have to stay in them.
+static HEAP_REGION_BASE: HeapRegionBaseCopy = HeapRegionBaseCopy(core::cell::UnsafeCell::new(0));
+
+/// The base of the heap region, which compressed cell pointers and cell values are offsets from. Zero until LibGC
+/// reserves the region, which happens before any cell exists.
#[inline(always)]
pub fn heap_region_base() -> usize {
- // SAFETY: LibGC sets the base once, when it sets up the region, before any cell exists.
- unsafe { crate::gc::capi::js_heap_region_base }
+ // SAFETY: Nothing writes the copy after the first cell exists, see HeapRegionBaseCopy.
+ unsafe { *HEAP_REGION_BASE.0.get() }
+}
+
+/// The copy of the heap region base, which LibJS registers with LibGC at static initialization.
+#[unsafe(no_mangle)]
+pub extern "C" fn js_heap_region_base_copy() -> *mut usize {
+ HEAP_REGION_BASE.0.get()
}
const _: () =
diff --git a/Libraries/LibJS/Rust/src/runtime/value.rs b/Libraries/LibJS/Rust/src/runtime/value.rs
index dd5bf5ff75f..89a9157aefe 100644
--- a/Libraries/LibJS/Rust/src/runtime/value.rs
+++ b/Libraries/LibJS/Rust/src/runtime/value.rs
@@ -14,7 +14,6 @@ use num_traits::Zero;
use crate::build_configuration::HEAP_REGION_OFFSET_MASK;
use crate::bytecode::executable::{PropertyLookupCache, StaticPropertyLookupCacheSite};
use crate::bytecode::property_access::{GetByIdMode, get_by_id};
-use crate::gc::capi::js_heap_region_base;
use crate::gc::class_id::ClassId;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
@@ -22,6 +21,7 @@ use crate::layout::function_object::FunctionObject;
use crate::layout::object::Object;
use crate::layout::primitive_string::PrimitiveString;
use crate::layout::value::Value;
+use crate::layout_forward::heap_region_base;
use crate::runtime::abstract_operations::{call, call_function_object};
use crate::runtime::accessor::Accessor;
use crate::runtime::array::Array;
@@ -51,8 +51,8 @@ use libjs_abi::value as nan_box;
/// compiler could otherwise keep instead of the value or the address while either is held across an allocation.
#[inline(always)]
fn decode_cell_address(encoded: u64) -> usize {
- // SAFETY: Cell values are offsets into the heap region, whose base LibGC fixed before any cell existed.
- let base = unsafe { js_heap_region_base } as u64;
+ // NB: Cell values are offsets into the heap region, whose base was fixed before any cell existed.
+ let base = heap_region_base() as u64;
let mut address = base + (encoded & HEAP_REGION_OFFSET_MASK);
// SAFETY: The assembly is empty: it only has the compiler put `encoded` and `address` in registers here.
unsafe {
diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txt
index 4122e550bfa..4a431564906 100644
--- a/Tests/LibGC/CMakeLists.txt
+++ b/Tests/LibGC/CMakeLists.txt
@@ -11,6 +11,7 @@ set(TEST_SOURCES
TestGCIdleCollection.cpp
TestGCIncrementalSweep.cpp
TestGCVisitor.cpp
+ TestMember.cpp
TestNanBoxedValue.cpp
TestPrimitiveStorage.cpp
)
diff --git a/Tests/LibGC/TestMember.cpp b/Tests/LibGC/TestMember.cpp
new file mode 100644
index 00000000000..9bb8dc643b0
--- /dev/null
+++ b/Tests/LibGC/TestMember.cpp
@@ -0,0 +1,374 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashMap.h>
+#include <AK/HashTable.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/Optional.h>
+#include <AK/Vector.h>
+#include <LibGC/Cell.h>
+#include <LibGC/CellAllocator.h>
+#include <LibGC/Function.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Member.h>
+#include <LibGC/Root.h>
+#include <LibTest/TestCase.h>
+
+namespace {
+
+class TestCell : public GC::Cell {
+ GC_CELL(TestCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(TestCell);
+
+public:
+ GC::Member<TestCell> next;
+ u32 value { 0 };
+
+private:
+ virtual void visit_edges(Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(next);
+ }
+};
+
+GC_DEFINE_ALLOCATOR(TestCell);
+
+class DerivedTestCell final : public TestCell {
+ GC_CELL(DerivedTestCell, TestCell);
+ GC_DECLARE_ALLOCATOR(DerivedTestCell);
+};
+
+GC_DEFINE_ALLOCATOR(DerivedTestCell);
+
+static GC::Heap& test_heap()
+{
+ static AK::NeverDestroyed<GC::Heap> heap([](auto&) { });
+ return *heap;
+}
+
+TEST_SETUP
+{
+ GC::Heap::set_default_heap_for_testing(test_heap());
+}
+
+static_assert(sizeof(GC::Member<TestCell>) == sizeof(u32));
+static_assert(sizeof(GC::NonnullMember<TestCell>) == sizeof(u32));
+static_assert(IsTriviallyCopyConstructible<GC::Member<TestCell>> && IsTriviallyMoveConstructible<GC::Member<TestCell>>);
+static_assert(IsTriviallyDestructible<GC::Member<TestCell>>);
+static_assert(IsTriviallyCopyConstructible<GC::NonnullMember<TestCell>> && IsTriviallyMoveConstructible<GC::NonnullMember<TestCell>>);
+static_assert(IsTriviallyDestructible<GC::NonnullMember<TestCell>>);
+
+TEST_CASE(base_copy_matches_the_heap_region)
+{
+ // NB: The first cell reserves the region, if nothing has yet.
+ (void)test_heap().allocate<TestCell>();
+ EXPECT_EQ(GC::heap_region_base(), js_heap_region_base);
+ EXPECT_EQ(GC::heap_region_base() % GC::HEAP_REGION_SIZE, 0u);
+}
+
+TEST_CASE(base_copy_registered_after_the_region_exists_gets_the_base)
+{
+ (void)test_heap().allocate<TestCell>();
+ // NB: Registrations are never undone, so this one is for the rest of the process.
+ static FlatPtr copy;
+ static GC::HeapRegionBaseCopyRegistration registration { copy };
+ EXPECT_NE(copy, 0u);
+ EXPECT_EQ(copy, js_heap_region_base);
+}
+
+TEST_CASE(member_round_trips_and_null_is_zero)
+{
+ auto cell = test_heap().allocate<TestCell>();
+
+ GC::Member<TestCell> member;
+ EXPECT(!member);
+ EXPECT_EQ(member.compressed(), 0u);
+ EXPECT_EQ(member.ptr(), nullptr);
+ EXPECT(member == nullptr);
+
+ member = cell;
+ EXPECT(member);
+ EXPECT_EQ(member.ptr(), cell.ptr());
+ EXPECT_EQ(member.compressed(), GC::compress(cell.ptr()));
+ EXPECT_EQ(&*member, cell.ptr());
+ EXPECT_EQ(member->value, 0u);
+
+ member = nullptr;
+ EXPECT(!member);
+
+ GC::NonnullMember<TestCell> nonnull = *cell;
+ EXPECT_EQ(nonnull.ptr(), cell.ptr());
+ EXPECT_EQ(nonnull.compressed(), GC::compress(cell.ptr()));
+}
+
+TEST_CASE(members_convert_to_and_from_stack_pointers)
+{
+ auto derived = test_heap().allocate<DerivedTestCell>();
+
+ GC::Member<DerivedTestCell> member = derived;
+ GC::Ptr<TestCell> base_ptr = member;
+ EXPECT_EQ(base_ptr.ptr(), derived.ptr());
+ GC::Ptr<GC::Cell> cell_ptr = member;
+ EXPECT_EQ(cell_ptr.ptr(), derived.ptr());
+ EXPECT_EQ(member.as_nonnull().ptr(), derived.ptr());
+
+ GC::NonnullMember<DerivedTestCell> nonnull = derived;
+ GC::Ref<TestCell> base_ref = nonnull;
+ EXPECT_EQ(base_ref.ptr(), derived.ptr());
+ GC::Ptr<TestCell> base_ptr_from_nonnull = nonnull;
+ EXPECT_EQ(base_ptr_from_nonnull.ptr(), derived.ptr());
+ TestCell& reference = nonnull;
+ EXPECT_EQ(&reference, derived.ptr());
+
+ GC::Member<TestCell> widened = nonnull;
+ EXPECT_EQ(widened.ptr(), derived.ptr());
+ GC::Member<TestCell> from_ptr = GC::Ptr<DerivedTestCell> { derived };
+ EXPECT_EQ(from_ptr.ptr(), derived.ptr());
+ GC::NonnullMember<TestCell> from_ref = derived;
+ EXPECT_EQ(from_ref.ptr(), derived.ptr());
+}
+
+TEST_CASE(members_compare_like_pointers)
+{
+ auto a = test_heap().allocate<TestCell>();
+ auto b = test_heap().allocate<DerivedTestCell>();
+
+ GC::Member<TestCell> member_a = a;
+ GC::Member<TestCell> member_b = b;
+ GC::NonnullMember<DerivedTestCell> nonnull_b = b;
+
+ EXPECT(member_a != member_b);
+ EXPECT(member_b == nonnull_b);
+ EXPECT(nonnull_b == member_b);
+ EXPECT(member_a == a);
+ EXPECT(a == member_a);
+ EXPECT(member_a != GC::Ptr<TestCell> { b });
+ EXPECT(member_b == GC::Ref<DerivedTestCell> { *b });
+ EXPECT(member_a == a.ptr());
+ EXPECT(b.ptr() == nonnull_b);
+ EXPECT(member_a != nullptr);
+ EXPECT(GC::Member<TestCell> {} == GC::Ptr<TestCell> {});
+
+ GC::Cell* as_cell = b.ptr();
+ EXPECT(member_b == as_cell);
+ EXPECT(nonnull_b == as_cell);
+}
+
+TEST_CASE(members_hash_like_pointers)
+{
+ auto a = test_heap().allocate<TestCell>();
+ auto b = test_heap().allocate<TestCell>();
+
+ EXPECT_EQ(Traits<GC::Member<TestCell>>::hash(a), Traits<GC::Ptr<TestCell>>::hash(a));
+ EXPECT_EQ(Traits<GC::NonnullMember<TestCell>>::hash(*a), Traits<GC::Ref<TestCell>>::hash(a));
+
+ HashTable<GC::Member<TestCell>> table;
+ table.set(a);
+ EXPECT(table.contains(GC::Ptr<TestCell> { a }));
+ EXPECT(!table.contains(GC::Ptr<TestCell> { b }));
+
+ HashMap<GC::NonnullMember<TestCell>, int> map;
+ map.set(*a, 1);
+ map.set(*b, 2);
+ EXPECT_EQ(map.get(GC::Ref<TestCell> { a }), 1);
+ EXPECT_EQ(map.get(GC::Ref<TestCell> { b }), 2);
+}
+
+class TestVisitor : public GC::Cell::Visitor {
+ virtual void visit_impl(GC::Cell& cell) override { visited_cells.append(&cell); }
+ virtual void visit_impl(ReadonlySpan<GC::NanBoxedValue>) override { }
+ virtual void visit_possible_values(ReadonlyBytes) override { }
+
+public:
+ Vector<GC::Cell*> visited_cells;
+};
+
+TEST_CASE(visitor_visits_member_slots)
+{
+ auto a = test_heap().allocate<TestCell>();
+ auto b = test_heap().allocate<TestCell>();
+
+ GC::Member<TestCell> member = a;
+ GC::Member<TestCell> null_member;
+ GC::NonnullMember<TestCell> nonnull = *b;
+ Vector<GC::Member<TestCell>> vector { a, nullptr, b };
+ Optional<GC::NonnullMember<TestCell>> optional = GC::NonnullMember<TestCell> { *a };
+
+ TestVisitor visitor;
+ visitor.visit(member);
+ visitor.visit(null_member);
+ visitor.visit(nonnull);
+ visitor.visit(vector);
+ visitor.visit(optional);
+
+ Vector<GC::Cell*> expected { a.ptr(), b.ptr(), a.ptr(), b.ptr(), a.ptr() };
+ EXPECT_EQ(visitor.visited_cells, expected);
+}
+
+TEST_CASE(members_keep_cells_alive)
+{
+ auto head = GC::make_root(test_heap().allocate<TestCell>());
+ head->next = test_heap().allocate<TestCell>();
+ head->next->value = 42;
+
+ test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);
+
+ EXPECT_EQ(head->next->value, 42u);
+}
+
+class FinalizationTrackingCell final : public GC::Cell {
+ GC_CELL(FinalizationTrackingCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(FinalizationTrackingCell);
+
+public:
+ explicit FinalizationTrackingCell(bool& finalized)
+ : m_finalized(finalized)
+ {
+ }
+
+private:
+ virtual void finalize() override
+ {
+ Base::finalize();
+ m_finalized = true;
+ }
+
+ bool& m_finalized;
+};
+
+GC_DEFINE_ALLOCATOR(FinalizationTrackingCell);
+
+// Keeps nothing on the stack that points at the cell the function captures, other than the root of the function.
+template<typename MakeCallable>
+static NEVER_INLINE GC::Root<GC::Function<size_t()>> make_function_capturing_a_member(bool& finalized, MakeCallable make_callable)
+{
+ GC::Member<FinalizationTrackingCell> member = test_heap().allocate<FinalizationTrackingCell>(finalized);
+ return GC::make_root(GC::create_function(test_heap(), make_callable(member)));
+}
+
+static NEVER_INLINE void clobber_the_stack()
+{
+ u8 volatile scratch[16 * KiB];
+ for (auto& byte : scratch)
+ byte = 0;
+}
+
+TEST_CASE(function_whose_only_capture_is_a_member_keeps_its_cell_alive)
+{
+ // NB: Static, since the cell outlives the test once nothing holds it anymore.
+ static bool finalized;
+ finalized = false;
+ auto function = make_function_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {
+ auto callable = [member] { return reinterpret_cast<size_t>(member.ptr()); };
+ static_assert(sizeof(callable) == sizeof(u32));
+ return callable;
+ });
+ clobber_the_stack();
+
+ test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);
+
+ EXPECT(!finalized);
+ EXPECT_NE(function->function()(), 0u);
+}
+
+TEST_CASE(function_whose_captures_end_in_a_member_keeps_its_cell_alive)
+{
+ // NB: Static, since the cell outlives the test once nothing holds it anymore.
+ static bool finalized;
+ finalized = false;
+ auto function = make_function_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {
+ auto callable = [first = static_cast<u32>(1), second = static_cast<u32>(2), member] {
+ return reinterpret_cast<size_t>(member.ptr()) + first + second;
+ };
+ // NB: The member is past the last whole word of the captures.
+ static_assert(sizeof(callable) == 3 * sizeof(u32));
+ return callable;
+ });
+ clobber_the_stack();
+
+ test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);
+
+ EXPECT(!finalized);
+ EXPECT_NE(function->function()(), 0u);
+}
+
+// Walks a list of cells through compressed pointers, decoding them against the base copy or against the base exported
+// from LibGC. The opaque call per cell keeps the compiler from hoisting the base out of the loop, as an ordinary DOM
+// walk with calls in its body would.
+static NEVER_INLINE void touch(TestCell& cell)
+{
+ cell.value += 1;
+ asm volatile("" ::: "memory");
+}
+
+static GC::Root<TestCell> const& benchmark_list()
+{
+ static GC::Root<TestCell> head = [] {
+ auto head = GC::make_root(test_heap().allocate<TestCell>());
+ GC::Ptr<TestCell> tail = head.ptr();
+ for (size_t i = 0; i < 100'000; ++i) {
+ auto cell = test_heap().allocate<TestCell>();
+ tail->next = cell;
+ tail = cell;
+ }
+ return head;
+ }();
+ return head;
+}
+
+template<typename LoadBase>
+static NEVER_INLINE void walk_benchmark_list(LoadBase load_base)
+{
+ auto* head = benchmark_list().ptr();
+ for (size_t round = 0; round < 1000; ++round) {
+ for (auto* cell = head; cell;) {
+ touch(*cell);
+ auto compressed = cell->next.compressed();
+ cell = compressed ? reinterpret_cast<TestCell*>(GC::decompress_nonnull(compressed, load_base())) : nullptr;
+ }
+ }
+}
+
+// The same walk, with the decode in a function of its own, so it loads the base (and its address) on every call.
+template<typename LoadBase>
+static NEVER_INLINE TestCell* next_cell(TestCell& cell, LoadBase load_base)
+{
+ auto compressed = cell.next.compressed();
+ return compressed ? reinterpret_cast<TestCell*>(GC::decompress_nonnull(compressed, load_base())) : nullptr;
+}
+
+template<typename LoadBase>
+static NEVER_INLINE void walk_benchmark_list_out_of_line(LoadBase load_base)
+{
+ auto* head = benchmark_list().ptr();
+ for (size_t round = 0; round < 1000; ++round) {
+ for (auto* cell = head; cell; cell = next_cell(*cell, load_base))
+ touch(*cell);
+ }
+}
+
+BENCHMARK_CASE(walk_members_out_of_line_with_exported_base)
+{
+ walk_benchmark_list_out_of_line([] { return js_heap_region_base; });
+}
+
+BENCHMARK_CASE(walk_members_out_of_line_with_base_copy)
+{
+ walk_benchmark_list_out_of_line([] { return GC::heap_region_base(); });
+}
+
+BENCHMARK_CASE(walk_members_with_base_copy)
+{
+ walk_benchmark_list([] { return GC::heap_region_base(); });
+}
+
+BENCHMARK_CASE(walk_members_with_exported_base)
+{
+ walk_benchmark_list([] { return js_heap_region_base; });
+}
+
+}
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 143ae874f8c..46438492974 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -258,7 +258,7 @@ if (NOT WIN32)
endif()
target_sources(TestLibWebView PRIVATE ${TEST_SOURCES})
-target_link_libraries(TestLibWebView PRIVATE LibAudio LibCompositing LibDatabase LibGfx LibHTTP LibIPC LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)
+target_link_libraries(TestLibWebView PRIVATE LibAudio LibCompositing LibDatabase LibGC LibGfx LibHTTP LibIPC LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)
if (APPLE)
add_dependencies(TestLibWebView ProcessReaper)