Skip to content

Memory Model

Buntos edited this page Dec 5, 2026 · 1 revision

Memory Model

H provides a hybrid memory model that combines garbage-collected ergonomics with deterministic, zero-GC systems primitives in the same codebase. Program entry initializes Boehm GC (libgc) via hl_init_args(argc, argv) -> GC_init(), while hot paths and FFI boundaries can opt into stack-allocated struct values, inline StaticArray[T, N], scoped bump arenas (with_arena), manual Heap allocation, and compile-time @[nogc] verification.


1. LLVM ABI & Memory Layout Reference

The following table documents the exact LLVM IR representation emitted by hlc on 64-bit targets (x86-64 and AArch64):

H Type LLVM IR Type Size (64-bit) Storage / Semantics
Bool i1 1 byte Value
I8, U8 i8 1 byte Value
I16, U16 i16 2 bytes Value
I32, U32 i32 4 bytes Value
I64, U64, Usize i64 8 bytes Value
F32 float 4 bytes Value
F64 double 8 bytes Value
String { ptr, i64 } 16 bytes Immutable value; ptr points to base of .rodata or GC_malloc_atomic(len + 1) buffer
Slice[T] { ptr, i64 } 16 bytes Non-owning view { ptr, len }
Array[T] ptr 8 bytes Pointer to 24-byte GC-allocated HlArray { data: ptr, len: i64, cap: i64 }
StaticArray[T, N] [N x T] N * sizeof(T) Inline unboxed fixed-size array
Ptr[T] ptr 8 bytes Non-nullable raw pointer
Arena ptr 8 bytes Pointer to HlArena bump allocator header
struct S %S = type { ... } Sum of aligned fields Unboxed inline value (@[repr(C)] preserves C field order)
class C ptr 8 bytes Pointer to GC-allocated %C = type { ... } object (GC_malloc)
Simple enum i32 4 bytes 0-based variant tag
Payload enum { i32, [W x i64] } 8 + W * 8 bytes i32 tag plus 8-byte-aligned payload storage sized to largest variant
@[nogc] Fn(...) -> R ptr 8 bytes Direct C-ABI function pointer
Fn(...) -> R { ptr, ptr } 16 bytes Fat closure { fn_ptr, env_ptr }; fn_ptr takes hidden env_ptr as arg 0
T? (NPO eligible) ptr 8 bytes Null-Pointer Optimization (null represents nil)
T? (non-NPO) { i1, T } align(T) + sizeof(T) Explicit presence flag + inner payload

2. GC classes vs. Value structs & mut def

Garbage-Collected class

  • Instances are allocated on the Boehm GC heap via hl_gc_alloc(sizeof(C)) (GC_malloc).
  • Values of type C are 8-byte reference pointers; passing or assigning a class copies the pointer without cloning fields.
  • Methods always receive self as a pointer and may mutate @field directly without mut def.
  • Because allocating a class invokes the GC, MyClass.new(...) is rejected inside @[nogc] functions.

Unboxed Value struct

  • Instances are unboxed values allocated on the stack, inside registers, or embedded directly inside other aggregates, StaticArrays, or arenas.
  • Constructing Vec2.new(3.0, 4.0) performs zero heap allocation and is legal inside @[nogc].
  • Adding @[repr(C)] guarantees C-compatible field order and padding for FFI structs.
  • Immutability by default: struct parameters and non-mut methods cannot assign to @field.
  • In-place mutation (mut def): Declaring a method mut def scale(factor: F64) -> Void passes self as a hidden Ptr[Vec2] pointing to the caller's storage. Calling a mut def method on a const binding or temporary rvalue (such as Vec2.new(1.0, 2.0).scale(2.0)) is a compile-time error.
  • Parameter passing ABI: In the bootstrap compiler (src/codegen.zig), immutable struct, StaticArray, and enum parameters <= 16 bytes pass by value in registers while larger values (> 16 bytes) pass via hidden const-pointer without copying.
@[repr(C)]
struct Vec2
  x: F64
  y: F64

  @[nogc]
  def dot(other: Vec2) -> F64
    @x * other.x + @y * other.y
  end

  @[nogc]
  mut def scale(factor: F64) -> Void
    @x *= factor
    @y *= factor
  end
end

3. String Layout, Base-Pointer Invariant & .rodata Coercion

String is an immutable 16-byte value { ptr: Ptr[U8], len: Usize } passed in two registers.

Base-Pointer & Atomic GC Invariant

Every String.ptr obeys two invariants:

  1. Base address only: ptr always points to byte 0 of either a static .rodata literal or a GC allocation — never an interior pointer offset.
  2. Pointer-free NUL-terminated buffer: Runtime-created strings are allocated via hl_gc_alloc_atomic(len + 1) (GC_malloc_atomic + zero-fill) with ptr[len] == 0. Because atomic GC blocks are never scanned for pointers and ptr is never offset into the interior of a block, Boehm GC retention stays precise and scanning overhead is avoided.

Zero-Copy Substrings (Slice[U8])

Because String.ptr must remain a base pointer, s.slice(start, stop) validates bounds via hl_slice_check(start, stop, s.len) and returns a zero-copy Slice[U8] ({ ptr + start, stop - start }, not NUL-terminated) rather than a String. Materializing an owned String from a slice uses sub.to_string (which copies into a fresh NUL-terminated atomic GC buffer via hl_str_from_bytes).

Plain Literals vs. Dynamic Strings at C Boundaries

Form Storage Allowed in @[nogc]? Passing to C Ptr[U8]
Plain literal "hello\n" Static .rodata (LLVMBuildGlobalStringPtr) Yes Implicitly coerces to Ptr[U8] at compile time
Interpolated "x=#{x}" or a + b GC atomic heap (GC_malloc_atomic) No Explicit s.cstr (O(1) extraction of s.ptr)
String.from_cstr(p) / String.from_bytes(p, n) GC atomic heap No Explicit s.cstr

When passing s.cstr to a C function, s must remain live for the duration of the C call.


4. Scoped Bump Arenas (with_arena)

with_arena(initial_cap) do |scratch| ... end creates a fast bump-pointer allocator backed by chained malloc blocks and destroys every block automatically when the scope exits (including via return, break, next, or ? propagation).

Runtime Layout (runtime/hl_runtime.hl)

@[repr(C)]
struct HlArenaBlock
  prev: Ptr[HlArenaBlock]?
  cap: Usize
  used: Usize
  # Followed immediately at byte offset 24 by `cap` bytes of payload storage
end

@[repr(C)]
struct HlArena
  current: Ptr[HlArenaBlock]?
  default_block_size: Usize
end
  • hl_arena_create(initial_cap) sets default_block_size to initial_cap if >= 256 bytes, or 4096 bytes otherwise.
  • arena.alloc[T]() calls hl_arena_alloc(arena, sizeof(T), alignof(T)), bumps blk.used to the required alignment boundary (chaining a new HlArenaBlock if the current block overflows), zero-initializes the memory via memset, and returns Ptr[T].
  • arena.alloc_slice[T](count) allocates count * sizeof(T) aligned zeroed bytes and returns Slice[T].
  • hl_arena_destroy(arena) walks blk.prev freeing all blocks and the HlArena header.

All arena operations are @[nogc]:

@[nogc]
def build_buffer(n: Usize) -> I32
  with_arena(1024) do |scratch|
    pkt = scratch.alloc[Packet]()
    pkt.id = 7
    sl = scratch.alloc_slice[I32](n)
    sl[0] = 42
    return sl[0]
  end
  0
end

5. Manual Heap Allocation (Heap.alloc / Heap.free)

For long-lived allocations that must outlive a lexical scope without GC overhead (for example, OS synchronization primitives like pthread_mutex_t in std/thread whose address must not move or confuse GC), H provides @[nogc] manual heap intrinsics:

  • Heap.alloc[T]() -> Ptr[T] — calls hl_manual_alloc(sizeof(T)) (calloc(1, size), panicking on OOM).
  • Heap.free(ptr) -> Void — calls hl_manual_free(ptr) (free(ptr)).

Pair Heap.alloc with defer Heap.free(p) or an explicit destroy() method:

@[nogc]
def use_manual_slot() -> I64
  slot = Heap.alloc[I64]()
  defer Heap.free(slot)
  slot.* = 99
  slot.*
end

6. Ptr[T] Operations & Single-Level Auto-Deref

Ptr[T] is a non-nullable typed raw pointer (use Ptr[T]? when nil is possible).

  • Single-level auto-dereference: When p has type Ptr[StructType], p.field reads or writes the field and p.method(...) invokes the method by dereferencing one pointer level automatically ((*p).field). Nested Ptr[Ptr[T]] does not auto-deref multiple levels.
  • Explicit dereference (p.*): Reads or writes the pointee (slot.* = 42, v = slot.*). Dereferencing Ptr[Void] is a compile-time error.
  • Pointer indexing (p[i]): Indexes i elements from p (unchecked C-style pointer arithmetic).
  • Pointer arithmetic (p.offset(delta: I64) -> Ptr[T]): Emits LLVM getelementptr by delta elements of type T.
  • Reinterpretation casts:
    • p.as_ptr[U]() -> Ptr[U] — reinterprets a pointer to another element type (zero runtime cost under opaque LLVM pointers).
    • p.as_fn[@[nogc] Fn(Args...) -> R]() — casts a raw code pointer (e.g., from objc_msg_lookup or CoreCLR hostfxr) into a callable raw function pointer.
    • (&raw_fn).as_ptr[Void]() — casts a @[nogc] function pointer to Ptr[Void].
    • int_val.as_ptr[T]() — converts an integer to Ptr[T] via inttoptr (used for sentinel constants such as -1 in hostfxr).

7. Null-Pointer Optimization (NPO) for Optionals (T?)

In compiler/codegen.hl, opt_uses_npo(inner) determines whether T? uses a compact 8-byte null-pointer encoding instead of a tagged { i1, T } struct:

def opt_uses_npo(inner: TypeRef) -> Bool
  if inner.kind == TypeKind.ptr_t or inner.kind == TypeKind.array_t
    return true
  end
  if inner.kind == TypeKind.fn_t and inner.fn_nogc
    return true
  end
  self.is_class_type(inner)
end
  • NPO types (8 bytes, zero tag overhead): Ptr[T]?, Array[T]?, (@[nogc] Fn(...) -> R)?, and MyClass?. Checking != nil emits a single icmp ne ptr %v, null (LLVMBuildIsNotNull), and unwrapping is a zero-cost no-op.
  • Tagged optionals ({ i1, T }): Primitives (I64?, Bool?, F64?), String?, Slice[T]?, StaticArray[T, N]?, struct?, enum?, and general fat Fn(...) -> R?. Presence is stored in field 0 (i1) and payload in field 1 (T).

8. @[nogc] Compile-Time Verification Rules

Functions and methods annotated with @[nogc] are statically checked by mark_gc_op during compilation to guarantee zero Boehm GC allocations. Inside any @[nogc] function or method, the compiler rejects:

  1. Calling non-@[nogc] H code: Calling any H function, method, generic instantiation, or Fn callback not marked @[nogc]. (extern "C" declarations are always permitted in @[nogc].)
  2. Class instantiation: Calling ClassName.new(...) (which invokes hl_gc_alloc).
  3. GC string operations: String interpolation ("#{...}"), String concatenation (+), String.from_cstr(...), String.from_bytes(...), and Slice[U8].to_string. (Plain string literals in .rodata, s.len, s.cstr, s.slice(a, b), and s[i] are all @[nogc].)
  4. GC collection allocations: Heap Array literals ([1, 2, 3] without a StaticArray[T, N] type annotation), Array[T].new(), and arr.push(...). (Use StaticArray[T, N] or arena.alloc_slice[T](n) instead; reading arr.len, arr.cap, arr[i], and arr.pop() does not allocate.)
  5. Capturing closures: Any fn(...) do ... end closure that captures outer local variables (since its environment struct is allocated via hl_gc_alloc). Stateless closures with @[nogc] bodies, &nogc_fn function pointers, and inlined do |x| ... end blocks (each, times, yield) are all permitted in @[nogc].

Closure ABI & Auto-Boxing

  • A @[nogc] Fn(A) -> R is an 8-byte raw function pointer with signature (A) -> R, directly ABI-compatible with C function pointers.
  • A general Fn(A) -> R is a 16-byte struct { fn_ptr: Ptr[Void], env_ptr: Ptr[Void]? } whose fn_ptr accepts (env_ptr: Ptr[Void]?, A) -> R.
  • When a raw @[nogc] Fn(A) -> R is passed where a general Fn(A) -> R is expected, coerce_val automatically synthesizes a lightweight wrapper thunk (__hl_raw_thunk_N) that discards the env_ptr argument and forwards to the raw function pointer, returning { thunk_ptr, null }.

Next: Generics and Interfaces

Clone this wiki locally