Author Topic: Square root. Why GCC behave like this?  (Read 5022 times)

Offline fredericopissarra

  • Full Member
  • **
  • Posts: 368
  • Country: br
Square root. Why GCC behave like this?
« on: April 10, 2019, 02:55:01 AM »
Does anybody knows why GCC create code behave like this for a simple call to sqrtf()? (x86-64 SysV ABI calling convetion):

Code: [Select]
; float f(float x) { return sqrt(x); }
f:
  pxor    xmm2,xmm2
  sqrtss  xmm1,xmm0
  ucomiss xmm2,xmm0
  ja      .L8
  movaps  xmm0,xmm1
  ret
.L8:
  sub     rsp,24
  movss   dword [rsp+12],xmm1
  call    sqrtf
  movss   xmm1,dword [rsp+12]
  add     rsp,24
  movaps  xmm0,xmm1
  ret

Notice, when x < 0, xmm1, which is the result of sqrtss instruction, is saved on stack; the library function sqrtf() is called, but xmm1 is restored from stack again and copied to xmm0...

The questions: Why the test? Why calling sqrtf and discarding the returned value from xmm0, reusing xmm1 got from sqrtss?

And, btw, sqrtss and sqrtf() calls gave me the same results for invalid values, i.e: -1.0, NAN, -NAN, INFINITY and -INFINITY... I didn't test for sNaN.

This kind of behavior happens, also, with fp87 instructions... Any thoughts?
« Last Edit: April 10, 2019, 02:59:40 AM by fredericopissarra »