Skip to content

Codegen: a type's body is defined before anything sizes it — an enum above its payload types keeps its payload (#1430) - #1449

Merged
ehartford merged 1 commit into
fixture-1424from
fix-1430-enum-layout-order
Sep 23, 2026
Merged

ehartford merged 1 commit into
fixture-1424from
fix-1430-enum-layout-order

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1430. Fixes #1448.

Root cause (exact line, lldb on a stage2 of origin/main 1c76062)

Codegen.declare_enum_type, src/Codegen.w:4042 let sz = self.abi_size_of(payload_ty), called from Pass 0b (src/Codegen.w:6294) in declaration order. For enum Outer: Inner(i: InnerE) above enum InnerE, the breakpoint on LLVMABISizeOfType from that line shows the payload { %InnerE } with LLVMCountStructElementTypes(%InnerE) = 0 (a bodiless placeholder from Pass 0a); the call returns 0, and src/Codegen.w:4061 sets %Outer's body with 1 element — { i32 }, no payload array. Every read of the payload is then out of bounds: got 0 for an enum payload, an SROA abort (DataLayout::getIndexedOffsetInType → reportFatalInternalError) for a struct payload, and the §10.9 Display BUG for error AppError from DbError. The same eager sizing sat in the generic-enum instance (get_or_create_generic_enum_type), Result, discriminant-enum and @[align] struct paths; and a payload-less discriminant enum or a bitpacked struct referenced before its declaration resolved to its bodiless placeholder instead of its repr/backing integer (LLVM verifier: "Cannot allocate unsized type").

Fix

  • Bodies are defined in dependency order, in one place. Pass 0b still walks declarations in order, but a reference to a type whose body is pending — resolve_type, sema_type_to_llvm, mir_sema_type_to_llvm — defines that body first (define_type_body: its own module's context, no generic frame active). Depth first, so every body is defined after the bodies it holds by value: a topological order of the type graph, computed on demand while resolving it. A reference to a body being defined is legal only through an indirection (Box, Vec, pointers — Sema already rejects by-value cycles as a dependency loop) and returns the placeholder.
  • Cycle/placeholder detection at every layout query. abi_size_of and the new abi_align_of (now also used by the @[align] path instead of raw wl_abi_*) first prove that no bodiless named struct is reachable by value (layout_is_complete, memoized per LLVM type) and report BUG: ... (#1430) instead of sizing one. After Pass 0b every registered body must be defined (verify_type_bodies_defined). Once nothing is pending, the reference hook is a single integer compare.
  • Variant rows are reserved before recursion. Defining a body can now recurse into another declaration, so declare_enum_type, declare_disc_enum_type and get_or_create_generic_enum_type reserve their variant rows before resolving payloads, as structs already did (reserve_struct_fields). The generic path needed this regardless of order: an enum that is the first use of H[i64] got H's rows interleaved into its own range and segfaulted (Enum declared around the first use of a generic enum instance: variant rows interleave, match segfaults #1448).
  • wl_is_opaque_struct (LLVMIsOpaqueStruct) added to LlvmBridge.w for the check.

TypeLayout.w is not changed: the emitted enum layout is derived in Codegen (LLVM DataLayout over the payload structs), and Sema's model disagrees with the emitted types for Option / Option[&T] / dyn fat pointers (#1438), so reading enum bodies from TypeLayout would have changed layouts of correctly ordered programs. Making TypeLayout the single layout authority is #1438.

Matrix (base stage2 of 1c76062 → this branch's release build)

case before after
enum payload = later enum (issue repro) got 0 got 7
enum payload = later struct (issue repro) LLVM ERROR (SROA abort) struct-in-enum 8
error AppError from DbError, DbError later (issue repro) BUG: no payload value ... gen_display_enum_variant runs; fixture prints every field + Display
tuple (Later, LaterE, i64) x=5555555555555 y=5555555555555 … (garbage), B line missing all fields correct
Option[Later] / Option[LaterE] x=4329144336 …, then SIGTRAP correct
Result[Later, LaterE] ok x=0 y=0, err B 1 4344070160 correct
Vec[Later] correct (indirection) correct
nested two levels (A → B → C reversed) LLVM ERROR correct
mutual recursion through Box (either order) legal, correct legal, correct, same sizes as the other order
generic enum G[T] instantiated with a later type LLVM ERROR correct
generic struct Pair[Later] LLVM ERROR correct
alias to a later type LLVM ERROR correct
across modules (root enum over module types; module enum above its types) LLVM ERROR correct
struct holding Option[LaterE] / Result[Later, str] ok x=0 y=0 correct
discriminant enum with later payloads move x=1 y=1, Tag arm lost correct
payload-less discriminant enum declared later (field + payload) "wrong argument type … Cannot allocate unsized type" correct
bitpacked struct declared later (payload + nested) "Cannot allocate unsized type" correct
@[align] struct over later types size 32 (ordered: 64) size 64 (field reads: #1445)
enum = first use of a generic enum instance (#1448) SIGSEGV correct
by-value cycle enum↔enum / enum↔struct dependency loop dependency loop (unchanged; new fixture)
facade resource as an enum payload (enum Conn: Open(db: Database, …), origin/modeled-c-stage5 + this patch) LIBCLANG FATAL ERROR (TypeSize) open id=4242 …, debug-alloc leak count=0
error AppError from DatabaseError over the stage-5 ok projection (same) BUG: no payload value … while formatting Failed / FailedWithResource / Ok all match; leak count=0

The stage-5 rows were run on a scratch worktree of origin/modeled-c-stage5 with this commit applied; this PR is based on origin/main and contains no facade code. With the patch, 15 of the 17 stage-5 behav_c_facade_* fixtures pass on its stage1; the other two fail identically on the unpatched stage-5 stage1 (memchr arity in std/re/pcre2_match.w; the harness with check exits 127). (test/debug_alloc/da_c_facade_error_owns_resource.w on stage 5 notes it could not compose into AppError because of #1430; that fixture can grow the conversion once this lands.)

ABI decision (docs/abi_roadmap.md Level 0)

The convention did not change: §2 already says an enum's payload area is its largest variant laid out as a struct; the old code violated it only for programs whose payload types were declared later, and those programs were broken. Evidence for correctly ordered code:

  • The four .wo bundles (pcre2, zlib, c_algorithms, tommyds) rebuilt by this branch's stage1 are byte-identical (.o and .wi; same nm symbol count, same sizes) to the same bundles built by the base compiler with the wo-drift rebuild arguments.
  • 1344 behavior/codegen/spec fixtures compile (build --emit-obj -O1) to byte-identical objects with the base stage2 and with this branch's release compiler; 0 differ (40 fixtures do not build standalone with either compiler, identically).

docs/with-abi.sha256 is not re-recorded: neither ABI-defining source (src/FnAbi.w, src/TypeLayout.w) changed, and no WITH_ABI_VERSION bump. (The bundle key includes the compiler source hash, so every .wo slot rebuilds once anyway.) That the emitted enum layout lives in unhashed Codegen.w is itself a gap, filed as #1438.

Verification (iterate tier + audits, driven by the pinned seed; no full battery yet)

  • with check src/main.w: ok. src/main build :dev and :stage2: green (the fixed stage1 compiled the whole compiler through the new path without a single BUG report).
  • src/main build :drop-audit: 176 cells, 0 non-PASS, 0 regressions; against the base compiler as baseline every cell same.
  • src/main build :move-audit: 73 cells, 0 vs-expected FAIL; against the base compiler as baseline 0 DIFF (the 42 DIFF vs the seed are main's own changes since the seed).
  • New fixtures pass on the release build and fail on base: behav_1430_enum_payload_declared_later, behav_1430_type_bodies_any_order, behav_1430_error_from_declared_later, behav_1430_cross_module_declared_later, codegen/enum_layout_declaration_order (Late*/Early* pairs, sizes pinned, Sema's T.size() agrees for these shapes). behav_1430_box_recursion_any_order and type_cycle_enum_struct pass on both (legality/cycle guards). Under --debug-alloc all are leak-free except the §10.9 fixture, whose leak is the generated error Display leak already filed as IoError.to_str() leaks five allocations per call #1392 (identical with the types declared first, on base).

Draft until the seed-driven battery (build, :fixpoint, :test, :test-green) is run and posted.

Found and filed (not fixed here)

@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, new seed, alone as a layout change, with :drop-audit/:move-audit) on main 1c76062 + a163e31: build ok, :fixpoint ok, :drop-audit ok, :move-audit ok; :test red only on debug-alloc-tests / da_option_filter_observes_payload — main's known #1424 red, fixed by stack #1437. Merge after #1437.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 06:22
…above its payload types keeps its payload (#1430)

`enum Outer: Inner(i: InnerE)` above `enum InnerE` read `Outer.Inner(InnerE.A(7))`
back as 0; a later struct payload aborted in SROA; `error AppError from DbError`
above DbError died generating Display. Root cause, observed in lldb on a stage2
of origin/main: Codegen.declare_enum_type at Codegen.w:4042,
`let sz = self.abi_size_of(payload_ty)`, called from Pass 0b (Codegen.w:6294) in
declaration order, sized `{ %InnerE }` while %InnerE was still a bodiless named
struct (LLVMCountStructElementTypes = 0); LLVMABISizeOfType returned 0 and
Codegen.w:4061 set Outer's body to `{ i32 }` with no payload array. The generic
enum instance (Option/user generic), Result, discriminant-enum and @[align]
struct paths sized the same way, and a payload-less discriminant enum or a
bitpacked struct referenced before its declaration resolved to its bodiless
placeholder instead of its repr/backing integer.

Pass 0b still walks declarations in order, but a reference to a type whose body
is pending (resolve_type, sema_type_to_llvm, mir_sema_type_to_llvm) now defines
that body first, in its own module's context with no generic frame active —
depth first, so every body is defined after the bodies it holds by value: a
topological order of the type graph computed while resolving it. A reference to
a body still being defined is legal only through an indirection (Box, Vec,
pointers; Sema rejects by-value cycles as a dependency loop) and returns the
placeholder. Every LLVM layout query (abi_size_of, the new abi_align_of used by
the @[align] path) first proves no bodiless named struct is reachable by value
and reports a BUG instead of sizing one, so no layout is ever computed from a
placeholder again; after Pass 0b every registered body must be defined.

Declaring a body can now recurse into another declaration, so each enum and
discriminant enum reserves its variant rows before resolving payloads, as
structs already did (reserve_struct_fields). The generic-enum path needed the
same reservation independently of order: `enum Plain: P(h: H[i64]) | Q(n: i64)`
instantiating H[i64] during Plain's declaration interleaved H's variant rows
into Plain's range and segfaulted.

ABI: no convention change for a correctly ordered program. The four .wo bundles
(pcre2, zlib, c_algorithms, tommyds) rebuilt by the fixed compiler are byte-
identical (.o and .wi) to the base compiler's, and 1344 behavior/codegen/spec
fixtures compile to byte-identical objects. docs/with-abi.sha256 is untouched:
neither ABI-defining source (FnAbi.w, TypeLayout.w) changed.

Fixtures: behav_1430_enum_payload_declared_later (enum, struct, tuple, Option,
Result, Vec, generic enum/struct, alias, nested three levels in reverse order),
behav_1430_type_bodies_any_order (struct via Option/Result, discriminant enum
with and without payloads, bitpacked), behav_1430_error_from_declared_later
(§10.9), behav_1430_cross_module_declared_later, behav_1430_box_recursion_any_order
(mutual recursion through Box stays legal), type_cycle_enum_struct (a by-value
cycle is still a loud error), codegen/enum_layout_declaration_order (Late*/Early*
pairs lay out identically; sizes pinned; Sema's model agrees).
@ehartford

Copy link
Copy Markdown
Contributor Author

Stack #1466 battery (seed-driven, new seed, cold c_import cache, with :drop-audit/:move-audit) on main 1c76062 + #1418 → #1419 → #1425 → #1428 → #1449 → #1377 → #1459 → #1460 → #1461 → #1462 (head cf36211, including the #1449/#1462 Codegen resolution and the fixed #1460): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Each branch holds exactly its tested commits on the layer below. Merge the whole stack: gh stack merge 1462 --squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant