仅以2的幂幂错过了clang中的优化

spy*_*r03 9 c++ x86 clang compiler-optimization

使用-Ofast进行编译时,clang正确推断出以下函数将始终返回0。

int zero(bool b) {
    const int x = 5;
    return (x * b) + (-x * b);
}
Run Code Online (Sandbox Code Playgroud)

编译为

zero(bool):                               # @zero(bool)
        xor     eax, eax
        ret
Run Code Online (Sandbox Code Playgroud)

但是,如果将常数更改为2的任意幂(1或0除外),则clang不再进行相同的推论

int zero(bool b) {
    const int x = 8;
    return (x * b) + (-x * b);
}
Run Code Online (Sandbox Code Playgroud)

编译为

zero(bool):                               # @zero(bool)
        mov     eax, edi
        shl     eax, 3
        xor     dil, 1
        movzx   ecx, dil
        lea     eax, [rax + 8*rcx]
        add     eax, -8
        ret
Run Code Online (Sandbox Code Playgroud)

用编译器资源管理器编译的代码。

如果我将函数参数更改为更大的值(short,int,long),则会正确进行优化。

是什么导致这种奇怪的边缘情况?

Nej*_*lof 2

这是Clang中的一个优化问题,在10.0.0版本之后修复。我们可以在9.0.1版本中重现这个问题。

在编译器资源管理器中比较了版本 9.0.1 和 10.0.0 。