Venemo
Venemo

Reputation: 19107

How to use GCC LTO with differently optimized object files?

I'm compiling an executable with arm-none-eabi-gcc for a Cortex-M4 based microcontroller. Non-performance-critical code is compiled with -Os (optimized for executable code size) and performance critical parts with another optimalization flags, eg. -Og / -O2 etc.

Is it safe to use -flto in such a build? If so, which optimalization flag should be passed to the linker?

Upvotes: 3

Views: 1806

Answers (1)

Pyves
Pyves

Reputation: 6493

According to the GCC documentation regarding optimise options:

It is recommended that you compile all the files participating in the same link with the same options

Such a statement is rather vague. Nevertheless, when digging into the release notes of GCC 5, there are some additional details:

Command-line optimization and target options are now streamed on a per-function basis and honored by the link-time optimizer. This change makes link-time optimization a more transparent replacement of per-file optimizations. It is now possible to build projects that require different optimization settings for different translation units (such as -ffast-math, -mavx, or -finline).

And also information about which flags are affected by such limitations and which aren't:

Note that this applies only to those command-line options that can be passed to optimize and target attributes. Command-line options affecting global code generation (such as -fpic), warnings (such as -Wodr), optimizations affecting the way static variables are optimized (such as -fcommon), debug output (such as -g), and --param parameters can be applied only to the whole link-time optimization unit. In these cases, it is recommended to consistently use the same options at both compile time and link time.

In your scenario, the optimisation flags -Og, -O2 and -Os can be passed as optimise attributes and do not fall into the cases where the compile time and link time flags ought to be the same. So yes, it should be safe to use -flto in such a build.

Regarding the optimisations flags passed at link time, as stated in the release notes:

Contrary to earlier GCC releases, the optimization and target options passed on the link command line are ignored.

GCC automatically determines which optimisation level to use, which is the highest level used when compiling the object files. You therefore don't need to pass any of your -O optimisation options to the linker.

Upvotes: 2

Related Questions