| Issue |
241270
|
| Summary |
[clang] optnone forces FP contraction ON over -ffp-contract=off / FP_CONTRACT OFF (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
For an `optnone` function (or `#pragma clang optimize off`), clang sets FP contraction to ON, also when the user asked for OFF. The function gets `llvm.fmuladd`; at -O3 IPSCCP propagates constants into it and the fmuladd is folded as a fused FMA.
**Reproducer** (`repro.c`)
```c
/* With -ffp-contract=off, -57.0 * 503599627370497.0 must be rounded before the
subtraction. Correct output (gcc, clang -O0): -0x1.f3096650f1925p+54.
clang -O3 prints ...926p+54: the optnone function n() gets llvm.fmuladd. */
int printf(const char *, ...);
static double m(void) { return -57.0; }
__attribute__((optnone, noinline)) double n(void) { return m() * 503599627370497.0 - 6411408346866781.0; }
int main(void) { printf("%a\n", n()); return 0; }
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 -ffp-contract=off repro.c -o ./o0
$ ./o0
-0x1.f3096650f1925p+54
$ clang -O3 -ffp-contract=off repro.c -o ./o3
$ ./o3
-0x1.f3096650f1926p+54
```
Expected (as `-O0`): `-0x1.f3096650f1925p+54`. `-O3` prints `-0x1.f3096650f1926p+54` (fused).
**Why the expected output is right**
With FP_CONTRACT OFF (command line or pragma) each operation must round on its own; contraction is not allowed. Constants only, no overflow. UBSan/ASan/MSan at -O0 are clean. (On an FMA target a run-time variant is wrong at -O0 too.)
**Potential Root cause**
`clang/lib/Sema/SemaDecl.cpp`, `Sema::applyFunctionAttributesBeforeParsingBody`: for a function with `OptimizeNoneAttr` it calls `FPO.setDisallowOptimizations()`. `setDisallowOptimizations()` calls `setFPPreciseEnabled(true)`, which calls `setAllowFPContractWithinStatement()` = `setFPContractModeOverride(FPM_On)` unconditionally (`clang/include/clang/Basic/LangOptions.h`). So the user's OFF becomes ON. PR #91061 wanted optnone to match -O0, but plain -O0 keeps OFF.
**Possible Proposed fix**
```diff
if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
FPOptionsOverride FPO;
FPO.setDisallowOptimizations();
+ if (CurFPFeatures.getFPContractMode() == LangOptions::FPM_Off)
+ FPO.setDisallowFPContract();
CurFPFeatures.applyChanges(FPO);
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs