[英]Why doesn't likely and unlikely macros have any effect on ARM assembly code?
I took below example from https://kernelnewbies.org/FAQ/LikelyUnlikely我从https://kernelnewbies.org/FAQ/LikelyUnlikely 中获取了以下示例
#include <stdio.h>
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
int main(char *argv[], int argc)
{
int a;
/* Get the value from somewhere GCC can't optimize */
a = atoi (argv[1]);
if (likely (a == 2))
a++;
else
a--;
printf ("%d\n", a);
return 0;
}
and compiled it https://godbolt.org/z/IC0aif with arm gcc 8.2 compiler
.并使用arm gcc 8.2 compiler
https://godbolt.org/z/IC0aif 。
In the original link, they have tested it for X86 and the assembly output is different if likely
(in the if condition in above code) is replaced with unlikely
, which shows the optimisation performed by compiler for branch prediction.在原始链接中,他们已经针对 X86 对其进行了测试,并且如果likely
(在上面代码中的 if 条件中)替换为unlikely
,则汇编输出是不同的,这显示了编译器为分支预测执行的优化。
But when I compile the above code for ARM (arm-gcc -O2), I don't see any difference in assembly code.但是当我为 ARM (arm-gcc -O2) 编译上面的代码时,我没有看到汇编代码有任何区别。 Below is the output of ARM assembly in both the case - likely
and unlikely
以下是两种情况下 ARM 程序集的输出 - likely
和unlikely
main:
push {r4, lr}
ldr r0, [r0, #4]
bl atoi
cmp r0, #2
subne r1, r0, #1
moveq r1, #3
ldr r0, .L6
bl printf
mov r0, #0
pop {r4, pc}
.L6:
.word .LC0
.LC0:
.ascii "%d\012\000"
Why doesn't the compiler optimize for branch prediction in case of ARM ?在 ARM 的情况下,为什么编译器不针对分支预测进行优化?
As @rici said, your code is simple enough that it can be realized by conditional instructions.正如@rici 所说,您的代码足够简单,可以通过条件指令来实现。 You can see a difference, eg, if you call functions which are implemented in a different compilation unit:您可以看到不同之处,例如,如果您调用在不同编译单元中实现的函数:
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
// only forward declarations:
void foo();
void bar();
int main(char *argv[], int argc)
{
if (likely (argc == 2))
foo();
else
bar();
}
Changing likely
to unlikely
switches the order of the if
and else
branch, for ARM and x86: https://godbolt.org/z/UDzvf0 .对于 ARM 和 x86,更改likely
unlikely
切换if
和else
分支的顺序: https : //godbolt.org/z/UDzvf0 。 If this really makes a difference likely depends on the hardware you are running on, whether you call the function the first time (otherwise, the CPU-internal branch prediction likely has a higher influence than the order of the instructions), and probably many other things.如果这真的有所不同,可能取决于您正在运行的硬件,您是否第一次调用该函数(否则,CPU 内部分支预测的影响可能比指令的顺序更大),以及可能还有许多其他事物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.