gpt4 book ai didi

c - 为什么 ret 会随着优化而消失?

转载 作者:行者123 更新时间:2023-12-05 00:11:41 24 4
gpt4 key购买 nike

int suma(int* array, int len)
{
asm(" xor %eax, %eax # resultado = 0 \n"
" xor %edx, %edx # i = 0 \n"
"1: add (%rdi,%rdx,4), %eax # res += array[i] \n"
" inc %edx # ++i \n"
" cmp %edx,%esi # i < len? \n"
" jne 1b # repetir \n"
// " ret \n"
);
}

int main()
{
int v[100];
return suma(v, 100);
}

为什么gcc插入 retsuma()-O0 ,但我必须自己在 -O3 上添加它?

来自 gcc -v :

gcc version 8.2.1 20181011 (Red Hat 8.2.1-4) (GCC) 

最佳答案

I assume 64bit..., array in rdi, len in esi.



您正在使用内联汇编,而不是在 __attribute__((naked,noinline)) 中函数,因此编译器可以在它想要的任何上下文中使用内联 asm 模板块。由于您没有使用任何输入/输出约束,并且您在不告诉编译器的情况下破坏了寄存器,除非您禁用优化,否则它将完全中断。

为了回答主要问题,编译器只需内联 suma进入 main .这是隐含的 volatile (因为它是一个基本的 asm 语句)所以它没有被优化掉。

但是执行在非空函数 ( suma ) 的末尾结束,这是未定义的行为 ,所以现代 GCC 只是放弃并省略了 ret操作说明。它假定执行永远不会采用该路径(因为未定义的行为),并且不会为它生成代码。

如果您添加 return 0;到最后 suma ,然后 main将以 ret 结尾操作说明。

令人惊讶的是, gcc only gives one warning on the Godbolt compiler explorer with -O3 -Wall :
<source>: In function 'int suma(int*, int)':
<source>:13:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
main 的结果 asm 输出是这样的,这当然完全坏了,因为 RDI 是 argc ;它从不为 int v[100] 保留空间因为它在 C 源代码中未使用或做过任何事情。
main:
xor %eax, %eax # resultado = 0
xor %edx, %edx # i = 0
1: add (%rdi,%rdx,4), %eax # res += array[i]
inc %edx # ++i
cmp %edx,%esi # i < len?
jne 1b # repetir

return 0;suma ,它和主要结束于 xorl %eax, %eax ; ret , 但当然 main仍然完全损坏,因为内联 asm 不使用任何输入约束。

关于c - 为什么 ret 会随着优化而消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52966290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com