gustavo
gustavo

Reputation: 138

Why g++ does not optimize this code removing the division (s / s)?

code example compiled with -O3 and -fno-inline in godbolt: https://godbolt.org/z/4rvxccsns

template <class T>
T numbbo(T r, unsigned s) {
    return 10.0 / (static_cast<float>(s) / static_cast<float>(s)) * (-1.0 + r);
}

int main(int argc, char **argv) {
    return numbbo(static_cast<float>(argc), argc) +
           numbbo(static_cast<double>(argc), argc);
}

Upvotes: 2

Views: 130

Answers (1)

A. K.
A. K.

Reputation: 38098

A more reduced example is

float numbbo(float r) {
    return r/r;
}

and the compiler won't optimized it as explained with reasons in the comments. The compiler generates

numbbo(float):
divss   xmm0, xmm0
ret

which is the best it can do to preserve the expected behavior.

Adding -Ofast will remove the division altogether.

numbbo(float):
        movss   xmm0, DWORD PTR .LC0[rip]
        ret
.LC0:
        .long   1065353216

Upvotes: 0

Related Questions