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

            Bug ID: 105973
           Summary: Wrong branch prediction for if (COND) { if(x)
                    noreturn1(); else noreturn2(); }
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
  Target Milestone: ---

Given this code:

__attribute__((noreturn)) void throw1();
__attribute__((noreturn)) void throw2();

typedef decltype(sizeof(0)) size_t;

#if defined LIKELY
# define PREDICT(C) __builtin_expect(C,1)
#elif defined UNLIKELY
# define PREDICT(C) __builtin_expect(C,0)
#else
# define PREDICT(C) (C)
#endif

template<typename T>
T* allocate(size_t n)
{
  if (PREDICT(n > (__PTRDIFF_MAX__ / sizeof(T))))
  {
    if (n > (__SIZE_MAX__ / sizeof(T)))
      throw1();
    throw2();
  }

  return (T*) ::operator new(n * sizeof(T));
}

int* alloc_int(size_t n)
{
  return allocate<int>(n);
}


The condition decorated with PREDICT is compiled to different code with
-DLIKELY and -DUNLIKELY, as expected.

However with neither macro defined, the result is the same as -DLIKELY (for any
optimization level > -O0). i.e. the calls to throw1 and throw1 come first and
the return statement requires a branch:

_Z9alloc_intm:
.LFB1:
        .cfi_startproc
        movq    %rdi, %rax
        shrq    $61, %rax
        je      .L2
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        shrq    $62, %rdi
        je      .L3
        call    _Z6throw1v
        .p2align 4,,10
        .p2align 3
.L3:
        call    _Z6throw2v
        .p2align 4,,10
        .p2align 3
.L2:
        .cfi_def_cfa_offset 8
        salq    $2, %rdi
        jmp     _Znwm
        .cfi_endproc


Surely this is wrong?

If calling a noreturn function is considered unlikely, then surely entering a
block that always calls a noreturn function should also be unlikely?

Clang gets this right, generating the same code as UNLIKELY by default, and
only requiring a branch for the return value when LIKELY is defined.


This code is reduced from std::allocator in libstdc++ and I thought I should be
able to remove a redundant __builtin_expect, but it's needed due to this.

Reply via email to