Skip to Content
marmot

Status: proposal. Area: verify (checks a proof removes). Review: backend, which has the loop passes. Numbers: verify-research.md, section 1b.

Problem

Rule V (backend/lib/Loops/Versioning.cpp, proved in verify/lean/RuleV.lean) versions a loop whose only exits besides the latch are bounds checks. A precondition computed before the loop implies that no check fires. A fast copy runs without the check exits. The original loop runs when the precondition fails, so panics happen exactly where Go panics. It runs only inside the parallelize pass, and Register.cpp adds that pass only with -par. Inside it, a loop is versioned only when the fast copy would run in parallel, or when it appends. So default release builds version no loop, and neither does gc.

Instruction counts with every index check removed (callgrind, private build, never landed): matmul -54%, fannkuch -20%, generic -13%, regexpbench -12%, sortslice -4.5%, nbody -3.2%. Quicksort (-18%) and heapsort (-16%) are out of reach: their checks are data dependent, and rule V needs affine indexes. nsieve's -57% was confounded by bool packing and does not count.

Proposal

  1. A versioning-only mode: MARMOT_LOOPS_VERSION=1, without -par. Then Register.cpp adds a pass that visits innermost loops and calls versionBoundsChecks. The switch is a CompileOptions field set from the env in marmot-backend, so it is in the cache fingerprint and in loops::cacheKey from the start. It does not parallelize and does not use the would-be-parallel probe. With -par the existing behavior stays.
  2. A cost policy in place of the parallel requirement. Version L only when:
    • L's trip count is not a constant below 16. The precondition also tests count >= 16 at run time, so a short loop takes the original copy after a few compares. This covers the case the parallel probe was protecting (fannkuch's 2 to 3 iteration flip loop).
    • every loaded bound's check loop can be hoisted, so it does not run on every entry of L (2).
    • L has at most 200 instructions, and a function grows by at most 50% in total. Never at -Os or -Oz.
  3. Hoisted check loops. A loaded bound (len(b[k]) in matmul's inner loop) gets a check loop over L's trip count before L. Run on every entry of L, it costs about what it saves (n loads per entry against 3 compare-and-branch pairs per iteration). Instead, place the check loop in the preheader of the outermost enclosing loop M where the base, start, step and count are invariant. No instruction of M may write the loaded memory (the existing alias test, over M instead of L). For matmul: once per multiply instead of n^2 times. If no such M exists beyond L itself, the loop is not versioned in this mode.

What must still hold (proof obligations)

  • Rule V's existing result (versioned_eq): under the precondition the fast copy equals the original, panics included, and the slow copy is the original.
  • New, hoisting: the min and max computed before M equal those that a check loop before each entry of L would compute. They do on two conditions at every entry of L inside M. The base, start, step and count have the values that they had before M (invariance). The loaded words have not changed (no write in M may alias them). A lemma in RuleV.lean: a fold over the same addresses of an unchanged memory gives the same result. The report check gets the hoist point and the invariance claims. verify/check checks again the loop copy, the precondition, and that M contains no store to the loaded base.
  • New, the trip count test: count >= 16 only strengthens the precondition, so it cannot make the fast copy run when a check could fire.

Review points (backend, 2026-11-17), all accepted

  1. Extension point: optimizer-early is right. LoopRotate, LICM, LoopVectorize, the unroller and SimplifyCFG run after it, so the fast copy gets hoisting, vectorization and cleanup. Skip loops of marmot-par-body functions (GpuLoopsPass runs at the same point later) and request LoopSimplify and LCSSA in the pass, as Versioning.cpp does inside parallelize.
  2. Parallel-only was a cost choice (entry cost, size, compile time over a whole program). No correctness reason is known.
  3. The trip count test computes backedge-taken count + 1 in a wider type, or with an explicit overflow test. A count of all ones wraps to 0. The same holds for steps other than 1.
  4. Hoisting to M: the no-write test covers every call in M that may write memory (growslice and write barriers included), not only stores. Race assumption: the fast copy reloads b[k] and len(b[k]) after a check done before M. So a concurrent writer could make it index out of bounds, where gc compares against the value that it loaded. Go gives no memory safety for racy multiword writes, and slice headers can tear in gc as well. So the proof note says that the rule holds for race-free programs.
  5. At most 8 versioned loops per function, besides the 50% growth cap.
  6. The switch is listed in backend/include/marmot/Driver/EnvSwitches.def as MARMOT_ENV_OWN (backend's new env switch test fails otherwise).
  7. Measurement adds tuios -release build time, code size per program and the number of loops versioned per program.

Interactions

  • Cache: the switch is a CompileOptions field from the start (MARMOT_LOOPS_VERSION read in marmot-backend.cpp), in WholeProgram.cpp's fingerprint (opts.loops.*) and in loops::cacheKey. An env-only switch would reuse cached objects (the B4 lesson).
  • Whole-program builds: versioning runs per module or function group at the optimizer-early extension point, after inlining, as parallelize does. Split modules (-split-large) version each group on its own, which is correct because a loop is never split across groups.
  • Vectorizer: a fully versioned fast copy has a single exit, which LLVM can vectorize. But Go's float semantics forbid reordering a float sum without -fast-fp, so matmul's inner reduction stays scalar. Its gain is the removed compares, branches and length loads, not SIMD.
  • tier0 and dev builds: unchanged (O2 and up only, release by default once flipped).

Measurement plan

  1. Experiment build (private), the bench set under callgrind: instructions per program with and without the switch, beside the ceiling numbers above.
  2. Code size of tuios and the bench set at -release (SPEC 3c: 0.8x of go), release build time (0.8x).
  3. Gates: the conformance matrix with the switch on, a fuzz round (tests/fuzz with -release) and the adversarial programs of verify (progs.sh). Then perfcmp in dev, O2 and release with -b-env MARMOT_LOOPS_VERSION=1, exit 0 before a flip.

Expected effect

From the ceiling: matmul can lose up to about half of its instructions if the three checks and the row length loads go. Hoisting makes that possible. Fannkuch, generic, regexpbench: 5 to 15%, depending on how many of their loops have affine indexes and a long enough trip count. The rest: no change. Risk: code size (one copy per versioned loop), build time (ScalarEvolution per loop), and the cost policy's threshold.

Revision 2 (2026-11-18): what the first gate showed, and the next design

Status: proposal for backend review. The opt-in mode landed (381316a0, dd7d8be5). It is not the default.

Findings

  1. perfcmp at 381316a0 (-b-env MARMOT_LOOPS_VERSION=1, O2 and release, INCONCLUSIVE at load 11.3, it would have said WORSE): O2 matmul 1.353 wall. Callgrind had shown -11.4% instructions in release.
  2. Cause: hoisting (proposal 3 above) was not built. The measurement went "no hoist first". The loaded-bound check loop ran on every entry of matmul's inner loop: 400 iterations of a serial cmov min chain over the 800 row lengths. The fast loop is bound by the latency of the float sum (Go forbids reordering it), so its removed compares saved no cycles. Fewer instructions, more cycles.
  3. Every bench binary changes with the switch, because cold runtime loops are versioned (goargs, MemProfile, memprofRecords, fdecimal.leftShift). This costs size and moves the layout of hot code for no gain, and it makes perfcmp rows of unchanged hot code noisy.
  4. Fixed now (dd7d8be5): the switch no longer turns on loaded bounds. Pin and stride stay.

Proposal

A. Loaded bounds only with hoisting (proposal 3, now required, not optional). The check loop goes to the preheader of the outermost loop M where base, start, step and count are invariant. Also nothing in M may write the loaded memory: stores and calls, growslice and write barriers included. The race note of review point 4 holds. If M would be L itself, the loop is not versioned with a loaded bound. Cost then: one check loop per execution of M, not per entry of L. A2. Read safety of a hoisted check loop (found while planning the code, not in the review). Today the check loop runs in the guard block of L, after the scalar conditions. These conditions keep its reads in bounds. For matmul, k <= count < len(b), so every b[k] header read is inside b. In the preheader of M, those scalar conditions are not evaluated yet. So a check loop could read past the end of the backing array of b. That is a fault at a page end, where Go would panic in order. So the conditions of every check that dominates the bound load in L must be invariant in M too. They are evaluated in the preheader of M before the check loop. If one is not, the loop is not versioned. The proof note gets this as a precondition of the hoisting lemma. A2b. As built (63425c89): "checks that dominate the bound load" is a conservative stand-in for the checks that guard the load's address. In matmul, the check on a[i] (k < len(a[i])) dominates the b[k] header load and varies with i. So M is the j loop. That is one check loop per row, not one per nest: 800 reads against 640000 inner iterations, about 0.1%. A finer rule (only checks whose index feeds the bound load's address) would hoist to the whole nest. Not built, since the per-row cost is negligible. A4. This is the state after the backend review of 63425c89 (not landed). The check loop in the preheader of M was unsafe when the row index bound comes from outside L. Examples are an if around L inside M, or a zero-trip M. The check loop then read past b with no guard. Proof by test: with b's headers at the end of a page before a PROT_NONE page, the hoisted build faulted where gc prints "sum 0". A cache replaced it. The check loop stays at the guard of L, with the same place and guards as before. It runs only on the first entry of L in a run of M. A done flag and the min/max sit in stack slots reset at M's preheader and promoted to registers. M's conditions stay (inputs invariant in M, no calls, no aliasing store). The A2 read guard is no longer needed. Cost per entry: one flag test. LoopInfo is updated (new blocks into L's parent, each check loop body a loop) and checked against a fresh LoopInfo under -verify-loop-info. A5. Race note (backend review point 3): the cache widens the window of review point 4. The fast copy trusts lengths read once per run of M, not once per entry of L. So a racy writer that shortens a row in between gives an out-of-bounds read without a panic. Same class as point 4 (Go gives no memory safety to racy multiword writes). The proof holds for race-free programs. A3. Expected gain, to measure first: matmul's fast loop stays bound by the float sum's latency, so even a hoisted check may give no cycles back. Job verify-sh-dd7d8be5a5-1118-154926 measures the no-check ceiling in cycles (perf stat cycles:u, 8 programs). A is built only if the ceiling shows a cycle gain of at least 3%. B. Cost policy, new rule: skip functions of standard library packages (the runtime included). Marker: a function attribute "marmot-std" (passthrough) that the frontend sets on every function of a package the loader reports as Standard (go list .Standard). It must be per function: WPO import and split parts move functions between modules. The backend tests F.hasFnAttribute("marmot-std"). Fallback until the attribute lands: the symbol's package path, std when its first path element has no dot and is not main. Known gap of the fallback: a module path without a dot in its first element (module foo) is legal. Its packages count as std, so they are never versioned. Lossy in both forms: generic instances keep the generic package name, so slices.SortFunc[main.T] counts as std although its loops run on user data. The runtime C symbols fall in std, as wanted. Reason for the rule: without a profile, std loops are cold in most programs. The bench data shows no std gain (regexpbench, sortslice, stringsearch within 0.05%). Revisit with PGO, which knows hot std code. C. Cost policy, per-entry precondition: what runs on every entry of L must be O(1) (compares of SCEV values). Anything with a loop (a check loop) must be hoisted out of every loop around L (A). D. Measure cycles, not instructions: perf stat -e cycles:u works on Linux with paranoid 2, which allows user events. Every candidate gets perf stat cycles before a perfcmp. Callgrind stays for attribution only.

Proof obligations (additions)

  • A: the hoisting lemma from "What must still hold" above: a fold over unchanged memory gives the same result. Also the invariance of base, start, step and count over M. verify/check re-checks the hoist point and that M has no write to the loaded base.
  • B and C: none (they only skip loops, skipping keeps the original code).

Measurement

  1. Perf stat cycles:u, generic and matmul, O2 and release, A/B (job verify-sh-dd7d8be5a5-1118-151034).
  2. After A and B: measure cycles on the bench set with hot changes only. First list the binaries whose hot code differs. Then run perfcmp -modes O2,release with generic in -programs.

On this page

Was this page helpful?

Report an issueOpen issues