Skip to content

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

Merged
R0Y00 merged 1 commit into
R0Y00:mainfrom
denn0x:cpu/lower-xchg
Nov 22, 2026
Merged

R0Y00 merged 1 commit into
R0Y00:mainfrom
denn0x:cpu/lower-xchg

Conversation

@denn0x

@denn0x denn0x commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

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 gpu_alias_lookup_writes_hardware: array atomics probe reads 256 per buffer on RX 9070 XT #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).

Lower register-register XCHG in all widths, reading both operands before
either write. 32-bit forms zero-extend both registers, so 87 C0 clears
the upper half of RAX while 90 and 66 90 stay NOPs.

XCHG with a memory operand is atomic on x86 without a LOCK prefix, so it
lowers to the host's _InterlockedExchange8/16//64 on the flat address
instead of a load and a store. The redundant explicit LOCK XCHG stays
rejected by the prefix check.

cpu_aot_xchg compares 18 value exports with a reference and runs two
token exports on eight threads, 100000 distinct tokens each: the values
returned plus the final slot must be the tokens and the initial value,
each once. A plain load/store control matches every value case but loses
or duplicates tokens; a one-way register write control mismatches values.

AI-assisted (Claude Code).
@R0Y00
R0Y00 merged commit 3a0f33b into R0Y00:main Nov 22, 2026
3 checks passed
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.

2 participants