Repository navigation
cvc::physics: dot() and vec3 * s give the same bits in every TU, contracted or not - #1635
Merged
Merged
Conversation
…racted or not cvc/physics/types.h's inline dot() fused into FMAs in any translation unit built with contraction: clang's default -ffp-contract=on on aarch64, gcc's default -ffp-contract=fast, MSVC's /fp:contract and /fp:fast. The deterministic sources are built with -ffp-contract=off, so the bits depended on the caller's flags, and in a shared macOS Debug build dyld bound libcvc's own calls to a test executable's contracted copy (the cause #1606 worked around with per-TU flags). Under -ffp-contract=fast the same held for a caller's p + v * s. Each product is now rounded before anything is added to it: - gcc and clang on aarch64 and x86-64: detail::rounded(), an empty asm on the product ("+w" / "+x", as glibc's math_opt_barrier). No instruction, and dot() stays inline. - MSVC: #pragma fp_contract(off) around the operators and dot() only (float_control push/pop). Checked in the generated code first. For arm64 macOS, clang 20 and 22 under -ffp-contract=off, on, fast and fast-honor-pragmas, at -O0 (the weak copy) and -O2 (inlined): no FMA in dot(), operator* or a caller's p + v * s. The instruction sequence is the uncontracted one. On an x86-64 with FMA, a hash over 200000 random inputs (inlined, the out-of-line copies, p + v * s) is the -ffp-contract=off hash for gcc 16, clang 20, MSVC 19.44 and clang-cl 22 in every mode. The old header gave five other hashes. What did not work: #pragma clang fp contract(off) and #pragma STDC FP_CONTRACT OFF (clang disregards them under -ffp-contract=fast, gcc ignores them), named temporaries (stop only -ffp-contract=on), gcc's optimize("fp-contract=off") (gcc then will not inline dot()). gcc's __builtin_assoc_barrier works, but clang has no such builtin. Goldens are untouched: the hardened helpers compute what the -ffp-contract=off sources always did.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follows #1606.
cvc/physics/types.h's inlinedot()gave bits that depended on the caller's contraction flags. In a shared macOS Debug build that reached libcvc itself, because dyld binds libcvc's own calls to the test executable's copy. #1606 worked around it by building three test files with-ffp-contract=off, and any new physics test that calleddot()without the flag would have hit it again.dot()andvec3 * snow give the uncontracted bits in every translation unit, whatever its-ffp-contractor/fp. No golden changes.Cause
A compiler may fuse a product and the sum it feeds into one FMA, which rounds once where the source rounds twice:
-ffp-contract=on), within one expression, where the target has an FMA: aarch64, or x86-64 with-mfma.-ffp-contract=fast, its C++ default)./fp:contractand/fp:fast.libcvc's deterministic sources are built with
-ffp-contract=off(/fp:precise), and the goldens are their results.types.h's helpers are inline, so every caller compiled its own copy with its own flags:dot()'s bodya.x * b.x + a.y * b.y + a.z * b.zfused under clang's and gcc's defaults (two FMAs).p + v * sfused under-ffp-contract=fast, onceoperator*andoperator+were inlined into it.Fix
Each product is rounded before anything is added to it.
detail::rounded(x)is an empty asm on the product ("+w"/"+x"), as glibc'smath_opt_barrieris. It emits no instruction, anddot()stays inline. It is applied indot()andoperator*.#pragma fp_contract(off)over the operators anddot()only, insidefloat_control(push)/pop. MSVC never contracts under/fp:preciseor/fp:strict(libcvc's default) in any case.The header comment, the
src/cvc/tests/CMakeLists.txtcomments anddocs/PHYSICS_API.mdnow say so. #1606's per-TU flags stay.physics_field_test.cppandph_train_test.cppstill need theirs for their own arithmetic (the coast distance, the double side ofEXPECT_DOUBLE_EQ).physics_dyn_boat_plant_test.cppno longer needs its flag (see Testing), but it is kept, as the bike and four-wheel tests keep theirs.How the mechanism was chosen
Each candidate was checked in the generated code, not taken from documentation. The aarch64 checks used clang 20.1 (zig 0.15.2) and clang 22.1.8 (cvcpkg
llvm) forarm64-apple-macos, which gave identical results. The x86-64 checks used gcc 16.1 (cvcpkgmingw-w64-gcc) with-mfma, and MSVC 19.44 with/arch:AVX2. "Holds" means the out-of-line copy (-O0) and the inlined copy (-O2) had no FMA.onfastonfast#pragma clang fp contract(off)in the body#pragma STDC FP_CONTRACT OFF__attribute__((optimize("fp-contract=off")))dot()__builtin_assoc_barrieron the productsThe pragma also held under clang's
-ffp-contract=fast-honor-pragmas. MSVC'sfp_contract(off)+float_controlheld under/fp:contractand/fp:fast, inlined too. After thepop, the including file's owna * b + cstill contracted, so the pragma does not leak.Testing
off,on,fast,fast-honor-pragmas; -O0 and -O2): no FMA indot()'s out-of-line copy,operator*'s, an inlineddot(), or a caller'sp + v * s. A plaina * b + cin the same file still fuses, which shows the TU really contracts. The inlineddot()isfmul, fmul, fadd, fmul, fadd, the uncontracted order.dot()inlined and through its out-of-line copy, plusp + v * sandt * b - a, inlined and throughoperator*'s copy. Every build printed the-ffp-contract=offhash,56bec10b08a80cd5. The builds were gcc 16 and clang 20 with-mfma(off,on,fast; -O0, -O2), MSVC 19.44/arch:AVX2(/fp:strict,precise,contract,fast;/Od,/O2) and clang-cl 22 (/fp:precise,/fp:fast). With today's header, 11 of those builds printed one of five other hashes: gcc and clangon(-O0 and -O2), gcc and clangfastat -O2, MSVC/fp:contractand/fp:fastat/O2, and clang-cl (whose/fp:preciseis-ffp-contract=on). Under clangfast, the inlineddot()even disagreed with its own out-of-line copy in 49187 of 200000 cases.-Wall -Wextra -Wpedantic -Werror, clang-Weverything(the one hit is the existing__CVC_PHYSICS_TYPES_H__guard name), MSVC/W4 /WX. clang-format 18.1.8 is clean.types.h(physics, ph, ocean, algo, holon, avatar, scene world). 794 tests passed and 28 skipped (optional deps).physics_replay_testmatched all 1240 steps of its trace. All four goldens passed, as did PhysicsFluidSurface's and PhysicsOceanSurface's.ci/full/physics-no-contracthas this commit's tree plus one temporary commit (ab3cd2c), which buildsphysics_dyn_boat_plant_test.cppwith the compiler's default contraction again. That is the setting under which DynBoatPlant's Debug golden failed before tests: the wake, boat-plant and tape tests without FMA contraction (master's macOS lanes) #1606. CI (recipe-first) 46202725919 is green on all six jobs. Both macOS lanes ran macos-26-arm64 20261123.0526.1 with AppleClang 21.0.0. ctest passed 100% (8781 tests in Debug, 8783 in Release), and no test needed a retry. PhysicsFieldWake, PhysicsFieldWakeShore and DynBoatPlant's CrossPlatformGoldenHash and PhTrain.TheTapesDerivativesMatchFiniteDifferences passed in both lanes. So a contracted test TU callingdot()no longer moves the Debug goldens.The same push's CI/CD 46202725942 passed every finished job but one (
package-linux / libcvc-debugwas still running when this was written):package-macos / libcvc-release-grpc-staticfailedPoolKillOwner.TwoAtOnceBothReturn(state_exec_router_test.cpp:3707, "the case missed its window (raise kMany)") on both tries. That is a thread-overlap timing test that includes no physics header, and master's last completed run of that job (46189598631) passed it.Other inline helpers with the same exposure (not changed here)
I compiled each header that the physics, ocean and algo exact sources reach (66 headers) with clang for arm64,
-ffp-contract=on -femit-all-decls, and listed every inline libcvc function whose IR has anllvm.fmuladd. Incvc/physics/it is onlydot(). Elsewhere:ocean::ewave::x_of/y_of(ewave.h),ocean::shore_grid::x/y(shore.h)origin + i * dxewave.cpp/shore.cpp(exact) and by default-flag TUs (cvcGL'scvcgl_ewave.cppamong them). In a macOS Debug build the copy libcvc calls can be a contracted one.height_field::max_x/max_y(geometry/height_field.h)_x0 + _dx * nalgo::add_gust_front(algo/gust_front.h)world/weather.cppandariadne/scene_weather.cpp(default flags) get different bits on arm64 fromocean_wind_test(built without contraction).nav::diff::*(diff_rollout.h,dyn_*.h, 33 functions),nav::detail::ipc_b/ipc_pw_knee(nav_potential.h),nav::kinematic_step(plant_types.h)ticks_per_step(core/clock_follower.h),ocean::texel_k(ocean/h0.h)0.5 * n) is exact.The small grid helpers (
x_of,shore_grid::x,max_x) could take the same barrier. The barrier would need a home that ocean (which may include onlycvc/algo) and geometry can both include, since the physics headers include only the standard library. That would be a follow-up.