Enable link-time optimization (after switching to avr-gcc 4.5 or greater) [imported]
This is Issue 660 moved from a Google Code project. Added by 2011-09-27T22:38:57.000Z by [email protected]. Please review that bug for more context and additional comments, but update this bug.
Original labels: Type-Defect, Priority-Medium
Original description
avr-gcc 4.5 has support for LTO. Enabling it would probably allow sizable object size reductions, especially with -Os when linking libraries spanning multiple compilation units.
Here's a comment copied from Google Code:
LTO stands for link-time optimization and basically it means deferring most optimizations until all compilation units (each file being compiled, including libraries) have been processed. As an example, consider a library function that's called only once in the current program. Without LTO both caller and callee will be compiled separately. With LTO the callee will be inlined (it's always profitable to inline a function that's called only once). While just inlining might look not much of a win, take into consideration that this also allows code specialization at compile-time. For more information, look up the -flto and -fwhole-program compile options (http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Optimize-Options)
I've been looking at LTO and whole program optimization as well, since it greatly increases optimization opportunities for a templated I/O library I've been working on.
To get this working, -flto needs to be passed to all C/C++ compiler commands and linker commands. It seems sensible to pass -O0 to the compiler commands since optimization is done in the linker stage, but a quick test shows that this greatly increases resulting binary size, so I guess not all optimizations are run at link time and -Os must still be passed both when compiling and linking.
I've tested this here on avr-gcc 4.7 in Debian using Arduino-mk and it indeed helps to reduce code size (haven't looked closely at code speed yet).
However, for optimal LTO, gcc needs a "linker plugin", which doesn't seem to be available in my setup (not sure if this is a limitation of the AVR target and/or if this was / will be fixed in a more recent GCC version, thogh). AFAIU this linker plugin serves two purposes: It allows gcc to get LTO information out of archives (allowing the arduino core code in libcore.a to be included in the LTO process) and it allows gcc to know which functions are externally visible (in this case, only main()) so it can really tell if a function is used or not.
As an alternative for such a linker plugin, -fwhole-program can be passed to the linker. This flag tells gcc, "I've passed you all the code for this program and only main() and any functions with the externally_visible attribute are externally visible". However, since no linker plugin is used, any .o files compiled without -flto and any .a files included in the link are not included in the LTO and the optimizer will pretend they don't exist. In the Arduino case, the LTO will not see the actual main() function (which is in libcore.a) referencing setup() and loop(), making it remove the setup() and loop() functions (and probably all of the rest of your code as well). After LTO, the linker will then try to link your (now-empty) program with libcore.a and error out with "undefined symbol setup" and "undefined symbol loop".
Making -fwhole-program can be done by marking setup and loop as externally visible. e.g. put this in Arduino.h (or any other place included in the .ino file, just in main.cpp isn't enough):
void loop(void) __attribute__((externally_visible));
void setup(void) __attribute__((externally_visible));
Doing this makes the program a bit smaller and probably faster as well (it allows inlining and removing functions that are called in on place only, for example). However, it is probably a bit error prone to manually keep this list of externally visible functions, so I would advise only applying it if linker plugin support for AVR isn't going to happen soon and it turns out the optimization gain of -fwhole-program is significant.
It seems that since gcc 4.8, avr-gcc has the linker plugin working, meaning we can enable -flto and it should just work :-)
This may be enable after merging #1903 (just to keep a note inside the pull request).
The -flto option needs to be passed to the linker as well (compiler.c.elf). Below are the extra flags I am using for Cosa build (See https://github.com/mikaelpatel/Cosa/blob/master/platform.txt-gcc-4.8.1)
# These can be overridden in platform.local.txt
compiler.c.extra_flags=-Wextra -flto
compiler.c.elf.extra_flags=-w -flto
compiler.S.extra_flags=
compiler.cpp.extra_flags=-Wextra -flto
compiler.ar.extra_flags=
compiler.objcopy.eep.extra_flags=
compiler.elf2hex.extra_flags=
This work nicely for the Cosa Arduino Framework. So far have all tests passed. Please note that some warnings from the link needs to suppressed (See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59396)
Cheers! Mikael
Current toolchain supports link time optimization, which is disabled by default. If you wish to use you can either modify platform.txt or provide your own custom core
There are still problems with the LTO plugin (for Windows). It is not always included and "collect" will fail. I have disabled LTO in the Arduino IDE build (platform.txt) and only use this from the Cosa command line build (Makefile).
Is it still the ambition to enable LTO, if this is possible without introducing any broken behaviour? If so, perhaps this issue should be left open, to track any problems and solutions with LTO found so far?
I just noticed a problem with LTO giving incorrect ISR warnings. This is reported upstream and fixed in 4.8.3.
I guess so, let's reopen this one and collect all the problems around LTO:
@mikaelpatel what's the problem you're facing exactly with the plugin? are you using the same toolchain shipped with Arduino for your makefile?
@Lauszus @xxxajk IIRC there was a problem with LTO and USB_Host_2 library?
if anyone has information and links, please post here.
Dev-list discussion here: https://groups.google.com/a/arduino.cc/d/msg/developers/21G5w2HbUOg/000Ql0O6CCwJ
@cmaglie we disable optimization in the code for the versions of GCC that we know have the problem.
Some goodies for the weekend:
a new shiny avr-gcc 5.1.0 for all major platforms with LTO plugin support!
Windows x86 OSX x86_64 Linux x86_64
All the toolchains has been cross compiled on Linux using this script (in case you want to compile it by yourself).
To enable LTO simply add the following flags to your platform.txt
compiler.c.extra_flags=-Wextra -flto
compiler.c.elf.extra_flags=-w -flto -fuse-linker-plugin
compiler.S.extra_flags=-flto
compiler.cpp.extra_flags=-Wextra -flto
compiler.objcopy.eep.extra_flags=
compiler.elf2hex.extra_flags=
and a platform-dependant
- UNIX
compiler.ar.extra_flags=--plugin={$extraction_path}/libexec/gcc/avr/5.1.0/liblto_plugin.so
- WINDOWS
compiler.ar.extra_flags=--plugin={$extraction_path}/libexec/gcc/avr/5.1.0/liblto_plugin-0.dll
As usual, testing and error reporting is VERY well accepted :wink:
@matthijskooijman - could you give this compiler+flags a spin with your arduino-mass-builder to get some metrics?
Cool! This script, is it based on on in the avr-toolchain repo? And the patch you linked is the only one applied, or does this include patches from Atmel too (like the ones in the avr-toolchain repo)?
In your compiler flags, I assume -Wextra isn't actually needed for LTO?
I didn't realize about -fuse-linker-plugin, so I tested without that before. Also, I take the ar options allow ar to store lto info inside .a files? From reading the gcc manpage, it looks like this option might not be needed if you call gcc-ar instead of just ar?
Finally, it seems that -fno-fat-lto-objects might be useful to speed up compilation by not generating machine code twice.
I'll run this through my mass-builder script, but I don't have a laptop adapter with me, so can't do that right now :-)
@cmaglie I just tried enabling LTO with the current toolchain bundled with the Arduino IDE and unfortunately the issue is still present:
Without LTO:
Sketch uses 21,908 bytes (8%) of program storage space. Maximum is 253,952 bytes.
Global variables use 968 bytes (11%) of dynamic memory, leaving 7,224 bytes for local variables. Maximum is 8,192 bytes.
With LTO:
Sketch uses 70,492 bytes (27%) of program storage space. Maximum is 253,952 bytes.
Global variables use 1,289 bytes (15%) of dynamic memory, leaving 6,903 bytes for local variables. Maximum is 8,192 bytes.
@facchinm I tried to test it with the updated toolchain you linked to, but I am getting the following error:
/Users/Lauszus/Github/Arduino/build/macosx/work/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -flto -I/Users/Lauszus/Github/Arduino/build/macosx/work/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Users/Lauszus/Github/Arduino/build/macosx/work/Arduino.app/Contents/Java/hardware/arduino/avr/variants/mega -I/Users/Lauszus/Dropbox/Arduino/libraries/USB_Host_Shield_2.0 -I/Users/Lauszus/Dropbox/Arduino/libraries/spi4teensy3 -I/Users/Lauszus/Github/Arduino/build/macosx/work/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI /var/folders/st/ln3d8j1n7x91gq9gk8304gtw0000gn/T/build1230170329459071487.tmp/sketch/PS3BT.cpp -o /var/folders/st/ln3d8j1n7x91gq9gk8304gtw0000gn/T/build1230170329459071487.tmp/sketch/PS3BT.cpp.o
FATAL:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../libexec/as/x86_64/as: I don't understand 'm' flag!
Error compiling.
@Lauszus it seems that the default x86_64 toolchain from Xcode was chosen for linking...
I suggest to extract the 5.1.0 toolchain in a different folder (not inside Arduino.app ) and then hardcode the path in compiler.path and compiler.ar.extra_flags fields.
I've tested it in a MacMini (10.9) and the paths are taken correctly.
BTW, thanks for testing!!
@matthijskooijman , you are clearly right about -Wextra, it was a leftover from previous tests.
ar and gcc-ar are alias in an effort to have the exact same compilation flags (and thus the same behaviour) on all the three platforms.
I've tested also with -fno-fat-lto-objects but I couldn't appreciate the speedup (I didn't measured it, though).
Finally, the script is loosely based on avr-toolchain repo but its main target is to enable canadian cross compiling for all the platform with the same flags on a single machine. No Atmel patch applied at the moment (except one for the GCC linker bug)
Eagerly waiting for the results of your tests!
@Lauszus , compiling the PS3BT example from your library gives the following result with the newest toolchain (under Linux)
Sketch uses 20,266 bytes (7%) of program storage space. Maximum is 253,952 bytes.
Global variables use 958 bytes (11%) of dynamic memory, leaving 7,234 bytes for local variables. Maximum is 8,192 bytes.
so it seems that LTO code has quite improved :wink:
I did a full test run. The 5.1 toolchain you supplied worked perfectly for me, I didn't see any of the errors @Lauszus saw.
I did four builds:
-
"base" is an unmodified Arduino toolchain / IDE, using yesterdays git master (ce595ce81).
-
"lto" is the default toolchain with LTO enabled. Specifically:
compiler.c.extra_flags=-flto compiler.c.elf.extra_flags=-flto -fuse-linker-plugin compiler.S.extra_flags=-flto compiler.cpp.extra_flags=-fltoUsing
avr-gcc-ardidn't work, since that complained that ar was compiled without plugin support. This also prevented using -fno-fat-lto-objects, since that resulted in missing symbols. -
"5.1" is the 5.1 toolchain linked above, with default flags:
compiler.path=/home/matthijs/avr-gcc-5.1/bin/ -
"5.1-lto" is the 5.1 toolchain with LTO enabled:
compiler.path=/home/matthijs/avr-gcc-5.1/bin/ compiler.c.extra_flags=-flto -fno-fat-lto-objects compiler.c.elf.extra_flags=-flto -fuse-linker-plugin compiler.S.extra_flags=-flto compiler.cpp.extra_flags=-flto compiler.ar.cmd=avr-gcc-arHere I used
avr-gcc-arinstead of the--pluginoption you suggested. AFAIUavr-gcc-arcalls the regularavr-ar, with that plugin option set to the proper path. A quick strace confirms this:matthijs@grubby:~$ strace -f -s 200 -e trace=execve ./avr-gcc-5.1/bin/avr-gcc-ar 2>&1 |grep execve execve("./avr-gcc-5.1/bin/avr-gcc-ar", ["./avr-gcc-5.1/bin/avr-gcc-ar"], [/* 73 vars */]) = 0 [pid 26265] execve("/home/matthijs/avr-gcc-5.1/bin/../lib/gcc/avr/5.1.0/../../../../avr/bin/ar", ["/home/matthijs/avr-gcc-5.1/bin/../lib/gcc/avr/5.1.0/../../../../avr/bin/ar", "--plugin", "/home/matthijs/avr-gcc-5.1/bin/../libexec/gcc/avr/5.1.0/liblto_plugin.so"], [/* 73 vars */]) = 0
The full data is available here:
https://www.google.com/fusiontables/DataSource?docid=1_tmjQtI1PrCz02fsV0N8AkOZ-2nF04XQ6QAhcM1H
None of the examples were broken or fixed by enabling LTO or upgrading the toolchain. 21 builds compiled to the exactly the same hex file (this was only bare minimum using the 5.1 toolchain without lto), all other builds were changed in some way.
Data size I had a closer look at some of the cases where the sizes increase. There are only 4 RAM size increases with 5.1-lto, all of which concern the tone() function on the Gemma. Somehow it seems that with lto, gcc fails to optimize away a few unused global variables. This same problem occurs with lto, but there it also occurs for other 32u4-based boards (the variable is not unused on e.g. 328). Somehow the non-lto build does optimize the variable away as it should. The lto build has a lot more RAM size increases, but I haven't looked closely at those. There might also be some increase that are masked by other decreases, resulting in a net decrease. On average, the datasize decreases by 2 bytes for lto and 17 bytes for 5.1-lto, and worst-case is a 17 respectively 8 byte increase, so I don't think this is something to worry about.
program size The size increases for flash are limited, only 6 builds for lto and 22 for 5.1-lto. The few size increases > 40 bytes (up to 180 bytes) seem related to the Gemma and the tone library (caused by #3519, I think). All other size increases add 36 bytes on the toneMultiple example. I couldn't really find what caused this, it seems that somehow the compiler is less smart about what timer could possibly be used and fails to remove some code.
Overall, it seems that lto enables more inlining to happen. I've seen main() become huge, but setup(), loop() and initVariant() disappeared, making the result significantly smaller. On average, sketches become 429 bytes smaller with lto and even 493 with 5.1-lto (and also 24 bytes smaller with 5.1 without lto).
On potential issue with lto is that it seems to kill debugging information
The gcc-4.9 and gcc-5.1 manpage says:
Link-time optimization does not work well with generation of debugging information. Combining -flto with -g is currently experimental and expected to produce unexpected results.
When disassembling code compiled with lto, I've seen that objdump was unable to show source.
This isn't much of an issue now, but we might need to keep this into account if debugging support is added to the compiler later (this would probably require the use of separate "debugging" recipies in platform.txt).
@matthijskooijman , great work as usual! I believe that a ~400 byte decrease in program size is enough to justify some extensive testing "in the field" to also check functionality compliance.
About debugging capability being lost, we only need to keep LTO flags separate from the standard flags and disable them when the target is set to debugging (just my thoughts, I'm not sure if/when the debugging capabilities will also be extended to AVR products)
@facchinm hmm I already tried that:
compiler.path=/Users/Lauszus/Downloads/pkg-x86_64-apple-darwin14/bin/
compiler.ar.extra_flags=--plugin=/Users/Lauszus/Downloads/pkg-x86_64-apple-darwin14/libexec/gcc/avr/5.1.0/liblto_plugin.so
But it keeps picking up the default toolchain. I guess it is a problem with my particular setup.