Skip to content

#1647 phases 2–4 completion: owner facts in codegen, per-instance Sema facts, projection declaration indexes (D65) - #2029

Merged
ehartford merged 12 commits into
fix-2017from
wave-d65b
Oct 3, 2026
Merged

ehartford merged 12 commits into
fix-2017from
wave-d65b

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

#1647 phases 2–4 completion (D65), on top of #2012.

Commits:

  • 8090ae5f..99f224e (rebased from wave-d65): reference place pointer from owners; sizeof/alignof from Sema; struct field LLVM types from Sema; field GEP index from Sema's declaration; closure capture modes from Sema's capture record.
  • Closure literal into a generic method — the GENERIC_CALL method arm registered a by-value closure literal's move only for machinery dispatch; a user generic method's specialization dropped it, and so did the caller (debug allocator: DOUBLE FREE of __closure_env_drop_1; ownership validator red on behav_gen_push_generic_and_methods, also on main). Validator verdicts now name bodies (fn sym1327(collect__sema__…)). Fixture: test/debug_alloc/da_closure_literal_into_generic_method.w.
  • Per-instance Sema facts — Sema records index element/base and field type/owner/declaration index keyed (specialization, node); MIR reads the index element from it (MirBody.instance_sym), named field projections carry Sema's declaration index (MirBody.proj_decl), codegen GEPs from it. audit:resolution judges every specialization body (was: 2 index places unjudged over src/main.w; the new fixture showed 2 field-place violations from last-instance types).
  • Generic struct instances from Sema — get_or_create_generic_struct_type(tid); monomorphize_struct_nodes (fields resolved under LLVM bindings, LLVM→Sema mapping) deleted.
  • Docs status + deep-debug-tool-tests entries.

Evidence: with-stage1 analyze src/main.w audit:all violations=0 (index-places 17441, 2 in specializations, unjudged 0; field decl indexes 70275; field projection index 224327 disagree 0). :gate green, :deep-debug-tool-tests green, :drop-audit green, 247 generics/struct/index/closure behavior tests green on stage1.

Remaining for phase 5: generic struct instance symbol text still spelled from LLVM arg types; lower_callable_expr observe-vs-move; ident-callee dispatch; sym_is_generic_fn; facades in MIR.

Eric Hartford added 12 commits October 3, 2026 05:01
…not the slot's LLVM type or the name `self` (#1647, D65)

mir_try_place_ptr_for_ref decided three things from representation and
syntax: whether an SSA local's value is its value's address (LLVM ptr,
or the local is named `self`, or its Sema type lowers to a non-pointer),
whether an unprojected slot holds a pointer value to load (the alloca's
or the local's LLVM type is `ptr`), and whether a local is indirect
(name `self` again, the LLVM shape of its Sema type).
mir_operand_local_holds_pointer re-derived the second from the LLVM type
for the marshalling fact.

Each now calls mode_decide with its owner's fact; the LLVM type is
verification (audit:codegen, in audit:all):
- the value is the address: FnAbi passes the local by address (the
  indirect-local table the prologues fill from PassMode);
- the slot holds a pointer value: an indirect local, a by-place capture
  of a pointer-valued binding, or a local whose type TypeLayout lays out
  as one address (type_layout_is_single_address: a thin reference or raw
  pointer, extern fn, Box[T]; or a nullable Option over one, with-abi
  §3) — mir_local_slot_holds_pointer, read by both functions.
The indirect-local branch after the slot test is deleted: its name and
LLVM-shape heuristic said "indirect" for 17511 locals FnAbi did not pass
by address, and it returned only through mir_indirect_value_local_ptr,
which is 0 unless FnAbi marked the local — unreachable for every local
it could change.

Evidence, `with-stage1 analyze src/main.w audit:all`:
- red (sites instrumented, still deciding by LLVM type): "place-for-ref
  slot holds a pointer value: 34965 of 34965 decisions taken from the
  LLVM type", and 47 disagreements with a first cut of the fact that
  counted every reference: `&str` is a {ptr, len} view (#1810), so the
  category is TypeLayout's, not TY_REF;
- green: slot-holds-pointer decisions=34943 disagree=0, value-is-address
  decisions=0; audit:all violations=0. behav_ffi_box_roundtrip (a Box
  cast to *mut c_void loads the box value) failed with a Sema-only fact
  and caught it (fact=false llvm-pointer=true) — Box is single-address in
  TypeLayout.
mode_decide's bookkeeping is mode_record, so a value-valued site can
share it.
…ad of re-resolving its AST node (#1647, D65; #1983's LLVM half)

#1983 made emit-c read a type-level builtin's type argument from Sema's
record (type_level_arg_in_body: the type a specialization was checked
with, frozen resolution elsewhere). The LLVM backend still resolved the
argument's AST node itself — gen_sizeof_alignof and the module-constant
evaluator called resolve_type under codegen's own type-parameter
bindings, the vector case re-resolved the node behind a check of its
spelling (`Vector`, `Mask`, a bare name), and alignof looked the type up
by the argument's NAME in named_types (a name two modules declare is two
types, #1446/#1457).

Now:
- current_body_owner_sym names the top-level body being emitted (a
  specialization's mono symbol, or the function's own); closures emitted
  inside keep it, as Sema's record does (current_specialization_sym);
- sema_type_level_arg reads Sema's fact for that body; its LLVM type is
  the decision (sema_type_level_arg_llvm, fact_decide), and under
  analysis the node's codegen resolution is the verification;
- the vector size/align and alignof's layout-model alignment read Sema's
  type (a declared struct or enum), never the spelling.
fact_decide is mode_decide for a value fact; mode_site_derivation names
what a site once re-derived its fact from.

Evidence, `with-stage1 analyze src/main.w audit:all`: red (the site
instrumented, still deciding from the AST node) "sizeof/alignof type
argument: 516 of 516 decisions taken from the AST type node, not from
Sema's type argument"; green decisions=516 disagree=0, violations=0.
…1647, D65; extends #1984)

#1984 made a generic-instance struct field the LLVM type of Sema's field
type; every other field still resolved its AST type node in codegen: a
plain struct field, a union field (whose size and alignment re-resolved
the node through Sema's frozen resolver too), and the payload of every
enum and discriminant-enum variant. Two derivations of one fact — the
type every MIR read of the field lowers is Sema's.

field_llvm_type is the one path: the LLVM type of Sema's type for the
field (type_reflection_field_type_frozen for struct and union, the
variant's TY_ENUM record for a payload), with the node's codegen
resolution as the verification under analysis (fact_decide,
audit:codegen). A generic instance's node is never resolved — that path
is the duplicate #1984 removed. A union measures its fields by Sema's
type. A discriminant-enum payload with no type is now a located error,
as the plain enum's already was (it silently left the payload struct
undeclared). A generic declaration's own body (`enum Slot[T]:
Full(T)`) is not a type: a payload naming its parameter has no concrete
Sema type, so the template keeps the node's codegen resolution,
unjudged, and a discriminant template whose payload has no layout
declares no payload struct, as before; its instances are Sema's
generic-instance types.

Evidence, `with-stage1 analyze src/main.w audit:all`: red (non-generic
fields, union fields and payloads instrumented, still deciding from the
node) "struct field LLVM type: 2490 of 2490 decisions taken from the AST
type node, not from Sema's field type"; green decisions=4089 (every
field path, generic instances included) disagree=0, violations=0.
behav_1482_flags_generic_payload_enum and behav_1768_generic_disc_enum_
payload failed while the template had no exemption ("unresolved payload
type for enum variant 'Full' in 'Slot'") and pass.
…ion judges index places and view-binding origins (#1647, D65)

Codegen chose a field projection's GEP index by looking the field's NAME
up in whichever LLVM struct the owner's representation was
(find_struct_type_by_llvm, then the registry): an LLVM type deciding a
declaration's identity. mir_field_index_decided now takes the index from
the declaration Sema resolved the owner to (mir_sema_field_index: the
field's position in Sema's struct record for the projection's source
type); the registry lookup is the verification under analysis
(fact_decide, audit:codegen). Positional owners (tuple elements, variant
payloads, compiler-laid-out records) have no Sema struct record and keep
their positional index. All four sites (both place walks, both aggregate
builders) read it.

audit:resolution gains two place lanes beside phase 3's field places:
- index places: MIR notes each place lowered from a source index
  expression (MirBody.index_place_*); mir_index_place_verdict requires an
  index projection whose type is Sema's type for the node (or that D27
  view's referent) over the base Sema's base expression has;
- view origins: an aliasing `let` records the place it names
  (let_binding_places); mir_view_origin_verdict requires its root to be
  a binding Sema recorded as an origin of the view (expr_view_dep_*).
lower_binding_alias_place's field projections now note their places, so
the field-place lane judges the view bindings' fields too.
test/internals/analysis_resolution_test.w plants each disagreement.

The index lane found one disagreement over src/main.w, in a
specialization's body: Sema keeps one type per AST node, so a template's
nodes hold the last instance checked (`xs[i]` in Vec[str].clone reads
&i32 after Vec[i32].clone is checked), while MIR's element type, derived
from the indexed place, is right for its instance. No per-instance node
fact exists for MIR to read; specialization bodies are reported as
unjudged (2 over src/main.w), not hidden. That Sema gap is the
foundation work the remaining MIR derivation waits on.

Evidence, `with-stage1 analyze src/main.w audit:all`:
- red: "field projection index: 224291 of 224291 decisions taken from
  the LLVM struct registry, not from Sema's field declaration";
- green: field projection index decisions=224207 disagree=0;
  index-places judged=17430 (2 in specialization bodies unjudged);
  alias-lets judged=32 (2 with Sema origins); violations=0.
…ure record, not the closure's spelling (#1647, D62/D63/D65)

Three stages decided a closure's capture semantics from `move` in its
source spelling (is_move_closure, is_by_place_closure) instead of from
the record Sema keeps per capture (closure_capture_summary: effect bits,
EFF_CAPTURE_BY_PLACE for a by-place capture): the LLVM backend's
capture mode and owned-environment decision (gen_closure), MirLower's
snapshot of a Copy view binding and its ever-moved guard
(closure_capture_source, prepare_anonymous_body), and emit-c's
environment kind (closure_env_kind_for).

Sema states the facts it already holds: closure_capture_by_place(node,
i) and closure_env_owned(node) (some capture held by value). Every stage
reads them. In the LLVM backend the spelling is the verification
(mode_decide, audit:codegen). The protocol captures MIR appends to a
gen-loop's `each` closure (its flag, return slot, producer) are MIR's
own and by place: MirBody.anonymous_capture_kinds records how MIR
materialized every capture (MIR_CAPTURE_LOCAL, _SNAPSHOT, _PLACE_REF,
_PROTOCOL), and codegen reads the protocol kind from it.

audit:resolution judges every NK_CLOSURE's captures against Sema's
record (mir_capture_verdict: a snapshot of a by-place capture, a
reference for a by-value one, and the capture count);
test/internals/analysis_resolution_test.w plants each.

Evidence: src/main.w has no closures (both codegen sites decisions=0,
audit:all violations=0). Over the closure fixtures, red (sites
instrumented, still deciding from the spelling), e.g.
behav_closure_copy_capture_modes.w "closure capture by place: 5 of 5
decisions taken from the closure's AST spelling, not from Sema's
capture facts", "closure owns its environment: 4 of 4"; green
disagree=0 and resolution closure-captures judged with 0 violations on
behav_closure_{copy_capture_modes, move_copy_snapshot, returned_move_env,
consumes_capture_by_call, let_bound_by_place, loop_env_per_iteration,
loop_spawn_os_index, read_after_last_use}, behav_callable_clone_and_
call_through, behav_1698_callable_param_view_tied. The protocol kind
exists because behav_gen_push_generic_and_methods disagreed in 15 of 33
decisions without it (index out of bounds at run time); it passes, 33
decisions, 0 disagreements.
…: its statement temporary is blanked, not dropped again (#1647, D63/D65)

behav_gen_push_generic_and_methods failed audit:all on main and on this
branch's base: "ownership MIR: fn sym1327 stmt10: drop of _6 after a path
reaching it moved it out and before its reset (Moved)". Reduced to
`nums() |> take(2) |> collect[Vec]()`: std.generators' `collect` calls
`g.each(x => ...)` on a generic `impl Gen[T]` receiver, and its MIR was

    _4 = const closure(node9861);
    call const fn sym904(move _1, move _4) -> ...
    drop(_4) @ drop#5 scope-exit _4;

Route: drop bug, debug allocator first. A capturing closure into a user
generic method (`h.apply(3, move (x: i32) -> i32 => x + s.len() as i32)`)
under `run --debug-alloc`: "DOUBLE FREE ... first_drop=drop#closure-env
__closure_env_drop_1 second_drop=drop#closure-env __closure_env_drop_1".
The exact line: MirLower's generic-call method arm (the GENERIC_CALL
branch of lower_method_call) passed a closure literal as `move` and
registered that move (consume_moved_operand) only when the call was
language machinery (`call_is_machinery_dispatch`, D63's spawn case). For a
user generic method the specialization owns the parameter (Sema's
signature consumes a plain `fn(T) -> U`) and drops it at its exit, and
the caller's statement temporary was dropped as well.

The move is now registered whenever the literal goes by value and Sema's
signature does not borrow the parameter (share-place); the temporary is
reset-on-move like any consumed argument.

The validator named bodies only by symbol id (`fn sym1327`), which cost a
--dump-mir per occurrence; validate-ownership, validate-all and
audit:all's MIR lane now print `fn sym1327(collect__sema__...)`
(mir_name_fn_syms).

test/debug_alloc/da_closure_literal_into_generic_method.w: red before
(DOUBLE FREE; validate-ownership failed in `main` and in collect's
specialization), green after (leak count=0, validate-ownership: ok;
behav_gen_push_generic_and_methods validate-ownership: ok).
…index element from it and every named field projection carries Sema's declaration index (#1647 phase 3, D65)

Sema keeps one type per AST node (typed_expr_types), so a generic
template's nodes carry whichever instance was checked last. audit:resolution
therefore skipped index places in specialization bodies ("2 unjudged" over
src/main.w: `xs[i]` in Vec[str].clone read &i32 once Vec[i32].clone was
checked), MirLower derived an index's element type from the indexed
place's type instead of reading Sema, and the field-place lane judged
specialization bodies against the wrong instance. A planted program shows
it (test/behavior/behav_1647_index_and_field_per_instance.w, the base
compiler):

    index-places judged=6085 in-specialization-bodies-unjudged=3
    violation: describe__sema__...: field place type (ty 16) disagrees
      with Sema's type for the node (ty 3) (field `first`, MIR str, Sema i32)
    violation: ... (field `second`, MIR i32, Sema str)
    compiler-analysis-audit: violations=2 FAILED

Sema now records, keyed (specialization symbol or 0, node), what a
template's instances differ in: a runtime index's element place type and
base (check_index -> note_index_element; index_element_in_body), and a
field access's type, owner and declaration index (check_expr /
check_field_access -> field_access_type_in_body, field_access_owner_in_body,
field_decl_index_in_body). A declaration's own body checked inside an
instance's check keys by 0 (check_fn_body / check_fn_body_at reset
current_specialization_sym).

MirBody.instance_sym names the specialization a body belongs to; the
specialization builder, a generic gen fn's producer, closures and gen-loop
bodies carry it. lower_index takes the element from Sema's per-instance
record and reports a node Sema never checked as a phase bug; the derivation
from the place type is gone.

A named struct field projection carries Sema's declaration index
(MirBody.proj_decl, new_named_field_place): a source field access reads the
node's per-instance index; other named projections (struct patterns,
`..` rest fields, functional update, debug formatters, generator state)
take the position from Sema's record. Codegen's projection GEP reads it
(mir_projection_field_index); the LLVM registry's lookup by name is the
verification, and a named projection that arrives without an index is
reported (audit:codegen site "field projection declaration index carried
by MIR"). Aggregates keep Sema's record by name (mir_sema_field_index now
asks Sema's struct_field_decl_index instead of walking the record itself).

audit:resolution judges every specialization body against its own
instance: index places by index_element_in_body (a node with no record is
a violation), field places by the per-instance type and owner, and each
named projection's declaration index (mir_field_decl_verdict, planted in
MirValidationTests).

Evidence, `with-stage1 analyze`:
- the fixture: index-places in-specialization-bodies=3 unjudged=0;
  field-places in-specialization-bodies=4 declaration-indexes=9508
  unrecorded=0; violations=0 ok.
- src/main.w: index-places judged=17441 in-specialization-bodies=2
  unjudged=0; field-places judged=70390 declaration-indexes=70275;
  field projection index decisions=224327 disagree=0; declaration index
  carried by MIR decisions=407 disagree=0; violations=0 ok.
- 247 behavior tests over generics, structs, fields, indexes and closures
  pass on stage1.
…d; the LLVM-binding path monomorphize_struct_nodes is deleted (#1647, D65)

lldb on the base stage1 building src/main.w, breakpoint on
Codegen.monomorphize_struct_nodes: every hit came from
sema_type_to_llvm <- gen_module_constant (`Atomic__i32`, a module-level
`Atomic[i32]`). sema_type_to_llvm held a Sema TypeId for the instance,
converted its arguments to LLVM types, installed them as codegen type
bindings and called monomorphize_struct, which resolved the declaration's
AST field types under those LLVM bindings and mapped LLVM types back to
Sema types (llvm_type_to_sema_type) for the instance's records. Two other
callers reached it the same way: infer_static_generic_struct_mono_sym
(bound LLVM argument types) and resolve_generic_type_nodes after frozen
Sema could not resolve a type node.

get_or_create_generic_struct_type(tid) lays the instance out from Sema:
its arguments (get_generic_inst_arg), its field types
(type_reflection_field_type_frozen), cached by TypeId; a field-count or
argument-count disagreement with the declaration is a reported BUG. The
static-method owner inference asks Sema for the instance its bound
arguments name (find_generic_inst_type) and lays that out; the type-node
fallback names the instance through Sema the same way and fails loudly when
Sema has none. monomorphize_struct and monomorphize_struct_nodes have no
caller and are deleted.

Remaining (phase 5): the instance's symbol text is still spelled from its
arguments' LLVM types (`Atomic__i32`), which method symbols and several
owner lookups parse.

Evidence: with-stage1 analyze src/main.w audit:all violations=0 ok (struct
field LLVM type and field projection index lanes disagree=0); 247
generics/struct/field/index/closure behavior tests pass on stage1.
…mir-sema-hardening status reflects what #1647 converted (#1647)

audit:all over behav_1647_index_and_field_per_instance.w and
behav_gen_push_generic_and_methods.w must be violations=0 ok. The plan's
"Not yet converted / covered" lines for phases 2-4 now list what wave-d65b
converted and what phase 5 still owns (implementation status, not
normative text).
… re-resolution of the AST type node (#1647, D65)

behav_iter_pipeline_local failed after 6664200: "BUG: generic struct type
`FilterIter` at node ... names no instance Sema created". lldb on
Codegen.type_fallback: resolve_generic_type_nodes <- resolve_type <-
declare_function_at_inner, resolving `-> FilterIter[VecIter[i32], i32]`
from the AST. Before 6664200 the miss fell into
monomorphize_struct_nodes and an LLVM-layout struct was invented.
declare_function_at_inner now lowers Sema's sig_return_type when Sema has
the signature, and reads the type node only for a function it has none
for.
…r a namesake (#1745, #1647)

behav_1745_user_type_named_like_std_private failed after 6664200:
"wrong argument type actual=i32 expected=__with_generator_state_13433".
WITH_DEBUG_TYPE_LAYOUT showed std.task's private PullCore[G] instance laid
out as the user's `type PullCore { tag: str, n: i32 }`:
TypeLayout.type_layout_generic_struct_field_type (and the field count,
pack cap and union size paths) took the instance's declaration from the
flat name map (type_decl_nodes.get(base_sym), the newest declaration of
that name), and with setup_generic_inst_substitution failing on the
non-generic namesake, fell back to its named_types fields. Sema's eager
field-type cache, and so every layout of the instance, was the user's
struct. The old codegen path resolved the fields itself from std's AST and
hid it; 6664200 reads Sema's record and exposed it.

TypeLayout now asks generic_inst_decl_node(tid) (the instance's recorded
template first), and generic_inst_template_tid, with no recorded template,
takes the one generic declaration of the name before any visibility-based
lookup: a non-generic namesake can never be an instance's template.

behav_1745 and behav_iter_pipeline_local pass on stage1.
d088467d changed which declaration TypeLayout reads for a generic
instance whose name a user type shadows; the layout convention is
unchanged, so WITH_ABI_VERSION stays. Every .wo rebuilds once.
@ehartford
ehartford marked this pull request as ready for review October 3, 2026 15:13
@ehartford
ehartford merged commit 74e3001 into main Oct 3, 2026
@ehartford
ehartford deleted the wave-d65b branch October 3, 2026 15:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant