仅在 2 的幂上错过了 clang 中的优化

Missed optimization in clang only on powers of two

本文关键字:clang 错过了 优化 仅在      更新时间:2023-10-16

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

int zero(bool b) {
    const int x = 5;
    return (x * b) + (-x * b);
}

编译为

zero(bool):                               # @zero(bool)
        xor     eax, eax
        ret

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

int zero(bool b) {
    const int x = 8;
    return (x * b) + (-x * b);
}

编译为

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

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

如果我将函数参数更改为更大的参数(短、整、长(,则优化正确。

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

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

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

相关文章: