' i%2 == 0'在Clang和GCC之间,为什么会这样编译?

发布于 2025-02-02 16:06:53 字数 925 浏览 1 评论 0 原文

我很好奇编译器是否对 n%&lt;的代码进行了明显的优化。等于 /不等于0 < / code>。确实他们确实如此,但是有一些有趣的细微差别,所以这里有两个问题:

  1. 对于 i%2 的情况,GCC和MSVC的产生似乎比Clang更复杂( https://godbolt.org/z/kawryoz1a ),但对于4、8、16的因素的输出相等 - 更简单 - 输出?

clang输出(预期):

test    dil, 1
sete    al

GCC输出:

mov     rax, rdi
not     rax
and     eax, 1

MSVC相同,但 MOV /不是之间的不同顺序。

  1. 为什么MSVC为4/8的签名整数(32和64位)生成更复杂的代码()? Clang和GCC不受签名的影响。
mov     rax, rcx
cdq
and     edx, 3
add     rax, rdx
and     eax, 3
cmp     rax, rdx
sete    al

为什么MSVC仍会为2个因素产生简单的代码?

PS这些编译器处于最大O级别,但我没有指定任何架构( -March )标志。

I was curious whether the compilers do the obvious optimization for code like N % <some factor of 2> equals / not equals 0. Indeed they do, but there are some interesting nuances, so here are two questions:

  1. Why do GCC and MSVC produce seemingly more complex output than clang for the case of i % 2 (https://godbolt.org/z/KaWrYoz1a), but equal - simpler - output for the factors of 4, 8, 16?

clang output (expected):

test    dil, 1
sete    al

GCC output:

mov     rax, rdi
not     rax
and     eax, 1

MSVC is the same, but different order between mov / not.

  1. Why does MSVC produce much more complex code for signed integers (both 32 and 64-bit) for factors of 4 / 8 (https://godbolt.org/z/xP1qcch8q)? Clang and GCC are unaffected by signedness.
mov     rax, rcx
cdq
and     edx, 3
add     rax, rdx
and     eax, 3
cmp     rax, rdx
sete    al

And why does MSVC still produce the simple code for the factor of 2?

P. S. The compilers are at their maximum O level, but I am not specifying any architecture (-march) flags.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文