Search code examples
c++gccintelpragmabranch-prediction

Is there a compiler hint for GCC to force branch prediction to always go a certain way?


For the Intel architectures, is there a way to instruct the GCC compiler to generate code that always forces branch prediction a particular way in my code? Does the Intel hardware even support this? What about other compilers or hardwares?

I would use this in C++ code where I know the case I wish to run fast and do not care about the slow down when the other branch needs to be taken even when it has recently taken that branch.

for (;;) {
  if (normal) { // How to tell compiler to always branch predict true value?
    doSomethingNormal();
  } else {
    exceptionalCase();
  }
}

As a follow on question for Evdzhan Mustafa, can the hint just specify a hint for the first time the processor encounters the instruction, all subsequent branch prediction, functioning normally?


Solution

  • As of C++20 the likely and unlikely attributes should be standardized and are already supported in g++9. So as discussed here, you can write

    if (a > b) {
      /* code you expect to run often */
      [[likely]] /* last statement here */
    }
    

    e.g. in the following code the else block gets inlined thanks to the [[unlikely]] in the if block

    int oftendone( int a, int b );
    int rarelydone( int a, int b );
    int finaltrafo( int );
    
    int divides( int number, int prime ) {
      int almostreturnvalue;
      if ( ( number % prime ) == 0 ) {
        auto k                         = rarelydone( number, prime );
        auto l                         = rarelydone( number, k );
        [[unlikely]] almostreturnvalue = rarelydone( k, l );
      } else {
        auto a            = oftendone( number, prime );
        almostreturnvalue = oftendone( a, a );
      }
      return finaltrafo( almostreturnvalue );
    }
    

    godbolt link comparing the presence/absence of the attribute