cpu: lower XCHG in the shared lifter, atomically for memory #380

Merged
denn0x merged 1 commit from upstream-pr/386 into main 2026-11-22 03:33:31 +00:00
denn0x commented 2026-11-22 00:03:17 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-22T00:03:17Z.


Change

Advances CPU translation coverage. XCHG is an independent problem: lower() today accepts only the NOP spellings 90 and 66 90, and rejects every real exchange. No open PR or issue claims it.

There is no prerequisite PR. The shared interface is lower() in tools/ffx_version_query.py, its INTEGER_HEADER, and CPU_FIXTURES in tools/form_coverage.py. #287, #289, #291, #326, #328, #331, #335, #368 and #379 also extend these. The insertions sit at anchors those PRs do not use. A trial merge of #368 and #379 into this branch is clean, and the combined tree passes all 45 cpu_ tests.

Lowering.

  • Register forms: register-register xchg in 8-, 16-, 32- and 64-bit widths, including the high-byte registers. Both operands are read before either is written.
    • In every 32-bit form both registers are zero-extended. So 87 C0 (xchg eax, eax) clears the upper half of RAX, while the one-byte 90 and 66 90 stay NOPs.
  • Memory forms: XCHG with a memory operand is atomic on x86 without a LOCK prefix (Intel SDM, XCHG). It lowers to the host's _InterlockedExchange8, _InterlockedExchange16, _InterlockedExchange or _InterlockedExchange64 on the flat address, instead of a flat load and store that would drop the atomicity.
    • This follows the reasoning of the existing LOCK rejection; the redundant explicit lock xchg stays rejected there.
    • INTEGER_HEADER gains #include <intrin.h>.
  • Small refactor: write() delegates register writes to a new write_register(), so both operands of a register swap can be written. Behaviour of existing callers is unchanged.

Not modelled: the ordering of the flat loads and stores around the exchange. A lifted function still uses plain memory accesses for everything else.

Fixture

tests/cpu/xchg.asm builds 18 value exports and two token exports.

Value exports. They cover al/cl, ah/al, ah/ch, r8b/al, ax/cx, r9w/r8w, eax/ecx (one-byte form), ecx/r9d, 87 C0, rax/rcx and r8/r9. The memory forms are byte (including ah), word, dword with either operand order, qword, and a misaligned qword.

  • emit asserts that 87 C0 was assembled as XCHG_RM32_R32.
  • The check compares RAX, RCX, R8, R9 and a 16-byte slot against a reference, for 64 value pairs per export.

Token exports (atomicity). swap_tokens64 and swap_tokens32 loop xchg on one shared qword or dword.

  • Eight threads start together on a barrier. Each exchanges 100000 distinct tokens.
  • The values the exchanges returned, plus the final slot, must be exactly the tokens and the initial value, each once.
  • ctypes releases the GIL, so the threads run concurrently. The plain control below shows that the check detects a non-atomic exchange.

Negative controls. Two translations of the same image are mutated after lowering; each must mismatch.

Control Mutation Value mismatches Lost or duplicated tokens
plain interlocked exchange replaced by a flat load and store 0/1152 qword 154284, dword 80536
oneway only the first register of a register swap written 512/1152 0

The check also verifies rejections and NOPs on synthetic bytes:

  • f0 48 87 01 (lock xchg) is rejected by the prefix check;
  • 90 and 66 90 still lower as NOP;
  • 87 c0 writes EAX.

On main, lower() rejects 87 c0 c3 with unsupported query operation.

Verification

Tested at 85cd5e0 on 4f6c39d. Windows 11 build 26200, MSVC 19.50.35720, Windows SDK 10.0.26100.0, Python 3.13, AMD Ryzen 7 7700 (8 cores, 16 threads).

ctest --preset dev --no-tests=error -R '^cpu_aot_xchg$' -V
93: native: 1152 value cases matched; 8 threads x 100000 tokens x 3 rounds, lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0}
93: lifted: 1152 value cases matched; 8 threads x 100000 tokens x 3 rounds, lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0}
93: control plain: 0/1152 value mismatches; lost or duplicated tokens {'swap_tokens64': 154284, 'swap_tokens32': 80536}
93: control oneway: 512/1152 value mismatches; lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0}
93: rejected lock xchg; 90 and 66 90 lower as NOP, 87 c0 writes EAX
1/1 Test #93: cpu_aot_xchg .....................   Passed   18.15 sec
  • Full suite: ctest --preset dev --no-tests=error --output-junit <repo>/out/test-results.xml gives 144 passed, 1 failed and 2 capability skips (bvh_wave64_warp, wave_shuffle_warp). The run includes the GPU tests. The failure is gpu_alias_lookup_writes_hardware, the RDNA 4 array-atomics probe tracked in #369, which fails the same way on main. This change touches no GPU code.
  • Pure-Python checks: tests/form_coverage_check.py and tests/docs_links_check.py pass.
  • Fork CI: the Windows build-and-test, Linux Python and gfx1013 LLVM jobs passed at 85cd5e0 in the fork's Windows checks run 44964482313.
  • Contention numbers: the token counts for the plain control vary from run to run: an earlier run gave 106564 and 79486. The check requires only that they are nonzero.

Coverage. python tools/form_coverage.py out/test-results.xml gives x64 56 of 948 forms, 55 without cpu_aot_xchg. The added form is xchg.

Measured, not established:

  • Atomicity is shown by the token test on one 8-core host. It is not a proof.
  • Memory ordering against the surrounding plain accesses is not preserved in general.

Evidence

The fixture is synthetic and original to this repository (MIT). docs/experiments.md documents the lowering, the fixture and its controls.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6536101785 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/386). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T00:03:17Z. --- ## Change Advances CPU translation coverage. XCHG is an independent problem: `lower()` today accepts only the NOP spellings `90` and `66 90`, and rejects every real exchange. No open PR or issue claims it. There is no prerequisite PR. The shared interface is `lower()` in `tools/ffx_version_query.py`, its `INTEGER_HEADER`, and `CPU_FIXTURES` in `tools/form_coverage.py`. #287, #289, #291, #326, #328, #331, #335, #368 and #379 also extend these. The insertions sit at anchors those PRs do not use. A trial merge of #368 and #379 into this branch is clean, and the combined tree passes all 45 `cpu_` tests. **Lowering.** - **Register forms:** register-register `xchg` in 8-, 16-, 32- and 64-bit widths, including the high-byte registers. Both operands are read before either is written. - In every 32-bit form both registers are zero-extended. So `87 C0` (`xchg eax, eax`) clears the upper half of RAX, while the one-byte `90` and `66 90` stay NOPs. - **Memory forms:** XCHG with a memory operand is atomic on x86 without a LOCK prefix ([Intel SDM](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html), XCHG). It lowers to the host's `_InterlockedExchange8`, `_InterlockedExchange16`, `_InterlockedExchange` or `_InterlockedExchange64` on the flat address, instead of a flat load and store that would drop the atomicity. - This follows the reasoning of the existing LOCK rejection; the redundant explicit `lock xchg` stays rejected there. - `INTEGER_HEADER` gains `#include <intrin.h>`. - **Small refactor:** `write()` delegates register writes to a new `write_register()`, so both operands of a register swap can be written. Behaviour of existing callers is unchanged. **Not modelled:** the ordering of the flat loads and stores around the exchange. A lifted function still uses plain memory accesses for everything else. ## Fixture `tests/cpu/xchg.asm` builds 18 value exports and two token exports. **Value exports.** They cover `al`/`cl`, `ah`/`al`, `ah`/`ch`, `r8b`/`al`, `ax`/`cx`, `r9w`/`r8w`, `eax`/`ecx` (one-byte form), `ecx`/`r9d`, `87 C0`, `rax`/`rcx` and `r8`/`r9`. The memory forms are byte (including `ah`), word, dword with either operand order, qword, and a misaligned qword. - `emit` asserts that `87 C0` was assembled as `XCHG_RM32_R32`. - The check compares RAX, RCX, R8, R9 and a 16-byte slot against a reference, for 64 value pairs per export. **Token exports (atomicity).** `swap_tokens64` and `swap_tokens32` loop `xchg` on one shared qword or dword. - Eight threads start together on a barrier. Each exchanges 100000 distinct tokens. - The values the exchanges returned, plus the final slot, must be exactly the tokens and the initial value, each once. - ctypes releases the GIL, so the threads run concurrently. The `plain` control below shows that the check detects a non-atomic exchange. **Negative controls.** Two translations of the same image are mutated after lowering; each must mismatch. | Control | Mutation | Value mismatches | Lost or duplicated tokens | |---|---|---|---| | `plain` | interlocked exchange replaced by a flat load and store | 0/1152 | qword 154284, dword 80536 | | `oneway` | only the first register of a register swap written | 512/1152 | 0 | The check also verifies rejections and NOPs on synthetic bytes: - `f0 48 87 01` (`lock xchg`) is rejected by the prefix check; - `90` and `66 90` still lower as NOP; - `87 c0` writes EAX. On `main`, `lower()` rejects `87 c0 c3` with `unsupported query operation`. ## Verification Tested at `85cd5e0` on `4f6c39d`. Windows 11 build 26200, MSVC 19.50.35720, Windows SDK 10.0.26100.0, Python 3.13, AMD Ryzen 7 7700 (8 cores, 16 threads). ```powershell ctest --preset dev --no-tests=error -R '^cpu_aot_xchg$' -V ``` ```text 93: native: 1152 value cases matched; 8 threads x 100000 tokens x 3 rounds, lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0} 93: lifted: 1152 value cases matched; 8 threads x 100000 tokens x 3 rounds, lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0} 93: control plain: 0/1152 value mismatches; lost or duplicated tokens {'swap_tokens64': 154284, 'swap_tokens32': 80536} 93: control oneway: 512/1152 value mismatches; lost or duplicated tokens {'swap_tokens64': 0, 'swap_tokens32': 0} 93: rejected lock xchg; 90 and 66 90 lower as NOP, 87 c0 writes EAX 1/1 Test #93: cpu_aot_xchg ..................... Passed 18.15 sec ``` - **Full suite:** `ctest --preset dev --no-tests=error --output-junit <repo>/out/test-results.xml` gives 144 passed, 1 failed and 2 capability skips (`bvh_wave64_warp`, `wave_shuffle_warp`). The run includes the GPU tests. The failure is `gpu_alias_lookup_writes_hardware`, the RDNA 4 array-atomics probe tracked in #369, which fails the same way on `main`. This change touches no GPU code. - **Pure-Python checks:** `tests/form_coverage_check.py` and `tests/docs_links_check.py` pass. - **Fork CI:** the Windows build-and-test, Linux Python and gfx1013 LLVM jobs passed at `85cd5e0` in the fork's `Windows checks` run [44964482313](https://github.com/denn0x/Xbox2Windows/actions/runs/44964482313). - **Contention numbers:** the token counts for the `plain` control vary from run to run: an earlier run gave 106564 and 79486. The check requires only that they are nonzero. **Coverage.** `python tools/form_coverage.py out/test-results.xml` gives x64 **56 of 948** forms, 55 without `cpu_aot_xchg`. The added form is `xchg`. **Measured, not established:** - Atomicity is shown by the token test on one 8-core host. It is not a proof. - Memory ordering against the surrounding plain accesses is not preserved in general. ## Evidence The fixture is synthetic and original to this repository (MIT). `docs/experiments.md` documents the lowering, the fixture and its controls. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets. _AI-assisted (Claude Code)._
upstream-sync closed this pull request 2026-11-24 06:42:46 +00:00
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
R0Y00/Xbox2Windows!380
No description provided.