已给予:
#include <string.h>
bool test_data(void *data)
{
return memcmp(data, "abcd", 4) == 0;
}
编译器可以将其优化为:
test_data:
cmpl $1684234849, (%rdi)
sete %al
ret
这很好.
但是如果我使用我自己的memcmp()
(不是来自<string.h>
),编译器就不能将其优化为一条cmpl
指令.相反,它会执行以下操作:
static int memcmp(const void *s1, const void *s2, size_t n)
{
const unsigned char *p1 = s1, *p2 = s2;
size_t i;
for (i = 0; i < n; i++) {
int ret = p1[i] - p2[i];
if (ret)
return ret;
}
return 0;
}
bool test_data(void *data)
{
return memcmp(data, "abcd", 4) == 0;
}
test_data:
cmpb $97, (%rdi)
jne .L5
cmpb $98, 1(%rdi)
jne .L5
cmpb $99, 2(%rdi)
jne .L5
cmpb $100, 3(%rdi)
sete %al
ret
.L5:
xorl %eax, %eax
ret
链接:https://godbolt.org/z/Kfhchr45a
- 是什么阻止了编译器进一步优化它?
- 我是不是做了什么阻碍了优化的事情?