GCC 可以为具有相同主体的函数优化代码大小吗?

Can GCC optimize code size for functions with the same body?

我正在使用 GDB 调试 C++ 程序,发现不同的函数结果是一样的。这就是我的意思:

some.hpp

class Base{
   virtual bool foo() const;
   virtual bool bar() const;
}

some.cpp

bool Base::foo() const {
  return false;
}

bool Base::bar() const {
  return false;
}

问题是在 gdb 中我看到以下内容:

(gdb) p someBaseObject->foo
 = {bool (const Base * const)} 0xdeadf00d <Base::foo() const>
(gdb) p someBaseObject->bar
 = {bool (const Base * const)} 0xdeadf00d <Base::foo() const>

我想 GCC 优化了这两个函数以节省代码大小。可以?这虽然使调试复杂化...

如果您想知道某些东西是如何编译的,查看编译器资源管理器通常会很有帮助。

这是您的代码(同时调用了两个函数) https://gcc.godbolt.org/z/g2hfcA

为 "inter-procedural optimization Identical Code Folding" -fipa-icf 启用编译器标志时,您允许编译器替换相同的函数。这导致 bar 在程序集中消失。如果你用 -O3 编译,它也会被激活。

GCC doc on -fipa-icf:

-fipa-icf:

Perform Identical Code Folding for functions and read-only variables. The optimization reduces code size and may disturb unwind stacks by replacing a function by equivalent one with a different name. The optimization works more effectively with link-time optimization enabled.

Although the behavior is similar to the Gold Linker’s ICF optimization, GCC ICF works on different levels and thus the optimizations are not same - there are equivalences that are found only by GCC and equivalences found only by Gold.

This flag is enabled by default at -O2 and -Os.