Maestro
Maestro

Reputation: 9518

Why does 'Link Time Optimization' results in larger binaries?

When I enable Link Time Optimization in GCC, the binaries produced become much larger. I expected GCC to be able to remove a lot of reduntant functions, and perform other optimizations otherwise impossible, so how come this makes the generated output grow?

Compiler flags:

-Os -c -fno-builtin -ffunction-sections -fdata-sections -flto -mcpu=cortex-m0 -mthumb 

Linker flags:

-nostdlib -s -Xlinker --gc-sections -flto -mcpu=cortex-m0 -mthumb -T

Upvotes: 13

Views: 10189

Answers (2)

Jan Hubička
Jan Hubička

Reputation: 649

Important thing for LTO is the working linker plugin support. Only with that GCC can make agressive unreachable code removal and other optimizaitons. Be sure you have plugin enabled linker (just try if LTO linking works with -fuse-linker-plugin)

Upvotes: 0

Did you strip the binary after linking with -flto (it should be provided both at compilation and at link time)?

BTW, notice that the same optimization flags (-flto -Os) should be passed both at compile time and at link time. If you forgot -like you did- any of them at linking phase, LTO won't work! (When using make you want CC=gcc -flto -Os not CFLAGS= -flto -Os).

You did forgot -Os at link time, in addition of -flto; just passing -flto at link time without any optimizations is wrong: the LTO phase would "de-optimize" at most

I know that -flto adds a lot of sections in the ELF object files and executables (those sections contain the serialization of GCC internal representations like Gimple....). I guess (but have not checked) that the linking does not remove them.

Also, the main point of LTO is to inline accross several compilation units and this is expected to grow the code. So perhaps you should not use LTO in your particular case.

Most redundant functions are already removed (by the linker "GC" on sections) even without LTO.

BTW, you could use objdumpor readelfto find out.

Upvotes: 18

Related Questions