LTO with LLVM and CMake

I am trying to apply Link Time Optimization with LLVM on a CMake Project, that creates a shared library. My question is pretty much the same as this one:

Switching between GCC and Clang/LLVM using CMake.

However, the answers do not seem to be applicable anymore, since llvm-ld is not present in the new versions. On the command line, I run the following commands to get LTO (Assuming there are only 2 .cpp files):

Compile to byte code:

clang++ -c FirstClass.cpp -O3 -flto -o FirstClass.bc
clang++ -c SecondClass.cpp -O3 -flto -o SecondClass.bc

Link byte code:

llvm-link FirstClass.bc SecondClass.bc -o unoptimized.bc

Optimize byte code:

opt -O3 unoptimized.bc -o optimized.bc

Convert byte code to shared object:

clang++ -shared optimized.bc -o libTest.so

Could somebody please tell me how to have CMake run the additional steps?

Answer

The correct way to use Clang and enable LTO is using the -flto flag to the clang command line both at compile and link time.

In addition, you will need to be working on a platform with a linker that either directly supports LTO (Apple’s platforms generally) or that have an LLVM linker plugin (Linux using the Gold linker, but I think some have gotten the BFD linker to support the linker plugin as well). If you’re using the linker plugin, you’ll need to make sure your install of LLVM built and installed the plugin. If it did, Clang will automatically add the necessary linker command line options to use the plugin when linking with -flto, even for shared objects.

Also, The LLVM project is working on a new linker (LLD) which will support LTO out of the box on all the platforms it supports, but it is still pretty early days. Currently I know of folks testing out its LTO support on Windows and Linux, and it seems to be working well but still misses many features.

Leave a Reply

Your email address will not be published. Required fields are marked *