Repository navigation
Set the x86 rounding mode with fesetround (fixes #23, #35, #41) - #58
reach2sayan wants to merge 5 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #58 +/- ##
===========================================
+ Coverage 83.12% 83.45% +0.33%
===========================================
Files 23 21 -2
Lines 1043 1058 +15
Branches 426 429 +3
===========================================
+ Hits 867 883 +16
+ Misses 167 166 -1
Partials 9 9
... and 2 files with indirect coverage changes Continue to review full report in Codecov by Harness.
🚀 New features to boost your workflow:
|
|
@Lastique x86-64 GCC moved to |
|
In principle, it makes sense that rounding control should only affect rounding and not other FPU behaviors. However, this seems to be not the case for most rounding backends in Boost.Interval. Take the recently updated PPC backend for example: I'm not sure if the current implementation (with full FPU control word updates used most of the time) was intentional. But if you think it should be changed, I would rather the behavior be consistent across all targets, where possible. Do you have any plans in addressing these inconsistencies and what do you think about this? Do you have an idea why the current implementation might be preferred? |
|
Also FYI, Boost 1.93.0 release cycle is upcoming. While it is possible to merge to develop and master during that time, merging to master is generally only allowed for bug fixes, and merging to develop might complicate things as it may affect dependent libraries. You can continue working in other branches, of course. I usually prefer to avoid merging to both develop and master during the release cycle, unless I intend to eventually request merging to master to include a change in the release. Wrt. this PR, as I commented above, I feel this is either incomplete or (if we end up updating all backends) will be too large to squeeze into the release. |
7446b6d to
d9b87cc
Compare
|
Library Intent: a rounding switch should change the rounding mode, plus whatever containment depends on, and leave traps and exception flags alone. In that light, some of the full writes look intentional:
How about we keep this PR to x86 only? It fixes:
#23 and the GCC 16 case give intervals that don't contain the true value on 32-bit x86. #41 is the same miscompilation: with 32-bit GCC 13 and C++03, one rounding variant in One small CI-only PR goes in first, #59 : it fixes the macOS jobs, which fail on the |
|
If you think subnormal handling, including raising the exceptions on underflow, should also be affected by the rounding control then this should also be done on x86/SSE. x87 already preserves subnormals, but it does generate exceptions. Also, if we're masking underflow exceptions then it would make sense to also mask overflow and inexact exceptions as well. Given this, the original Also, this means that If we consider the other backends (besides IA64) correct then yes, let's focus this PR on x86, but let's make it consistent with the other targets. We can work on IA64 separately (if we consider it important enough to keep, since the platform is largely dead). And we probably want to add ARM and ARM64 targets as well, if we agree I've merged the CI PR, you may need to rebase. |
|
Also, I couldn't find the discussion about subnormals and FPU exceptions in the docs. Maybe I missed it, but I think it would be useful if the behavior was documented for the specific rounding policies, somewhere in |
d9b87cc to
9f1a470
Compare
|
@Lastique My bad, I forgot +/-inf is the correct result of an overflow with directed rounding. So yes, we should control the traps too, not just the rounding mode. And on exit we should clear the flags raised inside interval code for exceptions the user unmasked, otherwise restoring their setting traps on what was correct behaviour in the library. Doing this properly needs more thought. A generic approach through the For now, #41 has a small fix in the same line as the previous PRs: a The docs would reflect the final changes |
I think |
9f1a470 to
14d4687
Compare
conv_down and conv_up computed from the argument directly, so the compiler could convert it once, before the change of rounding mode, and reuse the result for both bounds. Read it through detail::reload_operand, as rounded_arith_std already does. This matters once the mode is set with an inline ldmxcsr instead of a call: Clang 14 and older then hoist cvtsd2ss above it.
…oostorg#35) The x87 control word and MXCSR each hold their own rounding mode. 32-bit GCC and Clang set only the x87 word, so with -mfpmath=sse the bounds of interval<double> were rounded to nearest and 1/3 came out as a point interval (boostorg#23). x86-64 used fesetround, which changes only the rounding bits and leaves the caller's FTZ/DAZ and unmasked traps in force (boostorg#35). x86_rounding_control now inherits from x86_rounding (the x87 word, unchanged) and x86_mxcsr, which each platform header names: stmxcsr/ldmxcsr asm for GCC, Clang and 32-bit MSVC, the intrinsics for 64-bit MSVC, and mxcsr_none for Borland. The switches set both units with all exceptions masked and FTZ/DAZ off; saving and restoring covers both. x86-64 GCC and Clang use this backend instead of the C99 one. test/x86_rounding.cpp checks the control state inside and after, and subnormal handling; it runs a second time with -msse2 -mfpmath=sse.
Restoring set back the x87 control word only, so flags raised inside interval arithmetic (inexact, mostly) reached the caller. When the caller had a flag unmasked, the pending flag also trapped at the caller's next x87 instruction. The saved state now holds x87 status bits 0-7 too. x87_restore loads them together with the control word, so no flag raised inside is pending while the caller's word unmasks it: fnstenv, patch, fldenv. Each platform names its x87 status access x86_x87_status: asm for GCC, Clang and 32-bit MSVC, the shared x87_status_none for 64-bit MSVC and Borland, which have no x87 arithmetic to clean up. test/x86_rounding.cpp checks the flags after interval arithmetic, and that an unmasked inexact does not trap.
frndint rounds float and double too, in the x87 mode that the switches now set along with MXCSR; any x87 flag it raises is dropped when the caller's state is restored. Calling rint instead would not keep x87 out either: Clang on 32-bit x86 calls the libm rint, which is frndint in glibc.
One #if per platform for the register probes, one set_mode helper, and the inside-control constants named. On x86-64 float and double are already on SSE, so x86_rounding_sse duplicated x86_rounding.
14d4687 to
c530767
Compare
Depends on #59 for the macOS CI jobs (an SDK link error on the
macos-26runner, unrelated to this change).An x86 CPU has two separate floating-point units, and each has its own control register with its own rounding mode (Intel SDM, Volume 1: §8.1.5 "x87 FPU Control Word" and §10.2.3 "MXCSR Control and Status
Register"):
The rounding codes are the same in both:
00nearest,01down,10up,11toward zero.Setting one register does not change the other. After
fldcw, x87 instructions (fdiv,fsqrt, …) round up, but SSE instructions (divsd,sqrtsd, …) still round to nearest.The standard C function
fesetround()from<fenv.h>changes the rounding bits in the x87 word and in MXCSR, and nothing else. Exception masks and precision stay as they were.What each compiler used before this PR
fesetroundfldcwwith a fixed 16-bit constant_control87(..., _MCW_EM | _MCW_RC | _MCW_PC | _MCW_IC)_control87(..., _MCW_EM | _MCW_RC)On x86,
_control87sets both units; on x64 it sets MXCSR only (Microsoftdocs). So MSVC never had #23, only #35.
The constant used on 32-bit GCC/Clang (
detail/x86_rounding_control.hpp):0x1b7f("up") in binary is0001 1011 0111 1111:fldcwloads all 16 bits at once, so it sets all three fields.Issue #23: the wrong register
32-bit GCC or Clang with
-msse2 -mfpmath=sse:Both bounds come out rounded to nearest, so
interval<double>(1) / 3is the point interval[0.33333333333333331, 0.33333333333333331], which does not contain 1/3. Nothing reports an error.The original report on #23 reaches the same problem by a different route. The program's own arithmetic was x87, but it was linked against Intel's libm, whose
sqrtuses the SSE instructionsqrtsd. Sosqrtignored the rounding mode andtest_sqrtinmul.cppfailed. Compiler flags cannot work around this.Fix: use
fesetround, which also sets MXCSR.Issue #35: the library overwrites the user's settings
A program may deliberately change two things in the floating-point control registers:
feenableexcept(FE_DIVBYZERO)on Linux or_controlfp_s(&old, 0, _EM_ZERODIVIDE)on Windows, so that a division by zero stops the program immediately. This is useful for finding bugs.The library wrote the whole control word on every rounding change. After the first interval operation, every exception was masked again and precision was back to 64 bits, and nothing told the user.
That explains what the reporter of #35 saw. With exceptions unmasked,
width()traps on Linux x86-64, because that build usesfesetround, so the unmasked exception stays unmasked and fires. On Windows it never traps, because the MSVC code re-masks it. The same program behaves differently depending on the platform.The intended behaviour: the library changes the rounding bits and nothing else.
fesetrounddoes exactly that.Fix: the same change. On 32-bit GCC/Clang it fixes #23 and #35; on MSVC it fixes #35.
MSVC
__x86_64__is defined only by GCC and Clang. MSVC defines_M_X64instead, so it never took thefesetroundpath. It usedx86_rounding_control.hppwith the_control87code frommsvc_rounding_control.hpp._control87(new_value, mask)copies fromnew_valueonly the bits that are set inmask. The old call was:modeis the same constant as above (e.g.0x1b7ffor "up"), translated to Microsoft's bit layout. So it asks for "round up, all exceptions masked, 64-bit precision", and the mask lets all of it through. That is #35 on Windows. The only bits it should apply are_MCW_RC.What changes for MSVC:
boost/config/compiler/visualc.hppdefinesBOOST_NO_FENV_Honly before Visual Studio 2013. Every MSVC version in CI therefore has<fenv.h>, andx86_rounding_control.hppnow usesfesetroundthere, as it does for GCC and Clang.<fenv.h>, the_control87fallback now passes_MCW_RCalone. A CI job (msvc-14.3, no fenv) builds withBOOST_NO_FENV_Hdefined to test it.rintguard. On thefesetroundpath,c99sub_rounding_control.hppdeclaresextern "C" double rint(double)in namespacedetail.msvc_rounding_control.hppis included first and, on 32-bit MSVC, defines an inline C++rintin the same namespace. A C++-linkage declaration followed by a C-linkage one is a compile error, so MSVC's ownrintis now declared only whenBOOST_NO_FENV_His defined.Without
<fenv.h>on GCC, Clang and BorlandThe fallback still uses
fldcw(GCC/Clang) or_control87(Borland), but it now reads the control word, changes bits 10–11 and writes it back, instead of loading0x137fand friends. Exception masks and precision are left alone, as on thefesetroundpath. The x87 unit has no flush-to-zero bit, so nothing that matters for containment is lost. A CI job (GCC 32-bit, no fenv) tests it. Without<fenv.h>only the x87 unit gets the rounding mode, so SSE arithmetic in a 32-bit build still ignores it; x86-64 without<fenv.h>is already an#error.x87
long doubleand GCC 16An x87
long doubleneeds no rounding to memory, soforce_roundingfor it was an identity function, and nothing stopped the compiler from moving the computation past the next change of rounding mode. GCC 16 (MSYS2 MinGW32, release) moved the lower-bound division past thefesetroundthat restores the mode, sointerval<long double>(1)/3came out as a point interval. With GCC and Clang,force_roundingis now an empty asm that takes the value as an x87 register operand ("+t"), with a"memory"clobber; other compilers get thevolatileround trip used forfloatanddouble.Issue #41
det.cppfailed on MSYS2 MinGW32 because GCC 13 and later moved x87 arithmetic across the inlinefldcwat-O2, so one rounding variant came out narrower than correct rounding allows. Reproduced withg++-13 -m32 -O2 -std=c++03on Linux. Withfesetroundit passes. The MinGW32 CI job, disabled because of #41, is back.Behaviour change: x87 precision
The library no longer forces 64-bit x87 precision. On a platform whose default x87 precision is 53 bits,
interval<long double>results are now 53 bits wide instead of 64, but they still contain the true value. Linux, macOS and MinGW default to 64 bits, so nothing changes there; on MSVClong doubleisdouble.Tests
test/x86_rounding.cpp(new, x86 only): the rounding bits of the x87 word and of MXCSR after each mode change; exception masks and precision unchanged with divide-by-zero unmasked;to_intin every mode; directed1/3forfloat,doubleandlong double.test/rounding_mode.cpp: also run asrounding_mode_x86androunding_mode_sse(-msse2 -mfpmath=ssewith GCC/Clang).msvc-14.3, no fenv,GCC 32-bit, no fenv, and MSYS2gcc, MinGW32are new or restored.