https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66573

--- Comment #2 from Jason McG <jmcguiness at liquidcapital dot com> ---
If I try with this code:

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

extern void bar1();
extern void bar2();

void foo(bool i) {
//  if (i)
  if (likely(i))
        bar1();
  else
    bar2();
}

Then the assembly output for gcc 4.8.2 & 5.10 (the ones I tested) for -O0, -O1,
-O2 & -O3 is the same:

foo(bool):
        testb   %dil, %dil
        je      .L2
        jmp     bar1()
.L2:
        jmp     bar2()

i.e. gcc now behaves as per icc and clang++. So using __builtin_expect seems to
be a work-around to get gcc to behave like other compilers.

I would sincerely hope that at least the documentation for these optimisation
options warns the programmer that gcc optimises if-else statements in the
reverse manner to other major compilers and even across it's own optimisation
levels (!), as this apparent change in behaviour is most unexpected...

Reply via email to