是否有任何内置函数告诉编译器分支是否可预测?

Are there any builtins to tell compiler whether a branch is predictable?

我不是在问 __builtin_expect 这样的事情。我在考虑这样一种情况,我不知道一个分支通常是真还是假,但我知道知道它是可预测(或不可预测)。

我希望编译器知道分支是可预测的,更有可能生成分支,并且知道它是不可预测的,更有可能生成没有分支的条件执行指令。

这在主要编译器中可行吗? (特别考虑 gcc 和 clang)。


解释为什么 "predictable" 和 "likely" 不是一回事的例子

int x = rand()%2;
while (true) {
    if (x) {
        // do something
    }
}

if 声明既不太可能也不太可能,但高度可预测。

while (true) {
    if (rand()%5 > 0) {
        // do something
    }
}

在这种情况下,情况恰恰相反:分支很有可能(在 80% 的时间内发生),但不可预测。

正在将我的评论转化为答案:

clang 有 __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