You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Build performance: root-cause why builds are this slow and make them fast (incremental/cached compilation) #650
Every verification cycle (with build && with build :fixpoint && with build :test) rebuilds the entire compiler stage chain and recompiles the ~26k-line src/main.w at -O1 from scratch, then re-runs the full suite. A single gate is on the order of 10+ minutes, dominated by the -O1 whole-program recompile of main.w. This makes every one-line change to codegen/sema painfully slow to verify and is a serious drag on iteration.
Observed
with build alone: several minutes, most of it one with-stage2 build out/gen/main.w -O1 process pegging a single core.
:fixpoint rebuilds again (stage2 vs stage3).
:test then runs the whole suite serially.
No module-level incrementality: an edit to one file recompiles the whole main.w translation unit.
Why this matters
Correctness discipline here requires gating each change (build + fixpoint + suite) before the next, because miscompiles corrupt the self-host chain silently. If each gate is 10+ minutes, the cost of that (correct) discipline is enormous — it dominates the wall-clock of any multi-step refactor.
Directions to investigate (not prescriptive)
Incremental compilation / module caching — only recompile changed modules; cache object output keyed on source + deps (the build graph already tracks inputs). Biggest win.
Parallelize the -O1 codegen of independent modules / the test targets (many test lanes are embarrassingly parallel).
A fast inner-loop lane — a :check-only or -O0-forbidden-but-faster path for quick iteration, with the full -O1 gate reserved for pre-commit (careful: -O0 is forbidden for the shipped build; this would be a dev-only check lane, not a build artifact).
Cache the stage chain when sources are unchanged (skip rebuilding stage1/stage2 if inputs hash-match).
Spec / infra
Build-system / self-host toolchain performance. Relates to the build-graph caching already present (src/BuildGraphCache.w) — extend it to module-level compile caching for main.w.
changed the title [-]Test/gate cycle is ~10+ min, dominated by a full -O1 rebuild every run — need incremental/cached builds[/-][+]Build performance: root-cause why builds are this slow and make them fast (incremental/cached compilation)[/+]on Jul 16, 2026
Escalated to high-priority by maintainer (2026-07-16), and the mandate is broadened: not just incremental/cached gate runs — root-cause why the build is this slow, then make it fast. Every fix in the last two days paid this tax four to six times; it multiplies the cost of all other work.
Where to look first (hypotheses to measure, not assume)
Per-phase timing instrumentation — the build has no breakdown of lex/parse/sema/MIR/LLVM-opt/LLVM-codegen/link time per stage. Land a --time-phases (or build-graph timing report) FIRST; every subsequent decision should cite it.
Whole-ZCU monolith compiles. Each stage compiles the entire compiler as one unit every time. No object-level incrementality: a one-line SemaCheck.w edit recompiles everything, three times (stage1/stage2 + release link). Content-keyed module/object caching is the structural fix (precedent: the Test-graph cache key omits the compiler binary — miscompiled tests stay green across gate runs #655 test cache is fingerprint-keyed; the same discipline can key object artifacts by module content + compiler fingerprint).
LLVM share. If -O1 LLVM dominates, options are narrower (parallel codegen units, linker-side work) — measure before designing. -O0 remains forbidden; this issue does not touch optimization level.
Redundant regeneration: embedded-stdlib/clang-resource regen and bootstrap objects rebuild cadence — cheap wins if they re-run when inputs are unchanged.
Constraints
-O1 stays (invariant). Fixpoint determinism stays — any cache must be bit-honest or it will surface as fixpoint noise.
No external build tools; all in With per repo policy.
Suggested order: (1) timing instrumentation, (2) publish the measured breakdown here, (3) attack the top item, (4) re-measure. Success looks like: single-file compiler edit → green gates in low single-digit minutes.
Measured breakdown (mandate step 2) — full compiler compile, 280 s wall, M-series Darwin
Correction to my earlier comment: WITH_PROFILE=1 already exists and instruments every phase (I claimed otherwise — grep-before-assume). Numbers from WITH_PROFILE=1 with build src/main.w:
Phase
ms
share
frontend.read/parse/resolve/imports/c_import
~1,650
0.6%
frontend.comptime
2,841
1.0%
frontend.sema (decls=8852)
22,950
8.2%
sema — second full check in run_mir_lower (types=9440)
35,637
12.7%
mir.lower (bodies=6832)
13,099
4.7%
llvm.gen_module
14,053
5.0%
llvm.optimize
33,806
12.1%
llvm.emit_object
156,278
55.8%
link + dsymutil
549
0.2%
Cross-checked with three sample windows (no instrumentation needed):
Backend window (T+4:20): SUnit::addPred / SUnit::ComputeHeight (scheduling DAG) + regalloc interference dominate → the 156 s is single-threaded SelectionDAG/MISched/RA over one enormous module. TargetMachine already uses CodeGenLevelLess at -O1 (LlvmBridge.codegen_level), so there is no cheap knob here — the cost is module size × one thread.
Middle-end window (T+2:10): ~25% of samples in memcmp under InstCombinerImpl::visitInsertValueInst → simplifyExtractValueInst (recursive) — InstCombine churning on the very high volume of first-class-aggregate insertvalue/extractvalue traffic our codegen emits (str/Vec/Option headers crossing every call boundary). ValueSymbolTable::createValueName also present but secondary.
Sema window (T+0:30): hottest leaves are with_vec_get_ptr (out-of-line runtime call per element access, with rt_payload_start_is_owned checks) and Sema.find_trait_decl_node — a linear scan over all 8,852 decls per call (SemaDecl.w:2332).
The whole compile runs on one thread.
Structural finding: the module is fully sema-checked twice
compile_file_frontend runs a complete sema pass (22.9 s), then Compilation.run_mir_lower constructs a fresh Sema and runs check_module() again (35.6 s) because MIR lowering "owns the still-mutable semantic state". ~23 s of the build is a duplicated full check.
Attack plan (mandate step 3), in impact order
Parallel codegen units — the only fix that touches the 56%. Deterministically partition MIR bodies into K units, emit K modules on K threads (per-thread LLVMContext; cross-unit calls via extern declarations), link K objects. Attacks emit (156 s) + optimize (34 s) + gen (14 s) ≈ 204 s → ~204/K + overhead. On a 10-core host the full build should land in the ~60–90 s range. Fixpoint-safe by construction if the partition is decl-order-deterministic and link order is fixed. This is the rustc codegen-units design and it needs its own worked plan (unit boundaries, shared globals/strings, dsym).
Single-sema pipeline — eliminate the duplicated full check (~23 s): either hand the frontend's Sema to run_mir_lower or drop the frontend pass for build flows that immediately re-check. Needs care with pool/state ownership (the fresh-Sema design was deliberate).
Sema micro-fixes — find_trait_decl_node → collect-time HashMap (precedent: type_decl_nodes); audit other per-call linear scans over decls; consider inline fast-paths for hot runtime accessors (with_vec_get_ptr) since sema burns a large share of its time in call+bounds overhead per element access.
Aggregate-traffic reduction in codegen (middle-end relief): prefer memory-form aggregate construction where InstCombine chains get hot; measure llvm.optimize before/after.
Raw sample files parked at /tmp/650_sample_{early,mid,late}.txt on the build host.
How Go, Rust, Swift, and Zig solved this (read from .reference/ checkouts)
Go — owns the whole latency budget by not using LLVM (custom SSA backend), then parallelizes at two levels: per-package compiles at the build layer with a content-addressed action cache, and per-function backend workers inside each package (cmd/compile/internal/gc/compile.go: compilequeue + -c N workers, sorted longest-function-first "to avoid stragglers", object writing serialized after for determinism).
Rust — codegen units (rustc_monomorphize/src/partitioning.rs): partition all mono items into named CGUs (per source module, split stable/non-generic vs volatile/monomorphized), merge toward a target count; LLVM opt+emit run in parallel across CGUs under a coordinator; incremental compilation then reuses unchanged CGU objects by hash (their doc: the entire incremental win is tied to partitioning, because an LLVM module is opaque — you rebuild it whole or reuse it whole). Their explicitly stated trade-off: bigger CGUs = better inlining, smaller = better parallelism/incrementality.
Swift (docs/CompilerPerformance.md) — two modes: primary-file/batch (driver runs one frontend job per file/batch → file-level parallelism + incrementality; batch mode exists purely to kill the quadratic re-parsing of running too many frontends) and WMO — where even the single-frontend mode keeps "LLVM IR code-generation, which is always multithreaded" (module split per file under -num-threads).
Zig — two-pronged: -fincremental with long-lived compiler state and in-place binary patching (Compilation.zig), and skipping LLVM entirely for debug builds via self-hosted native backends (use_llvm toggle, src/arch/*) — LLVM is reserved for release artifacts.
What transfers to With's measured profile (156 s emit + 34 s opt + 14 s gen, all on one thread)
Codegen units are the industry answer to exactly our bottleneck — all four parallelize the backend; nobody ships a single-threaded whole-module LLVM emit. Direct transplant: partition MIR bodies into K units (deterministic by decl order, size-balanced à la Go's longest-first), K threads with per-thread LLVMContext, K objects, fixed link order. Attacks ~204 s of 280 s.
Parallelize the backend, not the frontend (Swift's lesson): N frontend jobs re-parse the world quadratically; our single frontend + parallel backend (the Go/Rust shape) avoids that trap entirely.
Long-term note (Zig's lesson): a fast non-LLVM dev backend is the endgame for iteration loops. Parking it — it needs its own policy discussion against the repo's -O1-everywhere invariant, and codegen-units + unit caching should land first since they need no policy change.
Recommended execution order stands: codegen-units → per-unit object cache → single-sema/with_vec_get_ptr inlining for the remaining sema share.
Codegen units — Milestone 1 landed (serial split), measured
Implemented the LLVM-SplitModule shape over a bitcode round-trip (modules can't leave their context): write bitcode once → per unit: fresh context, reparse, keep only that unit's function bodies (safe deleteBody: RAUW-to-undef → erase instructions → erase blocks), externalize internalized functions under a reserved __wcu$ prefix (identical rename in every parse; positional identity — bitcode reparses preserve definition order), unit 0 owns non-private global definitions and appending-linkage arrays, per-unit TM + -O pipeline + object, multi-object link with undefined-symbol union for runtime detection. Deterministic by construction (order-driven partition, no map iteration) — verified byte-identical unit objects across rebuilds.
Off by default (WITH_CODEGEN_UNITS, default 1) until the threaded milestone; module_object_mode (bootstrap/runtime objects) always single-unit.
Measurements (whole compiler, WITH_CODEGEN_UNITS=8, still serial)
Per-unit opt+emit: 18.1, 42.2, 28.7, 27.4, 27.9, 49.9, 10.4, 32.8 s (sum ≈ 237 s vs 190 s single-module — the K× reparse + per-unit pipeline overhead). Parallel projection: wall = max(unit) ≈ 50 s instead of 190 s. With the front half unchanged (~90 s incl. the duplicated sema), projected full build ≈ 140 s vs 280 s at K=8 — before fixing the two obvious follow-ups:
Balancing: 10–50 s spread shows basic-block count is a weak proxy for backend cost. Milestone 2 should oversubscribe (units ≈ 2-3× threads) and let the pool balance — Go's longest-first lesson.
Single-sema (−23 s) stacks on top → ~100 s territory; unit-level object caching then attacks the edit-loop case.
Correctness evidence: 3-unit probe binary runs; async/channel/task fixture batch green at K=4 (exercises runtime-need detection from non-primary units); the K=8-built compiler itself works (checks and runs fixtures); unit objects cleaned up with the canonical object (including stale higher-K leftovers).
Milestone 2 next: thread the unit loop (per-thread contexts are already the design; the loop body touches only bridge externs + locals), following the comptime-parallel precedent for runtime-thread fan-out.
Milestone 2 landed (5cfc137): threaded units — 280 s → 148.5 s measured (1.9×)
The unit loop now runs one worker thread per unit (with_thread_spawn/join, the comptime-parallel precedent; workers touch only their job slot, bridge externs, and a read-only plan copy — no compiler globals; failed spawns degrade to inline). Whole-compiler at WITH_CODEGEN_UNITS=8:
148.45 s wall vs 280 s baseline; 362 s user across 148 s wall (real concurrency)
LLVM stage: 14 s serial gen_module + parallel units, max-unit 53 s
Threaded-built compiler verified working; object-level determinism holds under threading (binary-level double-build diffs are pre-existing link nondeterminism — debug-map mtimes/UUID — present at K=1 too; fixpoint compares objects, unaffected)
Still opt-in (WITH_CODEGEN_UNITS, default 1). Remaining to flip the default (next session's work):
:fixpoint must compare unit sibling objects, not just the canonical one — flipping without that weakens the determinism gate.
Host-aware default K via with_sysinfo (cores + memory guard for the ~2.8 GB/unit peak on compiler-sized modules) and a small-module bypass (defined-fn threshold) so tiny builds skip the split.
Balancing: max-unit 53 s vs mean ~37 s — replace bb-count with a better cost proxy or oversubscribe units 2–3× threads.
Memory (parked): lazy bitcode materialization (LLVMGetBitcodeModuleInContext-style) would cut the pre-strip peak dramatically.
Remaining wall after flip projects to ~95–120 s; the sema double-check (−23 s) and unit-level object caching (the edit-loop win) stack after that.
Default flipped (9879ac6): codegen units are on for everyone
WITH_CODEGEN_UNITS is now an explicit override (any value, including forcing 1); unset picks the host-aware default: < 2000 MIR bodies → single unit (verified: tiny builds produce no siblings), larger modules split by logical cores (cap 8) with a memory guard (~3 GB per in-flight pre-strip parse; low-memory hosts stay single-unit).
--emit-obj / module-object builds remain single-object by contract — and since the fixpoint objects ride that flag while the stage2/stage3 compilers are now built through units, the existing :fixpoint gate is a transitive determinism proof for the unit pipeline. It held: full battery green with the default live (build, FIXPOINT, audit 0, all 9 test targets, evidence recorded).
Auto run on this host: K=8 selected, 153.5 s wall vs 280 s for the compiler self-build.
Scoreboard for this issue so far: 280 s → ~150 s for every big-module build, by default, no invariants touched (-O1 everywhere, fixpoint intact).
Remaining on the plan, in value order:
Unit balancing — auto run spread 21–63 s; a better cost proxy or 2–3× oversubscription recovers ~20–30 s of wall.
Single-sema — the duplicated full check is 23 s of every build.
Triage 2026-08-31: CLOSE (superseded). #679 is the live build-performance campaign with the measured breakdown and targets; this issue's own directions landed under its tag (codegen units 2f706c2/5cfc1377/9879ac66, post-link stamping 5f8ad53) or via #679/#686, with the remainder tracked by the open #682/#684.
Activity
[-]Test/gate cycle is ~10+ min, dominated by a full -O1 rebuild every run — need incremental/cached builds[/-][+]Build performance: root-cause why builds are this slow and make them fast (incremental/cached compilation)[/+]ehartford commentedon Jul 16, 2026
Escalated to high-priority by maintainer (2026-07-16), and the mandate is broadened: not just incremental/cached gate runs — root-cause why the build is this slow, then make it fast. Every fix in the last two days paid this tax four to six times; it multiplies the cost of all other work.
Fresh measurements (this week's sessions, M-series Darwin, -O1 throughout)
with build(seed → stage1 → stage2 → link): ~10–14 min wall.with build :stage1alone: ~3–4 min — one full-compiler compile is the atomic unit of pain.with check src/main.w: ~80 s (sema-only on the full ZCU) — so the majority of a stage build is MIR+codegen+LLVM, not checking.Where to look first (hypotheses to measure, not assume)
--time-phases(or build-graph timing report) FIRST; every subsequent decision should cite it.parallel()infrastructure exists (Regression: with get [email protected] fails (Conan package-revision query miscompiled) after generational-ownership Stage 2 #617); stage compiles and runtime-object builds that are independent should overlap. Check what the build graph already parallelizes vs serializes.Constraints
Suggested order: (1) timing instrumentation, (2) publish the measured breakdown here, (3) attack the top item, (4) re-measure. Success looks like: single-file compiler edit → green gates in low single-digit minutes.
Docs: record #637 fix, #676 minicoro deferral, #650 escalation in han…
ehartford commentedon Jul 16, 2026
Measured breakdown (mandate step 2) — full compiler compile, 280 s wall, M-series Darwin
Correction to my earlier comment:
WITH_PROFILE=1already exists and instruments every phase (I claimed otherwise — grep-before-assume). Numbers fromWITH_PROFILE=1 with build src/main.w:Cross-checked with three
samplewindows (no instrumentation needed):SUnit::addPred/SUnit::ComputeHeight(scheduling DAG) + regalloc interference dominate → the 156 s is single-threaded SelectionDAG/MISched/RA over one enormous module. TargetMachine already usesCodeGenLevelLessat -O1 (LlvmBridge.codegen_level), so there is no cheap knob here — the cost is module size × one thread.memcmpunderInstCombinerImpl::visitInsertValueInst → simplifyExtractValueInst(recursive) — InstCombine churning on the very high volume of first-class-aggregateinsertvalue/extractvaluetraffic our codegen emits (str/Vec/Option headers crossing every call boundary).ValueSymbolTable::createValueNamealso present but secondary.with_vec_get_ptr(out-of-line runtime call per element access, withrt_payload_start_is_ownedchecks) andSema.find_trait_decl_node— a linear scan over all 8,852 decls per call (SemaDecl.w:2332).Structural finding: the module is fully sema-checked twice
compile_file_frontendruns a complete sema pass (22.9 s), thenCompilation.run_mir_lowerconstructs a fresh Sema and runscheck_module()again (35.6 s) because MIR lowering "owns the still-mutable semantic state". ~23 s of the build is a duplicated full check.Attack plan (mandate step 3), in impact order
find_trait_decl_node→ collect-time HashMap (precedent:type_decl_nodes); audit other per-call linear scans over decls; consider inline fast-paths for hot runtime accessors (with_vec_get_ptr) since sema burns a large share of its time in call+bounds overhead per element access.llvm.optimizebefore/after.Raw sample files parked at /tmp/650_sample_{early,mid,late}.txt on the build host.
ehartford commentedon Jul 16, 2026
How Go, Rust, Swift, and Zig solved this (read from .reference/ checkouts)
Go — owns the whole latency budget by not using LLVM (custom SSA backend), then parallelizes at two levels: per-package compiles at the build layer with a content-addressed action cache, and per-function backend workers inside each package (
cmd/compile/internal/gc/compile.go:compilequeue+-c Nworkers, sorted longest-function-first "to avoid stragglers", object writing serialized after for determinism).Rust — codegen units (
rustc_monomorphize/src/partitioning.rs): partition all mono items into named CGUs (per source module, split stable/non-generic vs volatile/monomorphized), merge toward a target count; LLVM opt+emit run in parallel across CGUs under a coordinator; incremental compilation then reuses unchanged CGU objects by hash (their doc: the entire incremental win is tied to partitioning, because an LLVM module is opaque — you rebuild it whole or reuse it whole). Their explicitly stated trade-off: bigger CGUs = better inlining, smaller = better parallelism/incrementality.Swift (
docs/CompilerPerformance.md) — two modes: primary-file/batch (driver runs one frontend job per file/batch → file-level parallelism + incrementality; batch mode exists purely to kill the quadratic re-parsing of running too many frontends) and WMO — where even the single-frontend mode keeps "LLVM IR code-generation, which is always multithreaded" (module split per file under-num-threads).Zig — two-pronged:
-fincrementalwith long-lived compiler state and in-place binary patching (Compilation.zig), and skipping LLVM entirely for debug builds via self-hosted native backends (use_llvmtoggle,src/arch/*) — LLVM is reserved for release artifacts.What transfers to With's measured profile (156 s emit + 34 s opt + 14 s gen, all on one thread)
Recommended execution order stands: codegen-units → per-unit object cache → single-sema/
with_vec_get_ptrinlining for the remaining sema share.Sema: cache trait_sym -> decl node instead of scanning all decls (#650)
Docs: record #650 profile findings and attack plan in handoff
ehartford commentedon Jul 16, 2026
Codegen units — Milestone 1 landed (serial split), measured
Implemented the LLVM-SplitModule shape over a bitcode round-trip (modules can't leave their context): write bitcode once → per unit: fresh context, reparse, keep only that unit's function bodies (safe deleteBody: RAUW-to-undef → erase instructions → erase blocks), externalize internalized functions under a reserved
__wcu$prefix (identical rename in every parse; positional identity — bitcode reparses preserve definition order), unit 0 owns non-private global definitions and appending-linkage arrays, per-unit TM + -O pipeline + object, multi-object link with undefined-symbol union for runtime detection. Deterministic by construction (order-driven partition, no map iteration) — verified byte-identical unit objects across rebuilds.Off by default (
WITH_CODEGEN_UNITS, default 1) until the threaded milestone;module_object_mode(bootstrap/runtime objects) always single-unit.Measurements (whole compiler,
WITH_CODEGEN_UNITS=8, still serial)Per-unit opt+emit: 18.1, 42.2, 28.7, 27.4, 27.9, 49.9, 10.4, 32.8 s (sum ≈ 237 s vs 190 s single-module — the K× reparse + per-unit pipeline overhead). Parallel projection: wall = max(unit) ≈ 50 s instead of 190 s. With the front half unchanged (~90 s incl. the duplicated sema), projected full build ≈ 140 s vs 280 s at K=8 — before fixing the two obvious follow-ups:
Correctness evidence: 3-unit probe binary runs; async/channel/task fixture batch green at K=4 (exercises runtime-need detection from non-primary units); the K=8-built compiler itself works (checks and runs fixtures); unit objects cleaned up with the canonical object (including stale higher-K leftovers).
Milestone 2 next: thread the unit loop (per-thread contexts are already the design; the loop body touches only bridge externs + locals), following the comptime-parallel precedent for runtime-thread fan-out.
Backend: codegen units, milestone 1 — deterministic serial split (#650)
Backend: codegen units, milestone 2 — threaded unit pipeline (#650)
ehartford commentedon Jul 16, 2026
Milestone 2 landed (5cfc137): threaded units — 280 s → 148.5 s measured (1.9×)
The unit loop now runs one worker thread per unit (
with_thread_spawn/join, the comptime-parallel precedent; workers touch only their job slot, bridge externs, and a read-only plan copy — no compiler globals; failed spawns degrade to inline). Whole-compiler atWITH_CODEGEN_UNITS=8:Still opt-in (
WITH_CODEGEN_UNITS, default 1). Remaining to flip the default (next session's work):with_sysinfo(cores + memory guard for the ~2.8 GB/unit peak on compiler-sized modules) and a small-module bypass (defined-fn threshold) so tiny builds skip the split.LLVMGetBitcodeModuleInContext-style) would cut the pre-strip peak dramatically.Remaining wall after flip projects to ~95–120 s; the sema double-check (−23 s) and unit-level object caching (the edit-loop win) stack after that.
Backend: enable codegen units by default with a host-aware K (#650)
ehartford commentedon Jul 16, 2026
Default flipped (9879ac6): codegen units are on for everyone
WITH_CODEGEN_UNITSis now an explicit override (any value, including forcing 1); unset picks the host-aware default: < 2000 MIR bodies → single unit (verified: tiny builds produce no siblings), larger modules split by logical cores (cap 8) with a memory guard (~3 GB per in-flight pre-strip parse; low-memory hosts stay single-unit).--emit-obj/ module-object builds remain single-object by contract — and since the fixpoint objects ride that flag while the stage2/stage3 compilers are now built through units, the existing:fixpointgate is a transitive determinism proof for the unit pipeline. It held: full battery green with the default live (build, FIXPOINT, audit 0, all 9 test targets, evidence recorded).Scoreboard for this issue so far: 280 s → ~150 s for every big-module build, by default, no invariants touched (-O1 everywhere, fixpoint intact).
Remaining on the plan, in value order:
Build: stamp compiler version post-link so the build caches across co…
ehartford commentedon Aug 31, 2026
Triage 2026-08-31: CLOSE (superseded). #679 is the live build-performance campaign with the measured breakdown and targets; this issue's own directions landed under its tag (codegen units 2f706c2/5cfc1377/9879ac66, post-link stamping 5f8ad53) or via #679/#686, with the remainder tracked by the open #682/#684.