Skip to content

cpu: lower an opt-in x87 leaf profile with FADDP - #422

Merged
R0Y00 merged 2 commits into
R0Y00:mainfrom
denn0x:cpu/lower-x87-add-profile
Nov 22, 2026
Merged

R0Y00 merged 2 commits into
R0Y00:mainfrom
denn0x:cpu/lower-x87-add-profile

Conversation

@denn0x

@denn0x denn0x commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Change

Refs #406. This is the first PR of the plan agreed there: an opt-in x87 leaf-function profile in the shared lower() with one register-add form. Multiplication, division, conversions, constants, comparisons (with PF) and stack faults are left for later PRs, each with its own evidence.

Interface. lower(..., x87=False) is the default and still rejects every x87 instruction, so existing callers are unchanged. With x87=True the profile accepts:

  • fld and fstp with an m32, m64 or m80 memory operand;
  • faddp st(i), st for i from 1 to 7.

Stack model (tools/x87_lower.py).

  • Entry state: control word 0x027F (53-bit precision, round to nearest-even, all exceptions masked), TOP 0, eight empty registers and a clear status word. The function must return with the stack empty.
  • Static depths: a worklist over direct edges fixes the stack depth before every instruction at translation time. Each register becomes a C++ slot x87_slot[n], so no TOP exists at run time.
  • Checked once: the whole body is checked before any instruction is lowered.

Rejected at translation:

  • any other x87 instruction, including fldcw, fnstsw, fninit, fnstenv and wait, plus register forms of fld, fadd st, st(i) and faddp st(0), st;
  • a ninth push, and a pop or faddp without enough values;
  • depths that differ where control flow joins;
  • an x87 instruction not reachable from the entry through direct edges;
  • a nonempty stack at a return, a call, an indirect branch or an external edge.

Arithmetic (tools/x87_soft.h). The helpers use integers only, with no host floating point.

  • Register contents: a register holds the full 80-bit encoding.
  • m80: loads and stores copy all 80 bits, including NaN payloads, denormals, pseudo-denormals and unnormals.
  • m32 and m64 loads: they convert exactly and quiet a signaling NaN.
  • FADDP rounding: the sum rounds to 53 significand bits within the extended exponent range. A result below that range is denormalized first and then rounded at the same bit positions. Addends far apart keep a sticky bit.
  • Stores to m32 and m64: the value rounds again into the destination format.
  • Signed zero: an exact zero sum of nonzero addends is +0, and -0 + -0 is -0.
  • Special operands: NaNs follow the x87 column of SDM Vol. 1 Table 4-7: a QNaN beats an SNaN, otherwise the larger significand wins, and the result is quiet. Infinities of opposite sign, unnormals, pseudo-infinities and pseudo-NaNs give the indefinite.

Accepted encodings. Every 80-bit encoding is accepted as an operand, so there is no restriction to canonical finite values; the special-value semantics above are implemented and checked. The status word, exceptions and the other rounding modes are not modelled. This is safe only because the profile rejects every instruction that could observe or change them.

Measured, not taken from the SDM: when two NaNs of the same kind have equal significands, the positive one wins in either operand order. My first model returned the destination operand, and 7 of 8061 native cases disagreed, all of them -NaN(x) + +NaN(x).

Fixture

tests/cpu/x87_add.asm and .def are generated by tests/cpu/x87_add.py asm from the SEQUENCES table. The 16 exports are:

  • the nine load/store width pairs;
  • an m80 add stored to m80, m64 and m32;
  • an m64 add stored to m64 and m80;
  • an m32 add;
  • a three-value chain that uses faddp st(2), st and then faddp st(1), st.

Harness. tests/cpu/x87_harness.asm is native-only and never translated; CPU_FIXTURES maps it to None. For each call it:

  1. saves the caller's whole x87 state with fnsave, environment and all eight register values, which also leaves TOP 0 and an empty stack;
  2. loads control word 0x027F;
  3. calls the export;
  4. records the control, status and tag words the export left;
  5. restores the caller's state with frstor.

Harness check. x87_seeded enters each of the 16 exports with a live caller value in ST(0): pi with all 64 significand bits, held in the physical register each export reuses. It also loads control word 0x0F7F (64-bit precision, round toward zero). After the harness returns, it requires:

  • the value's 10 bytes, the control word, TOP 7 and the single valid tag to be unchanged;
  • the export's own output and its empty-stack entry state to be as before.

A control harness, x87_call_envonly, keeps only the environment (fnstenv/fninit/fldenv). It must lose the value around every export, and it does: the register comes back holding the fixture's last value.

The native and translated exports both run through it with identical input bytes.

Check. tests/cpu/x87_add.py check compares each 64-byte output block, plus 64 guard bytes on each side of the input and the output, against an independent fractions.Fraction model. It requires every export to return with control word 0x027F, TOP 0 and all tags empty. The 8085 cases include:

  • every ordered pair of 34 special 80-bit encodings (zeros, denormals, pseudo-denormals, extremes, infinities, QNaNs, SNaNs, the indefinite, an unnormal, a pseudo-infinity and a pseudo-NaN);
  • an m80 round trip with low bits set;
  • halfway sums that separate PC=53 from PC=64, such as 1 + 2^-53 and 1 + 2^-64;
  • a sum that needs the sticky bit (1 + 2^-53 + 2^-200);
  • double rounding through an m64 store, such as 1 + (2^-53 + 2^-105);
  • sums beyond the binary64 range, and extended-range overflow and underflow;
  • denormal results, cancellation and NaN ties;
  • narrow-store rounding boundaries at the m32 and m64 normal, subnormal and overflow edges;
  • 700 random pairs and 300 random three-value chains.

Negative controls. Six mutated translations of the same image must each mismatch:

Control Mutation Mismatches
pc64 the sum rounds to 64 significand bits 1089/8085
double the sum rounds in the binary64 exponent range 3845/8085
m80double m80 loads go through binary64 1485/8085
nosticky bits shifted out while aligning are dropped 48/8085
nanorder the first NaN operand always wins 58/8085
signedzero an exact cancellation gives -0 18/8085

Rejections. The check also confirms that the default lower() rejects fld. It then confirms that x87=True rejects 16 sequences outside the profile, each with its expected diagnostic.

Verification

Tested at cace6d2 on e5e0079 (it merges cleanly with ac48a50). Windows 11 build 26200, MSVC 19.50.35720, Windows SDK 10.0.26100.0, Python 3.13, AMD Ryzen 7 7700 (AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD).

cmake --build --preset dev --target cpu_x87_add_lifted
ctest --preset dev --no-tests=error -R '^cpu_aot_x87_add$' -V
95: 8085 cases over 16 exports (output block and guards) matched the reference in native and translated DLLs; each export returned with control 0x027f and an empty stack
95: processor: AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD
95: x87_call kept a live caller ST(0) value and control word 0x0f7f around all 16 native and translated exports; control envonly (FNSTENV/FLDENV): 16/16 lost it
95: control pc64: 1089/8085 mismatches
95: control double: 3845/8085 mismatches
95: control m80double: 1485/8085 mismatches
95: control nosticky: 48/8085 mismatches
95: control nanorder: 58/8085 mismatches
95: control signedzero: 18/8085 mismatches
95: rejected 17 sequences outside the profile, including: the profile off (default); fld st(1); fadd st, st(1); fnstsw ax; fldcw; fninit; wait; a ninth push; fstp on an empty stack; faddp with one value; faddp st(0), st; a return with a value; depths that differ at a join; a call with a live value; an external edge with a live value; an indirect jump with a live value; an unreachable fld
1/1 Test #95: cpu_aot_x87_add ..................   Passed
  • Existing lowerer regressions: ctest --preset dev --no-tests=error -R '^cpu_' -j 8 gives 44 of 44 passed.
  • Full suite: ctest --preset dev --no-tests=error -j 8 --output-junit <repo>/out/test-results.xml gives 145 passed, 1 failed and 2 capability skips (bvh_wave64_warp, wave_shuffle_warp) out of 148. The run includes the GPU tests. The failure is gpu_alias_lookup_writes_hardware, the RDNA 4 array-atomics probe recorded 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 cace6d2 in the fork's Windows checks run 44971715289. cpu_aot_x87_add ran and passed there (test 70 of 120). CI runs without -V, so the runner's CPU vendor is not in the log.

Coverage. python tools/form_coverage.py out/test-results.xml gives x64 58 of 948 forms, and 55 without cpu_aot_x87_add. The added forms are fld, fstp and faddp. The harness is native-only, so its fnstenv, fninit, fldcw and fldenv are not counted.

Not measured:

  • Intel CPUs. The fork CI pass is on a hosted runner whose vendor is not recorded. The NaN tie rule in particular is measured only on one AMD Zen 4 part.
  • faddp st(3) to st(7), st. Only st(1) and st(2) are exercised; the others use the same slot arithmetic.
  • Status-word flags (PE, UE, OE, IE, C1). They are not modelled, and the profile rejects every instruction that reads them.

Overlap

The shared interfaces are lower() in tools/ffx_version_query.py and CPU_FIXTURES in tools/form_coverage.py. I trial-merged this branch with every open cpu: PR.

No open PR touches x87.

Evidence

The fixture is synthetic and original to this repository (MIT). docs/experiments.md documents the profile, its accepted encodings, its rejection boundaries, the controls and the reproduction command.

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(..., x87=True) accepts FLD and FSTP with m32, m64 and m80 operands
and FADDP ST(i), ST(0) at stack depths fixed at translation time, from
control word 0x027F and an empty stack to an empty stack at return. Any
other x87 instruction, stack overflow or underflow, join mismatch,
unreachable x87 instruction or live x87 state at a call, return,
indirect branch or external edge is rejected. Arithmetic is integer-only in x87_soft.h:
53-bit rounding with the extended exponent range, exact m80 copies,
SDM Table 4-7 NaN selection.

cpu_aot_x87_add compares 16 exports over 8085 cases through a native
harness that fixes the entry state and reports the exit state, with
input and output guards and six mutated controls.

Refs R0Y00#406

AI-assisted (Claude Code).

R0Y00 commented Nov 22, 2026

Copy link
Copy Markdown
Owner

One harness issue at dd96335: x87_call saves the caller with fnstenv [rsp+72], then uses fninit and calls the native fixture. fldenv restores TOP and tags, but the saved environment contains no ST register payloads. A caller entering with a live value can therefore get a valid tag pointing to data overwritten by the fixture. Please save and restore the full x87 state around the harness call (a correctly sized fnsave/frstor area is one option). Add a native wrapper control that seeds a distinctive 80-bit ST value and non-default control word, invokes a fixture that reuses its slot, and checks both value bytes and environment on return. The fixture itself should still start with the agreed empty-stack profile.

x87_call kept only the caller's environment (FNSTENV/FLDENV), so a live
caller value in the register a fixture reuses came back overwritten.
It now uses FNSAVE/FRSTOR. x87_seeded enters each export with a live
ST(0) value and control word 0x0F7F and checks both on return; the old
environment-only harness is kept as a control that must lose the value.

AI-assisted (Claude Code).
@denn0x

denn0x commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@R0Y00 Fixed in cace6d2. x87_call now saves the caller's whole x87 state with fnsave into a 108-byte area and restores it with frstor. fnsave also leaves the agreed entry state (TOP 0, empty tags, clear status); the harness then loads 0x027F before the call.

New wrapper check. x87_seeded enters each of the 16 exports with a live caller value in ST(0): pi with all 64 significand bits, in the physical register the export reuses. It also loads control word 0x0F7F (PC=64, round toward zero). On return it checks:

  • the 10 value bytes, the control word, TOP 7 and tag word 0x3FFF;
  • that the export still started from the empty-stack profile and produced the expected output.

Negative control. The previous environment-only harness is kept as x87_call_envonly, and it must fail the wrapper check. It fails on 16 of 16 exports: the register comes back with the fixture's last value, for example +inf for add_three, instead of pi.

95: x87_call kept a live caller ST(0) value and control word 0x0f7f around all 16 native and translated exports; control envonly (FNSTENV/FLDENV): 16/16 lost it

The rest of the output is unchanged. ^cpu_ gives 44 of 44 passed, and fork CI run 44971715289 passed with cpu_aot_x87_add running. The PR body is updated to match.

AI-assisted (Claude Code).

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