cpu: lower x87 in the shared lifter with an exact extended-precision model #400

Open
opened 2026-11-22 00:33:27 +00:00 by denn0x · 11 comments
denn0x commented 2026-11-22 00:33:27 +00:00 (Migrated from github.com)
Contributor

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


Problem

docs/coverage/x64_zen2.tsv lists 100 x87 forms. No fixture covers any of them, and lower() in tools/ffx_version_query.py rejects every x87 instruction. No open PR or issue touches x87; I checked the diffs of the open cpu: PRs for x87 mnemonics.

Proposal

I'd like to take x87 in the shared lifter, as a short series. The first PR covers one behavior: the register stack, loads and stores, and the four basic operations.

Model.

  • Values: each of the eight registers is an exact software extended-precision value: sign, 15-bit exponent and 64-bit significand, with an explicit integer bit.
  • Rounding: arithmetic rounds to the precision control and the rounding control of the control word. A host double cannot stand in: even at 53-bit precision control, results beyond the double exponent range or in its subnormal range differ, and fld m80 and constants such as fldpi carry 64-bit significands into later operations.
  • Stack state: TOP and the tag word are tracked. Stack overflow and underflow produce the masked-exception result, the indefinite NaN.
  • Initial state: the soft-float code is emitted as a separate header, only for bodies that use x87. A lifted function starts from the state measured at a Windows x64 ctypes call on this branch: control word 0x027F (53-bit precision, round to nearest, all exceptions masked), tag word 0xFFFF (empty stack) and status word 0. The docs record that assumption.

First PR.

  • Lowered:
    • fld/fst/fstp for m32, m64, m80 and st(i);
    • fild/fist/fistp/fisttp;
    • fxch, fld1, fldz and the other load-constant forms;
    • fchs, fabs;
    • fadd/fsub/fsubr/fmul/fdiv/fdivr with their p and i forms;
    • fcomi/fcomip/fucomi/fucomip into ZF and CF, and the CF/ZF forms of fcmovcc.
  • Edge cases: NaN propagation, quieting of signaling NaNs, unnormal m80 operands and the integer indefinite of fist follow the Intel SDM and are checked against the native result.
  • Rejected with a diagnostic, and covered by rejection tests:
    • anything that exposes the status word or the environment: fnstsw, fstsw, fcom, ftst, fxam, fnstenv, fsave;
    • fldcw and fninit;
    • the transcendentals (fsin, fcos, fptan, fpatan, f2xm1, fyl2x, ...), whose results are not bit-reproducible from a specification;
    • fcmovu/fcmovnu, which need PF.

Later PRs, once the first is reviewed: a dynamic control word (fldcw, fnstcw, fninit, frndint under each rounding mode), then the status-word forms with their condition codes.

Shared interface: lower() and CPU_FIXTURES, which #287, #289, #291, #326, #328, #331, #335 and others also extend. The x87 branch is new code at its own anchor. The header is separate from INTEGER_HEADER, so non-x87 callers are unchanged.

Alternatives

  • Host double or long double. MSVC's long double is double, so it is inexact for the reasons above.
  • Inline x87 in the generated C++. MSVC x64 has no inline assembly, and emitting x87 again would test the host CPU rather than the translation.

Verification

A source-built MASM fixture with native and lifted DLLs is compared on every result word, the stack depth and ZF/CF. Its cases include:

  • m80 operands with low significand bits set;
  • constants multiplied by values;
  • results beyond the double exponent range;
  • double and extended subnormals;
  • NaN payloads;
  • stack overflow and underflow.

Negative controls are mutations of the generated C++, and each must mismatch:

  • a host-double arithmetic core;
  • rounding at 64 bits instead of the precision control;
  • a dropped integer bit.

Translation must reject fnstsw, fldcw and fsin.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6536373352 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T00:33:27Z. --- ### Problem `docs/coverage/x64_zen2.tsv` lists 100 x87 forms. No fixture covers any of them, and `lower()` in `tools/ffx_version_query.py` rejects every x87 instruction. No open PR or issue touches x87; I checked the diffs of the open `cpu:` PRs for x87 mnemonics. ### Proposal I'd like to take x87 in the shared lifter, as a short series. The first PR covers one behavior: the register stack, loads and stores, and the four basic operations. **Model.** - **Values:** each of the eight registers is an exact software extended-precision value: sign, 15-bit exponent and 64-bit significand, with an explicit integer bit. - **Rounding:** arithmetic rounds to the precision control and the rounding control of the control word. A host `double` cannot stand in: even at 53-bit precision control, results beyond the double exponent range or in its subnormal range differ, and `fld m80` and constants such as `fldpi` carry 64-bit significands into later operations. - **Stack state:** TOP and the tag word are tracked. Stack overflow and underflow produce the masked-exception result, the indefinite NaN. - **Initial state:** the soft-float code is emitted as a separate header, only for bodies that use x87. A lifted function starts from the state measured at a Windows x64 ctypes call on this branch: control word `0x027F` (53-bit precision, round to nearest, all exceptions masked), tag word `0xFFFF` (empty stack) and status word 0. The docs record that assumption. **First PR.** - **Lowered:** - `fld`/`fst`/`fstp` for m32, m64, m80 and `st(i)`; - `fild`/`fist`/`fistp`/`fisttp`; - `fxch`, `fld1`, `fldz` and the other load-constant forms; - `fchs`, `fabs`; - `fadd`/`fsub`/`fsubr`/`fmul`/`fdiv`/`fdivr` with their `p` and `i` forms; - `fcomi`/`fcomip`/`fucomi`/`fucomip` into ZF and CF, and the CF/ZF forms of `fcmovcc`. - **Edge cases:** NaN propagation, quieting of signaling NaNs, unnormal m80 operands and the integer indefinite of `fist` follow the Intel SDM and are checked against the native result. - **Rejected with a diagnostic, and covered by rejection tests:** - anything that exposes the status word or the environment: `fnstsw`, `fstsw`, `fcom`, `ftst`, `fxam`, `fnstenv`, `fsave`; - `fldcw` and `fninit`; - the transcendentals (`fsin`, `fcos`, `fptan`, `fpatan`, `f2xm1`, `fyl2x`, ...), whose results are not bit-reproducible from a specification; - `fcmovu`/`fcmovnu`, which need PF. **Later PRs, once the first is reviewed:** a dynamic control word (`fldcw`, `fnstcw`, `fninit`, `frndint` under each rounding mode), then the status-word forms with their condition codes. **Shared interface:** `lower()` and `CPU_FIXTURES`, which #287, #289, #291, #326, #328, #331, #335 and others also extend. The x87 branch is new code at its own anchor. The header is separate from `INTEGER_HEADER`, so non-x87 callers are unchanged. ### Alternatives - **Host `double` or `long double`.** MSVC's `long double` is `double`, so it is inexact for the reasons above. - **Inline x87 in the generated C++.** MSVC x64 has no inline assembly, and emitting x87 again would test the host CPU rather than the translation. ### Verification A source-built MASM fixture with native and lifted DLLs is compared on every result word, the stack depth and ZF/CF. Its cases include: - m80 operands with low significand bits set; - constants multiplied by values; - results beyond the double exponent range; - double and extended subnormals; - NaN payloads; - stack overflow and underflow. Negative controls are mutations of the generated C++, and each must mismatch: - a host-`double` arithmetic core; - rounding at 64 bits instead of the precision control; - a dropped integer bit. Translation must reject `fnstsw`, `fldcw` and `fsin`. _AI-assisted (Claude Code)._
R0Y00 commented 2026-11-24 06:48:16 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-22T00:57:05Z.


Please go ahead with a first PR for an opt-in x87 leaf-function profile in the shared lower(). One register-add form is enough to exercise the distinction between register precision, arithmetic precision and store precision.

  • Entry and exit. Specify CW 0x027F, TOP 0, eight empty slots and cleared status at entry. Have the native MASM wrapper save the caller’s x87 environment, establish this state for each comparison, then restore the caller’s environment. The ctypes observation is evidence for that particular call. Track TOP and slot occupancy, require a provably empty stack on every normal exit, and reject unknown initial depth, stack overflow or underflow, control-word changes, unmodeled state observations and live x87 state across calls.
  • First instruction set. Accept FLD m32/m64/m80, FSTP m32/m64/m80 and one register form of FADDP. Emit the integer-based extended-precision helpers only for functions using this profile. Preserve the sign, 15-bit exponent and all 64 significand bits including the explicit integer bit on loads and copies. Round the add to 53 significand bits, nearest-even, with the extended exponent range. Round again as required by the store format and preserve signed zero.
  • Value domain. Document the accepted encodings. A first implementation restricted to canonical finite values, including signed zeros and subnormals, is welcome if a checked entry reports unsupported runtime input before producing an invalid result. Otherwise implement and verify the observable special-value semantics of the accepted operations. Include cases for any arithmetic overflow or underflow the profile supports. This scope requires neither a complete status word nor exception emulation.
  • Acceptance. On Windows x64 CI, give the native MASM and translated paths identical input bytes and compare the output bytes. Include an m80 round trip with low significand bits set, an addition beyond the binary64 exponent range, a halfway sum that distinguishes PC=53 from PC=64, and narrow-store rounding boundaries. Check input/output guards, include negative controls that distinguish incorrect implementations, and run existing shared-lowerer regressions. Document the profile and its rejection boundaries alongside the reproduction command.

Multiplication, division, conversions, constants, comparisons and stack faults can each follow with their own evidence. When adding comparisons, account for every observable flag or reject consumers of unmodeled flags, including PF. This first PR can proceed as a bounded community experiment.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7071885220 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7071885220). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-22T00:57:05Z. --- Please go ahead with a first PR for an opt-in x87 leaf-function profile in the shared `lower()`. One register-add form is enough to exercise the distinction between register precision, arithmetic precision and store precision. - **Entry and exit.** Specify CW `0x027F`, TOP 0, eight empty slots and cleared status at entry. Have the native MASM wrapper save the caller’s x87 environment, establish this state for each comparison, then restore the caller’s environment. The ctypes observation is evidence for that particular call. Track TOP and slot occupancy, require a provably empty stack on every normal exit, and reject unknown initial depth, stack overflow or underflow, control-word changes, unmodeled state observations and live x87 state across calls. - **First instruction set.** Accept `FLD m32/m64/m80`, `FSTP m32/m64/m80` and one register form of `FADDP`. Emit the integer-based extended-precision helpers only for functions using this profile. Preserve the sign, 15-bit exponent and all 64 significand bits including the explicit integer bit on loads and copies. Round the add to 53 significand bits, nearest-even, with the extended exponent range. Round again as required by the store format and preserve signed zero. - **Value domain.** Document the accepted encodings. A first implementation restricted to canonical finite values, including signed zeros and subnormals, is welcome if a checked entry reports unsupported runtime input before producing an invalid result. Otherwise implement and verify the observable special-value semantics of the accepted operations. Include cases for any arithmetic overflow or underflow the profile supports. This scope requires neither a complete status word nor exception emulation. - **Acceptance.** On Windows x64 CI, give the native MASM and translated paths identical input bytes and compare the output bytes. Include an m80 round trip with low significand bits set, an addition beyond the binary64 exponent range, a halfway sum that distinguishes PC=53 from PC=64, and narrow-store rounding boundaries. Check input/output guards, include negative controls that distinguish incorrect implementations, and run existing shared-lowerer regressions. Document the profile and its rejection boundaries alongside the reproduction command. Multiplication, division, conversions, constants, comparisons and stack faults can each follow with their own evidence. When adding comparisons, account for every observable flag or reject consumers of unmodeled flags, including PF. This first PR can proceed as a bounded community experiment.
denn0x commented 2026-11-24 06:48:16 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-22T01:22:16Z.


Opened #422 for the first step: the opt-in lower(..., x87=True) profile with fld/fstp m32/m64/m80 and faddp st(i), st. It follows the entry/exit contract above, with static stack depths and the listed rejections, and is checked with identical input bytes through a native harness that saves and restores the caller's environment. All 80-bit encodings are accepted as operands, and special-value semantics are implemented and checked rather than restricted to canonical finite values. One rule was measured rather than taken from Table 4-7: with equal NaN significands, the positive NaN wins in either operand order. The PR body has the command, the 8085-case result, six controls and the rejection list. Multiplication and division, conversions, constants, comparisons (with PF) and stack faults will follow as separate PRs.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7072161154 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7072161154). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T01:22:16Z. --- Opened #422 for the first step: the opt-in `lower(..., x87=True)` profile with `fld`/`fstp` m32/m64/m80 and `faddp st(i), st`. It follows the entry/exit contract above, with static stack depths and the listed rejections, and is checked with identical input bytes through a native harness that saves and restores the caller's environment. All 80-bit encodings are accepted as operands, and special-value semantics are implemented and checked rather than restricted to canonical finite values. One rule was measured rather than taken from Table 4-7: with equal NaN significands, the positive NaN wins in either operand order. The PR body has the command, the 8085-case result, six controls and the rejection list. Multiplication and division, conversions, constants, comparisons (with PF) and stack faults will follow as separate PRs. _AI-assisted (Claude Code)._
denn0x commented 2026-11-24 06:48:25 +00:00 (Migrated from github.com)
Author
Contributor

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


Status. The series has landed through #462 (frndint), and #465 (fxtract) is open. Three more are ready and will open in order as each one merges:

  • fscale;
  • the ZF/CF forms of fcmovcc;
  • fiadd, fisub, fisubr, fimul, fidiv and fidivr with m16 and m32 operands.

With those, the first-PR list of this issue is covered except fcmovu and fcmovnu, which need PF.

Next: the dynamic control word, the first of the later steps above. I'd like your decisions on two points (3 and 4) before writing it.

Measured natively on the Ryzen 7 7700 with a probe: fldcw X, then fnstcw, then 1/3 computed and stored as m80.

  • fnstcw returns (X & 0x1F3F) | 0x0040. Bit 6 reads as 1, bits 7 and 13 to 15 read as 0, and bit 12 (the obsolete infinity control) is kept.
  • Precision control 00, 10 and 11 give 24, 53 and 64 bits. The reserved value 01 gives 64 bits on this part; the SDM leaves it reserved, so other CPUs may differ.
  • The four rounding modes give the documented results for 1/3 at 24 and 53 bits.
  • A word with an unmasked exception (fldcw 0x0000) faults on the next inexact result, as expected.

Proposal.

  1. Accepted forms: fldcw m16, fnstcw m16 and fstcw m16 (wait; fnstcw). fninit and fnclex also clear the status word, so they wait for the status-word step.

  2. Model: the lowered function keeps a local uint16_t x87_cw, initialised to 0x027F. Every rounding site reads PC and RC from it:

    • the arithmetic, fsqrt, fscale and frndint;
    • fist and fistp (fisttp always truncates);
    • the narrowing stores to m32 and m64;
    • the constant loads, whose last bit depends on RC.

    Exact operations do not change.

  3. Words the model cannot follow: a loaded word with any exception unmasked (bits 0 to 5 not all set), or with PC 01. Lowered code cannot fault as native does, so I propose a __fastfail at that fldcw, tested in a child process. Alternatively PC 01 could be modelled as 64 bits, but that holds only for the measured part. Which do you prefer?

  4. Exit: a function must still return with 0x027F, as the profile requires today. Translation cannot check this statically, because the word comes from memory, so I'd add a run-time check at each return that fails in the same way. Is a run-time contract check acceptable here, or would you rather reject functions whose fldcw operand is not the slot an earlier fnstcw in the same function wrote?

  5. Verification:

    • the MSVC truncation idiom (fnstcw; or 0C00h; fldcw; fistp; fldcw);
    • each rounding operation under every PC and RC pair;
    • fnstcw after every reserved-bit pattern above.

    Controls: RC ignored, PC ignored, fistp ignoring RC, the constant loads ignoring RC, and fnstcw returning the raw word.

Shared interface: only tools/x87_lower.py and tools/x87_soft.h. The helpers gain a control-word argument, so the generated code changes throughout the x87 profile, but no other caller of lower() changes.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7074824807 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7074824807). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T05:34:19Z. --- **Status.** The series has landed through #462 (`frndint`), and #465 (`fxtract`) is open. Three more are ready and will open in order as each one merges: - `fscale`; - the ZF/CF forms of `fcmovcc`; - `fiadd`, `fisub`, `fisubr`, `fimul`, `fidiv` and `fidivr` with m16 and m32 operands. With those, the first-PR list of this issue is covered except `fcmovu` and `fcmovnu`, which need PF. **Next: the dynamic control word**, the first of the later steps above. I'd like your decisions on two points (3 and 4) before writing it. **Measured natively** on the Ryzen 7 7700 with a probe: `fldcw X`, then `fnstcw`, then 1/3 computed and stored as m80. - `fnstcw` returns `(X & 0x1F3F) | 0x0040`. Bit 6 reads as 1, bits 7 and 13 to 15 read as 0, and bit 12 (the obsolete infinity control) is kept. - Precision control 00, 10 and 11 give 24, 53 and 64 bits. The reserved value 01 gives 64 bits on this part; the SDM leaves it reserved, so other CPUs may differ. - The four rounding modes give the documented results for 1/3 at 24 and 53 bits. - A word with an unmasked exception (`fldcw 0x0000`) faults on the next inexact result, as expected. **Proposal.** 1. **Accepted forms:** `fldcw m16`, `fnstcw m16` and `fstcw m16` (`wait; fnstcw`). `fninit` and `fnclex` also clear the status word, so they wait for the status-word step. 2. **Model:** the lowered function keeps a local `uint16_t x87_cw`, initialised to `0x027F`. Every rounding site reads PC and RC from it: - the arithmetic, `fsqrt`, `fscale` and `frndint`; - `fist` and `fistp` (`fisttp` always truncates); - the narrowing stores to m32 and m64; - the constant loads, whose last bit depends on RC. Exact operations do not change. 3. **Words the model cannot follow:** a loaded word with any exception unmasked (bits 0 to 5 not all set), or with PC 01. Lowered code cannot fault as native does, so I propose a `__fastfail` at that `fldcw`, tested in a child process. Alternatively PC 01 could be modelled as 64 bits, but that holds only for the measured part. Which do you prefer? 4. **Exit:** a function must still return with `0x027F`, as the profile requires today. Translation cannot check this statically, because the word comes from memory, so I'd add a run-time check at each return that fails in the same way. Is a run-time contract check acceptable here, or would you rather reject functions whose `fldcw` operand is not the slot an earlier `fnstcw` in the same function wrote? 5. **Verification:** - the MSVC truncation idiom (`fnstcw; or 0C00h; fldcw; fistp; fldcw`); - each rounding operation under every PC and RC pair; - `fnstcw` after every reserved-bit pattern above. Controls: RC ignored, PC ignored, `fistp` ignoring RC, the constant loads ignoring RC, and `fnstcw` returning the raw word. **Shared interface:** only `tools/x87_lower.py` and `tools/x87_soft.h`. The helpers gain a control-word argument, so the generated code changes throughout the x87 profile, but no other caller of `lower()` changes. _AI-assisted (Claude Code)._
R0Y00 commented 2026-11-24 06:48:25 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-22T05:37:46Z.


For the first dynamic-control-word profile, accept words with all six exceptions masked and PC=00, 10 or 11. Please retain the Ryzen PC=01 result as a hardware observation. An unsupported FLDCW must give the host a distinguishable profile-rejection status and leave the host running. A separate checked entry can return that status while preserving the fixed-profile ABI. If this revision has no error channel, restrict it to statically proven supported control words. With a checked entry, verify restoration to 0x027F at every normal return; branches and different save slots are fine. Please cover an unrestored return, an unmasked exception and reserved PC, and check which guest writes remain visible before each rejection. Fixed-control-word contributions can proceed independently.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7074857443 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7074857443). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-22T05:37:46Z. --- For the first dynamic-control-word profile, accept words with all six exceptions masked and PC=00, 10 or 11. Please retain the Ryzen PC=01 result as a hardware observation. An unsupported FLDCW must give the host a distinguishable profile-rejection status and leave the host running. A separate checked entry can return that status while preserving the fixed-profile ABI. If this revision has no error channel, restrict it to statically proven supported control words. With a checked entry, verify restoration to 0x027F at every normal return; branches and different save slots are fine. Please cover an unrestored return, an unmasked exception and reserved PC, and check which guest writes remain visible before each rejection. Fixed-control-word contributions can proceed independently.
denn0x commented 2026-11-24 06:48:27 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-22T06:51:59Z.


Status. The checked entry for the dynamic control word is written and tested. It follows the decision above. It will open after #476, the integer-operand arithmetic and fnstcw/fstcw/wait, which come first in that order. The branch is cpu/lower-x87-fldcw on my fork if you want an early look. Fork CI run 44995141203 passed at its head, 0c82e82.

Entry. lower(..., x87=x87_lower.Checked(reject)) is a separate entry, and the fixed profile keeps its ABI. All 110 generated cpu_x87_*.cpp files of the earlier tests are byte-identical.

Accepted words. fldcw accepts words with all six exceptions masked and precision control 00, 10 or 11. It keeps the word as fnstcw reads it back. Every rounding site follows it:

  • the arithmetic and fsqrt, which also follow the precision control;
  • fscale and frndint;
  • fist and fistp;
  • the m32 and m64 stores;
  • the five inexact constants.

Rejection statuses. The lowered function leaves through the caller's reject statement with a distinct status, and the host keeps running:

Status Cause
1 an unmasked exception
2 precision control 01
3 a return whose word is not 0x027F

Return check. It runs at every return, so a branch with two returns restoring from different slots is covered. A function that loads the word must not contain a call, an indirect branch or an external edge.

Fixture. cpu_aot_x87_fldcw has 15 exports and 15944 cases on the Ryzen 7 7700. The translation matched the model in every case, including the status, the output block with its guards, and the result word, which is written only on success. The exports include the MSVC truncation idiom, and one export makes guest stores before, between and after two fldcw. Each rejection keeps exactly the stores made before it.

Statuses observed:

Status Cases
accepted 14718
1 570
2 380
3 276

Native runs. 14994 native cases matched. The 570 unmasked cases run only translated, because natively they would trap. The 380 PC=01 cases ran natively as an observation, and all of them matched a 64-bit model on this part. Ten negative controls each mismatch; they include no return check, the check on only one of two returns, and a rejection that records its status but runs on.

One change to existing tests. Passing the word into the helpers also gave x87_div and x87_sqrt the round bit below the 64-bit result. Before, they had only the sticky bit, which is enough at 53 bits. This changes only the pc64 mutation counts of the div, sqrt and integer-operand tests. Every real case and every other control count is unchanged. That helper change is its own commit. I can open it as a separate PR ahead of the checked entry if you prefer to review the numerics apart.

Next: the status word. This is the last step listed in the issue. I'd like your call on its scope before I write it:

  1. Forms:

    • fcom, fcomp and fcompp, and the fucom forms, with m32, m64 and st(i);
    • ficom and ficomp;
    • ftst and fxam;
    • fnstsw ax, fstsw ax and fnstsw m16;
    • sahf in the integer lowering, which would define CF and ZF from C0 and C3. PF stays unmodelled, so jp, fcmovu and the other PF readers stay rejected.
  2. Condition codes and TOP: C0 to C3 come from the last compare or fxam. TOP is the static depth, so it is known at translation time.

  3. Sticky exception flags (IE, DE, ZE, OE, UE, PE and SF), which fnstsw also exposes. There are two options:

    • (a) Model them exactly. Every helper reports the flags it raises, and the native harness already records the status word each export leaves, so the comparison would cover them.
    • (b) As a first PR, accept a status-word read only when the translation proves that its consumers read the condition codes alone: fnstsw ax followed by test ah, imm8 with imm8 within C0 to C3, or by sahf. That leaves (a) for a second PR, which would also enable fnstsw m16 and fnclex.

    My preference is (a) in one PR, because (b) needs a consumer analysis that (a) would later delete.

  4. fninit: this would come with the status word. In the checked entry it would set x87_cw = 0x037F, which is 64-bit precision, so a return without a restore stops with status 3. It would be rejected unless the stack is empty.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7075574875 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7075574875). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T06:51:59Z. --- **Status.** The checked entry for the dynamic control word is written and tested. It follows the decision above. It will open after #476, the integer-operand arithmetic and `fnstcw`/`fstcw`/`wait`, which come first in that order. The branch is [`cpu/lower-x87-fldcw`](https://github.com/denn0x/Xbox2Windows/tree/cpu/lower-x87-fldcw) on my fork if you want an early look. Fork CI run [44995141203](https://github.com/denn0x/Xbox2Windows/actions/runs/44995141203) passed at its head, `0c82e82`. **Entry.** `lower(..., x87=x87_lower.Checked(reject))` is a separate entry, and the fixed profile keeps its ABI. All 110 generated `cpu_x87_*.cpp` files of the earlier tests are byte-identical. **Accepted words.** `fldcw` accepts words with all six exceptions masked and precision control 00, 10 or 11. It keeps the word as `fnstcw` reads it back. Every rounding site follows it: - the arithmetic and `fsqrt`, which also follow the precision control; - `fscale` and `frndint`; - `fist` and `fistp`; - the m32 and m64 stores; - the five inexact constants. **Rejection statuses.** The lowered function leaves through the caller's `reject` statement with a distinct status, and the host keeps running: | Status | Cause | |---|---| | 1 | an unmasked exception | | 2 | precision control 01 | | 3 | a return whose word is not `0x027F` | **Return check.** It runs at every return, so a branch with two returns restoring from different slots is covered. A function that loads the word must not contain a call, an indirect branch or an external edge. **Fixture.** `cpu_aot_x87_fldcw` has 15 exports and 15944 cases on the Ryzen 7 7700. The translation matched the model in every case, including the status, the output block with its guards, and the result word, which is written only on success. The exports include the MSVC truncation idiom, and one export makes guest stores before, between and after two `fldcw`. Each rejection keeps exactly the stores made before it. **Statuses observed:** | Status | Cases | |---|---| | accepted | 14718 | | 1 | 570 | | 2 | 380 | | 3 | 276 | **Native runs.** 14994 native cases matched. The 570 unmasked cases run only translated, because natively they would trap. The 380 PC=01 cases ran natively as an observation, and all of them matched a 64-bit model on this part. Ten negative controls each mismatch; they include no return check, the check on only one of two returns, and a rejection that records its status but runs on. **One change to existing tests.** Passing the word into the helpers also gave `x87_div` and `x87_sqrt` the round bit below the 64-bit result. Before, they had only the sticky bit, which is enough at 53 bits. This changes only the `pc64` mutation counts of the div, sqrt and integer-operand tests. Every real case and every other control count is unchanged. That helper change is its own commit. I can open it as a separate PR ahead of the checked entry if you prefer to review the numerics apart. **Next: the status word.** This is the last step listed in the issue. I'd like your call on its scope before I write it: 1. **Forms:** - `fcom`, `fcomp` and `fcompp`, and the `fucom` forms, with m32, m64 and `st(i)`; - `ficom` and `ficomp`; - `ftst` and `fxam`; - `fnstsw ax`, `fstsw ax` and `fnstsw m16`; - `sahf` in the integer lowering, which would define CF and ZF from C0 and C3. PF stays unmodelled, so `jp`, `fcmovu` and the other PF readers stay rejected. 2. **Condition codes and TOP:** C0 to C3 come from the last compare or `fxam`. TOP is the static depth, so it is known at translation time. 3. **Sticky exception flags** (IE, DE, ZE, OE, UE, PE and SF), which `fnstsw` also exposes. There are two options: - **(a)** Model them exactly. Every helper reports the flags it raises, and the native harness already records the status word each export leaves, so the comparison would cover them. - **(b)** As a first PR, accept a status-word read only when the translation proves that its consumers read the condition codes alone: `fnstsw ax` followed by `test ah, imm8` with `imm8` within C0 to C3, or by `sahf`. That leaves (a) for a second PR, which would also enable `fnstsw m16` and `fnclex`. My preference is (a) in one PR, because (b) needs a consumer analysis that (a) would later delete. 4. **`fninit`:** this would come with the status word. In the checked entry it would set `x87_cw = 0x037F`, which is 64-bit precision, so a return without a restore stops with status 3. It would be rejected unless the stack is empty. _AI-assisted (Claude Code)._
R0Y00 commented 2026-11-24 06:48:27 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-22T07:08:44Z.


For the first status-word PR, please take option (b). Accept FNSTSW AX when static analysis can prove that every reachable consumer observes only defined condition bits. Track C0/C2/C3 according to the instruction that produced them. Mark architecturally undefined bits unknown, and carry a preserved bit forward only when its previous definition is known.

For SAHF, the mapping is CF ← C0, PF ← C2, ZF ← C3. Follow flag uses along every successor, including JP and JNP. Apply the same check to other AX, AH and flag consumers. A useful negative control is a branch where one successor only tests a known bit and the other exposes an unknown bit. Include a native comparison that distinguishes ordered and unordered inputs through PF.

TOP is the three-bit physical stack index. From a known entry TOP, each push decrements it and each pop increments it modulo eight. Track slot tags separately from logical depth if the stack has holes. Memory-form status stores, observable sticky exception flags and FNINIT state reset can each follow with their own semantics and native regression cases.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7075739611 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7075739611). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-22T07:08:44Z. --- For the first status-word PR, please take option (b). Accept `FNSTSW AX` when static analysis can prove that every reachable consumer observes only defined condition bits. Track C0/C2/C3 according to the instruction that produced them. Mark architecturally undefined bits unknown, and carry a preserved bit forward only when its previous definition is known. For `SAHF`, the mapping is CF ← C0, PF ← C2, ZF ← C3. Follow flag uses along every successor, including `JP` and `JNP`. Apply the same check to other AX, AH and flag consumers. A useful negative control is a branch where one successor only tests a known bit and the other exposes an unknown bit. Include a native comparison that distinguishes ordered and unordered inputs through PF. TOP is the three-bit physical stack index. From a known entry TOP, each push decrements it and each pop increments it modulo eight. Track slot tags separately from logical depth if the stack has holes. Memory-form status stores, observable sticky exception flags and `FNINIT` state reset can each follow with their own semantics and native regression cases.
denn0x commented 2026-11-24 06:48:30 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-22T10:46:43Z.


Status. #534 and #535 have merged. #548 (PF after fcomi, with fcmovu and fcmovnu) is open. ftst/ficom/ficomp and then fxam follow it, in that order.

Next: fprem and fprem1. Before proposing a scope I measured both instructions on the Ryzen 7 7700 (AMD64 Family 25 Model 97 Stepping 2), with ctypes calling machine code against an exact Fraction model:

  • Full reduction. When the normalized exponent difference D is below 64, the remainder is exact. fprem truncates the quotient q and fprem1 rounds it to nearest-even. C0, C3 and C1 are bits 2, 1 and 0 of |q|, and C2 is 0. A zero remainder takes the sign of st(0). Nothing mismatched across random pairs from D = -66 to 70, denormal and pseudo-denormal divisors at D = 62 to 65, denormal results, exact multiples, ties and their neighbours, and fprem1 with st(0) between half of st(1) and st(1). Neither precision nor rounding control has any effect under any of the twelve masked control words.
  • C2 flips at exactly D = 64 for both instructions. D is computed on normalized exponents, which holds for denormal and pseudo-denormal st(1) too.
  • Partial reduction (D ≥ 64). The SDM says N is "an implementation-dependent number between 32 and 63". Here N = 32 + (D mod 32) in every sample from D = 64 to 1000. Both instructions truncate in this case, and C0, C1 and C3 are cleared.
  • NaN results (a NaN or unsupported operand, an infinite st(0) or a zero st(1)). The value follows the arithmetic NaN rules, the same as fadd. The SDM gives no status bits for this case. Here C0 and C3 keep their previous values and C1 and C2 are cleared.

Proposal. This follows the fldcw precedent: add it to the checked entry only, and keep rejecting both instructions in the fixed profile.

  • Status 4 for a partial reduction (D ≥ 64). The result there is implementation-dependent.
  • Status 5 for a NaN result in a function that contains fnstsw, because only the status bits are unspecified. Without fnstsw the NaN value is kept.
  • Otherwise the exact remainder, C0/C3/C1 from the quotient and C2 = 0, known to the status-word dataflow (C1 included).
  • The fmod idiom fprem; fnstsw ax; sahf; jp back is accepted, and depth and flags converge over the back edge. In an accepted run C2 is always 0, so the back edge is translated but never taken. The native loop, by contrast, does reduce partially and iterate. Its final value is the full remainder, whatever N is, because each partial step subtracts an even multiple of st(1). So the fixture can compare it on any host.

This is written and passes locally. The branch is cpu/lower-x87-fprem, stacked on fxam. cpu_aot_x87_fprem has 11 exports and 36952 cases: 27623 ok, 4104 partial and 5225 NaN in the translation. Native C2 is 1 in exactly the single-step cases rejected as partial, and the native result is a NaN in exactly the cases the model gives a NaN. Eight mutated controls each mismatch. I will open it after fxam, unless you want a different scope.

Request. If you have an Intel machine, could you run the probe below? It prints the D where C2 flips, the N values that fit, and the status bits after three NaN results with C3, C0, or C1 and C2 set beforehand. If Intel matches, a follow-up could model the partial step and the NaN-result bits instead of rejecting them.

fprem_vendor_probe.py (Windows x64, Python 3, standard library only)
"""FPREM/FPREM1 probe (Windows x64, Python 3): the partial-reduction rule and the status bits after a NaN result."""
import ctypes, platform, random, struct
from fractions import Fraction

k32 = ctypes.windll.kernel32
k32.VirtualAlloc.restype = ctypes.c_void_p
k32.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint32]
FN = ctypes.CFUNCTYPE(ctypes.c_uint16, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)


def make(op, pre=""):  # rcx = ST(0) m80, rdx = ST(1) m80, r8 = result m80; returns FNSTSW AX
    code = bytes.fromhex("db 2a db 29" + pre + op + "df e0 41 db 38 dd d8 c3")
    mem = k32.VirtualAlloc(None, 4096, 0x3000, 0x40)
    ctypes.memmove(mem, code, len(code))
    return FN(mem)


def run(f, a, b):
    buf = [ctypes.create_string_buffer(struct.pack("<QH", *v) + bytes(6), 16) for v in (a, b, (0, 0))]
    sw = f(*buf)
    return sw, struct.unpack("<QH", buf[2].raw[:10])


def value(v):
    e = v[1] & 0x7FFF
    return (-1) ** (v[1] >> 15) * Fraction(v[0]) * Fraction(2) ** ((e or 1) - 16383 - 63)


J, rng = 1 << 63, random.Random(1)
print("processor:", platform.processor())
for name, op in (("fprem", "d9 f8"), ("fprem1", "d9 f5")):
    f = make(op)
    flips = [d for d in range(56, 72) if (run(f, (J | rng.getrandbits(63), 16383 + d), (J | 5, 16383))[0] >> 10) & 1]
    print(name, "C2 set for exponent differences", flips[:3], "...")
    for d in (64, 65, 80, 95, 96, 127, 128, 200, 1000):
        fits, bits = set(range(32, 64)), set()
        for _ in range(50):
            a, b = (J | rng.getrandbits(63), 16383 + d), (J | rng.getrandbits(63), 16383)
            sw, r = run(f, a, b)
            bits.add((sw >> 8 & 1, sw >> 9 & 1, sw >> 10 & 1, sw >> 14 & 1))
            fits = {n for n in fits if value(r) == value(a) - int(value(a) / (value(b) * 2 ** (d - n))) * value(b) * 2 ** (d - n)}
        print(f"  D={d}: N fitting every sample {sorted(fits)}; (C0, C1, C2, C3) seen {sorted(bits)}")
    # Status bits after a NaN result, with C3 set (FTST of 0) or C0 set (FCOMP 1 > 0) or C2 and C1 (FXAM of -1) before.
    for label, pre in (("C3 before", "d9 ee d9 e4 dd d8"), ("C0 before", "d9 e8 d9 ee d8 d9 dd d8"),
                       ("C1, C2 before", "d9 e8 d9 e0 d9 e5 dd d8")):
        g = make(op, pre)
        seen = {k: run(g, *ab)[0] for k, ab in (("inf/1", ((J, 0x7FFF), (J, 16383))), ("1/0", ((J, 16383), (0, 0))),
                                                ("qnan/1", ((J | J >> 1, 0x7FFF), (J, 16383))))}
        print(f"  NaN result, {label}: " + ", ".join(f"{k} C0..C3={s >> 8 & 1}{s >> 9 & 1}{s >> 10 & 1}{s >> 14 & 1}"
                                                     for k, s in seen.items()))

Its output on the Ryzen 7 7700, for comparison:

processor: AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD
fprem C2 set for exponent differences [64, 65, 66] ...
  D=64: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=65: N fitting every sample [33]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=80: N fitting every sample [48]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=95: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=96: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=127: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=128: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=200: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=1000: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  NaN result, C3 before: inf/1 C0..C3=0001, 1/0 C0..C3=0001, qnan/1 C0..C3=0001
  NaN result, C0 before: inf/1 C0..C3=1000, 1/0 C0..C3=1000, qnan/1 C0..C3=1000
  NaN result, C1, C2 before: inf/1 C0..C3=0000, 1/0 C0..C3=0000, qnan/1 C0..C3=0000
fprem1 C2 set for exponent differences [64, 65, 66] ...
  D=64: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=65: N fitting every sample [33]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=80: N fitting every sample [48]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=95: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=96: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=127: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=128: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=200: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  D=1000: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)]
  NaN result, C3 before: inf/1 C0..C3=0001, 1/0 C0..C3=0001, qnan/1 C0..C3=0001
  NaN result, C0 before: inf/1 C0..C3=1000, 1/0 C0..C3=1000, qnan/1 C0..C3=1000
  NaN result, C1, C2 before: inf/1 C0..C3=0000, 1/0 C0..C3=0000, qnan/1 C0..C3=0000

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7078010414 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7078010414). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-22T10:46:43Z. --- **Status.** #534 and #535 have merged. #548 (PF after `fcomi`, with `fcmovu` and `fcmovnu`) is open. `ftst`/`ficom`/`ficomp` and then `fxam` follow it, in that order. **Next: `fprem` and `fprem1`.** Before proposing a scope I measured both instructions on the Ryzen 7 7700 (`AMD64 Family 25 Model 97 Stepping 2`), with ctypes calling machine code against an exact `Fraction` model: - **Full reduction.** When the normalized exponent difference D is below 64, the remainder is exact. `fprem` truncates the quotient q and `fprem1` rounds it to nearest-even. C0, C3 and C1 are bits 2, 1 and 0 of |q|, and C2 is 0. A zero remainder takes the sign of `st(0)`. Nothing mismatched across random pairs from D = -66 to 70, denormal and pseudo-denormal divisors at D = 62 to 65, denormal results, exact multiples, ties and their neighbours, and `fprem1` with `st(0)` between half of `st(1)` and `st(1)`. Neither precision nor rounding control has any effect under any of the twelve masked control words. - **C2 flips at exactly D = 64** for both instructions. D is computed on normalized exponents, which holds for denormal and pseudo-denormal `st(1)` too. - **Partial reduction (D ≥ 64).** The SDM says N is "an implementation-dependent number between 32 and 63". Here N = 32 + (D mod 32) in every sample from D = 64 to 1000. Both instructions truncate in this case, and C0, C1 and C3 are cleared. - **NaN results** (a NaN or unsupported operand, an infinite `st(0)` or a zero `st(1)`). The value follows the arithmetic NaN rules, the same as `fadd`. The SDM gives no status bits for this case. Here C0 and C3 keep their previous values and C1 and C2 are cleared. **Proposal.** This follows the `fldcw` precedent: add it to the checked entry only, and keep rejecting both instructions in the fixed profile. - Status 4 for a partial reduction (D ≥ 64). The result there is implementation-dependent. - Status 5 for a NaN result in a function that contains `fnstsw`, because only the status bits are unspecified. Without `fnstsw` the NaN value is kept. - Otherwise the exact remainder, C0/C3/C1 from the quotient and C2 = 0, known to the status-word dataflow (C1 included). - The fmod idiom `fprem; fnstsw ax; sahf; jp back` is accepted, and depth and flags converge over the back edge. In an accepted run C2 is always 0, so the back edge is translated but never taken. The native loop, by contrast, does reduce partially and iterate. Its final value is the full remainder, whatever N is, because each partial step subtracts an even multiple of `st(1)`. So the fixture can compare it on any host. This is written and passes locally. The branch is [`cpu/lower-x87-fprem`](https://github.com/denn0x/Xbox2Windows/tree/cpu/lower-x87-fprem), stacked on `fxam`. `cpu_aot_x87_fprem` has 11 exports and 36952 cases: 27623 ok, 4104 partial and 5225 NaN in the translation. Native C2 is 1 in exactly the single-step cases rejected as partial, and the native result is a NaN in exactly the cases the model gives a NaN. Eight mutated controls each mismatch. I will open it after `fxam`, unless you want a different scope. **Request.** If you have an Intel machine, could you run the probe below? It prints the D where C2 flips, the N values that fit, and the status bits after three NaN results with C3, C0, or C1 and C2 set beforehand. If Intel matches, a follow-up could model the partial step and the NaN-result bits instead of rejecting them. <details><summary>fprem_vendor_probe.py (Windows x64, Python 3, standard library only)</summary> ```python """FPREM/FPREM1 probe (Windows x64, Python 3): the partial-reduction rule and the status bits after a NaN result.""" import ctypes, platform, random, struct from fractions import Fraction k32 = ctypes.windll.kernel32 k32.VirtualAlloc.restype = ctypes.c_void_p k32.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint32] FN = ctypes.CFUNCTYPE(ctypes.c_uint16, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) def make(op, pre=""): # rcx = ST(0) m80, rdx = ST(1) m80, r8 = result m80; returns FNSTSW AX code = bytes.fromhex("db 2a db 29" + pre + op + "df e0 41 db 38 dd d8 c3") mem = k32.VirtualAlloc(None, 4096, 0x3000, 0x40) ctypes.memmove(mem, code, len(code)) return FN(mem) def run(f, a, b): buf = [ctypes.create_string_buffer(struct.pack("<QH", *v) + bytes(6), 16) for v in (a, b, (0, 0))] sw = f(*buf) return sw, struct.unpack("<QH", buf[2].raw[:10]) def value(v): e = v[1] & 0x7FFF return (-1) ** (v[1] >> 15) * Fraction(v[0]) * Fraction(2) ** ((e or 1) - 16383 - 63) J, rng = 1 << 63, random.Random(1) print("processor:", platform.processor()) for name, op in (("fprem", "d9 f8"), ("fprem1", "d9 f5")): f = make(op) flips = [d for d in range(56, 72) if (run(f, (J | rng.getrandbits(63), 16383 + d), (J | 5, 16383))[0] >> 10) & 1] print(name, "C2 set for exponent differences", flips[:3], "...") for d in (64, 65, 80, 95, 96, 127, 128, 200, 1000): fits, bits = set(range(32, 64)), set() for _ in range(50): a, b = (J | rng.getrandbits(63), 16383 + d), (J | rng.getrandbits(63), 16383) sw, r = run(f, a, b) bits.add((sw >> 8 & 1, sw >> 9 & 1, sw >> 10 & 1, sw >> 14 & 1)) fits = {n for n in fits if value(r) == value(a) - int(value(a) / (value(b) * 2 ** (d - n))) * value(b) * 2 ** (d - n)} print(f" D={d}: N fitting every sample {sorted(fits)}; (C0, C1, C2, C3) seen {sorted(bits)}") # Status bits after a NaN result, with C3 set (FTST of 0) or C0 set (FCOMP 1 > 0) or C2 and C1 (FXAM of -1) before. for label, pre in (("C3 before", "d9 ee d9 e4 dd d8"), ("C0 before", "d9 e8 d9 ee d8 d9 dd d8"), ("C1, C2 before", "d9 e8 d9 e0 d9 e5 dd d8")): g = make(op, pre) seen = {k: run(g, *ab)[0] for k, ab in (("inf/1", ((J, 0x7FFF), (J, 16383))), ("1/0", ((J, 16383), (0, 0))), ("qnan/1", ((J | J >> 1, 0x7FFF), (J, 16383))))} print(f" NaN result, {label}: " + ", ".join(f"{k} C0..C3={s >> 8 & 1}{s >> 9 & 1}{s >> 10 & 1}{s >> 14 & 1}" for k, s in seen.items())) ``` </details> Its output on the Ryzen 7 7700, for comparison: ```text processor: AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD fprem C2 set for exponent differences [64, 65, 66] ... D=64: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=65: N fitting every sample [33]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=80: N fitting every sample [48]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=95: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=96: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=127: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=128: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=200: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=1000: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] NaN result, C3 before: inf/1 C0..C3=0001, 1/0 C0..C3=0001, qnan/1 C0..C3=0001 NaN result, C0 before: inf/1 C0..C3=1000, 1/0 C0..C3=1000, qnan/1 C0..C3=1000 NaN result, C1, C2 before: inf/1 C0..C3=0000, 1/0 C0..C3=0000, qnan/1 C0..C3=0000 fprem1 C2 set for exponent differences [64, 65, 66] ... D=64: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=65: N fitting every sample [33]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=80: N fitting every sample [48]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=95: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=96: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=127: N fitting every sample [63]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=128: N fitting every sample [32]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=200: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] D=1000: N fitting every sample [40]; (C0, C1, C2, C3) seen [(0, 0, 1, 0)] NaN result, C3 before: inf/1 C0..C3=0001, 1/0 C0..C3=0001, qnan/1 C0..C3=0001 NaN result, C0 before: inf/1 C0..C3=1000, 1/0 C0..C3=1000, qnan/1 C0..C3=1000 NaN result, C1, C2 before: inf/1 C0..C3=0000, 1/0 C0..C3=0000, qnan/1 C0..C3=0000 ``` _AI-assisted (Claude Code)._
denn0x commented 2026-11-24 06:49:19 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-23T16:39:07Z.


Status. #893 (fprem and fprem1) has merged. #904 is open. It adds fninit and finit to the checked entry, the last item of the dynamic-control-word step: they load 0x037F, clear C0 to C3 and empty the stack, and the function must restore 0x027F before it returns.

Next, if it is in scope: fbstp and fbld. Neither appears in the plan above, so I'd like to check before opening it. The branch is written and passes locally.

  • fbstp m80, both profiles. Rounds ST(0) to an integer by the rounding control and stores 18 packed BCD digits with the sign of ST(0). A NaN, an infinity, an unsupported encoding or a rounded magnitude of 10^18 or more stores the packed BCD indefinite, as the SDM specifies for the masked invalid operation.
  • fbld m80, checked entry only. Loads the digits exactly, with the sign from bit 7 of byte 9. The SDM leaves the result undefined when a digit is above 9, so that case leaves with a new status 6 (bcddigit) instead of a guessed value. The fixed profile rejects fbld.
  • Test. cpu_aot_x87_bcd: 9 exports (3 in the fixed profile), about 22000 cases against an exact model, and nine mutated-translation controls. Native fbld with a digit above 9 would be recorded only as a hardware observation.
  • Rejection tests. fbstp currently stands for "outside the profile" in cpu_aot_x87_moves and cpu_aot_x87_integers. Those cases would use fnstenv and fnsave instead, which stay outside it.

Is this OK as the next PR after #904, or would you rather keep BCD out of the profile?

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7107464175 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7107464175). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-23T16:39:07Z. --- **Status.** #893 (`fprem` and `fprem1`) has merged. #904 is open. It adds `fninit` and `finit` to the checked entry, the last item of the dynamic-control-word step: they load `0x037F`, clear C0 to C3 and empty the stack, and the function must restore `0x027F` before it returns. **Next, if it is in scope: `fbstp` and `fbld`.** Neither appears in the plan above, so I'd like to check before opening it. The branch is written and passes locally. - **`fbstp m80`, both profiles.** Rounds ST(0) to an integer by the rounding control and stores 18 packed BCD digits with the sign of ST(0). A NaN, an infinity, an unsupported encoding or a rounded magnitude of 10^18 or more stores the packed BCD indefinite, as the SDM specifies for the masked invalid operation. - **`fbld m80`, checked entry only.** Loads the digits exactly, with the sign from bit 7 of byte 9. The SDM leaves the result undefined when a digit is above 9, so that case leaves with a new status 6 (`bcddigit`) instead of a guessed value. The fixed profile rejects `fbld`. - **Test.** `cpu_aot_x87_bcd`: 9 exports (3 in the fixed profile), about 22000 cases against an exact model, and nine mutated-translation controls. Native `fbld` with a digit above 9 would be recorded only as a hardware observation. - **Rejection tests.** `fbstp` currently stands for "outside the profile" in `cpu_aot_x87_moves` and `cpu_aot_x87_integers`. Those cases would use `fnstenv` and `fnsave` instead, which stay outside it. Is this OK as the next PR after #904, or would you rather keep BCD out of the profile? _AI-assisted (Claude Code)._
R0Y00 commented 2026-11-24 06:49:20 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-23T16:51:12Z.


The BCD pair fits as one focused follow-up after #904. Keep FBSTP output and guards byte-exact, including signed zero, rounding boundaries, the 18-digit limit and the masked-invalid encoding. For checked FBLD, reject an invalid digit through the existing status channel before storing a result; name and document the added status without changing existing codes. Record native observations for invalid input separately. Confirm the fixed entry still rejects FBLD and the replacement environment-op rejection tests still run in both Windows configurations.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7107771531 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7107771531). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-23T16:51:12Z. --- The BCD pair fits as one focused follow-up after #904. Keep FBSTP output and guards byte-exact, including signed zero, rounding boundaries, the 18-digit limit and the masked-invalid encoding. For checked FBLD, reject an invalid digit through the existing status channel before storing a result; name and document the added status without changing existing codes. Record native observations for invalid input separately. Confirm the fixed entry still rejects FBLD and the replacement environment-op rejection tests still run in both Windows configurations.
denn0x commented 2026-11-24 06:49:22 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by denn0x on 2026-11-23T17:11:14Z.


Status. #904 merged, and #916 (fbstp/fbld) is open as the follow-up agreed above. After #916, the x87 forms in docs/coverage/x64_zen2.tsv that the profile still rejects fall into four groups:

  • Excluded by design. The transcendentals: f2xm1, fsin, fcos, fsincos, fptan, fpatan, fyl2x, fyl2xp1.
  • Need a TOP and tag-word model the static-depth profile doesn't have. ffree, ffreep, fincstp, fdecstp, and the environment and state forms fnstenv, fldenv, fnsave, frstor, plus their wait forms. Several rejection tests also rely on them staying outside the profile. I don't plan to take these without a design discussion.
  • Alias. fstpnce (D9 D8+i), the undocumented alias of fstp st(i), which is rejected deliberately.
  • Legacy no-ops. fneni, fndisi and fnsetpm (DB E0, DB E1, DB E4), and their wait forms feni, fdisi and fsetpm.

The last group is the only one that fits the current profile. I measured it natively on the Ryzen 7 7700 (AMD64 Family 25 Model 97 Stepping 2). The method was an fnstenv snapshot, then fldenv of the same bytes, the instruction, and a second fnstenv:

State before CW SW TW Effect of each of the six forms
fcom less 0x027F 0x3100 0x1FFF unchanged
fcom equal 0x027F 0x7000 0x0FFF unchanged
fxam of -1 (C1 set) 0x027F 0x3600 0x0FFF unchanged
loaded CW 0x0C7F 0x0C7F 0x7000 0x0FFF unchanged

That is the same as fnop in every row. The proposal would accept the three as no-ops in both profiles and treat them like fnop for the condition codes. The current SDM does not document these encodings; older x87 references describe them as no-ops after the 80287. The wait forms would then follow from wait already being accepted. There would be a small differential fixture with a "mutate into fninit" control.

These are coverage-only: compilers do not emit them. If you'd rather close the x87 series after #916, I'll leave them out.

AI-assisted (Claude Code).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7108280452 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7108280452). Originally posted by [denn0x](https://github.com/denn0x) on 2026-11-23T17:11:14Z. --- **Status.** #904 merged, and #916 (`fbstp`/`fbld`) is open as the follow-up agreed above. After #916, the x87 forms in `docs/coverage/x64_zen2.tsv` that the profile still rejects fall into four groups: - **Excluded by design.** The transcendentals: `f2xm1`, `fsin`, `fcos`, `fsincos`, `fptan`, `fpatan`, `fyl2x`, `fyl2xp1`. - **Need a TOP and tag-word model the static-depth profile doesn't have.** `ffree`, `ffreep`, `fincstp`, `fdecstp`, and the environment and state forms `fnstenv`, `fldenv`, `fnsave`, `frstor`, plus their wait forms. Several rejection tests also rely on them staying outside the profile. I don't plan to take these without a design discussion. - **Alias.** `fstpnce` (D9 D8+i), the undocumented alias of `fstp st(i)`, which is rejected deliberately. - **Legacy no-ops.** `fneni`, `fndisi` and `fnsetpm` (DB E0, DB E1, DB E4), and their wait forms `feni`, `fdisi` and `fsetpm`. The last group is the only one that fits the current profile. I measured it natively on the Ryzen 7 7700 (`AMD64 Family 25 Model 97 Stepping 2`). The method was an `fnstenv` snapshot, then `fldenv` of the same bytes, the instruction, and a second `fnstenv`: | State before | CW | SW | TW | Effect of each of the six forms | | --- | --- | --- | --- | --- | | `fcom` less | `0x027F` | `0x3100` | `0x1FFF` | unchanged | | `fcom` equal | `0x027F` | `0x7000` | `0x0FFF` | unchanged | | `fxam` of -1 (C1 set) | `0x027F` | `0x3600` | `0x0FFF` | unchanged | | loaded CW `0x0C7F` | `0x0C7F` | `0x7000` | `0x0FFF` | unchanged | That is the same as `fnop` in every row. The proposal would accept the three as no-ops in both profiles and treat them like `fnop` for the condition codes. The current SDM does not document these encodings; older x87 references describe them as no-ops after the 80287. The wait forms would then follow from `wait` already being accepted. There would be a small differential fixture with a "mutate into `fninit`" control. These are coverage-only: compilers do not emit them. If you'd rather close the x87 series after #916, I'll leave them out. _AI-assisted (Claude Code)._
tedin7 commented 2026-11-24 06:50:14 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T03:23:22Z.


Claiming one more step of the status-word work: FNSTSW m16 (and FSTSW m16, which decodes as WAIT and FNSTSW m16) in tools/x87_lower.py, with its checks in tests/cpu/x87_fldcw.py and a paragraph in docs/experiments.md.

  • Form. fnstsw word ptr [mem] (DD /7). Memory cannot carry "unknown" bits, so the store is accepted only where the status-word dataflow knows all 16 bits (C0 to C3, the exception flags, SF, ES and B; TOP is the static depth). Today that is straight after fninit in the checked entry (every bit 0). Anywhere else it is rejected with the unknown bits named, and the fixed profile rejects it.
  • Not in scope. No exception-flag emulation, no new status codes, fnstsw ax behaves as before.
  • Environment. Linux x86-64: llvm-ml-19, lld-link-19, MinGW and Wine for the native-versus-translated comparison. I have no Windows/MSVC machine, so the MSVC and ML64 run is left to CI and I will say so in the PR.

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7121041900 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/406#issuecomment-7121041900). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T03:23:22Z. --- Claiming one more step of the status-word work: `FNSTSW m16` (and `FSTSW m16`, which decodes as WAIT and FNSTSW m16) in `tools/x87_lower.py`, with its checks in `tests/cpu/x87_fldcw.py` and a paragraph in `docs/experiments.md`. - **Form.** `fnstsw word ptr [mem]` (DD /7). Memory cannot carry "unknown" bits, so the store is accepted only where the status-word dataflow knows all 16 bits (C0 to C3, the exception flags, SF, ES and B; TOP is the static depth). Today that is straight after `fninit` in the checked entry (every bit 0). Anywhere else it is rejected with the unknown bits named, and the fixed profile rejects it. - **Not in scope.** No exception-flag emulation, no new status codes, `fnstsw ax` behaves as before. - **Environment.** Linux x86-64: `llvm-ml-19`, `lld-link-19`, MinGW and Wine for the native-versus-translated comparison. I have no Windows/MSVC machine, so the MSVC and ML64 run is left to CI and I will say so in the PR. _AI-assisted._
Sign in to join this conversation.
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#400
No description provided.