cpu: lower FSQRT in the x87 profile #454

Merged
denn0x merged 1 commit from upstream-pr/460 into main 2026-11-22 05:09:38 +00:00
denn0x commented 2026-11-22 05:05:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-22T05:05:01Z.


Change

Refs #406. This follows #456 (comparisons). It adds fsqrt to the opt-in x87 profile in lower(..., x87=True).

Semantics.

  • Rounding: the exact square root of st(0) is rounded under the profile's control word, to 53 significand bits and to nearest-even, within the extended exponent range. The result never leaves the extended normal range, so no overflow or underflow handling is needed.
  • Special operands: sqrt(-0) is -0 and sqrt(+inf) is +inf. A NaN is quieted. Any other negative operand and any unsupported encoding give the indefinite.

Out of scope: the transcendental instructions (fsin, fcos, fsincos, fptan, fpatan, f2xm1, fyl2x, fyl2xp1), fprem, fprem1, fscale and fxtract. They remain rejected.

Lowering (tools/x87_lower.py). x87_slot[top] = x87_sqrt(x87_slot[top]);, with an empty stack rejected as an underflow.

Helper (tools/x87_soft.h). x87_sqrt computes the root bitwise in integers:

  1. It scales the significand by 2^63 or 2^64, whichever makes the unbiased exponent even. That places the 64-bit integer root in [2^63, 2^64).
  2. It takes the root one bit at a time, squaring candidates with _umul128.
  3. A nonzero remainder becomes the sticky bit.
  4. It rounds through the existing x87_round with the arithmetic format.

Fixture

tests/cpu/x87_sqrt.asm and .def are generated by tests/cpu/x87_sqrt.py asm, and emit checks that every decoded x87 instruction is the form its sequence names. The .asm registers its test on its first line (; coverage: source cpu_aot_x87_sqrt). The 9 exports cover:

  • the root of an m80 value stored to m80, m64 and m32;
  • two roots in a row;
  • the roots of m64 and m32 loads, stored back to the same format;
  • sqrt(b) + a, and sqrt(a * a + b * b) (built from fld st(0), fmulp and faddp);
  • a root at depth 8, with all eight values stored.

Model. The model shares no code with tools/x87_soft.h. It takes an integer square root with about 160 bits, scaled to the operand's magnitude. An inexact root is replaced by the midpoint of its unit interval, which rounds the same way, and the result is then rounded to 53 bits. The arithmetic exports reuse the Fraction models of the add and multiply tests. The harness, input bytes, guards and live-value check are those of the earlier x87 PRs.

Cases. 13083 cases:

  • the special encodings, and perfect squares at both exponent parities;
  • 600 values next to the squares of 53-bit midpoints, whose roots fall within a few units of the last bit of a rounding tie;
  • 50 signaling NaNs;
  • random values over the whole exponent range, and denormals;
  • the m64 and m32 special encodings.

Negative controls. Six mutated translations must each mismatch:

Control Mutation Mismatches
pc64 the root rounds to 64 significand bits 4776/13083
double the root rounds in the binary64 exponent range 9027/13083
nosticky the remainder is ignored 168/13083
negzero sqrt(-0) gives +0 7/13083
negabs a negative operand gives the root of its magnitude 741/13083
snan a signaling NaN is returned unquieted 104/13083

nosticky is the control that the near-tie cases exist for. An ignored remainder changes a rounded root only when the 11 bits below the 53rd are exactly a half, which random inputs rarely hit.

Rejections. Translation rejects 6 sequences with the expected diagnostic: fsqrt on an empty stack, fsqrt whose result is left on the stack at the return, fsin, fsincos, fnsave and frstor.

Changes to existing tests. cpu_aot_x87_div used fsqrt as a rejection case. It becomes fnsave, an environment save that the profile will not lower, so the test keeps its number of rejections. Its case and control counts are unchanged.

Verification

Tested at 44b3707 on 6804d0d (the head of #456). main has since moved to 2bdb504 (the merge of #456, #327 and #459), and none of those touch the x87 files or tools/ffx_version_query.py. This branch merges cleanly into 2bdb504. 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_sqrt_lifted
ctest --preset dev --no-tests=error -R '^cpu_aot_x87_sqrt$' -V
13083 cases over 9 exports (output block and guards) matched the reference in native and translated DLLs; each export returned with control 0x027f and an empty stack
processor: AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD
x87_call kept a live caller ST(0) value and control word around all 9 native and translated exports
control pc64: 4776/13083 mismatches
control double: 9027/13083 mismatches
control nosticky: 168/13083 mismatches
control negzero: 7/13083 mismatches
control negabs: 741/13083 mismatches
control snan: 104/13083 mismatches
rejected 6 sequences outside the profile: fsqrt on an empty stack; fsqrt without a store; fsin; fsincos; fnsave; frstor
  • x87 regressions: all nine x87 tests pass (x87_add, x87_mul, x87_div, x87_sub, x87_moves, x87_constants, x87_integers, x87_compare, x87_sqrt).
  • Full suite: ctest --preset dev --no-tests=error -j 8 --output-junit test-results.xml gives 183 passed, 1 failed and 2 capability skips out of 186. The run includes the GPU tests. The failure is gpu_alias_lookup_writes_hardware, the RDNA 4 array-atomics probe recorded in #369, which fails the same way on main. This change touches no GPU code.
  • Pure-Python checks: tests/form_coverage_check.py, tests/docs_links_check.py and tests/bidi_controls_check.py pass.
  • Fork CI: the Windows build-and-test, Windows /O2 build-and-test, Linux Python and gfx1013 LLVM jobs passed at 44b3707 in the fork's Windows checks run 44987342880. Both Windows jobs ran and passed all nine x87 tests (158 of 158 tests in each).

Coverage. python tools/form_coverage.py out/build/dev/test-results.xml gives x64 158 of 948 forms, and 157 without cpu_aot_x87_sqrt. The added form is fsqrt.

Not measured:

  • Intel CPUs. All measurements are on one AMD Zen 4 part.
  • The other precision and rounding modes, because the profile rejects fldcw.
  • The status word, including the precision and invalid-operation flags, as in #422.

Overlap

I trial-merged this branch with all 88 open PRs. Each one conflicts in the same files against main and against this branch: the 16 that merge cleanly into main also merge cleanly here, and this branch adds no conflict to the others. The changes stay inside the x87 files, the new fixture, one rejection case of tests/cpu/x87_div.py, a CMake block after the cpu_aot_x87_compare test, and the x87 section of docs/experiments.md.

Evidence

The fixture is synthetic and original to this repository (MIT). docs/experiments.md documents the square root, the near-tie cases, 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).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6538711972 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/460). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T05:05:01Z. --- ## Change Refs #406. This follows #456 (comparisons). It adds `fsqrt` to the opt-in x87 profile in `lower(..., x87=True)`. **Semantics.** - **Rounding:** the exact square root of `st(0)` is rounded under the profile's control word, to 53 significand bits and to nearest-even, within the extended exponent range. The result never leaves the extended normal range, so no overflow or underflow handling is needed. - **Special operands:** sqrt(-0) is -0 and sqrt(+inf) is +inf. A NaN is quieted. Any other negative operand and any unsupported encoding give the indefinite. **Out of scope:** the transcendental instructions (`fsin`, `fcos`, `fsincos`, `fptan`, `fpatan`, `f2xm1`, `fyl2x`, `fyl2xp1`), `fprem`, `fprem1`, `fscale` and `fxtract`. They remain rejected. **Lowering (`tools/x87_lower.py`).** `x87_slot[top] = x87_sqrt(x87_slot[top]);`, with an empty stack rejected as an underflow. **Helper (`tools/x87_soft.h`).** `x87_sqrt` computes the root bitwise in integers: 1. It scales the significand by 2^63 or 2^64, whichever makes the unbiased exponent even. That places the 64-bit integer root in [2^63, 2^64). 2. It takes the root one bit at a time, squaring candidates with `_umul128`. 3. A nonzero remainder becomes the sticky bit. 4. It rounds through the existing `x87_round` with the arithmetic format. ## Fixture `tests/cpu/x87_sqrt.asm` and `.def` are generated by `tests/cpu/x87_sqrt.py asm`, and `emit` checks that every decoded x87 instruction is the form its sequence names. The `.asm` registers its test on its first line (`; coverage: source cpu_aot_x87_sqrt`). The 9 exports cover: - the root of an m80 value stored to m80, m64 and m32; - two roots in a row; - the roots of m64 and m32 loads, stored back to the same format; - `sqrt(b) + a`, and `sqrt(a * a + b * b)` (built from `fld st(0)`, `fmulp` and `faddp`); - a root at depth 8, with all eight values stored. **Model.** The model shares no code with `tools/x87_soft.h`. It takes an integer square root with about 160 bits, scaled to the operand's magnitude. An inexact root is replaced by the midpoint of its unit interval, which rounds the same way, and the result is then rounded to 53 bits. The arithmetic exports reuse the `Fraction` models of the add and multiply tests. The harness, input bytes, guards and live-value check are those of the earlier x87 PRs. **Cases.** 13083 cases: - the special encodings, and perfect squares at both exponent parities; - 600 values next to the squares of 53-bit midpoints, whose roots fall within a few units of the last bit of a rounding tie; - 50 signaling NaNs; - random values over the whole exponent range, and denormals; - the m64 and m32 special encodings. **Negative controls.** Six mutated translations must each mismatch: | Control | Mutation | Mismatches | |---|---|---| | `pc64` | the root rounds to 64 significand bits | 4776/13083 | | `double` | the root rounds in the binary64 exponent range | 9027/13083 | | `nosticky` | the remainder is ignored | 168/13083 | | `negzero` | sqrt(-0) gives +0 | 7/13083 | | `negabs` | a negative operand gives the root of its magnitude | 741/13083 | | `snan` | a signaling NaN is returned unquieted | 104/13083 | `nosticky` is the control that the near-tie cases exist for. An ignored remainder changes a rounded root only when the 11 bits below the 53rd are exactly a half, which random inputs rarely hit. **Rejections.** Translation rejects 6 sequences with the expected diagnostic: `fsqrt` on an empty stack, `fsqrt` whose result is left on the stack at the return, `fsin`, `fsincos`, `fnsave` and `frstor`. **Changes to existing tests.** `cpu_aot_x87_div` used `fsqrt` as a rejection case. It becomes `fnsave`, an environment save that the profile will not lower, so the test keeps its number of rejections. Its case and control counts are unchanged. ## Verification Tested at `44b3707` on `6804d0d` (the head of #456). `main` has since moved to `2bdb504` (the merge of #456, #327 and #459), and none of those touch the x87 files or `tools/ffx_version_query.py`. This branch merges cleanly into `2bdb504`. 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`). ```powershell cmake --build --preset dev --target cpu_x87_sqrt_lifted ctest --preset dev --no-tests=error -R '^cpu_aot_x87_sqrt$' -V ``` ```text 13083 cases over 9 exports (output block and guards) matched the reference in native and translated DLLs; each export returned with control 0x027f and an empty stack processor: AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD x87_call kept a live caller ST(0) value and control word around all 9 native and translated exports control pc64: 4776/13083 mismatches control double: 9027/13083 mismatches control nosticky: 168/13083 mismatches control negzero: 7/13083 mismatches control negabs: 741/13083 mismatches control snan: 104/13083 mismatches rejected 6 sequences outside the profile: fsqrt on an empty stack; fsqrt without a store; fsin; fsincos; fnsave; frstor ``` - **x87 regressions:** all nine x87 tests pass (`x87_add`, `x87_mul`, `x87_div`, `x87_sub`, `x87_moves`, `x87_constants`, `x87_integers`, `x87_compare`, `x87_sqrt`). - **Full suite:** `ctest --preset dev --no-tests=error -j 8 --output-junit test-results.xml` gives 183 passed, 1 failed and 2 capability skips out of 186. The run includes the GPU tests. The failure is `gpu_alias_lookup_writes_hardware`, the RDNA 4 array-atomics probe recorded in #369, which fails the same way on `main`. This change touches no GPU code. - **Pure-Python checks:** `tests/form_coverage_check.py`, `tests/docs_links_check.py` and `tests/bidi_controls_check.py` pass. - **Fork CI:** the Windows build-and-test, Windows `/O2` build-and-test, Linux Python and gfx1013 LLVM jobs passed at `44b3707` in the fork's `Windows checks` run [44987342880](https://github.com/denn0x/Xbox2Windows/actions/runs/44987342880). Both Windows jobs ran and passed all nine x87 tests (158 of 158 tests in each). **Coverage.** `python tools/form_coverage.py out/build/dev/test-results.xml` gives x64 **158 of 948** forms, and 157 without `cpu_aot_x87_sqrt`. The added form is `fsqrt`. **Not measured:** - Intel CPUs. All measurements are on one AMD Zen 4 part. - The other precision and rounding modes, because the profile rejects `fldcw`. - The status word, including the precision and invalid-operation flags, as in #422. ## Overlap I trial-merged this branch with all 88 open PRs. Each one conflicts in the same files against `main` and against this branch: the 16 that merge cleanly into `main` also merge cleanly here, and this branch adds no conflict to the others. The changes stay inside the x87 files, the new fixture, one rejection case of `tests/cpu/x87_div.py`, a CMake block after the `cpu_aot_x87_compare` test, and the x87 section of `docs/experiments.md`. ## Evidence The fixture is synthetic and original to this repository (MIT). `docs/experiments.md` documents the square root, the near-tie cases, the controls and the reproduction command. ## 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:43:08 +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!454
No description provided.