Skip to content

eZ80: no-wrap range facts restore the index fold (fusion_window_sum 2× faster) + widening byte-add wrong-code fix - #376

Merged
oisee merged 8 commits into
mainfrom
perf/ez80-nowrap-fold
Dec 1, 2026
Merged

oisee merged 8 commits into
mainfrom
perf/ez80-nowrap-fold

Conversation

@oisee

@oisee oisee commented Dec 1, 2026

Copy link
Copy Markdown
Owner

#370 fixed a wrong-code bug by refusing to fold a 16-bit index into a 24-bit eZ80 address everywhere. That made fusion_window_sum about 2× slower. This PR brings the fold back wherever the compiler can prove i + k does not wrap.

Range facts (pkg/mir2/nowrap_range.go)

The analysis runs on SSA MIR and is conservative: anything it cannot answer gets the full range of its width.

  • Value ranges:
    • constants, moves, zero-extension, AND;
    • shifts and multiplies, only while the exact result fits;
    • add and sub, only while the exact result fits;
    • block parameters: the union of the incoming values, each narrowed by the branch that passes it.
  • Compare facts: unsigned br_if, cond_ret and br_if2 edges. A fact holds in every block dominated by a single-predecessor edge target.
  • Load equivalence: two loads of the same global are the same value when no store can happen between them.
  • Where the proofs are recorded: MarkADLNoWrapAdds runs before coalescing. The emitter folds only when there is a matching proof.
    • When both widenings are zero-extending, the proof is hi(i) + k <= 0xFFFF.
    • When a widening is signed, the proof is <= 0x7FFF.
  • adl_index_share.go also accepts these facts.
  • eZ80 ptr_add with an immediate base now widens before LD HL, sym. This removes a PUSH/POP.

Wrong code fixed (Z80, Z80N, eZ80; already on main)

genWideningByteAdd fused ext(b) into an add the fold had already made silent, so the address used a garbage high byte.

  • Reproducer: TestFoldedAddIsNotFusedIntoWideningByteAdd. On main for Z80, blob[5 + u16(k >> 3)] gives 0; the right answer is 90.
  • The fix changes no product in the corpus.

Tests

Gates

  • Z80:
    • compile_sweep 0 changes;
    • C bench 1.0000;
    • fast profile PASS;
    • fuzzers: direct-call 0–19999 20000/20000, --signed 4000/4000, folded 3000/3000, byte-shifts 3000/3000.
  • Z80N: identical to main; fuzz_diff --target z80n 1000 + 1000.
  • eZ80:
    • corpus failures identical to main;
    • fuzz_diff --target ez80 2000 + 2000, fuzz_ptr 2000, fuzz_nowrap 2000;
    • Agon player byte-exact.

eZ80 cycles

main now
fusion_window_sum default 559,165 284,605 (0.51×)
fusion_window_sum size 622,635 258,315 (0.41×; the pre-#370 value)
checksum16 default 13,858,560 8,531,672 (0.62×)
bench geomean — 0.956 default / 0.964 size, no case slower
large eZ80 benchmark program — −0.5 % (v4) / −1.1 % (v0)
Agon player, cycles per frame 11,280 11,066

🤖 Generated with Claude Code

https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

oisee and others added 8 commits December 1, 2026 03:48
…ere i + k provably does not wrap

#370 turned the fold ptr_add @sym, (add i, k) -> (sym+k) + i off for every
ADL function, because the 16-bit sum is widened to 24 bits before the
address add and the two forms differ when i + k wraps. That made the C
benchmark case fusion_window_sum about 2x slower on the eZ80.

rangeFacts (nowrap_range.go) bounds 8/16-bit values from what SSA MIR
shows: constants, moves, byte zero-extension, AND, logical shifts, shifts
and multiplies by constants, exact add/sub, block parameters as the union
of their incoming arguments (each refined by the branch passing it; an
invariant passed back unchanged adds nothing), and compare facts from
br_if / cond_ret / br_if2 on unsigned compares, valid in every block the
decided edge dominates. Two loads of one global with no memory write on
any path between them count as one value (C lowers "if (c > limit)
c = limit" with two loads of limit). Everything else gets its full width.

MarkADLNoWrapAdds records, before PreallocCoalesce (the MIR stops being
SSA there), an upper bound on i + k for each word add of a constant
1..255; the emitter's fold reads it after allocation and requires
i + k <= 0xFFFF when both forms widen with zeros, else <= 0x7FFF. Without
a recorded proof the fold stays off. MZ_W59_NOWRAP=0 turns the proofs off
(measurement). Z80/Z80N output is unchanged (the fold there never needed
a proof).

Tests: TestNoWrapRange* (counted loops under a constant, byte, masked,
shifted or unknown bound: i + 1 proven, i + 2 refused at 0xFFFF; the
#370 parameter case, a down-counting loop, facts on the wrong edge / at a
join / from a signed compare, the clamped count with and without a store
between the loads), TestADLFoldNoWrapSignedLimit, and on the eZ80
emulator TestEZ80NoWrapFoldRefusedWhenIndexWraps (wrapping indices keep
the unfolded form and read arr[0]) and TestEZ80NoWrapFoldMadeWithProof
(window sum, guarded and masked index fold and give the right values).
TestEZ80PtrAddConstantFoldWraps fails with the unchecked fold (got 0,
want 7) and passes with this one.

fusion_window_sum, eZ80 cycles: before #370 267,280 (default) / 258,315
(size); main 559,165 / 622,635; now 284,605 / 258,315 (the unchecked fold
gives the same; the remaining default gap is allocation, not the fold).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
ShareADLIndexArithmetic rewrites ptr_add B, scale(ext(i + c)) into a field
access c past a dominating ptr_add B, scale(ext(i)) only when i + c cannot
wrap at i's width. The #370 proof accepted a loop induction counting up
from a constant under its own exit test; now an upper bound on i from
rangeFacts (nowrap_range.go) is accepted too: a dominating i < n with n a
byte, a masked value or a constant, the clamped-count shape, and so on.

eZ80 C benchmark: checksum16 13,858,560 -> 9,187,032 cycles (default),
the other 25 cases unchanged. The Agon player's assembly changes (byte-
exact: see the PR gates); FJORD-sized eZ80 benchmark program v0 avg
2,758,373 -> 2,755,909 cycles per picture, v4 unchanged. Z80 unaffected
(the pass runs for ADL only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
…ading the base

The generic ptr_add path loaded an immediate base (sym or a folded sym+k)
into HL and then widened the 16-bit offset pair to 24 bits, a sequence
that uses HL and so saved it around itself (PUSH HL ... POP HL, 8 cycles,
2 bytes). With an immediate base HL is about to be overwritten anyway:
the widening now comes first and its HL save is dead (adl_upper removes
it). Before this, a folded index held in IY cost more than the unfolded
form (stars+1 in the large eZ80 benchmark program's star loop). ADL only;
the Z80 path is unchanged.

eZ80 C benchmark: checksum16 9,187,032 -> 8,531,672 (default),
13,532,160 -> 12,389,760 (size); others unchanged. Large eZ80 benchmark
program, avg cycles per picture (600 pictures, byte-exact): v4 1,795,258
-> 1,785,616 (-0.5%), v0 2,755,909 -> 2,728,746 (-1.0%). Agon player avg
11,280 (main) -> 11,066 cycles per frame with this and the two commits
before it (not measured separately), byte-exact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
…c at the 16-bit wrap

Each seed is one function over a 32-byte and a 256-byte table whose
accesses arr[i + K] run with i in a window that keeps them in bounds:
0 <= i + K < 32, or i in 65536-K..65535 where the 16-bit sum wraps to
0..K-1. Shapes: up-counting loops under a literal, parameter, masked,
byte or clamped-count bound, down-counting loops, a guard compare (either
branch, all four unsigned relations, bounds near 0xFFFF), a masked index,
and byte-index loops reading tab[j] and tab[j + K] (u8 wrap, adjacent-
element sharing). Two value sets per program, oracle in Python, C and
Nanz, mz -b ez80 --asserts-force ez80, default and --Osize. It reports
how many addresses were folded (arr+K / tab+K in the assembly).

Seeds 0-199: this branch 200/200 with 530 folds; main 200/200 with 0
folds; a build with the fold made unconditionally (the #370 bug) fails
on wrapping seeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
…ong code, Z80 and eZ80)

ptrAddConstantFolds emits ptr_add @sym, (add c, ext(b)) as
(sym+c) + ext(b): the add emits nothing and the ptr_add reads the
extension's home as its index. genWideningByteAdd, at the extension, fused
it into that same add (reading the byte directly), so the extension never
reached its home and the address took whatever the home's high byte held.

Reduced: TestFoldedAddIsNotFusedIntoWideningByteAdd, blob[5 + u16(k >> 3)]
with B = 3 left by the caller: got 0, want 90 on Z80 (main; also Z80N by
the CLI), and on eZ80 once the fold is made again (TestEZ80ADLFindings
F07F12 failed with the no-wrap fold: got 0, want 10). The widening add now
leaves a folded add alone. No product of the Z80/Z80N corpus or the C
benchmark changes (compile_sweep 0 changes, Z80N text identical), nor any
eZ80 product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
…sion

arr[u16(b >> SH) + K] and arr[u16(b & M) + K]: the extension feeds the
folded add, the shape of the widening-add wrong code fixed in the
previous commit. Seeds 0-299: 300/300, 948 folded addresses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
…owrap-fold

One conflict, in the generic ptr_add path of z80codegen_inst.go: #374
asks the base's representation (address24) where this branch asked the
target (wide24) around the immediate-base widening; both widening sites
now use address24(base).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
No conflicts (#375: Frill, ObjC vtables on Z80, assert sandbox externs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

PR tests: 🟢 pass

Commit: aff5bf2f · Full test log

Check Result
Complete fresh Ruby/Crystal native pipeline 🟢 pass
Inherited compiler and complete frozen native gates 🟢 pass
Build mz, mza, mze, mzv 🟢 pass
Fast compiler regressions (deep suites run separately) 🟢 pass
Fibonacci compile + assemble 🟢 pass
Nanz language regressions 🟢 pass
Z3 West of House demo 🟢 pass
Z3 small conformance fixtures 🟢 pass

Deep pipeline domains and the full assertion corpus run on release tags, nightly and manual audits.
The external CZECH and full Zork I stories are not part of this PR gate.

@oisee
oisee merged commit 8b6d96c into main Dec 1, 2026
13 checks passed
oisee added a commit that referenced this pull request Dec 2, 2026
…ved) + eZ80 loop data movement, gap-example benchmarks (#380)

* Pin @z80_ixh/@z80_ixl/@z80_iyh/@z80_iyl parameters to their own half

The four index-half annotations all became ClassIXY8, a class any of
IXH/IXL/IYH/IYL satisfies. The callee's allocation was free to put an
@z80_ixl parameter in IXH, the caller followed that contract, and an
inline-asm body reading IXL got the other argument: with five register
arguments the call site emitted LD IXL,IXH / LD IXH,A and the two bytes
arrived swapped. The physical-alias form of an asm (in IXL, IXH) list
matched both names to the first ClassIXY8 parameter for the same reason.
Not a parallel-move problem: the copy was correct for the contract it
was given. Z80, Z80N and eZ80 were all affected.

Add hard-pin classes ClassRegIXH/IXL/IYH/IYL (appended after ClassFlag,
so existing class numbers and MIR dumps are unchanged), priced 0 only on
their half, and map the annotations and asm aliases to them.

scripts/fuzz_regargs.py: fuzz_diff only generates calls with up to three
u16 arguments and no annotations, so it cannot reach this. The new
generator builds 4-6-argument calls in annotated registers (index halves
included) through a forwarding function, so the parallel copy permutes
and breaks cycles; an asm leaf folds the bytes in order. On main 150 of
the first 200 seeds fail on Z80 and on eZ80; with the fix 2000/2000 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word compare: leave a live A to genCmp16's own save

When A holds a live value and no byte register is free, genCmp saved A on
the stack before every comparison (PUSH BC / PUSH AF ... POP BC / LD A,B /
POP BC, 17 cycles on eZ80). For a word comparison of two pairs that save
is redundant: genCmp16's general SBC HL,rr path runs under
saveWrittenScratch, which already saves each live register its body
writes, and SBC HL,rr does not write A. Skip the outer save for exactly
that path (not for a constant-zero right operand, whose BIT/OR forms
write A outside the wrapper).

Measured (eZ80 cycles): gap-map example x1 11,502 -> 9,802; large program
v0 2,728,746 -> 2,726,577, v4 1,785,616 -> 1,784,815 (both byte-exact);
eZ80 and Z80 C benchmarks unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Scratch saves: an i16 store through HL restores HL itself

saveWrittenScratch exempts the canonical word store LD (HL),lo / INC HL /
LD (HL),hi / DEC HL from saving a live HL, since the sequence ends with HL
unchanged. The exemption tested inst.Ty == TyU16, so the same sequence for
an i16 store pushed and popped the pointer around itself (8 cycles on
eZ80 per store through a loop-carried pointer). Take i16 too; the shape
check is unchanged.

Measured (eZ80 cycles): x1 9,802 -> 9,242; v4 1,784,815 -> 1,776,863,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add of a constant 1..3: advance the pointer in place with INC rr

`p = p.bytes(2)` lowers to ptr_add p, 2, not ptr_bump, and the generic
ptr_add form loaded the constant into a scratch pair and added it
(LD BC,2 / ADD HL,BC, with saves of a live scratch pair). When the result
and the base share a pair, emit INC rr per byte as OpPtrBump does: no
flags change, and in ADL INC rr carries into the upper byte like the
24-bit ADD it replaces (positive offsets only, so zero and sign extension
of the offset agree).

Measured (eZ80 cycles): x1 9,242 -> 8,942; v4 1,776,863 -> 1,772,628,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Dead constants: the offset of an INC-form ptr_add has no home

computeDeadConsts did not know that a ptr_add advancing a base in its own
pair by 1..3 is now INC rr, so the constant kept a home through the
allocator's trial. In x1 that home was BC, live exactly where the fraction
byte t needed the last free byte register, and t went to a static spill
slot stored and reloaded every iteration. Count that use as folded, with
the same conditions as tryPtrAddSmallConst (non-constant base, base and
result in the same pair).

Measured (eZ80 cycles): x1 8,942 -> 7,342 (no spill slot left in the
loop); v0, v4 unchanged (byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: gap-map examples x1-x6 as cycle-budget benchmarks

Six reduced loop shapes where natural Nanz loses to hand code on the
eZ80 (register allocation in a leaf loop and around a call, loop bound /
index work, invariants and induction variables, inlining a multiply
helper, guard-range products). TestEZ80GapExamples compiles each with a
small harness for the bare eZ80 shape, runs it with poisoned registers,
checks the shown results and fails when the region between OUT ($40) and
OUT ($41) exceeds its budget (today's cycles; lower a budget when a change
improves it). The hand-code cycles are recorded next to each budget as
the target, in the style of TestEZ80ADLVertexBench.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: pair copies out of IX/IY with LEA, HL into IX/IY through DE

The ADL emitter copies one pair to another with PUSH x / POP y (all 24
bits, flags kept), and adlLocalRewrites turns that into byte loads when
y's upper byte is dead. Copies out of IX/IY into HL, the other index
register, or a pair whose upper byte is live stayed on the stack: PUSH IX
/ POP HL is 9 cycles, and the scene runs such copies on every hot path.

- PUSH IX|IY / POP y -> LEA y, IX|IY+0 (3 cycles, exact 24-bit copy, no
  flags). The byte copy is kept when one of y's halves is dead, since
  that half's load is deleted afterwards (2 cycles).
- PUSH HL / POP IX|IY with the index register's upper byte dead ->
  EX DE,HL / LD IXH,D / LD IXL,E / EX DE,HL (6 cycles, flags kept).
- The upper-byte fact of IX/IY travels through LEA rr,IX+0 as it did
  through the stack, so widenings it made redundant stay removed.

Measured (eZ80 cycles): v0 2,726,577 -> 2,667,858 (-2.2%), v4 1,772,628
-> 1,732,267 (-2.3%), both byte-exact; x1 7,342 -> 7,242, x2 10,769 ->
10,313, x3 10,577 -> 10,492, x4 19,242 -> 18,212, x5 4,710 -> 4,542, x6
4,516 -> 4,452; eZ80 C benchmark geomean 0.9913 (default) / 0.9923
(size), no case slower. ADL-only pass: Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: take a PUSH x ... POP y copy at the POP when x is not written between

The emitter's parallel copies sequence a cycle as PUSH x / moves / POP y
(e.g. PUSH IY / LD B,D / LD C,E / POP DE for BC <- DE, DE <- IY), and the
pair-copy rewrites only matched an adjacent PUSH/POP. When nothing
between writes x, x still holds the pushed value at the POP, and the slot
is the POP's alone (adlMatchingPop admits no SP-relative access, branch
or label in between), so the same copy forms apply there: LEA y,IX|IY+0,
the byte loads, or HL -> IX|IY through DE. The EX DE,HL form, which
changes the source, still needs the two to be adjacent.

Measured (eZ80 cycles): v4 1,732,267 -> 1,705,702 (-1.5%), v0 2,667,858
-> 2,654,688, both byte-exact; x2 10,313 -> 9,857, x3 10,492 -> 10,186,
other examples unchanged; eZ80 C benchmark unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 gap examples: lower the budgets to this branch's cycles

x1 7,342 -> 7,242, x2 10,769 -> 9,857, x3 10,577 -> 10,186, x4 19,242 ->
18,212, x5 4,710 -> 4,542, x6 4,516 -> 4,452 (the ADL pair-copy rewrites).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add: load a homeless offset constant as an immediate

a96461a lets the dead-constant inventory drop the home of a ptr_add
offset 1..3 when the allocation puts base and result in one pair, since
tryPtrAddSmallConst emits INC rr. The inventory reads the allocation; the
emitter tests its current homes, which a relocation can change, and then
falls to the generic form, which read the dropped home. On Z80 that
miscompiled two C corpus files (assert_matrix: dowhile_break.c
chain_length, fatfs_lowlevel.c test_ld_word / test_fat12_entry, 9
asserts). The generic form now loads such an offset with LD rr,n.

Examples and gap budgets unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word add of 1: keep the HL operand swap unless INC rr will serve

genBinOp swaps a word ADD's operands when the right one lives in HL,
because the ADD path loads the left one into HL first. It skipped the
swap for an in-place step of 1 (lhs and result in one pair), expecting
the INC rr peephole further down, but that peephole also requires the
add's flags to be unobserved (and a register result). When they are
observed the ADD path ran, loaded lhs over the constant and emitted
i = i + i (PUSH BC / POP HL / ADD HL,HL): a loop counting from 0 never
ended. Gate the skip on the same conditions as the peephole.

The defect is in the target-independent word ADD path (older than the
eZ80 work; not introduced by #376). The reduced example is correct up to
#367 (fbb7172) and wrong from #368 (b4a013e, loop- and call-aware
eZ80 allocation), whose allocation of the shape (a conditional call
before the loop, a callee with its own loop, an index base + i) first
puts the constant in HL with the flags observed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* CI: classify this branch's new pipeline tests in the fast profile

run_stable_pipeline.py refuses unclassified tests. The eight new tests
(IX-half parameters, word compare / store / pointer-step / dead-offset
checks, the gap-map example budgets, the word unit-step fix) run in a
few seconds together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add INC form: eZ80 only

On the Z80 the INC rr form of a small constant pointer step (217b285,
a96461a) made the plain byte path of the FAT12 word workload faster
than its profile-guided word fusion (TestFATSequentialWordFusionNative:
unfused 92,928 -> 76,800 T against fused 89,088) and moved the pinned
deltas of TestFAT12BytePackingRetainsNativeAccessesAndWrap and
TestProfileGuidedSumVMZ80. Those are measurements of other passes, so
keep the Z80 product as it was: emit the form, and drop the offset's
home in the dead-constant inventory, only for 24-bit pairs (eZ80). The
eZ80 numbers are unchanged (gap budgets hold); the immediate fallback
of b50e4a8 stays for any disagreement between the two gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril canonical6 fixture: refresh MIX.COM hash after the smaller Z80 output

The fresh CI run shows every stage boundary still equal to the original Ruby;
only the compiled MIX.COM bytes changed (hash taken from that run's evidence).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril mix frozen replay: refresh the snapshot after the smaller Z80 output

Regenerated with freeze.py from this PR's fresh CI run. Only compiled-image
hashes, image sizes and T-state counts change; every case result is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
oisee added a commit that referenced this pull request Dec 2, 2026
…re, spill-victim guard, rotated zero test (#382)

* Pin @z80_ixh/@z80_ixl/@z80_iyh/@z80_iyl parameters to their own half

The four index-half annotations all became ClassIXY8, a class any of
IXH/IXL/IYH/IYL satisfies. The callee's allocation was free to put an
@z80_ixl parameter in IXH, the caller followed that contract, and an
inline-asm body reading IXL got the other argument: with five register
arguments the call site emitted LD IXL,IXH / LD IXH,A and the two bytes
arrived swapped. The physical-alias form of an asm (in IXL, IXH) list
matched both names to the first ClassIXY8 parameter for the same reason.
Not a parallel-move problem: the copy was correct for the contract it
was given. Z80, Z80N and eZ80 were all affected.

Add hard-pin classes ClassRegIXH/IXL/IYH/IYL (appended after ClassFlag,
so existing class numbers and MIR dumps are unchanged), priced 0 only on
their half, and map the annotations and asm aliases to them.

scripts/fuzz_regargs.py: fuzz_diff only generates calls with up to three
u16 arguments and no annotations, so it cannot reach this. The new
generator builds 4-6-argument calls in annotated registers (index halves
included) through a forwarding function, so the parallel copy permutes
and breaks cycles; an asm leaf folds the bytes in order. On main 150 of
the first 200 seeds fail on Z80 and on eZ80; with the fix 2000/2000 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word compare: leave a live A to genCmp16's own save

When A holds a live value and no byte register is free, genCmp saved A on
the stack before every comparison (PUSH BC / PUSH AF ... POP BC / LD A,B /
POP BC, 17 cycles on eZ80). For a word comparison of two pairs that save
is redundant: genCmp16's general SBC HL,rr path runs under
saveWrittenScratch, which already saves each live register its body
writes, and SBC HL,rr does not write A. Skip the outer save for exactly
that path (not for a constant-zero right operand, whose BIT/OR forms
write A outside the wrapper).

Measured (eZ80 cycles): gap-map example x1 11,502 -> 9,802; large program
v0 2,728,746 -> 2,726,577, v4 1,785,616 -> 1,784,815 (both byte-exact);
eZ80 and Z80 C benchmarks unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Scratch saves: an i16 store through HL restores HL itself

saveWrittenScratch exempts the canonical word store LD (HL),lo / INC HL /
LD (HL),hi / DEC HL from saving a live HL, since the sequence ends with HL
unchanged. The exemption tested inst.Ty == TyU16, so the same sequence for
an i16 store pushed and popped the pointer around itself (8 cycles on
eZ80 per store through a loop-carried pointer). Take i16 too; the shape
check is unchanged.

Measured (eZ80 cycles): x1 9,802 -> 9,242; v4 1,784,815 -> 1,776,863,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add of a constant 1..3: advance the pointer in place with INC rr

`p = p.bytes(2)` lowers to ptr_add p, 2, not ptr_bump, and the generic
ptr_add form loaded the constant into a scratch pair and added it
(LD BC,2 / ADD HL,BC, with saves of a live scratch pair). When the result
and the base share a pair, emit INC rr per byte as OpPtrBump does: no
flags change, and in ADL INC rr carries into the upper byte like the
24-bit ADD it replaces (positive offsets only, so zero and sign extension
of the offset agree).

Measured (eZ80 cycles): x1 9,242 -> 8,942; v4 1,776,863 -> 1,772,628,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Dead constants: the offset of an INC-form ptr_add has no home

computeDeadConsts did not know that a ptr_add advancing a base in its own
pair by 1..3 is now INC rr, so the constant kept a home through the
allocator's trial. In x1 that home was BC, live exactly where the fraction
byte t needed the last free byte register, and t went to a static spill
slot stored and reloaded every iteration. Count that use as folded, with
the same conditions as tryPtrAddSmallConst (non-constant base, base and
result in the same pair).

Measured (eZ80 cycles): x1 8,942 -> 7,342 (no spill slot left in the
loop); v0, v4 unchanged (byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: gap-map examples x1-x6 as cycle-budget benchmarks

Six reduced loop shapes where natural Nanz loses to hand code on the
eZ80 (register allocation in a leaf loop and around a call, loop bound /
index work, invariants and induction variables, inlining a multiply
helper, guard-range products). TestEZ80GapExamples compiles each with a
small harness for the bare eZ80 shape, runs it with poisoned registers,
checks the shown results and fails when the region between OUT ($40) and
OUT ($41) exceeds its budget (today's cycles; lower a budget when a change
improves it). The hand-code cycles are recorded next to each budget as
the target, in the style of TestEZ80ADLVertexBench.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: pair copies out of IX/IY with LEA, HL into IX/IY through DE

The ADL emitter copies one pair to another with PUSH x / POP y (all 24
bits, flags kept), and adlLocalRewrites turns that into byte loads when
y's upper byte is dead. Copies out of IX/IY into HL, the other index
register, or a pair whose upper byte is live stayed on the stack: PUSH IX
/ POP HL is 9 cycles, and the scene runs such copies on every hot path.

- PUSH IX|IY / POP y -> LEA y, IX|IY+0 (3 cycles, exact 24-bit copy, no
  flags). The byte copy is kept when one of y's halves is dead, since
  that half's load is deleted afterwards (2 cycles).
- PUSH HL / POP IX|IY with the index register's upper byte dead ->
  EX DE,HL / LD IXH,D / LD IXL,E / EX DE,HL (6 cycles, flags kept).
- The upper-byte fact of IX/IY travels through LEA rr,IX+0 as it did
  through the stack, so widenings it made redundant stay removed.

Measured (eZ80 cycles): v0 2,726,577 -> 2,667,858 (-2.2%), v4 1,772,628
-> 1,732,267 (-2.3%), both byte-exact; x1 7,342 -> 7,242, x2 10,769 ->
10,313, x3 10,577 -> 10,492, x4 19,242 -> 18,212, x5 4,710 -> 4,542, x6
4,516 -> 4,452; eZ80 C benchmark geomean 0.9913 (default) / 0.9923
(size), no case slower. ADL-only pass: Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: take a PUSH x ... POP y copy at the POP when x is not written between

The emitter's parallel copies sequence a cycle as PUSH x / moves / POP y
(e.g. PUSH IY / LD B,D / LD C,E / POP DE for BC <- DE, DE <- IY), and the
pair-copy rewrites only matched an adjacent PUSH/POP. When nothing
between writes x, x still holds the pushed value at the POP, and the slot
is the POP's alone (adlMatchingPop admits no SP-relative access, branch
or label in between), so the same copy forms apply there: LEA y,IX|IY+0,
the byte loads, or HL -> IX|IY through DE. The EX DE,HL form, which
changes the source, still needs the two to be adjacent.

Measured (eZ80 cycles): v4 1,732,267 -> 1,705,702 (-1.5%), v0 2,667,858
-> 2,654,688, both byte-exact; x2 10,313 -> 9,857, x3 10,492 -> 10,186,
other examples unchanged; eZ80 C benchmark unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 gap examples: lower the budgets to this branch's cycles

x1 7,342 -> 7,242, x2 10,769 -> 9,857, x3 10,577 -> 10,186, x4 19,242 ->
18,212, x5 4,710 -> 4,542, x6 4,516 -> 4,452 (the ADL pair-copy rewrites).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add: load a homeless offset constant as an immediate

a96461a lets the dead-constant inventory drop the home of a ptr_add
offset 1..3 when the allocation puts base and result in one pair, since
tryPtrAddSmallConst emits INC rr. The inventory reads the allocation; the
emitter tests its current homes, which a relocation can change, and then
falls to the generic form, which read the dropped home. On Z80 that
miscompiled two C corpus files (assert_matrix: dowhile_break.c
chain_length, fatfs_lowlevel.c test_ld_word / test_fat12_entry, 9
asserts). The generic form now loads such an offset with LD rr,n.

Examples and gap budgets unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word add of 1: keep the HL operand swap unless INC rr will serve

genBinOp swaps a word ADD's operands when the right one lives in HL,
because the ADD path loads the left one into HL first. It skipped the
swap for an in-place step of 1 (lhs and result in one pair), expecting
the INC rr peephole further down, but that peephole also requires the
add's flags to be unobserved (and a register result). When they are
observed the ADD path ran, loaded lhs over the constant and emitted
i = i + i (PUSH BC / POP HL / ADD HL,HL): a loop counting from 0 never
ended. Gate the skip on the same conditions as the peephole.

The defect is in the target-independent word ADD path (older than the
eZ80 work; not introduced by #376). The reduced example is correct up to
#367 (fbb7172) and wrong from #368 (b4a013e, loop- and call-aware
eZ80 allocation), whose allocation of the shape (a conditional call
before the loop, a callee with its own loop, an index base + i) first
puts the constant in HL with the flags observed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* CI: classify this branch's new pipeline tests in the fast profile

run_stable_pipeline.py refuses unclassified tests. The eight new tests
(IX-half parameters, word compare / store / pointer-step / dead-offset
checks, the gap-map example budgets, the word unit-step fix) run in a
few seconds together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add INC form: eZ80 only

On the Z80 the INC rr form of a small constant pointer step (217b285,
a96461a) made the plain byte path of the FAT12 word workload faster
than its profile-guided word fusion (TestFATSequentialWordFusionNative:
unfused 92,928 -> 76,800 T against fused 89,088) and moved the pinned
deltas of TestFAT12BytePackingRetainsNativeAccessesAndWrap and
TestProfileGuidedSumVMZ80. Those are measurements of other passes, so
keep the Z80 product as it was: emit the form, and drop the offset's
home in the dead-constant inventory, only for 24-bit pairs (eZ80). The
eZ80 numbers are unchanged (gap budgets hold); the immediate fallback
of b50e4a8 stays for any disagreement between the two gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril canonical6 fixture: refresh MIX.COM hash after the smaller Z80 output

The fresh CI run shows every stage boundary still equal to the original Ruby;
only the compiled MIX.COM bytes changed (hash taken from that run's evidence).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril mix frozen replay: refresh the snapshot after the smaller Z80 output

Regenerated with freeze.py from this PR's fresh CI run. Only compiled-image
hashes, image sizes and T-state counts change; every case result is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Spill rewrite: do not evict a far hotter neighbour for a temporary that found no register

A rewrite temporary that found no register made the next round spill its
cheapest register-resident neighbour. Next to a loop, once the cold
neighbours were spent, that was the loop's carried values: in the large
benchmark program's add loop a multiply result in the preamble evicted
both accumulators, one round after another, and the loop read and wrote
them through static slots every iteration.

The neighbour is now spilled only while its weighted uses are at most
four times the temporary's (MZ_W77_VICTIM; 0 restores the old rule);
otherwise the temporary keeps its memory home, which foldSpilledTemps
folds. eZ80 speed profile only (the spill rewrite runs nowhere else).

New gap example x7 (neutral reduction of that loop): 62,378 -> 59,584.
Large program natural source 2,654,688 -> 2,622,371 cycles per picture,
restructured 1,705,702 -> 1,705,669; eZ80 C benchmark unchanged.

MZ_PBQP_DEBUG also prints the function, the RN order and spills, and
the spill-rewrite rounds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 allocation: loop-header byte values pay twice the accumulator pressure

A byte value carried around a loop and homed in A holds A through the
whole body: every A-working instruction saves and restores it, and each
save takes a scratch byte register the other loop values could have
used. With frequency weights on (eZ80 speed profile) the accumulator
pressure of loop-header parameters is doubled (MZ_W77_ACCLOOP, percent).
The back-edge values are not charged more: they live only from late in
the body, and charging them pushed a fraction out of A that wanted it
(scene add loop +8k at 3x).

x4 18,212 -> 15,668 (counter i no longer in A; n and x leave memory),
x1 7,242 -> 7,145. Large program natural source 2,622,371 -> 2,621,636,
restructured 1,705,669 -> 1,701,587. eZ80 C benchmark unchanged; the Z80
allocation (no frequency weights) is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Loop rotation: drop the copied zero test of a counter the latch just stepped (eZ80)

A rotated loop header repeats its test at the back edge. For a
down-counted byte counter the latch ends with DEC r, which already sets
Z as the copied test (LD A,r / AND A, often inside a save and restore of
a live A, or INC r / DEC r) would. When nothing between the DEC and the
copy writes the flags or r, no label intervenes, and the copy's branches
read Z only, the test is dropped; what the save staged into A is kept as
one LD A,y.

Gated by the new target policy PolicyRotatedZeroTest (eZ80);
MZ_W77_ZTEST_Z80=1 applies it on the Z80 for measurement,
MZ_W77_ZTEST=0 disables it.

x1 7,145 -> 6,745. Large program restructured 1,701,587 -> 1,697,352
cycles per picture (its column-minimum walk), natural source unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 allocation: charge HL/DE homes of loop-carried words live across address arithmetic

The emitter forms indexed addresses in HL (ADD HL,rr for a pointer add,
ADD HL,HL for a scaled index). A word carried around a loop and homed in
HL or DE is saved and restored around each of them (PUSH HL/POP HL, EX
DE,HL pairs, PUSH/POP moves to BC/IX). With frequency weights on (eZ80
speed profile), a new PBQP term charges the HL and DE homes of
loop-header words by the weighted number of pointer adds and word shifts
in the loop they are live across and not operands of (MZ_W77_HLP=12,
MZ_W77_DEP=8 per weighted instruction). Steps on a carried value's own
update chain (p = p + 2, yh = yh + sh + 1) do not count: they update the
home in place. Charging word adds and subtracts as well moved values of
an arithmetic-only loop into memory (palette search +7k), so only address
arithmetic counts.

x7 59,584 -> 40,148, x4 15,668 -> 14,983, x5 4,542 -> 4,294. Large
program natural source 2,621,636 -> 2,453,354 cycles per picture (its add
loop's column index leaves HL), restructured 1,697,352 -> 1,694,278.
eZ80 C benchmark unchanged; Z80 allocation unchanged (no weights).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* HL pressure: leave loop accumulators their HL home

A carried word summed with a non-constant on its own update chain (sum =
sum + word) is added in place only in HL; elsewhere the sum is staged
through HL with PUSH/POP moves, which costs more than the saves around
the address arithmetic. The HL pressure no longer charges such
accumulators (MZ_W77_HLACC=0 restores the charge).

The previous commit's benchmark check ran a stale ez80_bench binary: it
had made checksum16 9.05% slower (sum moved from HL to BC). With this
change checksum16 is back to 8,531,032 cycles; fusion_window_sum loses
its 3% gain and x5 goes back to 4,542 (its budget returns to the value
it had before the previous commit). x7 stays at 40,148. Large program
natural source 2,453,354 -> 2,454,507, restructured 1,694,278 ->
1,695,399 cycles per picture.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
oisee added a commit that referenced this pull request Dec 2, 2026
…ks, signed range test as one compare (#383)

* Pin @z80_ixh/@z80_ixl/@z80_iyh/@z80_iyl parameters to their own half

The four index-half annotations all became ClassIXY8, a class any of
IXH/IXL/IYH/IYL satisfies. The callee's allocation was free to put an
@z80_ixl parameter in IXH, the caller followed that contract, and an
inline-asm body reading IXL got the other argument: with five register
arguments the call site emitted LD IXL,IXH / LD IXH,A and the two bytes
arrived swapped. The physical-alias form of an asm (in IXL, IXH) list
matched both names to the first ClassIXY8 parameter for the same reason.
Not a parallel-move problem: the copy was correct for the contract it
was given. Z80, Z80N and eZ80 were all affected.

Add hard-pin classes ClassRegIXH/IXL/IYH/IYL (appended after ClassFlag,
so existing class numbers and MIR dumps are unchanged), priced 0 only on
their half, and map the annotations and asm aliases to them.

scripts/fuzz_regargs.py: fuzz_diff only generates calls with up to three
u16 arguments and no annotations, so it cannot reach this. The new
generator builds 4-6-argument calls in annotated registers (index halves
included) through a forwarding function, so the parallel copy permutes
and breaks cycles; an asm leaf folds the bytes in order. On main 150 of
the first 200 seeds fail on Z80 and on eZ80; with the fix 2000/2000 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word compare: leave a live A to genCmp16's own save

When A holds a live value and no byte register is free, genCmp saved A on
the stack before every comparison (PUSH BC / PUSH AF ... POP BC / LD A,B /
POP BC, 17 cycles on eZ80). For a word comparison of two pairs that save
is redundant: genCmp16's general SBC HL,rr path runs under
saveWrittenScratch, which already saves each live register its body
writes, and SBC HL,rr does not write A. Skip the outer save for exactly
that path (not for a constant-zero right operand, whose BIT/OR forms
write A outside the wrapper).

Measured (eZ80 cycles): gap-map example x1 11,502 -> 9,802; large program
v0 2,728,746 -> 2,726,577, v4 1,785,616 -> 1,784,815 (both byte-exact);
eZ80 and Z80 C benchmarks unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Scratch saves: an i16 store through HL restores HL itself

saveWrittenScratch exempts the canonical word store LD (HL),lo / INC HL /
LD (HL),hi / DEC HL from saving a live HL, since the sequence ends with HL
unchanged. The exemption tested inst.Ty == TyU16, so the same sequence for
an i16 store pushed and popped the pointer around itself (8 cycles on
eZ80 per store through a loop-carried pointer). Take i16 too; the shape
check is unchanged.

Measured (eZ80 cycles): x1 9,802 -> 9,242; v4 1,784,815 -> 1,776,863,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add of a constant 1..3: advance the pointer in place with INC rr

`p = p.bytes(2)` lowers to ptr_add p, 2, not ptr_bump, and the generic
ptr_add form loaded the constant into a scratch pair and added it
(LD BC,2 / ADD HL,BC, with saves of a live scratch pair). When the result
and the base share a pair, emit INC rr per byte as OpPtrBump does: no
flags change, and in ADL INC rr carries into the upper byte like the
24-bit ADD it replaces (positive offsets only, so zero and sign extension
of the offset agree).

Measured (eZ80 cycles): x1 9,242 -> 8,942; v4 1,776,863 -> 1,772,628,
v0 unchanged (both byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Dead constants: the offset of an INC-form ptr_add has no home

computeDeadConsts did not know that a ptr_add advancing a base in its own
pair by 1..3 is now INC rr, so the constant kept a home through the
allocator's trial. In x1 that home was BC, live exactly where the fraction
byte t needed the last free byte register, and t went to a static spill
slot stored and reloaded every iteration. Count that use as folded, with
the same conditions as tryPtrAddSmallConst (non-constant base, base and
result in the same pair).

Measured (eZ80 cycles): x1 8,942 -> 7,342 (no spill slot left in the
loop); v0, v4 unchanged (byte-exact); eZ80 and Z80 C benchmarks unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: gap-map examples x1-x6 as cycle-budget benchmarks

Six reduced loop shapes where natural Nanz loses to hand code on the
eZ80 (register allocation in a leaf loop and around a call, loop bound /
index work, invariants and induction variables, inlining a multiply
helper, guard-range products). TestEZ80GapExamples compiles each with a
small harness for the bare eZ80 shape, runs it with poisoned registers,
checks the shown results and fails when the region between OUT ($40) and
OUT ($41) exceeds its budget (today's cycles; lower a budget when a change
improves it). The hand-code cycles are recorded next to each budget as
the target, in the style of TestEZ80ADLVertexBench.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: pair copies out of IX/IY with LEA, HL into IX/IY through DE

The ADL emitter copies one pair to another with PUSH x / POP y (all 24
bits, flags kept), and adlLocalRewrites turns that into byte loads when
y's upper byte is dead. Copies out of IX/IY into HL, the other index
register, or a pair whose upper byte is live stayed on the stack: PUSH IX
/ POP HL is 9 cycles, and the scene runs such copies on every hot path.

- PUSH IX|IY / POP y -> LEA y, IX|IY+0 (3 cycles, exact 24-bit copy, no
  flags). The byte copy is kept when one of y's halves is dead, since
  that half's load is deleted afterwards (2 cycles).
- PUSH HL / POP IX|IY with the index register's upper byte dead ->
  EX DE,HL / LD IXH,D / LD IXL,E / EX DE,HL (6 cycles, flags kept).
- The upper-byte fact of IX/IY travels through LEA rr,IX+0 as it did
  through the stack, so widenings it made redundant stay removed.

Measured (eZ80 cycles): v0 2,726,577 -> 2,667,858 (-2.2%), v4 1,772,628
-> 1,732,267 (-2.3%), both byte-exact; x1 7,342 -> 7,242, x2 10,769 ->
10,313, x3 10,577 -> 10,492, x4 19,242 -> 18,212, x5 4,710 -> 4,542, x6
4,516 -> 4,452; eZ80 C benchmark geomean 0.9913 (default) / 0.9923
(size), no case slower. ADL-only pass: Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: take a PUSH x ... POP y copy at the POP when x is not written between

The emitter's parallel copies sequence a cycle as PUSH x / moves / POP y
(e.g. PUSH IY / LD B,D / LD C,E / POP DE for BC <- DE, DE <- IY), and the
pair-copy rewrites only matched an adjacent PUSH/POP. When nothing
between writes x, x still holds the pushed value at the POP, and the slot
is the POP's alone (adlMatchingPop admits no SP-relative access, branch
or label in between), so the same copy forms apply there: LEA y,IX|IY+0,
the byte loads, or HL -> IX|IY through DE. The EX DE,HL form, which
changes the source, still needs the two to be adjacent.

Measured (eZ80 cycles): v4 1,732,267 -> 1,705,702 (-1.5%), v0 2,667,858
-> 2,654,688, both byte-exact; x2 10,313 -> 9,857, x3 10,492 -> 10,186,
other examples unchanged; eZ80 C benchmark unchanged in both profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 gap examples: lower the budgets to this branch's cycles

x1 7,342 -> 7,242, x2 10,769 -> 9,857, x3 10,577 -> 10,186, x4 19,242 ->
18,212, x5 4,710 -> 4,542, x6 4,516 -> 4,452 (the ADL pair-copy rewrites).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add: load a homeless offset constant as an immediate

a96461a lets the dead-constant inventory drop the home of a ptr_add
offset 1..3 when the allocation puts base and result in one pair, since
tryPtrAddSmallConst emits INC rr. The inventory reads the allocation; the
emitter tests its current homes, which a relocation can change, and then
falls to the generic form, which read the dropped home. On Z80 that
miscompiled two C corpus files (assert_matrix: dowhile_break.c
chain_length, fatfs_lowlevel.c test_ld_word / test_fat12_entry, 9
asserts). The generic form now loads such an offset with LD rr,n.

Examples and gap budgets unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Word add of 1: keep the HL operand swap unless INC rr will serve

genBinOp swaps a word ADD's operands when the right one lives in HL,
because the ADD path loads the left one into HL first. It skipped the
swap for an in-place step of 1 (lhs and result in one pair), expecting
the INC rr peephole further down, but that peephole also requires the
add's flags to be unobserved (and a register result). When they are
observed the ADD path ran, loaded lhs over the constant and emitted
i = i + i (PUSH BC / POP HL / ADD HL,HL): a loop counting from 0 never
ended. Gate the skip on the same conditions as the peephole.

The defect is in the target-independent word ADD path (older than the
eZ80 work; not introduced by #376). The reduced example is correct up to
#367 (fbb7172) and wrong from #368 (b4a013e, loop- and call-aware
eZ80 allocation), whose allocation of the shape (a conditional call
before the loop, a callee with its own loop, an index base + i) first
puts the constant in HL with the flags observed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* CI: classify this branch's new pipeline tests in the fast profile

run_stable_pipeline.py refuses unclassified tests. The eight new tests
(IX-half parameters, word compare / store / pointer-step / dead-offset
checks, the gap-map example budgets, the word unit-step fix) run in a
few seconds together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ptr_add INC form: eZ80 only

On the Z80 the INC rr form of a small constant pointer step (217b285,
a96461a) made the plain byte path of the FAT12 word workload faster
than its profile-guided word fusion (TestFATSequentialWordFusionNative:
unfused 92,928 -> 76,800 T against fused 89,088) and moved the pinned
deltas of TestFAT12BytePackingRetainsNativeAccessesAndWrap and
TestProfileGuidedSumVMZ80. Those are measurements of other passes, so
keep the Z80 product as it was: emit the form, and drop the offset's
home in the dead-constant inventory, only for 24-bit pairs (eZ80). The
eZ80 numbers are unchanged (gap budgets hold); the immediate fallback
of b50e4a8 stays for any disagreement between the two gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril canonical6 fixture: refresh MIX.COM hash after the smaller Z80 output

The fresh CI run shows every stage boundary still equal to the original Ruby;
only the compiled MIX.COM bytes changed (hash taken from that run's evidence).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* autosiril mix frozen replay: refresh the snapshot after the smaller Z80 output

Regenerated with freeze.py from this PR's fresh CI run. Only compiled-image
hashes, image sizes and T-state counts change; every case result is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Spill rewrite: do not evict a far hotter neighbour for a temporary that found no register

A rewrite temporary that found no register made the next round spill its
cheapest register-resident neighbour. Next to a loop, once the cold
neighbours were spent, that was the loop's carried values: in the large
benchmark program's add loop a multiply result in the preamble evicted
both accumulators, one round after another, and the loop read and wrote
them through static slots every iteration.

The neighbour is now spilled only while its weighted uses are at most
four times the temporary's (MZ_W77_VICTIM; 0 restores the old rule);
otherwise the temporary keeps its memory home, which foldSpilledTemps
folds. eZ80 speed profile only (the spill rewrite runs nowhere else).

New gap example x7 (neutral reduction of that loop): 62,378 -> 59,584.
Large program natural source 2,654,688 -> 2,622,371 cycles per picture,
restructured 1,705,702 -> 1,705,669; eZ80 C benchmark unchanged.

MZ_PBQP_DEBUG also prints the function, the RN order and spills, and
the spill-rewrite rounds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 allocation: loop-header byte values pay twice the accumulator pressure

A byte value carried around a loop and homed in A holds A through the
whole body: every A-working instruction saves and restores it, and each
save takes a scratch byte register the other loop values could have
used. With frequency weights on (eZ80 speed profile) the accumulator
pressure of loop-header parameters is doubled (MZ_W77_ACCLOOP, percent).
The back-edge values are not charged more: they live only from late in
the body, and charging them pushed a fraction out of A that wanted it
(scene add loop +8k at 3x).

x4 18,212 -> 15,668 (counter i no longer in A; n and x leave memory),
x1 7,242 -> 7,145. Large program natural source 2,622,371 -> 2,621,636,
restructured 1,705,669 -> 1,701,587. eZ80 C benchmark unchanged; the Z80
allocation (no frequency weights) is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Loop rotation: drop the copied zero test of a counter the latch just stepped (eZ80)

A rotated loop header repeats its test at the back edge. For a
down-counted byte counter the latch ends with DEC r, which already sets
Z as the copied test (LD A,r / AND A, often inside a save and restore of
a live A, or INC r / DEC r) would. When nothing between the DEC and the
copy writes the flags or r, no label intervenes, and the copy's branches
read Z only, the test is dropped; what the save staged into A is kept as
one LD A,y.

Gated by the new target policy PolicyRotatedZeroTest (eZ80);
MZ_W77_ZTEST_Z80=1 applies it on the Z80 for measurement,
MZ_W77_ZTEST=0 disables it.

x1 7,145 -> 6,745. Large program restructured 1,701,587 -> 1,697,352
cycles per picture (its column-minimum walk), natural source unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 allocation: charge HL/DE homes of loop-carried words live across address arithmetic

The emitter forms indexed addresses in HL (ADD HL,rr for a pointer add,
ADD HL,HL for a scaled index). A word carried around a loop and homed in
HL or DE is saved and restored around each of them (PUSH HL/POP HL, EX
DE,HL pairs, PUSH/POP moves to BC/IX). With frequency weights on (eZ80
speed profile), a new PBQP term charges the HL and DE homes of
loop-header words by the weighted number of pointer adds and word shifts
in the loop they are live across and not operands of (MZ_W77_HLP=12,
MZ_W77_DEP=8 per weighted instruction). Steps on a carried value's own
update chain (p = p + 2, yh = yh + sh + 1) do not count: they update the
home in place. Charging word adds and subtracts as well moved values of
an arithmetic-only loop into memory (palette search +7k), so only address
arithmetic counts.

x7 59,584 -> 40,148, x4 15,668 -> 14,983, x5 4,542 -> 4,294. Large
program natural source 2,621,636 -> 2,453,354 cycles per picture (its add
loop's column index leaves HL), restructured 1,697,352 -> 1,694,278.
eZ80 C benchmark unchanged; Z80 allocation unchanged (no weights).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* HL pressure: leave loop accumulators their HL home

A carried word summed with a non-constant on its own update chain (sum =
sum + word) is added in place only in HL; elsewhere the sum is staged
through HL with PUSH/POP moves, which costs more than the saves around
the address arithmetic. The HL pressure no longer charges such
accumulators (MZ_W77_HLACC=0 restores the charge).

The previous commit's benchmark check ran a stale ez80_bench binary: it
had made checksum16 9.05% slower (sum moved from HL to BC). With this
change checksum16 is back to 8,531,032 cycles; fusion_window_sum loses
its 3% gain and x5 goes back to 4,542 (its budget returns to the value
it had before the previous commit). x7 stays at 40,148. Large program
natural source 2,453,354 -> 2,454,507, restructured 1,694,278 ->
1,695,399 cycles per picture.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* ADL: a pair saved around scratch use takes the free one of BC/DE instead

The emitter saves a pair it needs as scratch with PUSH Y ... POP Y, also
when the other pair of BC/DE holds nothing live (PUSH BC / LEA BC,IX+0 /
ADD HL,BC / POP BC for an index-register addend, MLT staging, compare
temporaries). The ADL text pass now renames Y to Z in between and drops the
PUSH/POP when Z is neither read nor written there and dead after the POP
(the function's clobber contract counts: a preserved pair is live at RET),
Y is only read in between after a write there, and every instruction in
between names its B/C/D/E operands explicitly (no EX, DJNZ, block or port
instructions; nested PUSH/POP of other pairs only). An upper-byte
requirement left by a removed widening follows the renamed value. Like the
EX DE,HL copy it writes a register the original left alone, so it is
applied alone in its round.

Measured (eZ80 cycles): large program natural source 2,454,507 ->
2,436,986, restructured 1,695,399 -> 1,694,340 (both byte-exact);
eZ80 C benchmark geomean 0.9868 default / 0.9879 size, reverse_loop11
-29%, no case slower; gap examples x1-x7 unchanged. ADL-only pass:
Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: an 8.8 fraction kept in a word is computed in bytes, its carry with JR NC / INC

The natural form of a fixed-point step keeps the fraction in a word and
masks it back each iteration:

    yl = yl + sl; yh = yh + sh + i16(yl >> 8); yl = yl & 255

so the loop carries two more register pairs than the byte form needs (the
large benchmark program's hottest loop spilled its bound and step to
static slots for it).

- NarrowByteCarryWords (mir2): a word add of two zero-extended bytes whose
  sum is read only as `shr 8`, `and 255` or a byte truncation becomes a
  byte add; the shift becomes ext(cmp.ult sum8, operand8), the mask ext of
  the byte sum. The 9-bit sum of two bytes has the byte sum as its low byte
  and the add's carry as bit 8, so this is exact. Word block parameters
  whose incoming values are all zero-extended bytes (constants 0..255, ext
  of u8, AND with 0..255, the parameter itself or another such parameter)
  become byte parameters, widened once at the block top, when that lets
  such an add narrow. The carry is compared with the operand that is not
  loop-carried, so the old fraction dies at the add and the sum can take
  its home. eZ80 only (PolicyNarrowCarryWords).
- Emitter: `w = add x, ext(c)` right after the extension of a pending carry
  c, with x and w in one register pair that x leaves dead, is JR NC / INC
  rr at the extension (INC rr keeps the flags); the comparison whose only
  reader is that extension does not publish a byte first.
- fuzz_nowrap: a fraction-step shape (count, initial fraction, step kinds,
  operand order, and a variant whose word sum is also read as a word), drawn
  from a second random stream so earlier seeds keep their programs.

Measured (eZ80 cycles): large program natural source 2,436,986 ->
2,394,381, restructured unchanged 1,694,340 (both byte-exact); x2 9,857 ->
8,229, x7 40,148 -> 33,079 (budgets lowered), x1 x3-x6 unchanged; eZ80 C
benchmark unchanged in both profiles. fuzz_nowrap 0-299 300/300, ez80
pipeline tests pass. Z80/Z80N output unchanged (policy is eZ80-only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: pointer walks for indices bounded by an exit inside the loop

The affine pointer walk proved the index range from the header test alone
(a constant start and an ult/lt bound), so x2's shape

    while c <= c1 { if c > 80 { return } ... col[c] ... col[c] = .. ; c += 1 }

kept recomputing col + 2*c (with the ADL widening of the offset) for the
load and again for the store.

- affineGuardedIndexRange: for a byte or word index stepping by +-1, the
  branch facts of nowrap_range.go give its range at the latch, which bounds
  every completed iteration; when stepping it there cannot wrap, the index
  is its initial value plus the iteration count, as the walk is. The range
  for the address match is the union over the loop blocks below the header
  and the initial index (the cloned start address must be exact too: under
  ADL a wrapped 16-bit offset would start the 24-bit walk elsewhere).
- The address match accepts `shl x, 1` as x*2 (the load's form of the
  subscript; the store's is `mul x, 2`), so both share one walk.
- A walk admitted this way uses the eZ80 budget of four pairs (IX and IY
  besides HL/DE/BC) in the profitability model.
- eZ80 only (PolicyGuardedPointerWalks, PointerWalkOptions.Guarded).
- fuzz_nowrap: a guarded-walk shape (byte or word index, ascending with a
  break past K or descending with the access guarded), from the second
  random stream.

Measured (eZ80 cycles): x2 8,229 -> 7,960 (budget lowered); large program
natural 2,394,381 -> 2,393,069, restructured 1,694,340 -> 1,693,029 (both
byte-exact); eZ80 C benchmark unchanged; fuzz_nowrap 0-399 400/400.
Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80: a signed range test x >= 0 && x < K is one unsigned compare

The natural source guards its fast multiply paths with
`if rk >= 0 && rk < 16384 && ...` on a value passed in memory: two signed
word compares, each reloading the value into HL around a 24-bit SBC.

- FoldSignedRangeTests (mir2): for a signed word or byte x and
  0 < K <= its maximum, the short-circuit pair `x >= 0` then `x < K` (either
  order, also spelled x > -1 / x <= K-1, both leaving to the same block
  with the same arguments, the second block entered only from the first and
  holding only constants before its test) becomes `cmp.ult x, K`: negative
  values read unsigned are at least 2^(w-1) > K. Exact.
- Emitter: x <u K and x >=u K for a constant K with a zero low byte read
  only the high byte: LD A,(slot+1) / CP K>>8 from a static slot (or
  LD A,hi from a pair), instead of loading the word.
- fuzz_nowrap: a signed range-test shape (word or byte, both orders and
  spellings, K near the limits, values at and around both bounds), from the
  second random stream.
- eZ80 only (PolicyRangeTestFold).

Measured (eZ80 cycles): large program natural 2,393,069 -> 2,331,152,
restructured 1,693,029 -> 1,692,067 (both byte-exact); x6 4,452 -> 4,436
(budget lowered), other gap examples unchanged; eZ80 C benchmark unchanged.
fuzz_nowrap 0-599 600/600, fuzz_diff ez80 --signed 0-499 500/500.
Z80/Z80N output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* Pointer walks: keep the shl subscript match to the eZ80

Accepting `shl x, 1` as x*2 in the affine address match also let walks
fire on the Z80 (one compile_sweep change, examples/zx/tetris_playable).
The match was measured on the eZ80 only; it now applies with the guarded
walks (PolicyGuardedPointerWalks), and Z80 output is unchanged again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* eZ80 high-byte compare: keep a value live in A; fuzz_diff reducer: bound empty loops

Wrong code from dab0dce (this branch, not on main), found by
fuzz_diff --target ez80 seed 1919: the high-byte form of x >=u K / x <u K
(LD A,hi / CP K>>8) wrote A while A held a byte read after the comparison
(`d` in the guarded branch), so the function returned 60369 instead of
60365. It now takes the guards of tryBytewiseUnsignedCmp16: a branch-only
comparison, nothing live in A, no live pending accumulator or predicate.
Regression test: TestEZ80HighByteCompareKeepsA (the seed's program on the
eZ80 assert path; fails on dab0dce, passes now).

The gate hung for three hours on that seed: the deletion reducer removed
the body of `while lp6 < 1 { lp6 = lp6 + 1 }`, and the oracle interpreter
counted steps only per executed line, so a loop with an empty body spun
forever. Loop iterations now count toward the same 200000-step limit
(the reducer finishes the seed in 5 s; the old script was still running
after 60 s).

Large program after the guard: natural 2,332,159 (was 2,331,152),
restructured 1,693,029, both byte-exact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* CI pipeline profiles: classify the new eZ80 pipeline tests as fast

run_stable_pipeline.py refuses an inventory with unclassified tests:
TestEZ80GuardedPointerWalk, TestEZ80HighByteCompareKeepsA,
TestEZ80NarrowCarryWords and TestEZ80SignedRangeFold join the fast
profile next to TestEZ80GapExamples (each runs in under a second).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

* fuzz_nowrap: the fraction shape's counter is not named i8

Seed 1370 numbered the fraction loop's counter `i8`, a Nanz type name,
so the Nanz program did not parse (a generator failure, not a compiler
one; the C side passed). The counter is named fi<n> now; seed 1370
passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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