LLVM – How to Add Link-Time Optimization to LLVM-Based Compiler?

compilerllvmoptimizationperformance

I am designing and implementing a programming language, and I am using LLVM for native code generation. Among others, performance is a key feature of the language, and as such, I am looking to implementing link-time optimization. On the official LLVM site, I've read that

LLVM features powerful intermodular optimizations which can be used at link time.

However, the page in question does not mention how a user can request link-time optimization. In particular, it only explains the theory (and some big-picture decisions of implementation) of LTO, but it does not reference any API documentation nor a tutorial.

I have performed a quick search on Clang's code base, but the results aren't too informative or relevant either – I haven't even found what settings the -flto switch turns on in Clang, let alone the changes in code generation that make it possible for the linker to optimize across object files.

Now, I suppose doing LTO should go along the lines of:

  1. Generating some sort of metadata in the object/bitcode file so that the linker knows it can employ LTO. Maybe this needs to contain concrete information about the module, the functions to be optimized, etc. (I really have no idea what exactly should go in there…)

  2. Then adjusting my code generation procedure (i. e. the way I am using the LLVM API) in a manner that it "supports" LTO. After some researching on the internet, I've found this related LLVM source file, so I assume it's possible to automatize at least part of this task, but – as always – the autogen'd LLVM documentation is scarce at best.

So, my question is: is my description of the process of incorporating the LTO features of LLVM in my compiler correct, and if so, can you suggest me any sort of documentation or tutorial which I could base my project on?

Best Answer

You don't need to do anything besides generating a raw LLVM IR. Linker will take care of merging your IR modules together and compiling the resulting module - of course as long as you have your LLVM LTO plugin properly installed. LTO plugin is dumb, it will simply merge all the LLVM IR modules together.

Alternatively, you can merge your generated IR modules manually, using llvm-link tool.

Related Topic