x64_recomp: fix 8/16-bit inc/dec, CF preservation, and inc/dec/neg AF (X64-RECOMP-INCDEC-WIDTH-CF) #1313

Merged
quietfold merged 1 commit from upstream-pr/1313 into main 2026-11-28 19:38:43 +00:00
quietfold commented 2026-11-24 21:43:27 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by quietfold on 2026-11-24T21:43:27Z.


Item ID: X64-RECOMP-INCDEC-WIDTH-CF
AI-assisted: yes

Summary

Fixes five correctness bugs in tools/x64_recomp.py (_emit_incdec and _emit_negnot):

  1. 8-bit and 16-bit inc/dec added/subtracted 1 after shifting T0 left by 24/16:
    • _emit_incdec shifted T0 left by sh = 32 - sz * 8, then emitted adds/subs with immediate 1 and shifted right by sh.
    • This made 8-bit inc al and 16-bit inc ax complete no-ops (((v << 24) + 1) >> 24 == v) and broke ZF on 8/16-bit dec ((1 << 24) - 1 == 0x00FFFFFF, leaving Z=0).
    • Fixed by adding/subtracting 1 << sh (movz T1, 1 << (sh - 16), hw=1, sf=0 -> 0x01000000 / 0x00010000) when flags are live, and using plain add/sub + uxtb/uxth when flags are dead.
  2. inc/dec destroyed CF via bfi(T3, GTMP, 29, 1) copying bit 0 instead of bit 29:
    • BFI inserts the lowest bits (bit 0, always 0 in MRS NZCV) of GTMP into bit 29 of T3, unconditionally zeroing CF whenever keep_c ran.
    • Fixed by extracting bit 29 with a.ubfx(GTMP, GTMP, 29, 1) before a.bfi(T3, GTMP, 29, 1).
  3. keep_c = "C" in need was always False on same-block CF consumers:
    • Because "C" is not in FLAG_WRITERS["inc"]/FLAG_WRITERS["dec"] ("NZVPA"), self.needed[ins.addr] never contained "C", so stc; inc eax; jc or add; inc; adc clobbered ARM C.
    • Fixed by using non-flag-setting add/sub when not flaggy and always preserving ARM C around adds/subs when flaggy.
  4. Materialized dec inverted surviving CF via SUB_KIND:
    • _maybe_mkflags flipped ARM bit 29 for every SUB_KIND instruction including dec, even though dec does not write CF (inverting an upstream stc/clc/cmp carry bit).
    • Fixed in _emit_incdec by calling self._mkflags(0) directly on ins.addr in self.mat while saving/restoring bit 0 (EF_CF) of ctx.eflags in GTMP (preserved across rt_mkflags).
  5. Missing AF operand stashing on inc/dec/neg, and not running _stash_res/_maybe_mkflags:
    • Stashed CTX_A/CTX_B for inc/dec (orig, 1) and neg (0, orig) whenever "A" in need or ins.addr in self.mat so rt_mkflags computes exact AF.
    • Made not return immediately after _store so it never touches flags or context flag slots.

Merge compatibility

  • Keeps edits strictly inside _emit_incdec and _emit_negnot (lines 1655–1698 on main).
  • Verified 0 merge conflicts in a 9-way merge with #1174, #1202, #1205, #1211, #1213, #1279, #1296, and #1306.

Verification

Tested on Apple M5 arm64 (macOS 27.2.1, Python 3.14; CPU-only, no game files):

  • python3 -I tests/test_x64_recomp.py — 32 tests (6 ok, 26 skipped without runner)
  • python3 -I tests/test_x64_recomp_incdec.py -v — 8 tests (5 static ok, 3 exec skipped without runner)
  • Mutation proof: reverting tools/x64_recomp.py to upstream/main causes 5/5 static test failures in tests/test_x64_recomp_incdec.py.
  • Native Apple M5 execution (scratch 9-way merge with #1174, #1202, #1205, #1211, #1213, #1279, #1296, #1306 — 0 merge conflicts):
    • tests/test_x64_recomp_incdec.py — 8/8 OK (all 3 execution suites + 5 static tests, 0 skips)
    • tests/test_x64_recomp.py — 46/46 OK
    • tests/test_x64_recomp_sse.py — 16/16 OK
    • tests/test_x64_recomp_bitops.py — 9/9 OK
    • tests/test_x64_recomp_rcl_rcr.py — 5/5 OK
    • tests/test_x64_recomp_std_str.py — 5/5 OK
    • tests/test_x64_recomp_muldiv.py — 10/10 OK
    • tests/test_x64_recomp_shifts.py — 9/9 OK
    • tests/test_x64_recomp_atomics.py — 10/10 OK
    • Total: 118/118 native arm64 tests passing.
  • python3 -m compileall -q tools/x64_recomp.py tests/test_x64_recomp_incdec.py — OK
  • python3 -I scripts/check_no_game_data.py tools/x64_recomp.py tests/test_x64_recomp_incdec.py — OK
  • python3 -I tests/test_ci_registration.py — 15/15 OK
  • python3 -I tests/test_text_write_line_endings.py — 3/3 OK
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5480832445 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1313). Originally posted by [quietfold](https://github.com/quietfold) on 2026-11-24T21:43:27Z. --- Item ID: `X64-RECOMP-INCDEC-WIDTH-CF` AI-assisted: yes ## Summary Fixes five correctness bugs in `tools/x64_recomp.py` (`_emit_incdec` and `_emit_negnot`): 1. **8-bit and 16-bit `inc`/`dec` added/subtracted `1` after shifting `T0` left by 24/16**: - `_emit_incdec` shifted `T0` left by `sh = 32 - sz * 8`, then emitted `adds`/`subs` with immediate `1` and shifted right by `sh`. - This made 8-bit `inc al` and 16-bit `inc ax` complete no-ops (`((v << 24) + 1) >> 24 == v`) and broke `ZF` on 8/16-bit `dec` (`(1 << 24) - 1 == 0x00FFFFFF`, leaving `Z=0`). - Fixed by adding/subtracting `1 << sh` (`movz T1, 1 << (sh - 16), hw=1, sf=0` -> `0x01000000` / `0x00010000`) when flags are live, and using plain `add`/`sub` + `uxtb`/`uxth` when flags are dead. 2. **`inc`/`dec` destroyed `CF` via `bfi(T3, GTMP, 29, 1)` copying bit 0 instead of bit 29**: - `BFI` inserts the lowest bits (bit 0, always `0` in `MRS NZCV`) of `GTMP` into bit 29 of `T3`, unconditionally zeroing `CF` whenever `keep_c` ran. - Fixed by extracting bit 29 with `a.ubfx(GTMP, GTMP, 29, 1)` before `a.bfi(T3, GTMP, 29, 1)`. 3. **`keep_c = "C" in need` was always `False` on same-block `CF` consumers**: - Because `"C"` is not in `FLAG_WRITERS["inc"]`/`FLAG_WRITERS["dec"]` (`"NZVPA"`), `self.needed[ins.addr]` never contained `"C"`, so `stc; inc eax; jc` or `add; inc; adc` clobbered ARM `C`. - Fixed by using non-flag-setting `add`/`sub` when `not flaggy` and always preserving ARM `C` around `adds`/`subs` when `flaggy`. 4. **Materialized `dec` inverted surviving `CF` via `SUB_KIND`**: - `_maybe_mkflags` flipped ARM bit 29 for every `SUB_KIND` instruction including `dec`, even though `dec` does not write `CF` (inverting an upstream `stc`/`clc`/`cmp` carry bit). - Fixed in `_emit_incdec` by calling `self._mkflags(0)` directly on `ins.addr in self.mat` while saving/restoring bit 0 (`EF_CF`) of `ctx.eflags` in `GTMP` (preserved across `rt_mkflags`). 5. **Missing `AF` operand stashing on `inc`/`dec`/`neg`, and `not` running `_stash_res`/`_maybe_mkflags`**: - Stashed `CTX_A`/`CTX_B` for `inc`/`dec` (`orig`, `1`) and `neg` (`0`, `orig`) whenever `"A" in need or ins.addr in self.mat` so `rt_mkflags` computes exact `AF`. - Made `not` return immediately after `_store` so it never touches flags or context flag slots. ## Merge compatibility - Keeps edits strictly inside `_emit_incdec` and `_emit_negnot` (lines 1655–1698 on `main`). - Verified **0 merge conflicts** in a 9-way merge with `#1174`, `#1202`, `#1205`, `#1211`, `#1213`, `#1279`, `#1296`, and `#1306`. ## Verification Tested on Apple M5 arm64 (macOS 27.2.1, Python 3.14; CPU-only, no game files): - `python3 -I tests/test_x64_recomp.py` — 32 tests (6 ok, 26 skipped without runner) - `python3 -I tests/test_x64_recomp_incdec.py -v` — 8 tests (5 static ok, 3 exec skipped without runner) - Mutation proof: reverting `tools/x64_recomp.py` to `upstream/main` causes **5/5 static test failures** in `tests/test_x64_recomp_incdec.py`. - Native Apple M5 execution (scratch 9-way merge with `#1174`, `#1202`, `#1205`, `#1211`, `#1213`, `#1279`, `#1296`, `#1306` — 0 merge conflicts): - `tests/test_x64_recomp_incdec.py` — **8/8 OK** (all 3 execution suites + 5 static tests, 0 skips) - `tests/test_x64_recomp.py` — **46/46 OK** - `tests/test_x64_recomp_sse.py` — **16/16 OK** - `tests/test_x64_recomp_bitops.py` — **9/9 OK** - `tests/test_x64_recomp_rcl_rcr.py` — **5/5 OK** - `tests/test_x64_recomp_std_str.py` — **5/5 OK** - `tests/test_x64_recomp_muldiv.py` — **10/10 OK** - `tests/test_x64_recomp_shifts.py` — **9/9 OK** - `tests/test_x64_recomp_atomics.py` — **10/10 OK** - Total: **118/118 native arm64 tests passing**. - `python3 -m compileall -q tools/x64_recomp.py tests/test_x64_recomp_incdec.py` — OK - `python3 -I scripts/check_no_game_data.py tools/x64_recomp.py tests/test_x64_recomp_incdec.py` — OK - `python3 -I tests/test_ci_registration.py` — 15/15 OK - `python3 -I tests/test_text_write_line_endings.py` — 3/3 OK
copilot-pull-request-reviewer[bot] commented 2026-11-24 21:43:38 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-24T21:43:38Z.

Review: COMMENTED


Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6047891603 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1313#pullrequestreview-6047891603). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T21:43:38Z. **Review:** COMMENTED --- Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
whoalin1 commented 2026-11-24 23:24:40 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by whoalin1 on 2026-11-24T23:24:40Z.


Independent verification (Devin, AI-assisted — CPU-only, no GPU).

Checked out head 7e38867 detached. Read the diff in tools/x64_recomp.py:

  • 8/16-bit inc/dec now widen to 32 bits and add/subtract 1 << (32 - width*8) instead of 1, then mask back — matches x86 semantics.
  • CF preservation: live-flag path extracts ARM C (bit 29) via ubfx before bfi into NZCV; materialized path loads old CTX_EFLAGS, runs _mkflags, then bfi's bit 0 back so inc/dec don't clobber CF. dec correctly avoids SUB_KIND materialization inversion. Reads correctly.
  • neg/dec stash CTX_A/CTX_B when AF is needed; not leaves flags untouched and now masks with uxtb/uxth for 8/16-bit.

Ran:

  • py -3.14 -I tests/test_x64_recomp_incdec.py → 8 tests, OK (3 skipped: native-execution tests need Apple Silicon/QEMU, unavailable here)
  • pytest tests/test_x64_recomp_incdec.py → 5 passed, 3 skipped
  • py -3.14 -m compileall -q tools tests make_game.py → clean

Verdict: static encoding/semantics checks pass; execution coverage is skipped on this Windows host, so flag behavior is verified by inspection + encoding tests only. No game files needed. Looks good to merge pending a run on a host with QEMU/ARM.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7147367692 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1313#issuecomment-7147367692). Originally posted by [whoalin1](https://github.com/whoalin1) on 2026-11-24T23:24:40Z. --- Independent verification (Devin, AI-assisted — CPU-only, no GPU). Checked out head 7e38867 detached. Read the diff in tools/x64_recomp.py: - 8/16-bit inc/dec now widen to 32 bits and add/subtract `1 << (32 - width*8)` instead of 1, then mask back — matches x86 semantics. - CF preservation: live-flag path extracts ARM C (bit 29) via ubfx before bfi into NZCV; materialized path loads old CTX_EFLAGS, runs _mkflags, then bfi's bit 0 back so inc/dec don't clobber CF. dec correctly avoids SUB_KIND materialization inversion. Reads correctly. - neg/dec stash CTX_A/CTX_B when AF is needed; not leaves flags untouched and now masks with uxtb/uxth for 8/16-bit. Ran: - `py -3.14 -I tests/test_x64_recomp_incdec.py` → 8 tests, OK (3 skipped: native-execution tests need Apple Silicon/QEMU, unavailable here) - `pytest tests/test_x64_recomp_incdec.py` → 5 passed, 3 skipped - `py -3.14 -m compileall -q tools tests make_game.py` → clean Verdict: static encoding/semantics checks pass; execution coverage is skipped on this Windows host, so flag behavior is verified by inspection + encoding tests only. No game files needed. Looks good to merge pending a run on a host with QEMU/ARM.
kevincommits commented 2026-11-26 00:52:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by kevincommits on 2026-11-26T00:52:33Z.


Independent run with QEMU, to add the executed half to the review above. Apple M5 Pro, macOS 27.2.1 (26B131), Python 3.14.2, QEMU 11.1.3 from Homebrew. I merged main at 61732aca1 into the branch locally (907 commits behind, no conflicts). Head tested: 7e3886751.

Against a reference model: 202 of 1,032 checks are wrong on main, 0 of 1,032 on this branch.

  • The new test file has the wiring bug from #1409: as shipped under QEMU, python -I tests/test_x64_recomp_incdec.py is 8 run, 17 failures, because _runner's QEMU branch returns xr.run_kernel (raw bytes) where xr.run_result (the parsed value) is needed. With RUNNER swapped for xr.run_result in memory (no file changed): 8/8.

  • Beyond the file, generated cases under QEMU, each compared against a small Python model:

    • inc, dec, neg, not on rax/eax/ax/al;
    • values 0, 1, 2, 0x7f, 0x80, 0xff, 0x100, and at each width the largest positive value, the most negative value, their neighbours and all-ones;
    • checked per case: the full 64-bit register (untouched upper bits, zero-extension of a 32-bit write), ZF, SF and OF; CF for neg; and for inc/dec that CF survives from a preceding stc, clc, borrowing cmp and non-borrowing cmp. For not, that CF survives stc/clc.
    tool checks wrong
    main 1,032 202
    this branch 1,032 0

    On main the 8- and 16-bit forms are the bulk of it: inc al leaves the value unchanged (…a500 stays …a500, want …a501), SF/OF/ZF follow from that, and CF is not preserved across inc/dec (after stc a following setc reads 0).

    I left 24 more checks out of both rows: the ones whose operand is 64-bit all-ones. Loading that with mov rax, imm64 hangs on main and here alike (Asm.li(-1), fixed by #1339 and #1205), so they say nothing about this change.

  • Counts. tests/test_x64_recomp.py 33/33 and tests/test_recomp_census.py 11/11, the same as main. Full standalone suite: 514 run, 508 pass; the 6 that fail are main's 5 plus the new file, for the wiring reason.

Not tested: memory destinations, AF and PF, and the lock prefix. No game files used. AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7179201518 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1313#issuecomment-7179201518). Originally posted by [kevincommits](https://github.com/kevincommits) on 2026-11-26T00:52:33Z. --- Independent run with QEMU, to add the executed half to the review above. Apple M5 Pro, macOS 27.2.1 (26B131), Python 3.14.2, QEMU 11.1.3 from Homebrew. I merged `main` at `61732aca1` into the branch locally (907 commits behind, no conflicts). Head tested: `7e3886751`. **Against a reference model: 202 of 1,032 checks are wrong on `main`, 0 of 1,032 on this branch.** - The new test file has the wiring bug from #1409: as shipped under QEMU, `python -I tests/test_x64_recomp_incdec.py` is 8 run, 17 failures, because `_runner`'s QEMU branch returns `xr.run_kernel` (raw bytes) where `xr.run_result` (the parsed value) is needed. With `RUNNER` swapped for `xr.run_result` in memory (no file changed): 8/8. - Beyond the file, generated cases under QEMU, each compared against a small Python model: - `inc`, `dec`, `neg`, `not` on `rax`/`eax`/`ax`/`al`; - values 0, 1, 2, `0x7f`, `0x80`, `0xff`, `0x100`, and at each width the largest positive value, the most negative value, their neighbours and all-ones; - checked per case: the full 64-bit register (untouched upper bits, zero-extension of a 32-bit write), ZF, SF and OF; CF for `neg`; and for `inc`/`dec` that CF survives from a preceding `stc`, `clc`, borrowing `cmp` and non-borrowing `cmp`. For `not`, that CF survives `stc`/`clc`. | tool | checks | wrong | |---|---|---| | `main` | 1,032 | 202 | | this branch | 1,032 | 0 | On `main` the 8- and 16-bit forms are the bulk of it: `inc al` leaves the value unchanged (`…a500` stays `…a500`, want `…a501`), SF/OF/ZF follow from that, and CF is not preserved across `inc`/`dec` (after `stc` a following `setc` reads 0). I left 24 more checks out of both rows: the ones whose operand is 64-bit all-ones. Loading that with `mov rax, imm64` hangs on `main` and here alike (`Asm.li(-1)`, fixed by #1339 and #1205), so they say nothing about this change. - **Counts.** `tests/test_x64_recomp.py` 33/33 and `tests/test_recomp_census.py` 11/11, the same as `main`. Full standalone suite: 514 run, 508 pass; the 6 that fail are `main`'s 5 plus the new file, for the wiring reason. Not tested: memory destinations, AF and PF, and the `lock` prefix. No game files used. AI-assisted.
MoonEyes commented 2026-11-28 19:38:40 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-28T19:38:40Z.


Red/green: tests/test_x64_recomp_incdec.py fails 4 static emitter assertions on main (8/16-bit inc/dec delta, CF preservation, AF stash) and passes with the PR (cloud run on main 7daa4a4; execution tests skipped).
Targeted batch (PR tests, tests importing the changed modules, docs tests, translator when touched) merged on main 7daa4a4a5 in GitHub Actions: no new failure.
AI-assisted (Claude Code, Claude Opus 5.5)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7244698671 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1313#issuecomment-7244698671). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-28T19:38:40Z. --- Red/green: tests/test_x64_recomp_incdec.py fails 4 static emitter assertions on main (8/16-bit inc/dec delta, CF preservation, AF stash) and passes with the PR (cloud run on main 7daa4a4; execution tests skipped). Targeted batch (PR tests, tests importing the changed modules, docs tests, translator when touched) merged on main 7daa4a4a5 in GitHub Actions: no new failure. AI-assisted (Claude Code, Claude Opus 5.5)
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!1313
No description provided.