在OSX High Sierra上使用clang编译-O3代码时,我遇到了一个有趣的问题。代码是这样的:
#include <stdint.h>
#include <limits.h> /* for CHAR_BIT */
#include <stdio.h> /* for printf() */
#include <stddef.h> /* for size_t */
uint64_t get_morton_code(uint16_t x, uint16_t y, uint16_t z)
{
/* Returns the number formed by interleaving the bits in x, y, and z, also
* known as the morton code.
*
* See https://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableO
bvious.
*/
size_t i;
uint64_t a = 0;
for (i = 0; i < sizeof(x)*CHAR_BIT; i++) {
a |= (x & 1U << i) << (2*i) | (y & 1U << i) << (2*i + 1) | (z & 1U << i)
<< (2*i + 2);
}
return a;
}
int main(int argc, char **argv)
{
printf("get_morton_code(99,159,46) = %llun", get_morton_code(99,159,46));
return 0;
}
使用 cc -O1 -o test_morton_code test_morton_code.c
编译时,我得到以下输出:
get_morton_code(99,159,46) = 4631995
这是正确的。但是,使用 cc -O3 -o test_morton_code test_morton_code.c
编译时:
get_morton_code(99,159,46) = 4294967295
这是错误的。
同样奇怪的是,当从-O2
切换到-O3
时,此错误出现在我的代码中,而在上面的最小工作示例中,当从-O1
切换到-O2
时,它会出现。
这是编译器优化中的错误,还是我在做一些愚蠢的事情,只有在编译器更积极地优化时才会出现?
我正在使用以下版本的 clang:
snotdaqs-iMac:snoFitter snoperator$ cc --version
Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
UndefinedBehaviorSanitizer 在捕获此类错误方面非常有帮助:
$ clang -fsanitize=undefined -O3 o3.c
$ ./a.out
o3.c:19:2: runtime error: shift exponent 32 is too large for 32-bit type 'unsigned int'
get_morton_code(99,159,46) = 4294967295
一个可能的解决方法是用1ULL
替换1U
s,unsigned long long
至少是64位,可以移动那么远。
当循环中的i
为 15 时,2*i+2
为 32,并且您正在按未定义的unsigned int
中的位数移动unsigned int
。
您显然打算在 64 位字段中工作,因此将移位的左侧转换为 uint64_t
。
uint64_t
的适当printf
格式是 get_morton_code(99,159,46) = %" PRIu64 "n"
。 PRIu64
在<inttypes.h>
标头中定义。