Skip to content

Compute paired FMA lanes in double on CPUs without FMA3 - #426

Open
patchzyy wants to merge 4 commits into
mainfrom
fix/v2-paired-fma-without-fma3
Open

patchzyy wants to merge 4 commits into
mainfrom
fix/v2-paired-fma-without-fma3

Conversation

@patchzyy

@patchzyy patchzyy commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Refs #374. This doesn't close it: I couldn't run the game on a CPU without FMA3, so I haven't confirmed this removes the whole 3.5 fps.

What

On x86-64-v2 builds, every ps_madd/ps_msub/ps_nmadd/ps_nmsub lane goes through std::fma(float). That's a CRT fmaf call, and on a CPU without FMA3 the CRT does it in software. The reporter in #374 has an i5-2500 (no FMA3), so Setup gives them the v2 build.

PpcFusedMultiplyAddFloatViaDoubleInline gets the same result in double instead. A float product is exact in double, so only the add rounds before the conversion to float. That double rounding only differs from the fused rounding when the double sum lands exactly on a float halfway point. Those sums go back to std::fma, along with:

  • results at or below FLT_MIN (the subnormal halfway point is at a different bit)
  • infinite and NaN operands (in double, 0*Inf or an sNaN conversion raises FE_INVALID, which fmaf(0, Inf, qNaN) doesn't)
  • subnormal operands (under DAZ the CRT's software fmaf doesn't zero them the way the double conversion does)

CPUs with FMA3 but not the rest of v3 (e.g. Piledriver) still get v2, so __builtin_cpu_supports("fma") keeps them on the CRT call, which uses the hardware instruction there. On glibc, FMA4 with AVX (first-gen Bulldozer) also keeps the call, since glibc dispatches fmaf to FMA4.

On v3, ps_msub/ps_nmsub now emit vfmsub213ps directly. Clang lowers _mm_fmsub_ps to an FMA with a negated addend, and with a constant NaN subtractor it folds that into vfmadd (or folds the whole result), which flips the NaN's sign.

The v2 lane path also stops negating a NaN subtractor before the FMA. ps_msub/ps_nmsub on v3 (vfmsub), the NEON path and Gekko return that NaN with its sign intact, but v2 flipped it.

Numbers

Measured on this machine with the shipped llvm-mingw, -march=x86-64-v2 -fno-fast-math -ffp-contract=off. _set_FMA3_enable(0) forces the CRT software path:

per ps_madd, 4096 independent lanes CRT fmaf via double
CRT FMA3 path 3.7 ns 4.5 ns (not used: dispatch keeps the CRT call)
CRT software path (no-FMA3 CPU) 52 ns 4.5 ns

__THPInverseDCTY8's loop body has 24 paired madd-family ops (48 lanes) and runs once per row-pair, per 8x8 block. That's why the menus with video previews are where this shows up. Issue #56 already shows those screens dropping to 30-40 fps on an FMA3 CPU.

Tests

mkw_ppc_pair_fma_{v2,v3}_tests now compare both the dispatched helper and the double path directly against std::fma, bit for bit:

  • a constructed halfway double-rounding case, normal and subnormal

  • a 16x16x16 edge-value grid

  • 2M random triples, half of them raw bit patterns

  • ps_madds0/ps_madds1 lane selection, signed zeros, and quiet and signaling NaNs in the paired ops

  • ps_msub/ps_nmsub on operands loaded at run time: result bits, FE_INVALID (clear for a quiet NaN subtractor, set for a signaling one) and a*c - b operand order

  • FE_INVALID parity with std::fma for invalid and NaN inputs (operands come from volatiles and the result goes to one, so Clang can't move the call past the flag checks)

Each runs with FTZ/DAZ off and on, and in the Windows v2 build also against the CRT's software fmaf (that pass skips signaling-NaN subtractors, since that fmaf returns them unquieted without FE_INVALID). Removing any one of the fallbacks, or the NaN-subtractor fix, makes the test fail. The header also compiles for the glibc branch (-D__GLIBC__=2, with and without -mfma4). Full platform suite: 28/28 pass.

The real THP shard compiles against this header for v2 and v3. In the v2 IDCT the lanes inline to cvtsd2ss, with fmaf left only on the fallback edges.

Not covered: scalar fmadd/fmadds also use CRT double fma on v2, which costs about 50 ns in software against 2 ns. Fixing that needs double-double arithmetic, so it's left for a separate change.

Summary by CodeRabbit

  • Bug Fixes
    • Improved the consistency of PowerPC single-precision fused multiply-add results across supported processor configurations.
    • Corrected edge-case handling for subnormal values, rounding boundaries, and exceptional results, including when flush-to-zero modes are enabled.
    • Improved paired single-precision multiply-add and multiply-subtract behavior for signed zero and NaN values, while retaining existing non-IEEE flushing behavior.
    • Improved handling of fused operations in cases involving cancellation and halfway rounding.

x86-64-v2 builds lower every ps_madd/msub/nmadd/nmsub lane to std::fma(float),
a CRT call. On a CPU without FMA3 the CRT does that in software: about 52 ns per
ps_madd here against 4.5 ns for the same result computed in double. THP decoding
runs dozens of these per 8x8 block, so menus with video previews suffer most.

The double path is bit-identical to std::fma. It hands halfway sums, results at
or below FLT_MIN, non-finite results and subnormal operands back to std::fma.
CPUs that have FMA3 but still get the v2 build keep the CRT call, which reaches
the hardware instruction there.
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds float FMA helpers and runtime dispatch, routes paired-single lane operations through the dispatch, and adjusts x86-64 FMA subtract handling. Tests compare scalar and paired results with std::fma across rounding cases, exceptional values, randomized inputs, and runtime modes.

Changes: Float FMA

Layer / File(s) Summary
FMA implementation and paired-lane dispatch
runtime/include/isa/ppc_isa_float.h
Adds a double-based float FMA helper and dispatch based on x86-64 runtime FMA support. Paired-single lane helpers use the dispatch and preserve NaN signs for subtract forms. The x86-64 FMA subtract path uses vfmsub213ps inline assembly.
FMA accuracy and runtime-mode tests
runtime/tests/ppc_pair_fma_tests.cpp
Adds paired and scalar result and exception checks. Tests cover halfway rounding, exceptional values, deterministic randomized inputs, FTZ/DAZ modes, and Windows x86-64 FMA3 dispatch settings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Possibly related issues

Suggested reviewers: darthmdev, theofficialgman

Merge Risk: Minimal · up to f7a0b

This change speeds up paired fused multiply-add operations on x86-64-v2 CPUs without FMA3 while keeping results bit-identical to std::fma. I found no concrete correctness or stability risk, and the new tests cover the numerical and mode edge cases. Real-hardware performance on such CPUs is not confirmed, but that does not block merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title states the main change: paired FMA lanes are now computed in double precision on CPUs without FMA3. The raw summary confirms this: the new helper uses a double-precision path for normal or z…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title states the main change: paired FMA lanes are now computed in double precision on CPUs without FMA3. The raw summary confirms this: the new helper uses a double-precision path for normal or zero operands, and falls back to std::fma otherwise. The objectives match this scope. The title is concise, specific, and does not list files.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c7ff58c4-3c0e-4744-ac58-7cb91ab6edcd
Commits

Reviewing files that changed from the base of the PR and between 766f298 and f7a0ba3.

Files selected for processing: 2

  • runtime/include/isa/ppc_isa_float.h
  • runtime/tests/ppc_pair_fma_tests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

Non-finite operands now go straight to std::fma. Evaluating 0*Inf or converting
an sNaN in double raised FE_INVALID where fmaf(0, Inf, qNaN) does not.

On glibc, a CPU with FMA4 and AVX keeps the fmaf call, because glibc already
dispatches it to the FMA4 instruction (first-gen Bulldozer).

A NaN subtractor is no longer negated before the lane fma. x86 vfmsub on the v3
path, the NEON path and Gekko return it with its sign intact; v2 flipped it.

The tests also cover ps_madds0/ps_madds1, signed zeros, quiet and signaling
NaNs, and FE_INVALID parity. That check reads its operands from volatiles and
stores the result to one, so Clang cannot move the call past the flag calls.
Clang lowers _mm_fmsub_ps to an fma with a negated addend. With a constant NaN
subtractor it folds the negation into the constant and emits vfmadd, or folds
the whole result, flipping the NaN sign that vfmsub keeps. The Linux and Intel
macOS host jobs failed mkw_ppc_pair_fma_v3_tests on exactly that.

The tests now also run ps_msub/ps_nmsub on operands loaded at run time. They
check the result bits and FE_INVALID (clear for a quiet NaN subtractor, set for
a signaling one) and the a*c - b operand order. The CRT software fmaf pass only
runs where std::fma is actually a CRT call, and it skips the signaling cases,
because that fmaf returns sNaNs unquieted and raises nothing.
Plain asm let the compiler merge two identical ps_msub calls across an MXCSR
write, so a result computed before DAZ came on was reused after it. It could
also drop an unused vfmsub along with its FE_INVALID. The asm is now volatile
with a memory clobber; the real THP IDCT functions keep the same instruction
count. A new test runs the same ps_msub on both sides of MkwApplyHostNiMode and
expects FLT_MIN then 0. It covers only the asm path: v2 lanes are ordinary
std::fma, which the compiler may move across MXCSR writes like every other FP
operation in translated code.

The Windows v2 test assumed the CRT starts with FMA3 enabled. On a CPU without
FMA3 it starts in software mode, and the default pass then expected hardware
sNaN handling. The test now reads _get_FMA3_enable() and only forces the
software pass when the CRT started with FMA3, restoring the initial state after.
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.

1 participant