From 65bfc2d7c8a46d07c14e045bcb21e0494d466615 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:30:12 +0100 Subject: [PATCH 1/5] compute paired fma lanes in double on cpus without fma3 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. --- runtime/include/isa/ppc_isa_float.h | 49 +++++- runtime/tests/ppc_pair_fma_tests.cpp | 227 +++++++++++++++++++++++++-- 2 files changed, 261 insertions(+), 15 deletions(-) diff --git a/runtime/include/isa/ppc_isa_float.h b/runtime/include/isa/ppc_isa_float.h index c01377145..2ee11e7a6 100644 --- a/runtime/include/isa/ppc_isa_float.h +++ b/runtime/include/isa/ppc_isa_float.h @@ -431,6 +431,51 @@ inline double PpcPackIntegerWordInline(int32_t value) static_cast(static_cast(value))); } +// std::fma(a, c, b) for floats, computed without an FMA instruction and bit-identical to it. +// +// A float product is exact in double, so a*c+b computed in double rounds once before the +// conversion to float (a contracted double FMA gives the same sum). That double rounding equals +// the single fused rounding unless the double sum lands exactly on a float halfway point, and the +// halfway check below only knows where that point sits for normal floats. Halfway sums, results +// at or below FLT_MIN and non-finite results therefore go to std::fma. So do subnormal operands: +// under DAZ the conversion zeroes them, and the CRT's software fmaf does not treat them that way. +inline float PpcFusedMultiplyAddFloatViaDoubleInline(float a, float c, float b) +{ + const auto isSubnormal = [](float value) { + return (PpcBitCastToU32Inline(value) & 0x7FFFFFFFu) - 1u < 0x007FFFFFu; + }; + if (!isSubnormal(a) && !isSubnormal(c) && !isSubnormal(b)) [[likely]] { + const double sum = + static_cast(a) * static_cast(c) + static_cast(b); + const uint64_t bits = PpcBitCastToU64Inline(sum); + const uint64_t magnitude = bits & 0x7FFFFFFFFFFFFFFFULL; + constexpr uint64_t kFloatMinNormal = 0x3810000000000000ULL; + constexpr uint64_t kInfinity = 0x7FF0000000000000ULL; + // The 29 low bits double keeps below a normal float's last bit, and a float halfway point. + constexpr uint64_t kBelowFloatLsbMask = 0x1FFFFFFFULL; + constexpr uint64_t kFloatHalfway = 0x10000000ULL; + const bool normalOrZero = + magnitude == 0 || (magnitude > kFloatMinNormal && magnitude < kInfinity); + if (normalOrZero && (bits & kBelowFloatLsbMask) != kFloatHalfway) [[likely]] + return static_cast(sum); + } + return std::fma(a, c, b); +} + +// x86-64-v2 has no FMA instruction, so std::fma(float) is a CRT call there. On a CPU without FMA3 +// the CRT computes it in software at roughly 12x the cost of the hardware instruction, and the +// paired madd family makes two calls per instruction, which slows THP video decoding several +// times over on those CPUs. A v2 build also runs on CPUs that have FMA3 but not the rest of v3 +// (AMD Piledriver, for one), where the CRT reaches the hardware instruction and stays cheaper. +inline float PpcFusedMultiplyAddFloatInline(float a, float c, float b) +{ +#if defined(__x86_64__) && !defined(__FMA__) + if (!__builtin_cpu_supports("fma")) + return PpcFusedMultiplyAddFloatViaDoubleInline(a, c, b); +#endif + return std::fma(a, c, b); +} + template inline float PpcAccuratePsMaddLaneInline(float a, float c, float b) { @@ -439,14 +484,14 @@ inline float PpcAccuratePsMaddLaneInline(float a, float c, float b) // explicit float FMA therefore matches Gekko's single rounding point; // multiplying and adding separately can differ by an ULP on ordinary // vector and matrix workloads. - return PpcFlushSingleForNiInline(std::fma(a, c, signedB)); + return PpcFlushSingleForNiInline(PpcFusedMultiplyAddFloatInline(a, c, signedB)); } template inline float PpcAccuratePsMaddLaneNoNiInline(float a, float c, float b) { const float signedB = Subtract ? -b : b; - return std::fma(a, c, signedB); + return PpcFusedMultiplyAddFloatInline(a, c, signedB); } template diff --git a/runtime/tests/ppc_pair_fma_tests.cpp b/runtime/tests/ppc_pair_fma_tests.cpp index 7d7720256..ec5396b44 100644 --- a/runtime/tests/ppc_pair_fma_tests.cpp +++ b/runtime/tests/ppc_pair_fma_tests.cpp @@ -1,8 +1,15 @@ #include "isa/ppc_isa_float.h" +#include #include #include #include +#include +#include + +#if defined(__x86_64__) +#include +#endif namespace { @@ -37,22 +44,216 @@ bool CheckNegatedPair(double actual, float a0, float a1, float c0, float c1, flo return false; } -} // namespace +bool CheckPairedFamily(float a0, float a1, float c0, float c1, float b0, float b1) +{ + const double a = PpcPackPairedInline(a0, a1); + const double c = PpcPackPairedInline(c0, c1); + const double b = PpcPackPairedInline(b0, b1); -int main() + bool ok = true; + ok &= CheckPair(PPC_PsMaddNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, false, "ps_madd"); + ok &= CheckPair(PPC_PsMsubNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, true, "ps_msub"); + ok &= CheckNegatedPair(PPC_PsNmaddInline(a, c, b), a0, a1, c0, c1, b0, b1, false, "ps_nmadd"); + ok &= CheckNegatedPair(PPC_PsNmsubNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, true, + "ps_nmsub"); + return ok; +} + +bool CheckFmaResult(float actual, float expected, float a, float c, float b, const char* path, + const char* context) +{ + if (PpcBitCastToU32Inline(actual) == PpcBitCastToU32Inline(expected)) { + return true; + } + std::fprintf(stderr, + "%s %s: fma(%a, %a, %a) = %a (0x%08x), expected %a (0x%08x)\n", context, path, + static_cast(a), static_cast(c), static_cast(b), + static_cast(actual), PpcBitCastToU32Inline(actual), + static_cast(expected), PpcBitCastToU32Inline(expected)); + return false; +} + +// The double-based path is what a CPU without FMA3 takes; check it directly so hosts that have +// FMA3 (and dispatch to std::fma) still cover it. +bool CheckScalarFma(float a, float c, float b, const char* context) +{ + const float expected = std::fma(a, c, b); + bool ok = CheckFmaResult(PpcFusedMultiplyAddFloatViaDoubleInline(a, c, b), expected, a, c, b, + "via double", context); + ok &= CheckFmaResult(PpcFusedMultiplyAddFloatInline(a, c, b), expected, a, c, b, "dispatched", + context); + return ok; +} + +// a*c = 2^6 - 2^-40 sits just below the float halfway point between b and the next float, so the +// fused result is b. Rounded to double first, the sum lands exactly on that halfway point and +// ties-to-even then picks the next float, which is what a plain double evaluation returns. +bool CheckHalfwayDoubleRounding() +{ + const float a = 1.0f + std::ldexp(1.0f, -23); + const float c = 64.0f * (1.0f - std::ldexp(1.0f, -23)); + const float b = std::ldexp(1.0f, 30) + std::ldexp(1.0f, 7); + + const float fused = std::fma(a, c, b); + const float viaDouble = + static_cast(static_cast(a) * static_cast(c) + static_cast(b)); + if (fused != b || viaDouble == fused) { + std::fprintf(stderr, "halfway case no longer exercises double rounding\n"); + return false; + } + + bool ok = CheckScalarFma(a, c, b, "halfway double rounding"); + ok &= CheckScalarFma(-a, c, -b, "halfway double rounding (negated)"); + ok &= CheckPairedFamily(a, -a, c, c, b, -b); + return ok; +} + +// FLT_MIN - 3*2^-150 + 3*2^-190 lies just above the halfway point between the subnormals +// 0x007FFFFE and 0x007FFFFF. Double rounding drops the 2^-190 term, lands on that halfway point +// and ties to the even 0x007FFFFE. The normal-float halfway check cannot see this: the subnormal +// halfway bit sits one position higher in the double. +bool CheckSubnormalHalfwayDoubleRounding() +{ + const float a = -std::ldexp(3.0f + std::ldexp(3.0f, -20), -75); + const float c = std::ldexp(1.0f - std::ldexp(1.0f, -20), -75); + const float b = std::numeric_limits::min(); + + const float fused = std::fma(a, c, b); + const float viaDouble = + static_cast(static_cast(a) * static_cast(c) + static_cast(b)); + if (PpcBitCastToU32Inline(fused) != 0x007FFFFFu || viaDouble == fused) { + std::fprintf(stderr, "subnormal halfway case no longer exercises double rounding\n"); + return false; + } + + bool ok = CheckScalarFma(a, c, b, "subnormal halfway double rounding"); + ok &= CheckScalarFma(-a, c, -b, "subnormal halfway double rounding (negated)"); + return ok; +} + +bool CheckEdgeValues(const char* mode) { - const double a = PpcPackPairedInline(1.000000119f, -123.25f); - const double c = PpcPackPairedInline(33554431.0f, 0.0625f); - const double b = PpcPackPairedInline(-33554430.0f, 7.75f); + constexpr float kInf = std::numeric_limits::infinity(); + const std::array values{ + 0.0f, + -0.0f, + 1.0f, + -1.0f, + 0.5f, + 1.0f + std::numeric_limits::epsilon(), + std::numeric_limits::min(), + -std::numeric_limits::min(), + std::numeric_limits::denorm_min(), + -std::numeric_limits::min() * 0.75f, + std::numeric_limits::max(), + -std::numeric_limits::max(), + std::ldexp(1.0f, -63), + std::ldexp(1.0f, 64), + kInf, + -kInf, + }; bool ok = true; - ok &= CheckPair(PPC_PsMaddNoNiInline(a, c, b), 1.000000119f, -123.25f, - 33554431.0f, 0.0625f, -33554430.0f, 7.75f, false, "ps_madd"); - ok &= CheckPair(PPC_PsMsubNoNiInline(a, c, b), 1.000000119f, -123.25f, - 33554431.0f, 0.0625f, -33554430.0f, 7.75f, true, "ps_msub"); - ok &= CheckNegatedPair(PPC_PsNmaddInline(a, c, b), 1.000000119f, -123.25f, - 33554431.0f, 0.0625f, -33554430.0f, 7.75f, false, "ps_nmadd"); - ok &= CheckNegatedPair(PPC_PsNmsubNoNiInline(a, c, b), 1.000000119f, -123.25f, - 33554431.0f, 0.0625f, -33554430.0f, 7.75f, true, "ps_nmsub"); + for (const float a : values) { + for (const float c : values) { + for (const float b : values) { + ok &= CheckScalarFma(a, c, b, mode); + } + } + } + return ok; +} + +struct SplitMix64 { + uint64_t state; + + uint64_t Next() + { + uint64_t z = (state += 0x9E3779B97F4A7C15ULL); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31); + } +}; + +float RandomFloat(SplitMix64& rng) +{ + const uint64_t r = rng.Next(); + if ((r & 3u) == 0) { + // Any bit pattern: NaNs, infinities, subnormals and extreme exponents. + return PpcBitCastToFloatInline(static_cast(r >> 32)); + } + // Ordinary magnitudes, where the fast path does its work. + const uint32_t sign = static_cast(r >> 63) << 31; + const uint32_t exponent = 127u - 40u + static_cast((r >> 40) % 81u); + const uint32_t mantissa = static_cast(r >> 8) & 0x007FFFFFu; + return PpcBitCastToFloatInline(sign | (exponent << 23) | mantissa); +} + +bool CheckRandomized(const char* mode) +{ + SplitMix64 rng{0x5EED0F7A11ULL}; + int failures = 0; + for (int i = 0; i < 2'000'000 && failures < 8; ++i) { + const float a = RandomFloat(rng); + const float c = RandomFloat(rng); + float b = RandomFloat(rng); + if ((rng.Next() & 7u) == 0) { + // Near-total cancellation against the exact product. + b = -static_cast(static_cast(a) * static_cast(c)); + } + if (!CheckScalarFma(a, c, b, mode)) { + ++failures; + } + } + return failures == 0; +} + +// The runtime models Gekko NI mode as MXCSR FTZ+DAZ (MkwApplyHostNiMode). +struct FlushToZeroScope { +#if defined(__x86_64__) + explicit FlushToZeroScope(bool enable) : saved(_mm_getcsr()) + { + constexpr unsigned kFtzDaz = 0x8040u; + _mm_setcsr(enable ? (saved | kFtzDaz) : (saved & ~kFtzDaz)); + } + ~FlushToZeroScope() { _mm_setcsr(saved); } + unsigned saved; +#else + explicit FlushToZeroScope(bool) {} +#endif +}; + +bool CheckAgainstReference(const char* reference) +{ + bool ok = CheckPairedFamily(1.000000119f, -123.25f, 33554431.0f, 0.0625f, -33554430.0f, 7.75f); + ok &= CheckHalfwayDoubleRounding(); + ok &= CheckSubnormalHalfwayDoubleRounding(); + + for (const bool flushToZero : {false, true}) { + FlushToZeroScope scope(flushToZero); + char mode[64]; + std::snprintf(mode, sizeof(mode), "%s, %s", reference, flushToZero ? "FTZ/DAZ" : "IEEE"); + ok &= CheckEdgeValues(mode); + ok &= CheckRandomized(mode); + } + return ok; +} + +} // namespace + +#if defined(_WIN32) && defined(__x86_64__) +extern "C" __declspec(dllimport) int _set_FMA3_enable(int flag); +#endif + +int main() +{ + bool ok = CheckAgainstReference("CRT default"); +#if defined(_WIN32) && defined(__x86_64__) + // A CPU without FMA3 gets the CRT's software fmaf as std::fma; compare against that too. + _set_FMA3_enable(0); + ok &= CheckAgainstReference("CRT software fmaf"); + _set_FMA3_enable(1); +#endif return ok ? 0 : 1; } From cbd7a8b8f26582b5aac506df538c7a57b41bd163 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:25:50 +0100 Subject: [PATCH 2/5] keep fma flags, fma4 and nan subtractor signs on the v2 lane path 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. --- runtime/include/isa/ppc_isa_float.h | 57 +++++++---- runtime/tests/ppc_pair_fma_tests.cpp | 137 +++++++++++++++++++++++++-- 2 files changed, 169 insertions(+), 25 deletions(-) diff --git a/runtime/include/isa/ppc_isa_float.h b/runtime/include/isa/ppc_isa_float.h index 2ee11e7a6..f449112ae 100644 --- a/runtime/include/isa/ppc_isa_float.h +++ b/runtime/include/isa/ppc_isa_float.h @@ -436,50 +436,69 @@ inline double PpcPackIntegerWordInline(int32_t value) // A float product is exact in double, so a*c+b computed in double rounds once before the // conversion to float (a contracted double FMA gives the same sum). That double rounding equals // the single fused rounding unless the double sum lands exactly on a float halfway point, and the -// halfway check below only knows where that point sits for normal floats. Halfway sums, results -// at or below FLT_MIN and non-finite results therefore go to std::fma. So do subnormal operands: -// under DAZ the conversion zeroes them, and the CRT's software fmaf does not treat them that way. +// halfway check below only knows where that point sits for normal floats. Halfway sums and results +// at or below FLT_MIN therefore go to std::fma. So do subnormal operands (under DAZ the conversion +// zeroes them, unlike the CRT's software fmaf) and non-finite operands (evaluating 0*Inf or +// converting an sNaN in double would raise FE_INVALID before falling back to std::fma). inline float PpcFusedMultiplyAddFloatViaDoubleInline(float a, float c, float b) { - const auto isSubnormal = [](float value) { - return (PpcBitCastToU32Inline(value) & 0x7FFFFFFFu) - 1u < 0x007FFFFFu; + const auto isNormalOrZero = [](float value) { + const uint32_t absBits = PpcBitCastToU32Inline(value) & 0x7FFFFFFFu; + return absBits == 0u || (absBits - 0x00800000u) < 0x7F000000u; }; - if (!isSubnormal(a) && !isSubnormal(c) && !isSubnormal(b)) [[likely]] { + if (isNormalOrZero(a) && isNormalOrZero(c) && isNormalOrZero(b)) [[likely]] { const double sum = static_cast(a) * static_cast(c) + static_cast(b); const uint64_t bits = PpcBitCastToU64Inline(sum); const uint64_t magnitude = bits & 0x7FFFFFFFFFFFFFFFULL; constexpr uint64_t kFloatMinNormal = 0x3810000000000000ULL; - constexpr uint64_t kInfinity = 0x7FF0000000000000ULL; // The 29 low bits double keeps below a normal float's last bit, and a float halfway point. constexpr uint64_t kBelowFloatLsbMask = 0x1FFFFFFFULL; constexpr uint64_t kFloatHalfway = 0x10000000ULL; - const bool normalOrZero = - magnitude == 0 || (magnitude > kFloatMinNormal && magnitude < kInfinity); - if (normalOrZero && (bits & kBelowFloatLsbMask) != kFloatHalfway) [[likely]] + if ((magnitude == 0 || magnitude > kFloatMinNormal) && + (bits & kBelowFloatLsbMask) != kFloatHalfway) [[likely]] return static_cast(sum); } return std::fma(a, c, b); } -// x86-64-v2 has no FMA instruction, so std::fma(float) is a CRT call there. On a CPU without FMA3 -// the CRT computes it in software at roughly 12x the cost of the hardware instruction, and the -// paired madd family makes two calls per instruction, which slows THP video decoding several -// times over on those CPUs. A v2 build also runs on CPUs that have FMA3 but not the rest of v3 -// (AMD Piledriver, for one), where the CRT reaches the hardware instruction and stays cheaper. +// x86-64-v2 has no FMA instruction, so std::fma(float) is a CRT call there. On a CPU without +// hardware FMA the CRT computes it in software at roughly 12x the cost of the hardware +// instruction, and the paired madd family makes two calls per instruction, which slows THP video +// decoding several times over on those CPUs. A v2 build also runs on CPUs that have hardware FMA +// without the rest of v3 (AMD Piledriver with FMA3, or first-gen Bulldozer with FMA4 on glibc), +// where the CRT reaches the hardware instruction and stays cheaper. inline float PpcFusedMultiplyAddFloatInline(float a, float c, float b) { -#if defined(__x86_64__) && !defined(__FMA__) - if (!__builtin_cpu_supports("fma")) +#if defined(__x86_64__) && !defined(__FMA__) && !(defined(__GLIBC__) && defined(__FMA4__)) + bool crtHasHardwareFma = __builtin_cpu_supports("fma"); +#if defined(__GLIBC__) + // glibc's fmaf also dispatches to FMA4. + crtHasHardwareFma = crtHasHardwareFma || + (__builtin_cpu_supports("fma4") && __builtin_cpu_supports("avx")); +#endif + if (!crtHasHardwareFma) return PpcFusedMultiplyAddFloatViaDoubleInline(a, c, b); #endif return std::fma(a, c, b); } +// The addend a lane FMA sees. A NaN subtractor stays unnegated: x86 vfmsub (the v3 path), the NEON +// path and Gekko all return it with its sign intact, and negating it first would flip that sign. +template +inline float PpcPsMaddLaneAddendInline(float b) +{ + if constexpr (Subtract) { + if ((PpcBitCastToU32Inline(b) & 0x7FFFFFFFu) <= 0x7F800000u) + return -b; + } + return b; +} + template inline float PpcAccuratePsMaddLaneInline(float a, float c, float b) { - const float signedB = Subtract ? -b : b; + const float signedB = PpcPsMaddLaneAddendInline(b); // Paired values are stored as exact float32 lanes in this runtime. An // explicit float FMA therefore matches Gekko's single rounding point; // multiplying and adding separately can differ by an ULP on ordinary @@ -490,7 +509,7 @@ inline float PpcAccuratePsMaddLaneInline(float a, float c, float b) template inline float PpcAccuratePsMaddLaneNoNiInline(float a, float c, float b) { - const float signedB = Subtract ? -b : b; + const float signedB = PpcPsMaddLaneAddendInline(b); return PpcFusedMultiplyAddFloatInline(a, c, signedB); } diff --git a/runtime/tests/ppc_pair_fma_tests.cpp b/runtime/tests/ppc_pair_fma_tests.cpp index ec5396b44..dae5894ce 100644 --- a/runtime/tests/ppc_pair_fma_tests.cpp +++ b/runtime/tests/ppc_pair_fma_tests.cpp @@ -1,6 +1,7 @@ #include "isa/ppc_isa_float.h" #include +#include #include #include #include @@ -18,29 +19,41 @@ bool SameBits(double lhs, double rhs) return PpcBitCastToU64Inline(lhs) == PpcBitCastToU64Inline(rhs); } +// The addend of a fused subtract: a NaN subtractor keeps its sign, as x86 vfmsub and Gekko leave it. +float SubtractAddend(float b, bool subtract) +{ + return subtract && !std::isnan(b) ? -b : b; +} + bool CheckPair(double actual, float a0, float a1, float c0, float c1, float b0, float b1, bool subtract, const char* operation) { - const float expected0 = subtract ? std::fma(a0, c0, -b0) : std::fma(a0, c0, b0); - const float expected1 = subtract ? std::fma(a1, c1, -b1) : std::fma(a1, c1, b1); + const float expected0 = std::fma(a0, c0, SubtractAddend(b0, subtract)); + const float expected1 = std::fma(a1, c1, SubtractAddend(b1, subtract)); const double expected = PpcPackPairedInline(expected0, expected1); if (SameBits(actual, expected)) { return true; } - std::fprintf(stderr, "%s produced the wrong paired lanes\n", operation); + std::fprintf(stderr, "%s produced the wrong paired lanes (0x%016llx, expected 0x%016llx)\n", + operation, static_cast(PpcBitCastToU64Inline(actual)), + static_cast(PpcBitCastToU64Inline(expected))); return false; } bool CheckNegatedPair(double actual, float a0, float a1, float c0, float c1, float b0, float b1, bool subtract, const char* operation) { - const float expected0 = -std::fma(a0, c0, subtract ? -b0 : b0); - const float expected1 = -std::fma(a1, c1, subtract ? -b1 : b1); + const float raw0 = std::fma(a0, c0, SubtractAddend(b0, subtract)); + const float raw1 = std::fma(a1, c1, SubtractAddend(b1, subtract)); + const float expected0 = std::isnan(raw0) ? raw0 : -raw0; + const float expected1 = std::isnan(raw1) ? raw1 : -raw1; const double expected = PpcPackPairedInline(expected0, expected1); if (SameBits(actual, expected)) { return true; } - std::fprintf(stderr, "%s produced the wrong paired lanes\n", operation); + std::fprintf(stderr, "%s produced the wrong paired lanes (0x%016llx, expected 0x%016llx)\n", + operation, static_cast(PpcBitCastToU64Inline(actual)), + static_cast(PpcBitCastToU64Inline(expected))); return false; } @@ -53,12 +66,122 @@ bool CheckPairedFamily(float a0, float a1, float c0, float c1, float b0, float b bool ok = true; ok &= CheckPair(PPC_PsMaddNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, false, "ps_madd"); ok &= CheckPair(PPC_PsMsubNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, true, "ps_msub"); + ok &= CheckPair(PPC_PsMadds0Inline(a, c, b), a0, a1, c0, c0, b0, b1, false, "ps_madds0"); + ok &= CheckPair(PPC_PsMadds1Inline(a, c, b), a0, a1, c1, c1, b0, b1, false, "ps_madds1"); ok &= CheckNegatedPair(PPC_PsNmaddInline(a, c, b), a0, a1, c0, c1, b0, b1, false, "ps_nmadd"); ok &= CheckNegatedPair(PPC_PsNmsubNoNiInline(a, c, b), a0, a1, c0, c1, b0, b1, true, "ps_nmsub"); return ok; } +bool CheckPairedSpecialCases() +{ + const float posQNaN = PpcBitCastToFloatInline(0x7FC12345u); + const float negQNaN = PpcBitCastToFloatInline(0xFFC54321u); + const float sNaN = PpcBitCastToFloatInline(0x7F812345u); + + bool ok = true; + // Signed-zero propagation and exact cancellation across both lanes and broadcast ops. + ok &= CheckPairedFamily(0.0f, -0.0f, 1.0f, 1.0f, 0.0f, -0.0f); + ok &= CheckPairedFamily(-0.0f, 0.0f, 1.0f, -1.0f, -0.0f, -0.0f); + ok &= CheckPairedFamily(3.0f, -3.0f, 2.0f, 2.0f, -6.0f, 6.0f); + // Distinct broadcast multiplier lanes to catch ps_madds0 / ps_madds1 lane selection bugs. + ok &= CheckPairedFamily(2.0f, 5.0f, 7.0f, -11.0f, 13.0f, -17.0f); + // Quiet and signaling NaNs: verify negated ops preserve NaN sign bits. + ok &= CheckPairedFamily(posQNaN, 2.0f, 3.0f, -4.0f, 1.0f, negQNaN); + ok &= CheckPairedFamily(sNaN, 1.0f, 2.0f, 3.0f, 4.0f, sNaN); + return ok; +} + +#if defined(__GNUC__) || defined(__clang__) +#define PPC_FMA_TEST_NOINLINE __attribute__((noinline)) +#elif defined(_MSC_VER) +#define PPC_FMA_TEST_NOINLINE __declspec(noinline) +#else +#define PPC_FMA_TEST_NOINLINE +#endif + +PPC_FMA_TEST_NOINLINE float EvalStdFma(float a, float c, float b) +{ + return std::fma(a, c, b); +} + +PPC_FMA_TEST_NOINLINE float EvalViaDoubleFma(float a, float c, float b) +{ + return PpcFusedMultiplyAddFloatViaDoubleInline(a, c, b); +} + +PPC_FMA_TEST_NOINLINE float EvalDispatchedFma(float a, float c, float b) +{ + return PpcFusedMultiplyAddFloatInline(a, c, b); +} + +// The operands are read from volatiles after feclearexcept and the result is stored to one before +// fetestexcept. Clang otherwise treats the noinline FP call as side-effect free and is free to move +// it past either flag call. +float EvaluateTrackingInvalid(float (*eval)(float, float, float), float a, float c, float b, + bool& invalid) +{ + volatile float va = a; + volatile float vc = c; + volatile float vb = b; + volatile float result; + std::feclearexcept(FE_ALL_EXCEPT); + result = eval(va, vc, vb); + invalid = std::fetestexcept(FE_INVALID) != 0; + return result; +} + +bool CheckInvalidExceptionParity(const char* mode) +{ + constexpr float kInf = std::numeric_limits::infinity(); + const float posQNaN = PpcBitCastToFloatInline(0x7FC01234u); + const float negQNaN = PpcBitCastToFloatInline(0xFFC05678u); + const float sNaN = PpcBitCastToFloatInline(0x7F801234u); + + struct Case { + float a; + float c; + float b; + const char* label; + }; + const std::array cases{{ + {0.0f, kInf, posQNaN, "0 * +Inf + qNaN"}, + {kInf, 0.0f, posQNaN, "+Inf * 0 + qNaN"}, + {-0.0f, -kInf, posQNaN, "-0 * -Inf + qNaN"}, + {0.0f, -kInf, negQNaN, "0 * -Inf + -qNaN"}, + {kInf, 1.0f, -kInf, "+Inf * 1 + -Inf"}, + {sNaN, 1.0f, 0.0f, "sNaN * 1 + 0"}, + {1.0f, 1.0f, posQNaN, "1 * 1 + qNaN"}, + }}; + + bool ok = true; + for (const Case& tc : cases) { + bool expectedInvalid = false; + const float expected = EvaluateTrackingInvalid(&EvalStdFma, tc.a, tc.c, tc.b, expectedInvalid); + + const auto verifyPath = [&](const char* path, float (*eval)(float, float, float)) { + bool actualInvalid = false; + const float actual = EvaluateTrackingInvalid(eval, tc.a, tc.c, tc.b, actualInvalid); + if (PpcBitCastToU32Inline(actual) != PpcBitCastToU32Inline(expected) || + actualInvalid != expectedInvalid) { + std::fprintf(stderr, + "%s %s (%s): got 0x%08x (FE_INVALID=%d), expected 0x%08x " + "(FE_INVALID=%d)\n", + mode, path, tc.label, PpcBitCastToU32Inline(actual), + actualInvalid ? 1 : 0, PpcBitCastToU32Inline(expected), + expectedInvalid ? 1 : 0); + return false; + } + return true; + }; + + ok &= verifyPath("via double", &EvalViaDoubleFma); + ok &= verifyPath("dispatched", &EvalDispatchedFma); + } + return ok; +} + bool CheckFmaResult(float actual, float expected, float a, float c, float b, const char* path, const char* context) { @@ -227,6 +350,7 @@ struct FlushToZeroScope { bool CheckAgainstReference(const char* reference) { bool ok = CheckPairedFamily(1.000000119f, -123.25f, 33554431.0f, 0.0625f, -33554430.0f, 7.75f); + ok &= CheckPairedSpecialCases(); ok &= CheckHalfwayDoubleRounding(); ok &= CheckSubnormalHalfwayDoubleRounding(); @@ -234,6 +358,7 @@ bool CheckAgainstReference(const char* reference) FlushToZeroScope scope(flushToZero); char mode[64]; std::snprintf(mode, sizeof(mode), "%s, %s", reference, flushToZero ? "FTZ/DAZ" : "IEEE"); + ok &= CheckInvalidExceptionParity(mode); ok &= CheckEdgeValues(mode); ok &= CheckRandomized(mode); } From 766f298953e0162fce7e1b0320468f5d4e7b5353 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:34:40 +0100 Subject: [PATCH 3/5] emit vfmsub213ps for paired fused subtract on v3 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. --- runtime/include/isa/ppc_isa_float.h | 9 ++- runtime/tests/ppc_pair_fma_tests.cpp | 100 +++++++++++++++++++++++++-- 2 files changed, 103 insertions(+), 6 deletions(-) diff --git a/runtime/include/isa/ppc_isa_float.h b/runtime/include/isa/ppc_isa_float.h index f449112ae..9af87e3bb 100644 --- a/runtime/include/isa/ppc_isa_float.h +++ b/runtime/include/isa/ppc_isa_float.h @@ -707,7 +707,14 @@ inline PpcPairVec PpcFmsubPairInline(PpcPairVec multiplicand, PpcPairVec multipl { #if defined(__x86_64__) #if defined(__FMA__) - return _mm_fmsub_ps(multiplicand, multiplier, subtractor); + // Not _mm_fmsub_ps: Clang lowers it to an FMA with a negated addend, which it may fold into a + // constant subtractor and emit as vfmadd, flipping the sign of a NaN subtractor. vfmsub213ps + // keeps that sign. dst = multiplier * multiplicand - subtractor. + PpcPairVec result = multiplicand; + __asm__("vfmsub213ps {%2, %1, %0|%0, %1, %2}" + : "+x"(result) + : "x"(multiplier), "x"(subtractor)); + return result; #else const double a = PpcM128ToPsInline(multiplicand); const double c = PpcM128ToPsInline(multiplier); diff --git a/runtime/tests/ppc_pair_fma_tests.cpp b/runtime/tests/ppc_pair_fma_tests.cpp index dae5894ce..fd66ec228 100644 --- a/runtime/tests/ppc_pair_fma_tests.cpp +++ b/runtime/tests/ppc_pair_fma_tests.cpp @@ -132,6 +132,93 @@ float EvaluateTrackingInvalid(float (*eval)(float, float, float), float a, float return result; } +PPC_FMA_TEST_NOINLINE double EvalPsMsub(double a, double c, double b) +{ + return PPC_PsMsubNoNiInline(a, c, b); +} + +PPC_FMA_TEST_NOINLINE double EvalPsNmsub(double a, double c, double b) +{ + return PPC_PsNmsubNoNiInline(a, c, b); +} + +// Same pinning as EvaluateTrackingInvalid, for a paired op on operands only known at run time. +double EvaluatePairTrackingInvalid(double (*eval)(double, double, double), double a, double c, + double b, bool& invalid) +{ + volatile double va = a; + volatile double vc = c; + volatile double vb = b; + volatile double result; + std::feclearexcept(FE_ALL_EXCEPT); + result = eval(va, vc, vb); + invalid = std::fetestexcept(FE_INVALID) != 0; + return result; +} + +// ps_msub/ps_nmsub return a NaN subtractor with its sign intact and quieted, raising FE_INVALID +// only for a signaling one, and compute a*c - b in the right operand order. These operands are +// loaded at run time; the constant ones in CheckPairedSpecialCases catch compile-time folding. +// The CRT's software fmaf (what std::fma is on a CPU without FMA3) returns a signaling NaN +// unquieted and without FE_INVALID, and v2 lanes are std::fma by contract, so that reference +// skips the signaling cases. +bool CheckRuntimeFusedSubtract(const char* mode, bool crtSoftwareReference) +{ + struct Case { + float b0; + float b1; + uint32_t lane0; + uint32_t lane1; + bool invalid; + const char* label; + }; + const float negQNaN = PpcBitCastToFloatInline(0xFFC54321u); + const float posSNaN = PpcBitCastToFloatInline(0x7F812345u); + const float negSNaN = PpcBitCastToFloatInline(0xFF812345u); + // a = (2, 3), c = (5, 7): a*c - b = (10 - b0, 21 - b1). + const std::array cases{{ + {1.0f, 0.5f, PpcBitCastToU32Inline(9.0f), PpcBitCastToU32Inline(20.5f), false, + "finite"}, + {negQNaN, 1.0f, 0xFFC54321u, PpcBitCastToU32Inline(20.0f), false, "-qNaN subtractor"}, + {1.0f, posSNaN, PpcBitCastToU32Inline(9.0f), 0x7FC12345u, true, "+sNaN subtractor"}, + {negSNaN, 1.0f, 0xFFC12345u, PpcBitCastToU32Inline(20.0f), true, "-sNaN subtractor"}, + }}; + const double a = PpcPackPairedInline(2.0f, 3.0f); + const double c = PpcPackPairedInline(5.0f, 7.0f); + + bool ok = true; + for (const Case& tc : cases) { + if (crtSoftwareReference && tc.invalid) { + continue; + } + const double b = PpcPackPairedInline(tc.b0, tc.b1); + const auto lane = [](uint32_t bits, bool negate) { + const bool isNan = (bits & 0x7FFFFFFFu) > 0x7F800000u; + return negate && !isNan ? bits ^ 0x80000000u : bits; + }; + for (const bool negated : {false, true}) { + bool invalid = false; + const double actual = EvaluatePairTrackingInvalid(negated ? &EvalPsNmsub : &EvalPsMsub, + a, c, b, invalid); + const double expected = PpcPackPairedInline( + PpcBitCastToFloatInline(lane(tc.lane0, negated)), + PpcBitCastToFloatInline(lane(tc.lane1, negated))); + if (!SameBits(actual, expected) || invalid != tc.invalid) { + std::fprintf(stderr, + "%s %s (%s): got 0x%016llx (FE_INVALID=%d), expected 0x%016llx " + "(FE_INVALID=%d)\n", + mode, negated ? "ps_nmsub" : "ps_msub", tc.label, + static_cast(PpcBitCastToU64Inline(actual)), + invalid ? 1 : 0, + static_cast(PpcBitCastToU64Inline(expected)), + tc.invalid ? 1 : 0); + ok = false; + } + } + } + return ok; +} + bool CheckInvalidExceptionParity(const char* mode) { constexpr float kInf = std::numeric_limits::infinity(); @@ -347,7 +434,7 @@ struct FlushToZeroScope { #endif }; -bool CheckAgainstReference(const char* reference) +bool CheckAgainstReference(const char* reference, bool crtSoftwareReference) { bool ok = CheckPairedFamily(1.000000119f, -123.25f, 33554431.0f, 0.0625f, -33554430.0f, 7.75f); ok &= CheckPairedSpecialCases(); @@ -359,6 +446,7 @@ bool CheckAgainstReference(const char* reference) char mode[64]; std::snprintf(mode, sizeof(mode), "%s, %s", reference, flushToZero ? "FTZ/DAZ" : "IEEE"); ok &= CheckInvalidExceptionParity(mode); + ok &= CheckRuntimeFusedSubtract(mode, crtSoftwareReference); ok &= CheckEdgeValues(mode); ok &= CheckRandomized(mode); } @@ -367,17 +455,19 @@ bool CheckAgainstReference(const char* reference) } // namespace -#if defined(_WIN32) && defined(__x86_64__) +// Only a build without __FMA__ calls the CRT's fmaf; a v3 build compiles std::fma to vfmadd. +#if defined(_WIN32) && defined(__x86_64__) && !defined(__FMA__) +#define PPC_FMA_TEST_CRT_SOFTWARE_FMAF 1 extern "C" __declspec(dllimport) int _set_FMA3_enable(int flag); #endif int main() { - bool ok = CheckAgainstReference("CRT default"); -#if defined(_WIN32) && defined(__x86_64__) + bool ok = CheckAgainstReference("CRT default", false); +#if defined(PPC_FMA_TEST_CRT_SOFTWARE_FMAF) // A CPU without FMA3 gets the CRT's software fmaf as std::fma; compare against that too. _set_FMA3_enable(0); - ok &= CheckAgainstReference("CRT software fmaf"); + ok &= CheckAgainstReference("CRT software fmaf", true); _set_FMA3_enable(1); #endif return ok ? 0 : 1; From f7a0ba3e5e0117ae2f67d966aa3904eef324bf61 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:42:47 +0100 Subject: [PATCH 4/5] order the v3 vfmsub asm against ni mode and read the crt fma3 state 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. --- runtime/include/isa/ppc_isa_float.h | 11 ++++-- runtime/tests/ppc_pair_fma_tests.cpp | 56 +++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/runtime/include/isa/ppc_isa_float.h b/runtime/include/isa/ppc_isa_float.h index 9af87e3bb..25dc6bb22 100644 --- a/runtime/include/isa/ppc_isa_float.h +++ b/runtime/include/isa/ppc_isa_float.h @@ -709,11 +709,14 @@ inline PpcPairVec PpcFmsubPairInline(PpcPairVec multiplicand, PpcPairVec multipl #if defined(__FMA__) // Not _mm_fmsub_ps: Clang lowers it to an FMA with a negated addend, which it may fold into a // constant subtractor and emit as vfmadd, flipping the sign of a NaN subtractor. vfmsub213ps - // keeps that sign. dst = multiplier * multiplicand - subtractor. + // keeps that sign. dst = multiplier * multiplicand - subtractor. Volatile with a memory clobber + // so it is neither merged nor moved across an MXCSR write (NI mode) or fenv call, nor dropped + // with the FE_INVALID it raises when the result goes unused. PpcPairVec result = multiplicand; - __asm__("vfmsub213ps {%2, %1, %0|%0, %1, %2}" - : "+x"(result) - : "x"(multiplier), "x"(subtractor)); + __asm__ __volatile__("vfmsub213ps {%2, %1, %0|%0, %1, %2}" + : "+x"(result) + : "x"(multiplier), "x"(subtractor) + : "memory"); return result; #else const double a = PpcM128ToPsInline(multiplicand); diff --git a/runtime/tests/ppc_pair_fma_tests.cpp b/runtime/tests/ppc_pair_fma_tests.cpp index fd66ec228..0be4357d8 100644 --- a/runtime/tests/ppc_pair_fma_tests.cpp +++ b/runtime/tests/ppc_pair_fma_tests.cpp @@ -434,6 +434,43 @@ struct FlushToZeroScope { #endif }; +// The same ps_msub on both sides of an NI toggle: 2^-149 * 2^23 - 0 is FLT_MIN while DAZ is off +// and 0 once it is on. Plain locals and identical operands let the compiler merge the two calls +// unless the v3 vfmsub asm is ordered against the MXCSR write. The v2 lanes are ordinary +// std::fma, which the compiler may merge or move across MXCSR writes like any other FP operation +// in translated code, so only the asm path is checked. +bool CheckFusedSubtractFollowsNiMode() +{ +#if defined(__x86_64__) && defined(__FMA__) + const float denormal = PpcBitCastToFloatInline(0x00000001u); + const double a = PpcPackPairedInline(denormal, 2.0f); + const double c = PpcPackPairedInline(std::ldexp(1.0f, 23), 3.0f); + const double b = PpcPackPairedInline(0.0f, 1.0f); + + MkwApplyHostNiMode(0); + const double ieee = PPC_PsMsubNoNiInline(a, c, b); + MkwApplyHostNiMode(0x4u); + const double flushed = PPC_PsMsubNoNiInline(a, c, b); + MkwApplyHostNiMode(0); + + const double expectedIeee = PpcPackPairedInline(PpcBitCastToFloatInline(0x00800000u), 5.0f); + const double expectedFlushed = PpcPackPairedInline(0.0f, 5.0f); + if (SameBits(ieee, expectedIeee) && SameBits(flushed, expectedFlushed)) { + return true; + } + std::fprintf(stderr, + "ps_msub across an NI toggle: got 0x%016llx then 0x%016llx, expected 0x%016llx " + "then 0x%016llx\n", + static_cast(PpcBitCastToU64Inline(ieee)), + static_cast(PpcBitCastToU64Inline(flushed)), + static_cast(PpcBitCastToU64Inline(expectedIeee)), + static_cast(PpcBitCastToU64Inline(expectedFlushed))); + return false; +#else + return true; +#endif +} + bool CheckAgainstReference(const char* reference, bool crtSoftwareReference) { bool ok = CheckPairedFamily(1.000000119f, -123.25f, 33554431.0f, 0.0625f, -33554430.0f, 7.75f); @@ -458,17 +495,26 @@ bool CheckAgainstReference(const char* reference, bool crtSoftwareReference) // Only a build without __FMA__ calls the CRT's fmaf; a v3 build compiles std::fma to vfmadd. #if defined(_WIN32) && defined(__x86_64__) && !defined(__FMA__) #define PPC_FMA_TEST_CRT_SOFTWARE_FMAF 1 +extern "C" __declspec(dllimport) int _get_FMA3_enable(void); extern "C" __declspec(dllimport) int _set_FMA3_enable(int flag); #endif int main() { - bool ok = CheckAgainstReference("CRT default", false); + bool ok = CheckFusedSubtractFollowsNiMode(); #if defined(PPC_FMA_TEST_CRT_SOFTWARE_FMAF) - // A CPU without FMA3 gets the CRT's software fmaf as std::fma; compare against that too. - _set_FMA3_enable(0); - ok &= CheckAgainstReference("CRT software fmaf", true); - _set_FMA3_enable(1); + // On a CPU without FMA3 the CRT starts with its software fmaf; elsewhere force that path for + // a second pass, since it is what std::fma is on the CPUs the double path exists for. + const int initialFma3 = _get_FMA3_enable(); + ok &= CheckAgainstReference(initialFma3 != 0 ? "CRT default (FMA3)" : "CRT default (software fmaf)", + initialFma3 == 0); + if (initialFma3 != 0) { + _set_FMA3_enable(0); + ok &= CheckAgainstReference("CRT software fmaf", true); + _set_FMA3_enable(initialFma3); + } +#else + ok &= CheckAgainstReference("CRT default", false); #endif return ok ? 0 : 1; } From 5d21e5d1fc2a2b025a41a80c8d45d9c14ecccb44 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:48:47 +0100 Subject: [PATCH 5/5] shorten fma comments --- runtime/include/isa/ppc_isa_float.h | 31 +++++++----------------- runtime/tests/ppc_pair_fma_tests.cpp | 36 +++++++++------------------- 2 files changed, 19 insertions(+), 48 deletions(-) diff --git a/runtime/include/isa/ppc_isa_float.h b/runtime/include/isa/ppc_isa_float.h index 25dc6bb22..f83dd04ed 100644 --- a/runtime/include/isa/ppc_isa_float.h +++ b/runtime/include/isa/ppc_isa_float.h @@ -431,15 +431,8 @@ inline double PpcPackIntegerWordInline(int32_t value) static_cast(static_cast(value))); } -// std::fma(a, c, b) for floats, computed without an FMA instruction and bit-identical to it. -// -// A float product is exact in double, so a*c+b computed in double rounds once before the -// conversion to float (a contracted double FMA gives the same sum). That double rounding equals -// the single fused rounding unless the double sum lands exactly on a float halfway point, and the -// halfway check below only knows where that point sits for normal floats. Halfway sums and results -// at or below FLT_MIN therefore go to std::fma. So do subnormal operands (under DAZ the conversion -// zeroes them, unlike the CRT's software fmaf) and non-finite operands (evaluating 0*Inf or -// converting an sNaN in double would raise FE_INVALID before falling back to std::fma). +// Bit-identical std::fma(float) without an FMA instruction: a float product is exact in double. +// Halfway sums, results <= FLT_MIN and subnormal/non-finite operands fall back to std::fma. inline float PpcFusedMultiplyAddFloatViaDoubleInline(float a, float c, float b) { const auto isNormalOrZero = [](float value) { @@ -452,7 +445,7 @@ inline float PpcFusedMultiplyAddFloatViaDoubleInline(float a, float c, float b) const uint64_t bits = PpcBitCastToU64Inline(sum); const uint64_t magnitude = bits & 0x7FFFFFFFFFFFFFFFULL; constexpr uint64_t kFloatMinNormal = 0x3810000000000000ULL; - // The 29 low bits double keeps below a normal float's last bit, and a float halfway point. + // Double bits below a normal float's LSB, and the halfway pattern within them. constexpr uint64_t kBelowFloatLsbMask = 0x1FFFFFFFULL; constexpr uint64_t kFloatHalfway = 0x10000000ULL; if ((magnitude == 0 || magnitude > kFloatMinNormal) && @@ -462,12 +455,8 @@ inline float PpcFusedMultiplyAddFloatViaDoubleInline(float a, float c, float b) return std::fma(a, c, b); } -// x86-64-v2 has no FMA instruction, so std::fma(float) is a CRT call there. On a CPU without -// hardware FMA the CRT computes it in software at roughly 12x the cost of the hardware -// instruction, and the paired madd family makes two calls per instruction, which slows THP video -// decoding several times over on those CPUs. A v2 build also runs on CPUs that have hardware FMA -// without the rest of v3 (AMD Piledriver with FMA3, or first-gen Bulldozer with FMA4 on glibc), -// where the CRT reaches the hardware instruction and stays cheaper. +// On v2, std::fma is a CRT call that is ~12x slower in software without hardware FMA (THP decode). +// Use the double path there; CPUs with FMA3/FMA4 keep the CRT's hardware path. inline float PpcFusedMultiplyAddFloatInline(float a, float c, float b) { #if defined(__x86_64__) && !defined(__FMA__) && !(defined(__GLIBC__) && defined(__FMA4__)) @@ -483,8 +472,7 @@ inline float PpcFusedMultiplyAddFloatInline(float a, float c, float b) return std::fma(a, c, b); } -// The addend a lane FMA sees. A NaN subtractor stays unnegated: x86 vfmsub (the v3 path), the NEON -// path and Gekko all return it with its sign intact, and negating it first would flip that sign. +// The addend a lane FMA sees; a NaN subtractor stays unnegated so its sign matches Gekko/vfmsub. template inline float PpcPsMaddLaneAddendInline(float b) { @@ -707,11 +695,8 @@ inline PpcPairVec PpcFmsubPairInline(PpcPairVec multiplicand, PpcPairVec multipl { #if defined(__x86_64__) #if defined(__FMA__) - // Not _mm_fmsub_ps: Clang lowers it to an FMA with a negated addend, which it may fold into a - // constant subtractor and emit as vfmadd, flipping the sign of a NaN subtractor. vfmsub213ps - // keeps that sign. dst = multiplier * multiplicand - subtractor. Volatile with a memory clobber - // so it is neither merged nor moved across an MXCSR write (NI mode) or fenv call, nor dropped - // with the FE_INVALID it raises when the result goes unused. + // Asm, not _mm_fmsub_ps: Clang can fold that into vfmadd and flip a NaN subtractor's sign. + // Volatile + memory clobber keeps it ordered against MXCSR (NI mode) and fenv calls. PpcPairVec result = multiplicand; __asm__ __volatile__("vfmsub213ps {%2, %1, %0|%0, %1, %2}" : "+x"(result) diff --git a/runtime/tests/ppc_pair_fma_tests.cpp b/runtime/tests/ppc_pair_fma_tests.cpp index 0be4357d8..da624020b 100644 --- a/runtime/tests/ppc_pair_fma_tests.cpp +++ b/runtime/tests/ppc_pair_fma_tests.cpp @@ -116,9 +116,7 @@ PPC_FMA_TEST_NOINLINE float EvalDispatchedFma(float a, float c, float b) return PpcFusedMultiplyAddFloatInline(a, c, b); } -// The operands are read from volatiles after feclearexcept and the result is stored to one before -// fetestexcept. Clang otherwise treats the noinline FP call as side-effect free and is free to move -// it past either flag call. +// Volatiles pin the call between feclearexcept and fetestexcept; Clang would otherwise move it. float EvaluateTrackingInvalid(float (*eval)(float, float, float), float a, float c, float b, bool& invalid) { @@ -156,12 +154,8 @@ double EvaluatePairTrackingInvalid(double (*eval)(double, double, double), doubl return result; } -// ps_msub/ps_nmsub return a NaN subtractor with its sign intact and quieted, raising FE_INVALID -// only for a signaling one, and compute a*c - b in the right operand order. These operands are -// loaded at run time; the constant ones in CheckPairedSpecialCases catch compile-time folding. -// The CRT's software fmaf (what std::fma is on a CPU without FMA3) returns a signaling NaN -// unquieted and without FE_INVALID, and v2 lanes are std::fma by contract, so that reference -// skips the signaling cases. +// ps_msub/ps_nmsub keep a NaN subtractor's sign and raise FE_INVALID only for sNaN, on run-time +// operands. The CRT's software fmaf doesn't quiet sNaN, so that reference skips those cases. bool CheckRuntimeFusedSubtract(const char* mode, bool crtSoftwareReference) { struct Case { @@ -283,8 +277,7 @@ bool CheckFmaResult(float actual, float expected, float a, float c, float b, con return false; } -// The double-based path is what a CPU without FMA3 takes; check it directly so hosts that have -// FMA3 (and dispatch to std::fma) still cover it. +// Check the double path directly so hosts with FMA3 still cover it. bool CheckScalarFma(float a, float c, float b, const char* context) { const float expected = std::fma(a, c, b); @@ -295,9 +288,8 @@ bool CheckScalarFma(float a, float c, float b, const char* context) return ok; } -// a*c = 2^6 - 2^-40 sits just below the float halfway point between b and the next float, so the -// fused result is b. Rounded to double first, the sum lands exactly on that halfway point and -// ties-to-even then picks the next float, which is what a plain double evaluation returns. +// a*c sits just below a float halfway point, so fused gives b; rounding to double first lands on +// the halfway point and ties-to-even picks the next float. bool CheckHalfwayDoubleRounding() { const float a = 1.0f + std::ldexp(1.0f, -23); @@ -318,10 +310,8 @@ bool CheckHalfwayDoubleRounding() return ok; } -// FLT_MIN - 3*2^-150 + 3*2^-190 lies just above the halfway point between the subnormals -// 0x007FFFFE and 0x007FFFFF. Double rounding drops the 2^-190 term, lands on that halfway point -// and ties to the even 0x007FFFFE. The normal-float halfway check cannot see this: the subnormal -// halfway bit sits one position higher in the double. +// Same double-rounding trap between two subnormals, where the normal-float halfway check can't see +// it; this is why results <= FLT_MIN fall back to std::fma. bool CheckSubnormalHalfwayDoubleRounding() { const float a = -std::ldexp(3.0f + std::ldexp(3.0f, -20), -75); @@ -434,11 +424,8 @@ struct FlushToZeroScope { #endif }; -// The same ps_msub on both sides of an NI toggle: 2^-149 * 2^23 - 0 is FLT_MIN while DAZ is off -// and 0 once it is on. Plain locals and identical operands let the compiler merge the two calls -// unless the v3 vfmsub asm is ordered against the MXCSR write. The v2 lanes are ordinary -// std::fma, which the compiler may merge or move across MXCSR writes like any other FP operation -// in translated code, so only the asm path is checked. +// Same ps_msub either side of an NI toggle must give FLT_MIN then 0; catches the v3 asm being +// merged or moved across the MXCSR write. bool CheckFusedSubtractFollowsNiMode() { #if defined(__x86_64__) && defined(__FMA__) @@ -503,8 +490,7 @@ int main() { bool ok = CheckFusedSubtractFollowsNiMode(); #if defined(PPC_FMA_TEST_CRT_SOFTWARE_FMAF) - // On a CPU without FMA3 the CRT starts with its software fmaf; elsewhere force that path for - // a second pass, since it is what std::fma is on the CPUs the double path exists for. + // Also force the CRT's software fmaf for a second pass when this CPU has FMA3. const int initialFma3 = _get_FMA3_enable(); ok &= CheckAgainstReference(initialFma3 != 0 ? "CRT default (FMA3)" : "CRT default (software fmaf)", initialFma3 == 0);