I'm writing a C function float foo(float x)
which manipulates a floating-point value. It so happens, that I can guarantee the function will only ever be called with finite values - neither NaN's, nor +inf, nor -inf. Is it possible to "tell" this to the compiler (without actually doing runtime work which ensures it, like comparing, or zeroing bits and such)? For it to be able to optimize the code based on that assumption?
Notes:
_Float16
/float16_t
, double
, long double
.Compiler | Compile-time Assumption | In-Code Hint | Denormal Control |
---|---|---|---|
GCC ≥13 | -ffinite-math-only |
stop excution using __builtin_unreachable() |
Use FTZ/DAZ or -ffast-math |
Clang | -ffinite-math-only |
__builtin_assume() , __attribute__((assume)) |
Same as GCC |
MSVC | /fp:fast |
__assume(_finite(x)) |
Flush-to-zero set via flags or code |
Examples:
#include <math.h>
float foo(float x) {
__builtin_assume(isfinite(x));
// or: __builtin_assume(!isnan(x) && x != INFINITY && x != -INFINITY);
// Now x is assumed finite
return x * 2.0f;
}
__attribute__((assume("finite-arg"))) float foo(float x);
clang -O2 -ffinite-math-only -fno-trapping-math foo.c -o foo
gcc -O2 -ffinite-math-only -fno-trapping-math foo.c -o foo
float foo(float x) {
__assume(_finite(x));
return x * 2.0f;
}