Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C/C++ compilers optimizing across compilation units?

Tags:

c

optimization

Optimizations such as constant propagation are possible across functions within the same compilation unit (ie. same file).

For example :

int f(int x)
{
    return 3 + x;
}

int main(void)
{
    printf("%d\n", 1 + f(4));
    return 0;
}

In that example, I think that a sufficiently smart compiler can propagate the '4' constant to the function 'f', solving the integer arithmetic with the other constant '3', and propagates back the result value thus folding everything to the final value '8'.

(Well, correct me if I'm wrong..)

However, what is happening if the function 'f' is in another compilation unit. Since they both units are compiled separately, the compiler can't optimize that way.

Does it mean that optimizations are only possible within the same compilation unit, or is there some form late optimizations performed of link-time?

like image 789
Gabriel Cuvillier Avatar asked Aug 23 '10 10:08

Gabriel Cuvillier


1 Answers

Both MSVC (since 8.0: VS2005) and GCC (since 4.5) support the concept.

  • MSVC uses a compiler switch /GL and linker switch /LTCG. Documentation

  • GCC must have it enabled and uses the -flto, -fwhole-program, -fwhopr, and/or -combine to the same effect. Documentation (search for the options in your browser)

The "problem" is that every compilation unit (source file) (and in the case of MSVC every library) needs to be compiled with this, so you can't use old binary object files compiled without it. It also makes debugging harder, because the optimizer is a lot more aggressive and unpredictable.

like image 112
rubenvb Avatar answered Oct 31 '22 09:10

rubenvb