Skip to content

cpu:lower baseline 128-bit SSE packed single-precision arithmetic instructions - #575

Closed
stan495 wants to merge 1 commit into
R0Y00:mainfrom
stan495:cpu/sse-float-arith
Closed

stan495 wants to merge 1 commit into
R0Y00:mainfrom
stan495:cpu/sse-float-arith

Conversation

@stan495

@stan495 stan495 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Change

This change lowers the baseline 128-bit legacy SSE packed single-precision floating-point arithmetic instructions (addps, subps, mulps, divps) in tools/ffx_version_query.py. It maps each operation across all four 32-bit float lanes while preserving the upper 128 bits of the destination YMM register.

This advances x64 Zen 2 instruction-form coverage by adding 4 previously uncovered forms to the SSE group in docs/coverage/dashboard.svg.

Verification

Tested on Windows 11 x64 with an AMD Ryzen 7 7800X3D (Zen 4) CPU and MSVC 19.44 / CMake 3.31 at commit 9386d7a.

  1. Built the native fixture and lifted target:
cmake --build --preset dev --target cpu_sse_float_arith_lifted

Result: Succeeded without diagnostics.

  1. Ran the differential check:
ctest --preset dev --no-tests=error -R '^cpu_aot_sse_float_arith$' -V

Result:

142: 35 baseline 128-bit SSE packed single-precision arithmetic cases matched native and translated DLLs
1/1 Test #142: cpu_aot_sse_float_arith ..........   Passed    0.14 sec
100% tests passed, 0 tests failed out of 1
  1. Verified repository static checks:
.\out\pe-env\Scripts\python.exe tests/form_coverage_check.py
.\out\pe-env\Scripts\python.exe tests/dependency_paths_check.py
.\out\pe-env\Scripts\python.exe tests/docs_links_check.py

Result: All passed (Checked 10 Markdown files and 119 links. Self-test passed.).

Evidence and follow-up

tests/cpu/sse_float_arith.asm is a new source-built synthetic MASM fixture submitted under the MIT License. It defines 7 exports exercising:

  • Dual-register binary arithmetic: addps, subps, mulps, divps
  • Self-aliased register variants: addps xmm0, xmm0 (doubling), subps xmm0, xmm0 (zeroing idiom), and mulps xmm0, xmm0 (squaring)

The test vectors evaluate 5 input sets including positive/negative normals, signed zeros (+0.0 / -0.0), extreme magnitudes, and infinities (inf / -inf).

Negative control: check_rejections() asserts that EVEX encodings (vaddps, vsubps, vmulps, vdivps) and legacy XMM memory forms without an alignment contract are explicitly rejected with ValueError.

Reproduction notes and build commands are documented in docs/experiments.md. Follow-up PRs can lower the remaining SSE packed single-precision forms: bitwise logic (andps, andnps, orps, xorps) and comparisons/approximations (minps, maxps, sqrtps, rsqrtps, rcpps).

This change was AI-assisted.

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.

@stan495 stan495 changed the title lower baseline 128-bit SSE packed single-precision arithmetic instructions cpu:lower baseline 128-bit SSE packed single-precision arithmetic instructions Nov 22, 2026
@stan495
stan495 force-pushed the cpu/sse-float-arith branch from 9386d7a to 7bac921 Compare November 22, 2026 13:31

R0Y00 commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Please keep the native 16-byte output contract and establish this profile's MXCSR at entry: exceptions masked, nearest-even rounding, DAZ and FTZ off (control bits matching 0x1f80, with existing sticky bits allowed). Keep the register-only scope and leave code that reads or exports exception status to a separate change. Compare all four lanes as raw words against native SSE under normal and /O2 Windows builds. Use both operand orders and single and double qNaN/sNaN cases with distinct signs and payloads. Matching Windows intrinsics are a good candidate if they pass those comparisons.

@stan495
stan495 force-pushed the cpu/sse-float-arith branch from 7bac921 to 74c2023 Compare November 22, 2026 14:58
@stan495

stan495 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Updated and rebased onto upstream/main (f8d11ad):

  1. Profile MXCSR & Scope:

    • Enforced MXCSR profile contract at function entry via _mm_setcsr((_mm_getcsr() & 0x3fu) | 0x1f80u): exceptions masked, nearest-even rounding, DAZ and FTZ off (control mask 0xffc0 matches 0x1f80, while preserving caller sticky bits in bits 0-5).
    • Preserved the 16-byte native output contract and register-only scope without exporting exception status flags.
  2. NaN Propagation & MSVC /O2 Commutativity:

    • Tested matching Windows intrinsics under MSVC /O2; compiler optimizations reorder the commutative intrinsics (_mm_add_ps / _mm_mul_ps), swapping destination/source registers and failing double-NaN comparisons by returning the source payload instead of the destination payload.
    • Handled via lane helper sse_arith_f32 in tools/ffx_version_query.py following the architectural x86 SSE NaN selection rules (matching tools/cpu_sse_aot.py): destination quieted NaN on destination NaN, otherwise source quieted NaN, and default signed NaN (0xffc00000) on invalid operations.
  3. Expanded Test Matrix:

    • Compares all four lanes as raw 32-bit hex words against the native DLL.
    • Exercises both operand orders (va, vb) and (vb, va) for all binary arithmetic operations.
    • Covers single and double qNaN/sNaN cases with distinct signs and payloads (packed without float conversion), tested under both clean MXCSR and with existing sticky bits allowed (0x1fbf).
    • Verified 504 test cases passing bit-for-bit under both normal (dev preset) and /O2 (release preset) Windows builds.

@stan495
stan495 force-pushed the cpu/sse-float-arith branch from 74c2023 to ff84027 Compare November 22, 2026 16:30

@MarlomMedeiros MarlomMedeiros left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent run on AMD Ryzen 7 5800X3D, Windows 11 build 26300.10075, MSVC 14.52.37025, SDK 10.0.26100.0, on ff84027:

ctest --preset dev --no-tests=error -R '^cpu_aot_sse_float_arith$' -V
# 504 baseline 128-bit SSE packed single-precision arithmetic cases matched native and translated DLLs — Passed

Second AMD datapoint (author used a 7600): both confirm the destination-NaN-wins selection, which also matches the architected rule in SDM Vol.1 Table 4-7 for non-MIN/MAX SSE arithmetic, so the pinned a | quiet order is the right model, and if silicon ever deviated the differential would fail loudly as designed.

Semantic review of sse_arith_f32: every branch checks out. x != x correctly isolates NaN inputs before the generated-NaN override, a|quiet/b|quiet quiet sNaNs preserving sign+payload, subps does not negate a source NaN, and 0xffc00000 is exactly the SP QNaN indefinite hardware produces for masked invalid ops. Denormals run on host SSE under the same forced MXCSR as native, DAZ/FTZ off. The VEX/EVEX/memory rejection paths behave as the test asserts (distinct iced mnemonics fall to the generic reject; addps xmm,[mem] raises the expected diagnostic). divps_self_op being absent looks deliberate (x/x is uninformative) but is worth noting below.

Three findings, none blocking:

  1. The lifted-side _mm_setcsr is unverifiable by this test. tools/ffx_version_query.py emits _mm_setcsr(...) at function entry, but check() sets the same MXCSR on the thread before every round via lifted.set_mxcsr, so deleting the emitted line would still pass the whole suite. If "establishing the profile's MXCSR at entry" is a claimed guarantee, consider a case that pre-sets a non-profile MXCSR (e.g. FTZ on) immediately before a lifted call and reads it back after, which would exercise the emitted line directly.

  2. _mm_setcsr mutates the caller thread's FP environment permanently (clears DAZ/FTZ, forces round-nearest, preserves sticky bits) with no restore. Native leaves it alone. For this fixture that's masked by the test's own set/restore, but lower() is also used by generate() for real images, so a lifted function containing these ops silently reprograms host FP state for the remainder of its run. Probably intended (the guest profile is the contract) but worth an explicit sentence in the docs.

  3. Coverage asymmetries: divps_self_op is missing (the one self-op that exercises 0/0 and inf/inf invalid paths), every export writes xmm0 so wide1/wide2 destination paths are emitted but never executed, and only 16 output bytes are observable, so upper-wideN corruption would be invisible. Also x != x depends on /fp:precise (fine under the presets today, would break under /fp:fast).

Integration note: the base (2f1f832) predates sse2_shift_pack_ops, fma_packed, and avx2_perm_ops in the same has_wide chain, plus new lowering arms and the CMakeLists.txt/experiments.md anchors this PR touches, so a rebase will conflict in all three files; resolutions look mechanical. It also lands adjacent to #602's sse34_fp_ops in the same regions, so whichever merges second will need the same trivial union.

AI-assisted: yes. All reported checks ran locally on the hardware listed.

@stan495
stan495 force-pushed the cpu/sse-float-arith branch from ff84027 to a0b3769 Compare November 23, 2026 00:59
@stan495

stan495 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @MarlomMedeiros for the detailed independent review, hardware verification, and helpful findings!

I have addressed all the feedback and rebased the branch onto current upstream/main (67edabe):

  1. Lifted _mm_setcsr Verification (Finding 1):

    • Added a dedicated test step in tests/cpu/sse_float_arith.py that pre-sets a non-profile MXCSR state (0x9fa5, FTZ bit 15 set, caller sticky bits 0x25 in bits 0-5) immediately prior to invoking the lifted function.
    • Asserts that upon entry, the emitted _mm_setcsr restores control bits 6-15 to profile contract 0x1f80 (FTZ/DAZ cleared, exceptions masked) while strictly preserving caller sticky bits. Confirmed that removing the emitted line fails this assertion.
  2. Caller FP Environment Mutation Contract (Finding 2):

    • Added an explicit note in docs/experiments.md documenting that the emitted _mm_setcsr establishes the guest profile on the calling thread without restoring previous host MXCSR control bits, treating the guest FP profile as the persistent execution contract for lifted functions containing packed SSE arithmetic.
  3. Coverage Asymmetries & /fp:precise Independence (Finding 3):

    • divps_self_op: Added to MASM fixture and test harness, validating self-division across normals as well as 0/0 and inf/inf invalid operations producing indefinite QNaN 0xffc00000.
    • Destination Register Coverage: Added addps_xmm1_dst_op and addps_xmm2_dst_op to exercise and verify wide1 and wide2 destination lowering paths against native execution.
    • Bit-exact NaN Detection: Replaced floating-point comparisons (x != x) in sse_arith_f32 with bitwise helper is_nan_f32(u) ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu) != 0), eliminating dependency on /fp:precise.
    • Expanded Matrix: Test comparisons now cover 560 cases matching bit-for-bit between native and lifted DLLs across both normal (dev) and /O2 (release) presets.
  4. Rebase & Integration:

@stan495
stan495 force-pushed the cpu/sse-float-arith branch from a0b3769 to c3e7568 Compare November 23, 2026 01:13
@stan495

stan495 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Closing this PR as the lowering for ADDPS, SUBPS, MULPS, and DIVPS (along with the broader packed float instruction set) has been addressed and merged in #725. Thank you @R0Y00 and @MarlomMedeiros for the detailed reviews, guidance, and hardware verification!

@stan495 stan495 closed this Nov 23, 2026
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.

3 participants