2

In the GCC built-ins description, it says:

GCC provides built-in versions of the ISO C99 floating-point comparison macros that avoid raising exceptions for unordered operands. They have the same names as the standard macros ( isgreater, isgreaterequal, isless, islessequal, islessgreater, and isunordered) , with _builtin prefixed. We intend for a library implementor to be able to simply #define each standard macro to its built-in equivalent. In the same fashion, GCC provides fpclassify, isfinite, isinf_sign, isnormal and signbit built-ins used with _builtin prefixed. The isinf and isnan built-in functions appear both with and without the _builtin prefix.

So, I'm not quite able to parse this. When should floating-point comparisons raise exceptions? Does the C standard mandate they do? Mandate they don't? Doesn't mandate anything? And - does __builtin_isnan() act differently than isnan() ?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

2

By exception here, the GCC docs refer to IEEE 754 floating point exceptions. If you do something like

a < b

and one of the operands is a NaN, an FP exception (invalid) will be raised. That means a bit in the FPU will remain set until it's explicitly cleared by the programmer. By instead using isgreater/isless/etc. the programmer can avoid triggering the FP exception.

janneb
  • 36,249
  • 2
  • 81
  • 97
  • So, the "exception" text only regards LT/GT/LTE/GTE, and not anything else? i.e. not isnan ? – einpoklum Jun 28 '21 at 13:48
  • Yes, my interpretation of the text you quoted is that GCC provides the other builtins so that standard library implementations can use it, and the exception part applies only to the comparisons. – janneb Jun 28 '21 at 13:57
  • Interpretation is fine, but... I want to know this for certain. – einpoklum Jun 28 '21 at 14:09
  • 1
    If you want something more authoritative than the docs I suggest you write up a few small test programs and see how it behaves and what kind of ASM it generates, or look at the compiler sources (I'd guess the first place to look for would be grepping for BUILT_IN_ISNAN in gcc/builtins.c). – janneb Jun 28 '21 at 22:10
  • Good idea. I made the mistake of trying to look isnan() up in the glibc sources and gout discouraged :-( – einpoklum Jun 28 '21 at 22:13
  • (To be fair, neither glibc nor gcc sources are particularly easy to get into as an outsider) For an example test program and the ASM generated, see e.g. https://godbolt.org/z/54Er63aPc – janneb Jun 28 '21 at 22:25