1

I stumbled upon this problem here on stackoverflow: When not compiled with -ffast-math the sqrt-function was not inlined and thus libm was needed at link time.

However, I don't understand what is preventing the compilers (clang as well as gcc) from inlining the sqrt-function without the -ffast-math.

Compiling

#include <cmath>
double my_sqrt(double val){
  return sqrt(val);
}

with clang and -02 yields (similar with gcc, even if gcc's result doesn't look optimal to me):

my_sqrt(double):                            # @my_sqrt(double)
        sqrtsd  %xmm0, %xmm1
        ucomisd %xmm1, %xmm1
        jp      .LBB0_2
        movapd  %xmm1, %xmm0
        retq
.LBB0_2:
        jmp     sqrt                    # TAILCALL

As I understand it, a build-in sqrt-function/CPU-instruction (sqrtsd) is called and if result is NaN (PF-flag is set for ucomisd) the library-version is used.

Maybe I'm mistaken, but NaN is the result if argument is negative, so what could the library-sqrt-function do better as to return a NaN? Why to call it then?

ead
  • 32,758
  • 6
  • 90
  • 153
  • `sqrt()` has to set `errno` on NaN. Use `-fno-math-errno` to omit conforming with this bad design decision that hardly any code ever wants. – Peter Cordes Nov 06 '17 at 14:29
  • @MichaelPetch In the linked question the answer must be somewhere along `It's using the library sqrt function for error handling.` but that seems to be a little bit curtly – ead Nov 06 '17 at 14:32
  • I just finished expanding Jester's answer there to explain it better. It's only to preserve the clunky `errno`-setting behaviour of the `sqrt()` library function that nobody cares about. So use `-fno-math-errno`. – Peter Cordes Nov 06 '17 at 14:43
  • 1
    'As I understand it, a build-in sqrt-function (sqrtsd) is called' - it does not call function, sqrtsd is CPU instruction. – Anty Nov 07 '17 at 11:31

0 Answers0