GCC 可以从最终输出中消除什么样的死代码? [英] What kind of dead code can GCC eliminate from the final output?

查看:17
本文介绍了GCC 可以从最终输出中消除什么样的死代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直被告知编译器足够聪明,可以消除死代码.我正在编写的大部分代码在编译时都有很多已知信息,但代码必须以最通用的形式编写.我不知道任何程序集,所以我无法检查生成的程序集.在最终的可执行文件中可以有效地消除什么样的代码?

I have always been told that compiler is sufficient smart to eliminate dead code. Much of the code that I am writing has a lot of information known at compile time but the code has to be written in most generic form. I don't know any assembly so I cannot examine the generated assembly. What kind of code that can be effectively eliminated in the final executable?

几个例子但不限于

f(bool b){
 if(b){
  //some code
 }else{
  //some code
 }
}
f(true);
//////////////////////////
template<bool b>
f(){
 if(b){
  //some code
 }else{
  //some code
 }
}
f<true>();
///////////////////////////

如果f的定义在其他目标代码中,而被调用的f(true)在main中怎么办?链接时间优化会有效消除死代码吗?促进消除死代码的编码风格/编译器选项/技巧是什么?

What if definition of f is in other objective code and the the called f(true) is in main. Will link time optimisation effectively eliminate the dead code? What is the coding style/compiler option/trick to facilitate dead code elimination?

推荐答案

通常,如果您使用 以下标志上的-O标志被开启:

Typically, if you're compiling with the -O flag on the following flags are turned on:

      -fauto-inc-dec 
      -fcompare-elim 
      -fcprop-registers 
      -fdce  
      [...]

-fdce 代表死代码消除.我建议您编译您的二进制文件时使用或不使用(即通过显式关闭)此选项,以确保您的二进制文件是否按照您希望的那样优化.

-fdce stands for Dead Code Elimination. I'd suggest you compile your binaries with and without (i.e. by turning off explicitly) this option to make sure if your binaries are as optimized as you'd like them to be.

了解编译器的不同阶段:

  • SSA 积极的死代码消除.由 `-fssa-dce' 打开选项.此遍执行消除被认为不必要的代码因为它对程序没有外部可见的影响.它以线性时间运行.

至于帮助链接器消除死代码通过 此演示文稿.两个主要的收获是:

As for helping the linker with dead code elimination go through this presentation. Two major takeaways being:

用 -ffunction-sections -fdata-sections 编译你的模块——那里没有缺点!

Compile your modules with -ffunction-sections -fdata-sections – there are no downsides to it!

  • 这包括静态库,而不仅仅是二进制文件——让图书馆的用户受益于更有效地去除死代码.
  • 将您的二进制文件与--gc-sections,除非您必须链接到使用魔术部分的讨厌的第三方静态库.

您可能还想看看 这个 GCC 错误(查看可能会错过哪些优化机会以及原因).

You may also want to take a look at this GCC bug (to see what chances of optimization may be missed and why).

这篇关于GCC 可以从最终输出中消除什么样的死代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆