一位同事向我展示了我认为没有必要的代码,但果然,这是必要的。我希望大多数编译器会将所有这三种相等测试尝试视为等效:
#include <cstdint>
#include <cstring>
struct Point {
std::int32_t x, y;
};
[[nodiscard]]
bool naiveEqual(const Point &a, const Point &b) {
return a.x == b.x && a.y == b.y;
}
[[nodiscard]]
bool optimizedEqual(const Point &a, const Point &b) {
// Why can't the compiler produce the same assembly in naiveEqual as it does here?
std::uint64_t ai, bi;
static_assert(sizeof(Point) == sizeof(ai));
std::memcpy(&ai, &a, sizeof(Point));
std::memcpy(&bi, &b, sizeof(Point));
return ai == bi;
}
[[nodiscard]]
bool optimizedEqual2(const Point &a, const Point &b) {
return std::memcmp(&a, &b, sizeof(a)) == 0;
}
[[nodiscard]]
bool naiveEqual1(const Point &a, const Point &b) {
// Let's try avoiding any jumps by using bitwise and:
return (a.x == b.x) & (a.y == b.y);
}
但令我惊讶的是,只有那些memcpy
or memcmp
由 GCC 转换为单个 64 位比较。为什么? (https://godbolt.org/z/aP1ocs https://godbolt.org/z/aP1ocs)
对于优化器来说,如果我检查连续的四个字节对的相等性,这与比较所有八个字节相同,这不是很明显吗?
尝试避免分别对两个部分进行布尔化可以在某种程度上提高编译效率(减少一条指令并且不会错误地依赖 EDX),但仍然是两个独立的 32 位操作。
bool bithackEqual(const Point &a, const Point &b) {
// a^b == 0 only if they're equal
return ((a.x ^ b.x) | (a.y ^ b.y)) == 0;
}
GCC 和 Clang 在传递结构时都有相同的错过优化value (so a
在 RDI 中并且b
位于 RSI 中,因为这就是 x86-64 System V 的调用约定将结构打包到寄存器中的方式):https://godbolt.org/z/v88a6s https://godbolt.org/z/v88a6s。 memcpy / memcmp 版本都编译为cmp rdi, rsi
/ sete al
,但其他的则执行单独的 32 位操作。
struct alignas(uint64_t) Point
令人惊讶的是,在参数位于寄存器中的按值情况下仍然有帮助,优化了 GCC 的 naiveEqual 版本,但不是 bithack XOR/OR。 (https://godbolt.org/z/ofGa1f https://godbolt.org/z/ofGa1f)。这是否给我们提供了有关 GCC 内部结构的任何提示?对齐对 Clang 没有帮助。