I'm not asking about things like __builtin_expect
. I'm thinking of the case where I don't know that a branch will be usually true or usually false, but I do know that it's predictable (or not).
I would expect the compiler, knowing a branch is predictable, to be more likely to generate branches, and knowing it's unpredictable, to be more likely to generate conditionally-executed instructions with no branches.
Is this possible in major compilers? (Thinking specifically of gcc and clang).
Examples explaining why "predictable" and "likely" are not the same thing
int x = rand()%2;
while (true) {
if (x) {
// do something
}
}
The if
statement is neither likely or unlikely, but highly predictable.
while (true) {
if (rand()%5 > 0) {
// do something
}
}
In this case, the opposite is true: the branch is highly likely (taken 80% of the time), but unpredictable.
Converting my comment into an answer:
clang has __builtin_unpredictable
:
__builtin_unpredictable
is used to indicate that a branch condition is unpredictable by hardware mechanisms such as branch prediction logic.Example of use:
if (__builtin_unpredictable(x > 0)) { foo(); }
https://clang.llvm.org/docs/LanguageExtensions.html#builtin-unpredictable