gpt4 book ai didi

c - GCC Optimization 删除了函数 Prologue 和 Epilogue

转载 作者:太空狗 更新时间:2023-10-29 15:02:31 24 4
gpt4 key购买 nike

采用空程序

//demo.c

int main(void)
{

}

在默认优化下编译程序。

gcc -S  demo.c -o dasm.asm 

我得到程序集输出为

//Removed labels and directive which are not relevant

main:

pushl %ebp // prologue of main
movl %esp, %ebp // prologue of main
popl %ebp // epilogue of main
ret

现在在-O2 优化下编译程序。

gcc -O2 -S  demo.c -o dasm.asm 

我得到了优化的程序集

main:

rep
ret

在我最初的搜索中,我发现优化标志 -fomit-frame-pointer 负责删除序言和结尾。

我在 gcc compiler manual 中找到了有关该标志的更多信息.但是无法理解下面手册给出的删除序言和结语的原因。

Don't keep the frame pointer in a register for functions that don't need one.

有没有其他的方式来表达上述原因?

"rep" 指令出现在-02 优化处的原因是什么?

为什么 main 函数不需要堆栈帧初始化?

如果帧指针的设置不是在主函数中完成的,那么这个工作由谁来完成?

它是由操作系统完成的还是硬件的功能?

最佳答案

编译器变得越来越聪明,它知道您不需要将堆栈帧指针存储在寄存器中,因为无论您放入 main() 函数中的什么都不会使用堆栈。

至于代表:

Here's the principle. The processor tries to fetch the next few instructions to be executed, so that it can start the process of decoding and executing them. It even does this with jump and return instructions, guessing where the program will head next.

What AMD says here is that, if a ret instruction immediately follows a conditional jump instruction, their predictor cannot figure out where the ret instruction is going. The pre-fetching has to stop until the ret actually executes, and only then will it be able to start looking ahead again.

The "rep ret" trick apparently works around the problem, and lets the predictor do its job. The "rep" has no effect on the instruction.

来源:某论坛,google一句话找到。

需要注意的一点是,没有序言并不意味着没有堆栈,您仍然可以轻松地压入和弹出,只是复杂的堆栈操作会很困难。

没有序言/结尾的函数通常被称为。黑客们非常喜欢使用它们,因为当你跳转到它们时它们不会污染堆栈,我必须承认我知道除了优化之外它们没有其他用途。在 Visual Studio 中,它是通过以下方式完成的:

__declspec(naked)

关于c - GCC Optimization 删除了函数 Prologue 和 Epilogue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15563427/

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