我有一个只包含以下内容的 cpp 文件:
void f(int* const x)
{
(*x)*= 2;
}
我编译:
g++ -S -masm=intel -O3 -fno-exceptions -fno-asynchronous-unwind-tables f.cpp
这导致 f.s
包含:
.section __TEXT,__text,regular,pure_instructions
.macosx_version_min 10, 12
.intel_syntax noprefix
.globl __Z1fPi
.p2align 4, 0x90
__Z1fPi: ## @_Z1fPi
## BB#0:
push rbp
mov rbp, rsp
shl dword ptr [rdi]
pop rbp
ret
.subsections_via_symbols
如果我删除 push
、mov
和 pop
指令并进行汇编(在 mac 上,我使用的是 Clang),则生成的目标文件小 4 个字节。链接和执行会导致相同的行为和相同大小的可执行文件。
这表明这些指令是多余的——为什么编译器要费心把它们放进去?这仅仅是留给链接器的优化吗?
最佳答案
CLANG/CLANG++ 既是原生编译器又是支持多目标的交叉编译器。在 OS/X 上,默认情况下目标通常是 x86_64-apple-darwin
的变体(用于 64 位代码)和 i386-apple-darwin
用于 32 位代码。您看到的代码类似于这种形式:
push rbp
mov rbp, rsp
[snip]
pop rbp
ret
是为了引入栈帧而产生的。默认情况下 CLANG++ implicitly enables stack frames for the Apple Darwin targets .这不同于 x86_64-linux-gnu
和 i386-linux-gnu
等 Linux 目标。堆栈框架对于某些分析和展开库来说非常方便,并且可以帮助在 OS/X 平台上进行调试,这就是我相信他们选择默认打开它们的原因。
您可以使用 -fomit-frame-pointer
选项显式省略 CLANG++ 的帧指针。如果你使用构建命令
g++ -S -masm=intel -O3 -fno-exceptions -fno-asynchronous-unwind-tables \
-fomit-frame-pointer f.cpp
输出类似于:
shl dword ptr [rdi]
ret
查看具有不同目标的代码
如果您对 CLANG++ 使用不同的目标,您会发现行为是不同的。这是一个 x86-64 Linux 目标,我们没有明确省略帧指针:
clang++ -target x86_64-linux-gnu -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables f.cpp
生成:
shl dword ptr [rdi]
ret
这是您的原始 x86-64 Apple Darwin 目标:
clang++ -target x86_64-apple-darwin -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables f.cpp
生成:
push rbp
mov rbp, rsp
shl dword ptr [rdi]
pop rbp
ret
然后是省略了帧指针的 x86-64 Apple 目标:
clang++ -target x86_64-apple-darwin -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables -fomit-frame-pointer f.cpp
生成:
shl dword ptr [rdi]
ret
您可以在 Godbolt 上对这些目标进行比较.生成代码的第一列类似于问题 - Apple target with implicit frame pointers。第二个是没有帧指针的 Apple 目标,第三个是 x86-64 Linux 目标。
关于c++ - 汇编的 c++ 似乎包含多余的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43792447/