navid/haze / commit

9d1d3caf43f3

Navid M <navidmomtahen@gmail.com> · 2026-12-02

parents: 111bf5c1dba3

Browse files at this commit · Download source

docs: add immix collector specification
--- /dev/null+++ b/docs/XYZ_IMMIX_COLLECTOR_SPECIFICATION.md@@ -0,0 +1,1372 @@+# xyz Immix Collector Specification++*Draft 0.2 · C++23 runtime · UQBE backend*++## 1. Goals and non-goals++### Goals++- Precise, parallel, stop-the-world mark-region garbage collection.+- Opportunistic evacuation of fragmented blocks.+- Extremely cheap allocation through inline thread-local bump pointers.+- No write barrier for immutable heap objects.+- Dense side metadata with predictable memory overhead.+- Bounded allocation and collection overhead for heaps reaching tens of GiB.+- Native integration with UQBE without introducing an LLVM dependency.+- Portable runtime implementation across supported UQBE targets.++### Non-goals (v1)++- Concurrent marking.+- Conservative scanning.+- Finalizers.+- Interior pointers stored in heap objects.+- Pointer tagging exposed to xyz programs.+- Incremental collection.+- Concurrent evacuation.+- General-purpose weak references.++### Design principles++1. The compiler owns managed-pointer correctness.+2. The runtime owns heap management, tracing, evacuation, and reclamation.+3. UQBE generates ordinary machine-code calls, not GC-specific LLVM-style intrinsics.+4. Managed references are always identifiable as exact object-base pointers.+5. Every potential collection point has a compiler-generated root map.+6. The collector never needs to inspect arbitrary machine registers.++---++## 2. The key bet: immutability removes the write barrier++xyz heap objects are immutable after construction.++An object can only reference objects that already existed when it was constructed. Consequently, an older object can never acquire a reference to a younger object.++The resulting graph has a useful directional property:++- Older objects may reference older objects.+- Younger objects may reference older objects.+- Younger objects may reference younger objects created before them.+- Older objects cannot reference younger objects.++This provides two important properties:++- No write barrier is needed.+- No remembered set is needed for generational collection.++### Compiler enforcement++The compiler must guarantee that heap fields cannot be modified after object publication.++Object construction follows this sequence:++1. Allocate zero-initialized storage.+2. Initialize all scalar fields.+3. Initialize all managed references.+4. Publish the object.+5. Never modify its fields again.++The collector is permitted to modify object storage internally when rewriting references during evacuation.++### Future mutable objects++If xyz eventually introduces mutable heap cells, such as `Ref` or lazy thunk updates, they must use an explicit mutation API:++`xyz_wb(obj, slot, value)`++This operation will:++1. Update the reference.+2. Set the `REMEMBERED` header flag.+3. Append the object to a per-thread remembered buffer.++Mutable objects must not bypass this API.++This is not required by v1.++---++## 3. Heap layout++### 3.1 Virtual reservation++The collector reserves one large contiguous virtual address range.++Default configuration:++- Reservation: 64 GiB.+- Alignment: 2 MiB.+- Block size: 32 KiB.+- Commitment: on demand.+- Huge pages: opportunistic.+- Unused memory: released or reclaimed using platform-specific virtual-memory operations.++The heap uses a single base address:++`heap_base`++Block lookup is a shift:++```cpp+constexpr u32 BLOCK_SHIFT = 15;+constexpr u64 BLOCK_SIZE = 1ull << BLOCK_SHIFT;++inline u32 block_index(const void* ptr) {+    return (static_cast<const u8*>(ptr) -+            heap_base) >> BLOCK_SHIFT;+}+```++The implementation must validate that the pointer belongs to the managed reservation before performing this calculation.++### 3.2 Object layout constants++| Constant | Value | Description |+|---|---:|---|+| Granule | 16 B | Minimum object alignment |+| Header | 8 B | Object metadata |+| Line | 128 B | Allocation/reclamation granularity |+| Block | 32 KiB | Immix allocation unit |+| Lines per block | 256 | Fixed |+| Small object | ≤128 B | Normal allocation |+| Medium object | ≤8 KiB | Multi-line allocation |+| Large object | >8 KiB | Large object space |++Object sizes include their headers and are rounded up to 16-byte alignment.++Small objects may span two lines. An object is live only when its header has been marked; every line it intersects is subsequently marked live.++The collector must not assume that an object occupies exactly one line.++### 3.3 Side metadata++Metadata is allocated separately from object storage.++**Line metadata**++One byte per line.++256 bytes per block.++A line is considered live when its metadata byte equals the current collection epoch.++During allocation, the relevant line metadata is also updated to reflect the current allocation epoch.++The collector uses line metadata to determine which regions of a block can be reused.++Importantly, line-level reclamation is conservative: a line containing even one live object cannot be reclaimed.++**Block metadata**++16 bytes per block.++```cpp+struct BlockMeta {+    u32 next;+    u16 holes;+    u16 marked_lines;+    u8  state;+    u8  generation;+    u8  flags;+    u8  age;+    u32 owner;+};+```++Block states:++```cpp+enum class BlockState : u8 {+    FREE,+    ALLOCATING,+    RECYCLABLE,+    FULL,+    EVAC_SOURCE,+    EVAC_TARGET,+    LOS_RESERVED+};+```++`generation` identifies whether the block belongs to the nursery or old generation.++`owner` identifies the mutator responsible for the block. Unowned blocks use a reserved identifier.++**Metadata reservation**++At the default 64 GiB heap size:++- Line metadata: 512 MiB.+- Block metadata: 32 MiB.++Total: approximately 0.83% of the reserved heap.++### 3.4 Object header++```cpp+struct Header {+    u32 type_id;+    u8  mark;+    u8  flags;+    u16 aux;+};++static_assert(sizeof(Header) == 8);+```++Flags:++```cpp+enum HeaderFlags : u8 {+    PINNED     = 1 << 0,+    REMEMBERED = 1 << 1,+    LARGE      = 1 << 2+};+```++The header is eight-byte aligned and accessed atomically when concurrent collector workers may inspect it.++The header has three logical states:++- Normal object header.+- Busy evacuation state.+- Forwarded object.++Forwarding replaces the complete 64-bit header with:++`new_address | 1`++The low bit is available because managed objects are at least 16-byte aligned.++A forwarded object must never be interpreted as a normal header.++The collector uses acquire/release operations when publishing and consuming forwarding pointers.++### 3.5 Type descriptors++The runtime maintains a type descriptor table.++```cpp+struct TypeDesc {+    u32 size;+    u16 pointer_count;+    u16 flags;+    const u32* pointer_offsets;+};+```++Pointer offsets are relative to the beginning of the object.++For larger structures, descriptors may use compressed pointer-offset sequences or bitmaps.++Arrays contain their element type and length in their allocation metadata.++The collector must support:++- Fixed-size structures.+- Arrays of scalar values.+- Arrays of managed references.+- Structures containing mixed scalar and reference fields.++All pointer fields contain exact managed object-base pointers.++The compiler and runtime must agree on the descriptor layout.++---++## 4. Allocation++### 4.1 Mutator state++Each mutator owns a cache-line-aligned `Mutator` structure.++```cpp+struct Mutator {+    void* cursor;+    void* limit;++    void* ocursor;+    void* olimit;++    void* nursery_cursor;+    void* nursery_limit;++    RootFrame* root_frame;++    u32 thread_id;+    u32 flags;++    u8 poll;+    u8 reserved[7];+};+```++The normal allocation region uses the current block's available lines.++The overflow allocator handles medium allocations.++The nursery allocator is used when generational mode is enabled.++The mutator structure is accessed through thread-local storage.++### 4.2 Inline allocation++The common allocation path must be emitted directly by UQBE.++Conceptually:++```cpp+inline void* alloc(Mutator& m, u32 size, u32 type) {+    auto p = m.cursor;+    auto n = static_cast<u8*>(p) + size;++    if (n > m.limit)+        return alloc_slow(m, size, type);++    m.cursor = n;++    store_header(p, type);++    return p;+}+```++The compiler supplies a compile-time object size whenever possible.++The fast path:++- Performs no locking.+- Performs no system calls.+- Does not allocate auxiliary metadata.+- Does not call the runtime.+- Does not perform a collection.++Target: approximately six machine instructions on x86-64, excluding any required header initialization.++### 4.3 Slow allocation++The slow path follows this order:++1. Find another available hole in the current block.+2. Acquire a recyclable block from the mutator's local cache.+3. Refill the cache from global block lists.+4. Acquire a free block.+5. Acquire an additional committed block if permitted by the growth budget.+6. Trigger collection.+7. Retry allocation.++Global block lists must use a concurrency-safe algorithm.++A block must have exactly one allocating owner at any given time.++### 4.4 Zero initialization++All allocated object storage is zero-initialized.++Freshly committed pages are already zeroed by the operating system.++Reused holes are cleared when acquired.++Zeroing occurs outside the inline fast path.++The runtime may use architecture-specific vectorized clearing.++### 4.5 Prefetching++When acquiring a new hole, the allocator may prefetch 256 bytes ahead of the allocation cursor.++Prefetching must remain an optimization, not a correctness requirement.++### 4.6 Medium objects++Medium allocations use whole-line regions.++An allocation that cannot fit in the current hole must not consume unrelated remaining space.++Medium allocations are placed into dedicated multi-line regions or blocks obtained from the overflow allocator.++### 4.7 Large object space++Objects larger than 8 KiB use the large object space (LOS).++LOS objects:++- Are never evacuated.+- Have separate allocation metadata.+- Participate in normal marking.+- Are reclaimed during LOS sweeping.+- Are independently committed and released.++Large objects must not consume ordinary Immix blocks.++---++## 5. Collection++The collector uses parallel stop-the-world mark-region collection with opportunistic evacuation.++All collection workers operate against a stable heap.++### 5.1 Safepoint rendezvous++Every mutator periodically checks its safepoint poll flag.++The compiler inserts polls:++- At loop back-edges.+- At recursive function entry.+- At allocation slow paths.+- At calls that may trigger collection.++The fast poll is a single conditional branch.++When a collection is requested:++1. The collector sets the global collection request.+2. Mutators observe their poll flags.+3. Each mutator publishes its active root frame.+4. Mutators enter a parked state.+5. The collector begins once all required mutators are safe.++Threads executing native code require special handling.++A thread may be excluded from the rendezvous only if it has entered a GC-safe native region and guarantees that it holds no unpinned managed pointers.++Otherwise, the collector must wait for it to reach a safepoint.++A native thread holding managed references must either:# xyz Immix Collector Specification++*Draft 0.1 · C++23 runtime · LLVM statepoint backend*++## 1. Goals and non-goals++**Goals:** precise, parallel, stop-the-world mark-region collector with opportunistic evacuation; the cheapest possible allocation (inline bump pointer); **no write barrier**; dense side metadata; predictable pauses for heaps up to tens of GiB.++**Non-goals (v1):** concurrent marking, conservative scanning, finalizers, interior pointers stored in the heap, pointer tagging.++## 2. The key bet: immutability removes the barrier++xyz heap data is immutable (no `mut`), so an object can only point to objects that existed before it. Old objects therefore never point to young ones. This gives two things for free:++- no write barrier and no remembered set;+- sticky-mark-bit minor collections (section 6) that trace only from roots and stop at any already-marked object.++Any future mutable heap cell (`Ref`, lazy thunk update) must go through `xyz_wb(obj)`, which sets a `REMEMBERED` header bit and appends to a per-thread buffer. Nothing else in the design changes.++## 3. Heap layout++One large `PROT_NONE` virtual reservation (default 64 GiB, 2 MiB aligned, `MADV_HUGEPAGE`), committed on demand. Block lookup is a shift: `idx = (addr - heap_base) >> 15`.++| Constant | Value | Notes |+| --- | --- | --- |+| Granule / alignment | 16 B | all objects, minimum object 16 B |+| Line | 128 B | 8 granules |+| Block | 32 KiB | 256 lines |+| Small | ≤ 128 B | marks one line (+ implicit next line) |+| Medium | ≤ 8 KiB | marks every spanned line; uses overflow allocator |+| Large | > 8 KiB | large object space (LOS), never moved |++**Side tables** (separate reservation, never interleaved with objects):++- *Line marks:* 1 byte per line (256 B per block). A line is live iff its byte equals the current epoch.+- *Block metadata:* 16 B per block: `state` (free, recyclable, full, evac-source, evac-target), `holes`, `marked_lines`, `age`, `next` (32-bit list link).++**Object header (8 B):**++```cpp+struct Header {          // little-endian, 8 bytes+  u32 type_id;           // index into the type table+  u8  mark;              // == epoch when marked+  u8  flags;             // PINNED | REMEMBERED | LARGE+  u16 aux;               // e.g. small array length+};                       // forwarded: whole word = (new_addr | 1)+```++The type table entry holds `size`, a pointer count, and a pointer bitmap (up to 62 words) or run-length offsets. Arrays carry `{elem_type_id, len}` after the header. Heap fields hold base pointers only.++## 4. Allocation++Each mutator owns a `Mutator` struct (TLS, `initial-exec`, cache-line aligned) holding two bump regions: `cursor/limit` for the current hole and `ocursor/olimit` for overflow (medium objects).++```cpp+inline void* alloc(Mutator& m, u32 size, u32 type) {   // size: constexpr, 16-aligned+  auto p = m.cursor, n = p + size;+  if (n > m.limit) [[unlikely]] return alloc_slow(m, size, type);+  m.cursor = n;+  store_header(p, type);+  return p;                                             // payload already zero+}+```++The compiler emits this inline as IR (about 6 instructions). The slow path, in order:++1. Next hole in the current block, found with SIMD compare of line bytes against the epoch, then `countr_zero` on the movemask.+2. Next recyclable block from the thread's local cache, refilled in batches of 4 from the global lock-free lists.+3. A free block.+4. Trigger a collection.++**Zeroing** happens per hole at acquisition (`memset`; fresh `mmap` pages are already zero). Prefetch-for-write 256 B ahead of `cursor` when entering a hole. Medium objects that don't fit the hole go to the overflow allocator, which uses whole free blocks, so holes are not burned.++## 5. Collection (parallel, stop-the-world)++1. **Rendezvous:** polls and handshakes bring mutators to safepoints. Threads in native code are marked `IN_NATIVE` with their last Xyz frame published, so the GC does not wait for them.+2. **Choose evacuation set** (only if fragmented): from last cycle's histogram, take blocks with the most holes and least live data, until their live bytes fit in the reserved target space (≥ 2% of heap, minimum 8 blocks).+3. **Roots:** stack maps (section 7), the global root table, and the pinned set.+4. **Trace + evacuate in one pass.** Per-thread mark stacks (1K-entry chunks) with Chase-Lev work stealing, and an 8-entry prefetch FIFO between popping a reference and scanning the object.+   - Marking is test-then-CAS on `mark`, followed by relaxed line-mark stores.+   - If the object lies in an evac-source block and is not pinned: CAS the header to `BUSY`, copy into the thread's evac block, release-store the forwarding word; losers spin and follow it.+   - Every visited slot is rewritten in place with the new address.+5. **Sweep:** parallel over blocks, touching only the line-mark table (0.8% of heap). Count live lines with SIMD, reclassify the block, splice into per-thread lists, then merge. No object is touched. The epoch increments instead of clearing marks (clear only on wrap at 255).+6. **LOS sweep**, and release of surplus blocks (`MADV_FREE` after a lag).+7. **Resize:** target heap = max(64 MiB, live × 1.5), tunable.++A collection is triggered when free + recyclable blocks are exhausted and the growth budget is spent.++## 6. Generational mode (sticky Immix, v3)++- **Minor GC:** do not bump the epoch. Trace from roots and stop at any marked object. Survivors stay marked (old) and unmarked lines are reusable. No remembered set, no barrier.+- **Full GC:** bump the epoch, which implicitly unmarks everything, and run the normal cycle with evacuation.+- Minor GCs never evacuate. Trigger a full GC when old-generation growth exceeds a threshold or fragmentation does.++## 7. LLVM integration++- **Managed pointers** are `ptr addrspace(1)`. Functions carry `gc "statepoint-example"`, and the `RewriteStatepointsForGC` pass converts calls to `gc.statepoint` with `gc.relocate` / `gc.result`. Derived pointers are handled by LLVM as (base, derived) pairs.+- **Safepoint polls:** the frontend inserts them at loop back-edges and on entry to recursive functions: `if (tls->poll) xyz_gc_poll()`. A guard-page poll is a later optimization.+- **Stack maps:** parse `.llvm_stackmaps` (v3) once at startup into an open-addressing hash from return address to record. Per statepoint record: skip the 3 leading constants and the deopt operands, then read the (base, derived) location pairs. After relocation, rewrite `derived = new_base + (derived - old_base)`.+- **Roots are stack slots only.** Keep the default of no GC pointers in callee-saved registers (`fixup-statepoint-caller-saved`), so every root is a spill slot.+- **Stack walking:** frame-pointer chain (`"frame-pointer"="all"` on every function). The caller's SP at a call site is `callee_FP + 16`; resolve `Indirect [SP + off]` locations from that.+- **Allocation calls:** declare `@xyz_alloc_slow` with `allockind("alloc,zeroed")`, `allocsize(0)` and `noalias` return, so LLVM can delete dead allocations and forward stores. Do escape analysis in the frontend and stack-allocate non-escaping values.+- **Runtime entry points that can GC** (`alloc_slow`, `poll`) are ordinary statepoint calls. On entry they record the caller's FP and return address in `Mutator`, so the collector can start walking.+- **Dev builds:** LLVM is linked dynamically into the *compiler only*. The runtime is a static `libxyzrt.a` built without LLVM headers, and it parses the stack-map format itself.+- **Pin the LLVM version.** The statepoint intrinsics are still documented as experimental.++## 8. Runtime ABI++| Symbol | Purpose |+| --- | --- |+| `xyz_alloc_slow(size, type_id)` | slow path allocation, may GC |+| `xyz_alloc_large(size, type_id)` | LOS allocation |+| `xyz_gc_poll()` | safepoint slow path |+| `xyz_thread_attach/detach()` | register a mutator |+| `xyz_native_enter/exit()` | publish frame, set `IN_NATIVE` |+| `xyz_pin(obj)` / `xyz_unpin(obj)` | set `PINNED`, for FFI |+| `xyz_root_add/remove(slot*)` | global roots |+| `xyz_wb(obj)` | only if mutable cells exist |++## 9. C++23 coding rules++- `-fno-exceptions -fno-rtti`, no libstdc++ allocation on any GC path; the runtime owns its memory via `mmap`.+- `constexpr` for all layout constants. Use `std::countr_zero` and `std::bit_ceil` for line and block math.+- `[[likely]]`/`[[unlikely]]` and `[[assume]]` (alignment) on hot paths; `std::unreachable()` in impossible states.+- `std::expected` for OS failures; `std::start_lifetime_as` for header and side-table views where the toolchain supports it.+- `alignas(std::hardware_destructive_interference_size)` on per-thread state and deques.+- SIMD behind one small abstraction with AVX2, NEON, and scalar paths; verify all three agree in tests.++## 10. Verification and milestones++**Debug modes:** `XYZ_GC_STRESS=n` (collect every n allocations), poison freed lines (`0xDD`) and ASan-poison them, a heap verifier run before and after every GC (every reachable reference points into a live line, no dangling forwards, line marks cover all live objects), and a deterministic seed for work-stealing order.++| Milestone | Scope |+| --- | --- |+| M0 | Single-threaded, non-moving, full GC, statepoints and stack maps working |+| M1 | Parallel marking and sweep, SIMD hole finding |+| M2 | Opportunistic evacuation, pinning |+| M3 | Sticky minor GCs, no barrier |+| M4 | Tuning: huge pages, prefetch depth, NUMA-aware block caches |+++- Pin those objects.+- Use registered handles.+- Leave the native region before collection proceeds.++A collector must never move an object while native code may still be dereferencing its old address.++### 5.2 Evacuation-set selection++Evacuation is opportunistic.++The collector examines fragmentation statistics from the previous cycle.++Candidate blocks are ranked by:++1. Lowest live-line ratio.+2. Highest number of reusable holes.+3. Lowest evacuation cost.+4. Lowest number of pinned objects.++Blocks containing pinned objects may be excluded.++The collector selects blocks until their live data fits into the available evacuation target space.++Default target reserve:++- At least 2% of the heap.+- At least eight blocks.++Evacuation must be disabled when the available target capacity is insufficient.++### 5.3 Root discovery++Roots are obtained from:++1. Compiler-generated shadow-stack frames.+2. Global root registrations.+3. Registered native handles.+4. Pinned object registrations.+5. Runtime-owned roots.++No arbitrary register scanning is performed.++No arbitrary machine-stack scanning is performed.++The collector does not need to understand the machine register allocator.++### 5.4 Parallel marking++Each collector worker owns a mark stack.++Stacks use 1K-entry chunks.++Workers use a Chase-Lev work-stealing deque.++An eight-entry prefetch FIFO may be used between popping a reference and scanning its object.++The marking procedure:++1. Validate the object pointer.+2. Check its header.+3. Determine whether it has already been marked.+4. Atomically claim it if necessary.+5. Mark all intersecting lines.+6. Scan its pointer fields.+7. Push discovered references onto the worker's mark stack.++Object marking uses an atomic test-and-set or compare-and-exchange operation.++Line metadata updates must be atomic or otherwise synchronized between workers.++### 5.5 Evacuation++When an object belongs to an evacuation-source block:++1. Check whether it is pinned.+2. Atomically transition its header to `BUSY`.+3. Allocate destination storage.+4. Copy the object.+5. Publish the forwarding pointer with release semantics.+6. Return the destination address.++Other workers encountering `BUSY` wait until forwarding is published.++Workers encountering a forwarded object follow its forwarding pointer.++Objects outside evacuation-source blocks are marked in place.++Every scanned reference slot is rewritten to the resolved address.++Root slots are also rewritten.++The collector must ensure that each object is scanned exactly once after its final address has been resolved.++### 5.6 Sweeping++Sweeping runs in parallel after marking and evacuation complete.++For each ordinary block:++1. Count live lines.+2. Identify contiguous dead-line regions.+3. Calculate the remaining hole count.+4. Update block state.+5. Reclassify the block.+6. Add reusable blocks or holes to the appropriate allocation lists.++Sweeping primarily operates on side metadata.++Object headers are not individually inspected during ordinary sweeping unless required for verification or block-specific processing.++Partially live lines are retained.++This is an intentional property of line-granularity reclamation.++### 5.7 Epoch management++The collector increments the major collection epoch after a successful full collection.++An epoch wrap requires clearing the affected metadata before reusing the epoch value.++The implementation must ensure that epoch reuse cannot cause stale marks to be interpreted as current marks.++### 5.8 LOS sweeping++LOS allocations are swept independently.++Unmarked objects are released.++Marked objects remain in place.++### 5.9 Heap resizing++The target heap size is:++`max(64 MiB, live_bytes * 1.5)`++The multiplier is configurable.++The collector may retain surplus committed blocks for subsequent allocations.++Unused pages are released after a configurable retention period.++---++## 6. Generational mode (sticky Immix, v3)++Generational collection is an extension of the primary Immix collector.++It relies on the immutable-object construction rule.++### 6.1 Generational allocation++New objects are allocated into nursery blocks.++Objects in nursery blocks may reference:++- Earlier nursery objects.+- Existing old-generation objects.++Old-generation objects cannot reference nursery objects.++Blocks have a generation field.++A block is promoted as a unit.++This avoids introducing mixed-generation object tracking into the line allocator.++### 6.2 Minor collection++Minor collection:++1. Stops mutators.+2. Enumerates roots.+3. Traces nursery references.+4. Stops traversal at old-generation objects.+5. Marks live nursery objects.+6. Reclaims dead nursery lines.+7. Promotes surviving nursery blocks.+8. Reinitializes nursery allocation state.++Old-generation objects are not recursively scanned.++No remembered set is needed because old objects cannot reference nursery objects.++Minor collections do not evacuate objects.++### 6.3 Promotion++Promotion happens at block granularity.++If a nursery block contains surviving objects, the entire block becomes old-generation storage.++Unmarked lines can be reused according to normal Immix reclamation rules.++This may retain some dead space when live and dead objects share lines.++That trade-off is intentional.++### 6.4 Full collection++Full collection:++- Advances the major epoch.+- Traces all reachable objects.+- Reclaims both generations.+- Performs normal evacuation.+- Promotes surviving objects into the old generation.++### 6.5 Collection triggers++A full collection is triggered when:++- Old-generation growth exceeds a configured threshold.+- Fragmentation exceeds a threshold.+- The heap growth budget is exhausted.+- A configurable number of minor collections have elapsed.++Generational mode is optional and should not complicate the initial implementation.++---++## 7. UQBE integration++This replaces the entire LLVM integration section.++UQBE is responsible for generating machine code and ordinary calls into the xyz runtime.++The collector does not depend on LLVM.++### 7.1 Backend model++The compilation pipeline is:++```text+xyz source+    |+    v+xyz frontend+    |+    v+xyz IR+    |+    +---- Type descriptors+    |+    +---- Managed-pointer liveness+    |+    +---- Safepoint identification+    |+    +---- Root-frame generation+    |+    v+UQBE IL+    |+    v+UQBE backend+    |+    v+Native object code+    |+    v+xyz linker+    |+    v+Executable + xyz runtime+```++UQBE continues to handle:++- SSA lowering.+- Register allocation.+- Instruction selection.+- Calling-convention lowering.+- Stack-frame generation.+- Native code emission.++The frontend handles GC-specific correctness.++### 7.2 No special GC instructions++The initial implementation requires no GC-specific UQBE IL instructions.++All collector operations are represented through ordinary function calls and stack-slot operations.++This is deliberate.++QBE's existing scalar IL is sufficient for the required integration.++Architecture-specific optimizations remain inside UQBE or the C++ runtime.++### 7.3 Shadow-stack root frames++Instead of parsing LLVM stack maps or attempting to reconstruct roots from arbitrary machine instructions, xyz uses explicit shadow-stack frames.++Each managed function that can participate in collection receives a compiler-generated root frame.++Conceptually:++```cpp+struct RootFrame {+    RootFrame* previous;+    const RootMap* descriptor;+    void** slots;+};+```++The descriptor identifies the managed-reference slots.++The frame is linked into the current mutator's root chain.++On function entry:++```cpp+xyz_root_enter(&frame);+```++On function exit:++```cpp+xyz_root_leave(&frame);+```++The runtime maintains the root-frame chain in thread-local mutator state.++The frame must remain valid for the complete duration of its registration.++### 7.4 Root slots++Every managed reference that must survive a safepoint has an associated root slot.++The compiler emits stores into those slots before a potentially collecting call.++After the call, relocated references are reloaded into their corresponding SSA values.++Conceptually:++```text+store managed_pointer, root_slot++call xyz_alloc_slow++managed_pointer = load root_slot+```++The runtime updates the root slots during evacuation.++This guarantees that register allocation cannot accidentally hide a managed pointer from the collector.++The compiler must calculate liveness at each safepoint and ensure every live managed reference is represented.++Dead references need not be published.++### 7.5 Root-map descriptors++Root maps are generated by the xyz frontend.++A descriptor contains:++- Number of root slots.+- Slot offsets or indices.+- Managed-reference type information where required.+- Frame size.+- Optional debugging metadata.++A static descriptor is emitted into the executable's read-only data section.++The runtime receives a pointer to this descriptor when entering a root frame.++There is no runtime stack-map parser.++There is no return-address hash table.++There is no LLVM `.llvm_stackmaps` section.++### 7.6 UQBE stack slots++Root slots are represented using ordinary UQBE stack allocation.++For example, conceptually:++```text+%root =l alloc8 8+storel %object, %root+```++The frontend must ensure that root slots are not optimized away or invalidated before a collection.++This requires treating the root-frame registration and root-slot accesses as observable memory operations.++If necessary, the frontend should introduce explicit runtime calls around safepoints to prevent invalid compiler transformations.++The UQBE optimizer must preserve the required memory dependencies.++### 7.7 Safepoint polls++The frontend inserts ordinary calls to:++```cpp+xyz_gc_poll()+```++Polls are required at:++- Loop back-edges.+- Recursive function entry.+- Potentially unbounded execution paths.+- Allocation slow paths.+- Explicit runtime safepoints.++The fast path reads a thread-local poll flag and returns immediately when no collection is requested.++A guard-page implementation may be introduced later.++### 7.8 Calls that may collect++Every function that may trigger collection must be identified by the frontend.++The compiler must distinguish:++- Functions that cannot collect.+- Functions that may collect.+- Functions that enter native code.+- Functions that allocate managed objects.++A function that calls another potentially collecting function must preserve all live managed references across that call.++This is ordinary interprocedural effect propagation.++### 7.9 Allocation lowering++Managed allocations use two paths.++**Inline allocation**++The frontend emits direct cursor/limit operations against the current mutator.++The generated code initializes the object header and returns the managed pointer.++**Slow allocation**++The frontend emits an ordinary call:++```cpp+extern "C" void* xyz_alloc_slow(+    u32 size,+    u32 type_id+);+```++The function may collect.++All live managed references must be published before entering it.++Unlike LLVM, UQBE does not need allocation-specific attributes or `allockind` metadata.++Escape analysis remains a frontend optimization.++Non-escaping objects may be stack-allocated when their lifetimes and semantics permit it.++### 7.10 Derived pointers++Managed references stored in the heap and shadow stack are always object-base pointers.++Interior pointers are not permitted to survive safepoints.++If the compiler generates a temporary derived pointer into an object payload, it must either:++- Recompute it after the safepoint using the relocated base pointer.+- Preserve the base pointer and byte offset, then reconstruct the derived pointer.++The collector never needs to relocate arbitrary interior pointers.++### 7.11 Native ABI++The runtime is compiled independently from UQBE.++The frontend and runtime agree on the platform's C ABI.++UQBE is responsible for selecting the correct target calling convention.++The runtime must support the calling conventions implemented by the corresponding UQBE target, including:++- System V AMD64.+- Microsoft x64.+- AArch64 platform ABIs.++The collector must not depend on a particular register assignment or machine stack layout.++### 7.12 Object files and linking++The collector runtime is a static library:++`libxyzrt.a`++The executable links against it using the normal xyz linking pipeline.++The runtime does not link against UQBE.++UQBE does not link against the collector.++This preserves the separation between compiler, backend, and runtime.++---++## 8. Runtime ABI++The runtime exposes a small C-compatible interface.++| Symbol | Purpose |+|---|---|+| `xyz_alloc_slow(size, type_id)` | Slow managed allocation |+| `xyz_alloc_large(size, type_id)` | LOS allocation |+| `xyz_gc_poll()` | Safepoint poll |+| `xyz_gc_collect()` | Explicit collection request |+| `xyz_thread_attach()` | Register a mutator |+| `xyz_thread_detach()` | Unregister a mutator |+| `xyz_root_enter(frame)` | Register a shadow-stack frame |+| `xyz_root_leave(frame)` | Unregister a shadow-stack frame |+| `xyz_root_add(slot)` | Register a global root |+| `xyz_root_remove(slot)` | Remove a global root |+| `xyz_native_enter()` | Enter a GC-safe native region |+| `xyz_native_exit()` | Leave a GC-safe native region |+| `xyz_pin(obj)` | Pin a managed object |+| `xyz_unpin(obj)` | Unpin a managed object |+| `xyz_wb(obj, slot, value)` | Future mutable-object barrier |++All public entry points use C linkage.++The runtime must document which functions may trigger collection.++---++## 9. C++23 runtime implementation++### 9.1 Compilation++The runtime is built independently from the compiler.++Recommended flags:++```text+-std=c++23+-fno-exceptions+-fno-rtti+```++No LLVM headers or libraries are required.++The runtime must not use general-purpose standard-library allocation on collector-critical paths.++Memory ownership is handled through platform virtual-memory primitives.++### 9.2 Memory management++The runtime uses:++- `mmap` / `munmap` on Linux.+- `VirtualAlloc` / `VirtualFree` on Windows.+- `mmap` / `munmap` on macOS.++Platform-specific functionality is isolated behind a small memory abstraction.++OS failures are reported through an explicit error mechanism.++`std::expected` may be used for non-critical initialization and configuration paths.++### 9.3 Layout++All layout constants are `constexpr`.++Use:++- `std::countr_zero` for bit operations.+- `std::bit_ceil` for capacity calculations.+- `std::memcpy` for object copying.+- Explicit atomic operations for concurrent metadata.+- `alignas(std::hardware_destructive_interference_size)` for per-thread state.++Use `std::start_lifetime_as` where supported and appropriate.++Do not assume that C++ object lifetime rules automatically permit arbitrary typed access to reserved virtual memory.++### 9.4 SIMD++SIMD is implemented inside the C++ runtime.++The initial abstraction supports:++- AVX2.+- NEON.+- Scalar fallback.++SIMD is used for:++- Line metadata scanning.+- Hole discovery.+- Zeroing.+- Live-line counting.+- Selected bitmap operations.++UQBE does not need first-class vector instructions for the initial collector.++Architecture-specific SIMD code must be tested against the scalar implementation.++### 9.5 Concurrency++The collector uses:++- Atomic block ownership.+- Atomic object-marking state.+- Atomic forwarding publication.+- Parallel work-stealing queues.+- Stop-the-world synchronization.++The implementation must avoid ABA problems in global block lists.++Thread-local allocation state must be isolated to avoid false sharing.++---++## 10. Verification and testing++### 10.1 Debug modes++Environment variables:++```text+XYZ_GC_STRESS=1+XYZ_GC_VERIFY=1+XYZ_GC_POISON=1+XYZ_GC_LOG=1+XYZ_GC_DISABLE_EVAC=1+XYZ_GC_DISABLE_GENERATIONAL=1+```++`XYZ_GC_STRESS` forces collection after a configurable number of allocations.++`XYZ_GC_VERIFY` enables heap verification before and after collection.++`XYZ_GC_POISON` poisons reclaimed memory.++`XYZ_GC_LOG` prints collection statistics.++### 10.2 Heap verification++The verifier checks:++- Every reachable reference points to a valid managed object.+- Every reachable object has a valid type descriptor.+- Every live object intersects appropriately marked lines.+- No object contains an invalid managed reference.+- No forwarded object contains an invalid forwarding address.+- No two mutators own the same allocation block.+- No live pinned object has moved.+- No evacuated source block is released while references to it remain.+- No root frame references invalid stack storage.++### 10.3 Stress testing++Tests must cover:++- Allocation without collection.+- Repeated full collections.+- Collection during recursive execution.+- Collection during nested function calls.+- Objects containing references.+- Arrays of references.+- Objects spanning multiple lines.+- Medium and large allocations.+- Fragmented heaps.+- Multiple mutators.+- Concurrent marking workers.+- Evacuation races.+- Pinning and unpinning.+- Native calls.+- Thread attachment and detachment.+- Heap exhaustion.+- Epoch wraparound.+- Generational promotion.+- Dead objects sharing lines with live objects.++### 10.4 Sanitizers++Development builds should support:++- AddressSanitizer.+- UndefinedBehaviorSanitizer.+- ThreadSanitizer.++ASan poisoning must be coordinated with the allocator and collector.++TSan builds should exercise concurrent marking, forwarding, and block ownership.++### 10.5 Determinism++A configurable deterministic seed controls work-stealing order and stress-test scheduling.++This allows GC failures to be reproduced more reliably.++---++## 11. Performance targets++These are engineering targets, not guaranteed performance claims.++| Metric | Target |+|---|---|+| Inline allocation | Approximately 6 instructions |+| Small-object allocation | No locks |+| Fast safepoint poll | One predictable branch |+| Side metadata | Approximately 0.83% of reserved heap |+| Marking | Parallel |+| Sweeping | Parallel |+| Evacuation | Opportunistic |+| Write barriers | None for immutable objects |+| Runtime LLVM dependency | None |+| Stack-map parsing | None |+| Register scanning | None |++The most important optimization priority is maintaining a cheap allocation path.++Collection throughput is secondary to avoiding unnecessary overhead on ordinary object creation.++---++## 12. Implementation milestones++| Milestone | Scope |+|---|---|+| M0 | Single-threaded, non-moving full Immix collector |+| M1 | UQBE shadow-stack integration and compiler-generated root maps |+| M2 | Safepoint rendezvous and multi-threaded allocation |+| M3 | Parallel marking and sweeping |+| M4 | Opportunistic evacuation and forwarding |+| M5 | Pinning and native interoperation |+| M6 | Sticky generational collection |+| M7 | Huge pages, prefetching, SIMD tuning, NUMA-aware block caches |++### M0 — Basic collector++Implement the heap reservation, block allocator, type descriptors, marking, and sweeping.++No evacuation or generational mode.++### M1 — UQBE integration++Implement root-frame generation in the xyz frontend.++Generate ordinary UQBE stack-slot operations and calls to the runtime.++Verify that a managed reference survives a collection across nested function calls.++This milestone establishes the compiler/runtime contract.++### M2 — Multithreading++Implement mutator registration, safepoint rendezvous, thread-local allocation, and concurrent collector workers.++### M3 — Parallel collection++Introduce work stealing, parallel tracing, parallel sweeping, and SIMD line discovery.++### M4 — Evacuation++Implement forwarding, destination allocation, reference rewriting, and fragmentation-driven evacuation.++### M5 — Native interoperation++Implement pinning, native handles, native-region registration, and safe transitions between managed and native execution.++### M6 — Generational collection++Introduce nursery blocks, sticky marking, block promotion, and minor collection.++### M7 — Tuning++Optimize memory commitment, huge-page usage, NUMA placement, prefetching, and allocator locality.++---++## 13. Final architectural constraints++The following properties are mandatory:++1. The runtime must not depend on LLVM.+2. UQBE must not require LLVM-style statepoint support.+3. All managed roots must be explicitly published.+4. All heap references must be precise object-base pointers.+5. No managed pointer may remain hidden in an untracked register across a safepoint.+6. No object may be moved while native code can still dereference its old address.+7. No old-generation object may acquire a reference to a nursery object.+8. Allocation blocks must have exclusive mutator ownership.+9. Evacuation must never release a source block before all references have been rewritten.+10. The normal allocation path must remain independent of collector synchronization.++**The collector is a runtime subsystem, not a compiler backend feature. UQBE only needs to generate the correct allocation operations, root-frame accesses, and safepoint calls.**