Skip to content

Compiler: window codegen-unit fan-out; dispose base LLVM module and MIR before fan-out (study delta 2) #681

Closed

Description

@ehartford

Part of #679. codegen_units_emit spawns ALL K unit threads unconditionally (src/compiler/CodegenUnits.w:243-254), each re-parsing the FULL whole-module bitcode into a private LLVMContext (~3 GB/unit per the in-source comment at :57-61), while the parent keeps the un-disposed base module, AST, Sema, and MIR live (src/compiler/Backend.w:66-69). K = min(cores, 8, (mem_gb-6)/3) (:71) grows peak with host RAM instead of bounding it: K=8 ≈ 24 GB of LLVM + ~2.5 GB frontend ≈ the observed 31.7 GB peak. Quick tier: window spawns to W in flight; free base module + MIR before fan-out (audit Backend.w:66 post-codegen last_mir_module read first). Structural tier: split bitcode per unit BEFORE spawning so each thread parses ~1/K. References: rustc write.rs queue_full_enough/:1839 + per-worker module free :1409-1412; Zig Zcu.zig:5226 10-MiB AIR backpressure. Gate on /drop-audit if any lowering is touched. Expected: W=4 + freed base ≈ 14-17 GB; structural tier <8 GB.

Activity

  1. ehartford commented on Jul 18, 2026

    @ehartford
    ContributorAuthor

    Structural design CONFIRMED FEASIBLE (2026-07-18 feasibility read), sized days-not-weeks:

    Per-unit IR generation from MIR — replace the generate-whole-module → bitcode → K×(full parse + strip) pipeline with K threads each generating their unit's module directly:

    • Per-thread Codegen instance: own LLVMContext/module/builder/target_machine + own InternPool CLONE (cheap — symbol table is MBs; codegen-interned ids are thread-local, names reach LLVM as strings so cross-thread id divergence is harmless).
    • Shared READ-ONLY Sema/AstPool/MirModule via raw pointers in the job struct — the existing codegen-unit thread precedent (CodegenUnits.w:213-216) and, critically, audit:all's frozen-phase invariant already guarantees codegen never re-enters mutable Sema (the audit enforces exactly the property the threads need). gen_module_from_mir currently takes move MirModule — needs a borrow variant.
    • Each thread generates: module preamble (globals/strings/types — duplicated per unit, a fraction of the measured 14.5s gen_module) + unit-k function BODIES + declarations for out-of-unit functions, with the existing __wcu$ rename scheme applied at generation.
    • Plan keying moves from bitcode-positional to MIR-order (same deterministic order the current plan iterates).

    Why this is now load-bearing (maintainer directive): after #681/#682/#683, the goal is peak build memory UNDER 8 GB (build on 8 GB machines, Mac/Linux/Windows). The bitcode round-trip architecture cannot fit: ~3 GB/unit parse × K, or one whole-module pipeline that likely exceeds 8 GB alone. Per-unit generation makes peak ≈ frontend + max(unit module), and composes with #685 (drop AST/MIR after their consumers).

    Measured evidence backing the design: 16 units under the current architecture REGRESSES (56.7s max unit, 30.5 GB peak — parse contention, see docs/build_time_log.md); unit balance is already instruction-count-based (cf22186). Landed today as the quick tier: codegen_units_emit disposes the base module immediately after the bitcode write (deinit() was never called — the module leaked until exit); RSS A/B in flight.

    Gates for the implementation session: fixpoint (byte-identical objects vs current pipeline is NOT expected — the units' content changes shape? No: same functions, same bodies, same renames → outputs should converge; treat any divergence as a real finding), /drop-audit before+after, full battery. Prerequisite reading: Codegen.w init/preamble paths; the 82 self.intern mutation sites are the clone-boundary checklist.

  2. ehartford commented on Jul 18, 2026

    @ehartford
    ContributorAuthor

    ARCHITECTURE REVISION (supersedes the per-thread-Codegen design above). While implementing the sharing groundwork, two facts changed the shape:

    1. gen_module_from_mir now reads MIR through a raw pointer (landing as the first increment) — the sharing contract works for MIR because its access surface was 22+466 sites in a dozen mechanical patterns.
    2. Sema CANNOT be shared the same way: its access surface is hundreds of distinct method calls, the ref-returning accessor that would make it a one-pattern rewrite segfaults (filed Compiler: reference returned from raw-pointer deref compiles but segfaults at runtime #687), and per-thread Sema copies (K × ~GB) are fatal to the 8 GB goal.

    Revised design — serial per-unit generation, parallel per-unit optimize+emit:

    • Parent loop, k in 0..K: construct cg_k (own context/module; sema/pool/intern copied as today — only ONE alive at a time), generate ONLY unit-k bodies (Pass 2 / gen_mir_only_functions / generator-next filtered by a fn_sym→unit plan computed from MIR statement counts; synthesized fns — runtime init helpers, wrapped main — pinned to unit 0; internal-linkage fns renamed __wcu$$name consistently at declare time in every unit), write unit-k bitcode (~1/K size), dispose cg_k.
    • Threads then parse SMALL per-unit bitcode (~1.5s vs ~12s full-module) + optimize + emit, as today minus the strip pass.
    • Peak memory: frontend + ONE unit module + K small thread modules ≈ frontend + module — the 8 GB shape. No shared-Sema problem exists at all.
    • Wall: serial gen ≈ today's whole-module gen + K× preamble + K× cg-construction (~10-20 s added serial), repaid by the thread-parse drop and by unit counts >8 becoming viable (the 16-unit regression was pure parse contention).
    • Determinism: generation fully sequential; plan keyed by MIR order + statement counts.

    Landed so far: MIR-via-pointer refactor (in battery now), base-module disposal (88ade44). Next increments: fn_sym-keyed plan from MIR; Pass-2/mir-only/generator filters + unit-0 pinning; declare-time renames; the serial-gen loop + slim thread path.

  3. ehartford commented on Jul 18, 2026

    @ehartford
    ContributorAuthor

    STRUCTURAL TIER LANDED: a497d14 (MIR via raw pointer — the sharing contract) + bc0c983 (per-unit generation from MIR, serial gen + parallel slim emit) + 88ade44 (disposal quick tier). Measured on a stage-equivalent compiler compile: peak RSS 21.1 -> 13.2 GB (-37%), max unit 50.3 -> 36.7 s, wall neutral. Fixpoint byte-identical through the new pipeline; drop-audit 25/25; 1876 tests green; the produced compiler self-checks. Bring-up finding worth keeping: synthesized external bodies (prelude trait defaults) must be demoted outside unit 0 — handled by a deterministic post-gen walk sharing the old strip's global-ownership rules. Next in this issue: retest 12/16 units (parse no longer scales with count), then small-host unit formula tuning toward the 8 GB target. The old strip pipeline (codegen_units_plan/strip/emit_one) is now dead code — cleanup commit to follow.

  4. added 4 commits that reference this issue on Jul 18, 2026
  5. ehartford commented on Jul 19, 2026

    @ehartford
    ContributorAuthor

    WINDOWED EMIT CONCURRENCY LANDED (final tier) + dead strip pipeline deleted. The "small-host formula" leftover produced a decisive negative result that reshaped the fix:

    Verification finding: peak memory is K-INDEPENDENT under full concurrency. Measured compiling the compiler on the 18-core/128 GB host: 15.3 GB @ K=5 (what the old formula picked for an 8 GB host), 13.2 GB @ K=8, 14.4–15.5 GB @ K=16 — in-flight IR totals the whole program however it is sliced, so capping unit COUNT cannot protect a small host. The old mem_cap on K was a no-op against its own target.

    Fix: memory bounds emit CONCURRENCY, not unit count.

    • K = min(cores, 16) purely (≥2000-body size gate unchanged); more, smaller units only shrink the serial-gen spike.
    • Emit threads run through a join-oldest sliding window (the test-runner pattern): W = clamp(budget / (IR_est/K), 1, K), budget = mem − 5 GiB frontend reserve (measured envelope 4.9 GB), IR_est = plan_cost × 36 KB/stmt (calibrated: emit-phase delta 10.5 GB ÷ plan_cost 289004 at K=16).
    • WITH_CODEGEN_EMIT_WIDTH overrides; [profile] prints plan_cost/window.

    Verified:

    Also deleted the dead pre-#681 strip pipeline (codegen_units_plan/codegen_units_strip/codegen_unit_emit_one/codegen_units_emit/codegen_units_plan_copy, CodegenUnitPlan/CodegenUnitJob), −221 lines, as its own gated commit.

    Closing: all #681 tiers are complete (disposal, MIR-via-pointer, per-unit generation, 16-unit default, windowed emit, strip-pipeline removal). Real-8 GB-hardware verification under actual memory pressure moves to the north-star campaign (#679; needs #682/#685 for margin).

  6. added a commit that references this issue on Jul 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions