22

Suppose i have:

double f(const double *r) {
    return 0*(r[0]*r[1]);
}

should compiler be able to optimize out the segment, or does it still have to perform operation, in case the values might be inf or nan?

gcc -O3 -S test.c:

        .file   "test.c"
        .text
        .p2align 4,,15
.globl f
        .type   f, @function
f:
.LFB0:
        .cfi_startproc
        movsd   (%rdi), %xmm0
        mulsd   8(%rdi), %xmm0
        mulsd   .LC0(%rip), %xmm0
        ret
        .cfi_endproc
.LFE0:
        .size   f, .-f
        .section        .rodata.cst8,"aM",@progbits,8
        .align 8
.LC0:
        .long   0
        .long   0
        .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
        .section        .note.GNU-stack,"",@progbits

seems no elimination?

aha:

gcc -O3  -ffast-math  -S test.c

        .file   "test.c"
        .text
        .p2align 4,,15
.globl f
        .type   f, @function
f:
.LFB0:
        .cfi_startproc
        xorpd   %xmm0, %xmm0
        ret
        .cfi_endproc
.LFE0:
        .size   f, .-f
        .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
        .section        .note.GNU-stack,"",@progbits
Anycorn
  • 48,681
  • 42
  • 161
  • 257

2 Answers2

14

It isn't only inf and NaN that prevent the optimization there, it's also the sign - 0.0 * something negative is -0.0, otherwise it's 0.0, so you actually have to compute the sign of r[0]*r[1].

etarion
  • 16,415
  • 4
  • 42
  • 65
13

Depends on whether the compiler implements IEEE754. Neither C nor C++ requires that a compiler supports NaN, but IEEE754 does.

MSalters
  • 167,472
  • 9
  • 150
  • 334