306 lines · plain
1======================================================2LLVM Link Time Optimization: Design and Implementation3======================================================4 5.. contents::6 :local:7 8Description9===========10 11LLVM features powerful intermodular optimizations which can be used at link12time. Link Time Optimization (LTO) is another name for intermodular13optimization when performed during the link stage. This document describes the14interface and design between the LTO optimizer and the linker.15 16Design Philosophy17=================18 19The LLVM Link Time Optimizer provides complete transparency, while doing20intermodular optimization, in the compiler tool chain. Its main goal is to let21the developer take advantage of intermodular optimizations without making any22significant changes to the developer's makefiles or build system. This is23achieved through tight integration with the linker. In this model, the linker24treats LLVM bitcode files like native object files and allows mixing and25matching among them. The linker uses `libLTO`_, a shared object, to handle LLVM26bitcode files. This tight integration between the linker and LLVM optimizer27helps to do optimizations that are not possible in other models. The linker28input allows the optimizer to avoid relying on conservative escape analysis.29 30.. _libLTO-example:31 32Example of link time optimization33---------------------------------34 35The following example illustrates the advantages of LTO's integrated approach36and clean interface. This example requires a system linker which supports LTO37through the interface described in this document. Here, clang transparently38invokes system linker.39 40* Input source file ``a.c`` is compiled into LLVM bitcode form.41* Input source file ``main.c`` is compiled into native object code.42 43.. code-block:: c++44 45 --- a.h ---46 extern int foo1(void);47 extern void foo2(void);48 extern void foo4(void);49 50 --- a.c ---51 #include "a.h"52 53 static signed int i = 0;54 55 void foo2(void) {56 i = -1;57 }58 59 static int foo3() {60 foo4();61 return 10;62 }63 64 int foo1(void) {65 int data = 0;66 67 if (i < 0)68 data = foo3();69 70 data = data + 42;71 return data;72 }73 74 --- main.c ---75 #include <stdio.h>76 #include "a.h"77 78 void foo4(void) {79 printf("Hi\n");80 }81 82 int main() {83 return foo1();84 }85 86To compile, run:87 88.. code-block:: console89 90 % clang -flto -c a.c -o a.o # <-- a.o is LLVM bitcode file91 % clang -c main.c -o main.o # <-- main.o is native object file92 % clang -flto a.o main.o -o main # <-- standard link command with -flto93 94* In this example, the linker recognizes that ``foo2()`` is an externally95 visible symbol defined in LLVM bitcode file. The linker completes its usual96 symbol resolution pass and finds that ``foo2()`` is not used97 anywhere. This information is used by the LLVM optimizer and it98 removes ``foo2()``.99 100* As soon as ``foo2()`` is removed, the optimizer recognizes that condition ``i101 < 0`` is always false, which means ``foo3()`` is never used. Hence, the102 optimizer also removes ``foo3()``.103 104* And this in turn, enables linker to remove ``foo4()``.105 106This example illustrates the advantage of tight integration with the107linker. Here, the optimizer can not remove ``foo3()`` without the linker's108input.109 110Alternative Approaches111----------------------112 113**Compiler driver invokes link time optimizer separately.**114 In this model the link time optimizer is not able to take advantage of115 information collected during the linker's normal symbol resolution phase.116 In the above example, the optimizer can not remove ``foo2()`` without the117 linker's input because it is externally visible. This in turn prohibits the118 optimizer from removing ``foo3()``.119 120**Use separate tool to collect symbol information from all object files.**121 In this model, a new, separate, tool or library replicates the linker's122 capability to collect information for link time optimization. Not only is123 this code duplication difficult to justify, but it also has several other124 disadvantages. For example, the linking semantics and the features provided125 by the linker on various platform are not unique. This means, this new tool126 needs to support all such features and platforms in one super tool or a127 separate tool per platform is required. This increases maintenance cost for128 link time optimizer significantly, which is not necessary. This approach129 also requires staying synchronized with linker developments on various130 platforms, which is not the main focus of the link time optimizer. Finally,131 this approach increases end user's build time due to the duplication of work132 done by this separate tool and the linker itself.133 134Multi-phase communication between ``libLTO`` and linker135=======================================================136 137The linker collects information about symbol definitions and uses in various138link objects which is more accurate than any information collected by other139tools during typical build cycles. The linker collects this information by140looking at the definitions and uses of symbols in native .o files and using141symbol visibility information. The linker also uses user-supplied information,142such as a list of exported symbols. LLVM optimizer collects control flow143information, data flow information and knows much more about program structure144from the optimizer's point of view. Our goal is to take advantage of tight145integration between the linker and the optimizer by sharing this information146during various linking phases.147 148Phase 1 : Read LLVM Bitcode Files149---------------------------------150 151The linker first reads all object files in natural order and collects symbol152information. This includes native object files as well as LLVM bitcode files.153To minimize the cost to the linker in the case that all .o files are native154object files, the linker only calls ``lto_module_create()`` when a supplied155object file is found to not be a native object file. If ``lto_module_create()``156returns that the file is an LLVM bitcode file, the linker then iterates over the157module using ``lto_module_get_symbol_name()`` and158``lto_module_get_symbol_attribute()`` to get all symbols defined and referenced.159This information is added to the linker's global symbol table.160 161 162The lto* functions are all implemented in a shared object libLTO. This allows163the LLVM LTO code to be updated independently of the linker tool. On platforms164that support it, the shared object is lazily loaded.165 166Phase 2 : Symbol Resolution167---------------------------168 169In this stage, the linker resolves symbols using global symbol table. It may170report undefined symbol errors, read archive members, replace weak symbols, etc.171The linker is able to do this seamlessly even though it does not know the exact172content of input LLVM bitcode files. If dead code stripping is enabled then the173linker collects the list of live symbols.174 175Phase 3 : Optimize Bitcode Files176--------------------------------177 178After symbol resolution, the linker tells the LTO shared object which symbols179are needed by native object files. In the example above, the linker reports180that only ``foo1()`` is used by native object files using181``lto_codegen_add_must_preserve_symbol()``. Next the linker invokes the LLVM182optimizer and code generators using ``lto_codegen_compile()`` which returns a183native object file created by merging the LLVM bitcode files and applying184various optimization passes.185 186Phase 4 : Symbol Resolution after optimization187----------------------------------------------188 189In this phase, the linker reads optimized a native object file and updates the190internal global symbol table to reflect any changes. The linker also collects191information about any changes in use of external symbols by LLVM bitcode192files. In the example above, the linker notes that ``foo4()`` is not used any193more. If dead code stripping is enabled then the linker refreshes the live194symbol information appropriately and performs dead code stripping.195 196After this phase, the linker continues linking as if it never saw LLVM bitcode197files.198 199.. _libLTO:200 201``libLTO``202==========203 204``libLTO`` is a shared object that is part of the LLVM tools, and is intended205for use by a linker. ``libLTO`` provides an abstract C interface to use the LLVM206interprocedural optimizer without exposing details of LLVM's internals. The207intention is to keep the interface as stable as possible even when the LLVM208optimizer continues to evolve. It should even be possible for a completely209different compilation technology to provide a different libLTO that works with210their object files and the standard linker tool.211 212``lto_module_t``213----------------214 215A non-native object file is handled via an ``lto_module_t``. The following216functions allow the linker to check if a file (on disk or in a memory buffer) is217a file which libLTO can process:218 219.. code-block:: c220 221 lto_module_is_object_file(const char*)222 lto_module_is_object_file_for_target(const char*, const char*)223 lto_module_is_object_file_in_memory(const void*, size_t)224 lto_module_is_object_file_in_memory_for_target(const void*, size_t, const char*)225 226If the object file can be processed by ``libLTO``, the linker creates a227``lto_module_t`` by using one of:228 229.. code-block:: c230 231 lto_module_create(const char*)232 lto_module_create_from_memory(const void*, size_t)233 234and when done, the handle is released via235 236.. code-block:: c237 238 lto_module_dispose(lto_module_t)239 240 241The linker can introspect the non-native object file by getting the number of242symbols and getting the name and attributes of each symbol via:243 244.. code-block:: c245 246 lto_module_get_num_symbols(lto_module_t)247 lto_module_get_symbol_name(lto_module_t, unsigned int)248 lto_module_get_symbol_attribute(lto_module_t, unsigned int)249 250The attributes of a symbol include the alignment, visibility, and kind.251 252Tools working with object files on Darwin (e.g. lipo) may need to know properties like the CPU type:253 254.. code-block:: c255 256 lto_module_get_macho_cputype(lto_module_t mod, unsigned int *out_cputype, unsigned int *out_cpusubtype)257 258``lto_code_gen_t``259------------------260 261Once the linker has loaded each non-native object files into an262``lto_module_t``, it can request ``libLTO`` to process them all and generate a263native object file. This is done in a couple of steps. First, a code generator264is created with:265 266.. code-block:: c267 268 lto_codegen_create()269 270Then, each non-native object file is added to the code generator with:271 272.. code-block:: c273 274 lto_codegen_add_module(lto_code_gen_t, lto_module_t)275 276The linker then has the option of setting some codegen options. Whether or not277to generate DWARF debug info is set with:278 279.. code-block:: c280 281 lto_codegen_set_debug_model(lto_code_gen_t)282 283which kind of position independence is set with:284 285.. code-block:: c286 287 lto_codegen_set_pic_model(lto_code_gen_t)288 289And each symbol that is referenced by a native object file or otherwise must not290be optimized away is set with:291 292.. code-block:: c293 294 lto_codegen_add_must_preserve_symbol(lto_code_gen_t, const char*)295 296After all these settings are done, the linker requests that a native object file297be created from the modules with the settings using:298 299.. code-block:: c300 301 lto_codegen_compile(lto_code_gen_t, size*)302 303which returns a pointer to a buffer containing the generated native object file.304The linker then parses that and links it with the rest of the native object305files.306