Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c++ - What kind of dead code can GCC eliminate from the final output?

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?

Few examples but not limited to

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>();
///////////////////////////

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

Read about the different passes of the compiler:

  • SSA Aggressive Dead Code Elimination. Turned on by the `-fssa-dce' option. This pass performs elimination of code considered unnecessary because it has no externally visible effects on the program. It operates in linear time.

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

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

  • This includes static libraries, not just binaries – make it possible for users of your library to benefit from more efficient dead code removal.
  • Link your binaries with --gc-sections, unless you have to link against nasty third-party static library which uses magic sections.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...