Design and Implementation — LLVM 20.0.0git documentation (2024)

Description

LLVM features powerful intermodular optimizations which can be used at linktime. Link Time Optimization (LTO) is another name for intermodularoptimization when performed during the link stage. This document describes theinterface and design between the LTO optimizer and the linker.

Design Philosophy

The LLVM Link Time Optimizer provides complete transparency, while doingintermodular optimization, in the compiler tool chain. Its main goal is to letthe developer take advantage of intermodular optimizations without making anysignificant changes to the developer’s makefiles or build system. This isachieved through tight integration with the linker. In this model, the linkertreats LLVM bitcode files like native object files and allows mixing andmatching among them. The linker uses libLTO, a shared object, to handle LLVMbitcode files. This tight integration between the linker and LLVM optimizerhelps to do optimizations that are not possible in other models. The linkerinput allows the optimizer to avoid relying on conservative escape analysis.

Example of link time optimization

The following example illustrates the advantages of LTO’s integrated approachand clean interface. This example requires a system linker which supports LTOthrough the interface described in this document. Here, clang transparentlyinvokes system linker.

--- a.h ---extern int foo1(void);extern void foo2(void);extern void foo4(void);--- a.c ---#include "a.h"static signed int i = 0;void foo2(void) { i = -1;}static int foo3() { foo4(); return 10;}int foo1(void) { int data = 0; if (i < 0) data = foo3(); data = data + 42; return data;}--- main.c ---#include <stdio.h>#include "a.h"void foo4(void) { printf("Hi\n");}int main() { return foo1();}

To compile, run:

% clang -flto -c a.c -o a.o # <-- a.o is LLVM bitcode file% clang -c main.c -o main.o # <-- main.o is native object file% clang -flto a.o main.o -o main # <-- standard link command with -flto
  • In this example, the linker recognizes that foo2() is an externallyvisible symbol defined in LLVM bitcode file. The linker completes its usualsymbol resolution pass and finds that foo2() is not usedanywhere. This information is used by the LLVM optimizer and itremoves foo2().

  • As soon as foo2() is removed, the optimizer recognizes that condition i< 0 is always false, which means foo3() is never used. Hence, theoptimizer also removes foo3().

  • And this in turn, enables linker to remove foo4().

This example illustrates the advantage of tight integration with thelinker. Here, the optimizer can not remove foo3() without the linker’sinput.

Alternative Approaches

Compiler driver invokes link time optimizer separately.

In this model the link time optimizer is not able to take advantage ofinformation collected during the linker’s normal symbol resolution phase.In the above example, the optimizer can not remove foo2() without thelinker’s input because it is externally visible. This in turn prohibits theoptimizer from removing foo3().

Use separate tool to collect symbol information from all object files.

In this model, a new, separate, tool or library replicates the linker’scapability to collect information for link time optimization. Not only isthis code duplication difficult to justify, but it also has several otherdisadvantages. For example, the linking semantics and the features providedby the linker on various platform are not unique. This means, this new toolneeds to support all such features and platforms in one super tool or aseparate tool per platform is required. This increases maintenance cost forlink time optimizer significantly, which is not necessary. This approachalso requires staying synchronized with linker developments on variousplatforms, which is not the main focus of the link time optimizer. Finally,this approach increases end user’s build time due to the duplication of workdone by this separate tool and the linker itself.

Multi-phase communication between libLTO and linker

The linker collects information about symbol definitions and uses in variouslink objects which is more accurate than any information collected by othertools during typical build cycles. The linker collects this information bylooking at the definitions and uses of symbols in native .o files and usingsymbol visibility information. The linker also uses user-supplied information,such as a list of exported symbols. LLVM optimizer collects control flowinformation, data flow information and knows much more about program structurefrom the optimizer’s point of view. Our goal is to take advantage of tightintegration between the linker and the optimizer by sharing this informationduring various linking phases.

Phase 1 : Read LLVM Bitcode Files

The linker first reads all object files in natural order and collects symbolinformation. This includes native object files as well as LLVM bitcode files.To minimize the cost to the linker in the case that all .o files are nativeobject files, the linker only calls lto_module_create() when a suppliedobject file is found to not be a native object file. If lto_module_create()returns that the file is an LLVM bitcode file, the linker then iterates over themodule using lto_module_get_symbol_name() andlto_module_get_symbol_attribute() to get all symbols defined and referenced.This information is added to the linker’s global symbol table.

The lto* functions are all implemented in a shared object libLTO. This allowsthe LLVM LTO code to be updated independently of the linker tool. On platformsthat support it, the shared object is lazily loaded.

Phase 2 : Symbol Resolution

In this stage, the linker resolves symbols using global symbol table. It mayreport undefined symbol errors, read archive members, replace weak symbols, etc.The linker is able to do this seamlessly even though it does not know the exactcontent of input LLVM bitcode files. If dead code stripping is enabled then thelinker collects the list of live symbols.

Phase 3 : Optimize Bitcode Files

After symbol resolution, the linker tells the LTO shared object which symbolsare needed by native object files. In the example above, the linker reportsthat only foo1() is used by native object files usinglto_codegen_add_must_preserve_symbol(). Next the linker invokes the LLVMoptimizer and code generators using lto_codegen_compile() which returns anative object file creating by merging the LLVM bitcode files and applyingvarious optimization passes.

Phase 4 : Symbol Resolution after optimization

In this phase, the linker reads optimized a native object file and updates theinternal global symbol table to reflect any changes. The linker also collectsinformation about any changes in use of external symbols by LLVM bitcodefiles. In the example above, the linker notes that foo4() is not used anymore. If dead code stripping is enabled then the linker refreshes the livesymbol information appropriately and performs dead code stripping.

After this phase, the linker continues linking as if it never saw LLVM bitcodefiles.

libLTO

libLTO is a shared object that is part of the LLVM tools, and is intendedfor use by a linker. libLTO provides an abstract C interface to use the LLVMinterprocedural optimizer without exposing details of LLVM’s internals. Theintention is to keep the interface as stable as possible even when the LLVMoptimizer continues to evolve. It should even be possible for a completelydifferent compilation technology to provide a different libLTO that works withtheir object files and the standard linker tool.

lto_module_t

A non-native object file is handled via an lto_module_t. The followingfunctions allow the linker to check if a file (on disk or in a memory buffer) isa file which libLTO can process:

lto_module_is_object_file(const char*)lto_module_is_object_file_for_target(const char*, const char*)lto_module_is_object_file_in_memory(const void*, size_t)lto_module_is_object_file_in_memory_for_target(const void*, size_t, const char*)

If the object file can be processed by libLTO, the linker creates alto_module_t by using one of:

lto_module_create(const char*)lto_module_create_from_memory(const void*, size_t)

and when done, the handle is released via

lto_module_dispose(lto_module_t)

The linker can introspect the non-native object file by getting the number ofsymbols and getting the name and attributes of each symbol via:

lto_module_get_num_symbols(lto_module_t)lto_module_get_symbol_name(lto_module_t, unsigned int)lto_module_get_symbol_attribute(lto_module_t, unsigned int)

The attributes of a symbol include the alignment, visibility, and kind.

Tools working with object files on Darwin (e.g. lipo) may need to know properties like the CPU type:

lto_module_get_macho_cputype(lto_module_t mod, unsigned int *out_cputype, unsigned int *out_cpusubtype)

lto_code_gen_t

Once the linker has loaded each non-native object files into anlto_module_t, it can request libLTO to process them all and generate anative object file. This is done in a couple of steps. First, a code generatoris created with:

lto_codegen_create()

Then, each non-native object file is added to the code generator with:

lto_codegen_add_module(lto_code_gen_t, lto_module_t)

The linker then has the option of setting some codegen options. Whether or notto generate DWARF debug info is set with:

lto_codegen_set_debug_model(lto_code_gen_t)

which kind of position independence is set with:

lto_codegen_set_pic_model(lto_code_gen_t)

And each symbol that is referenced by a native object file or otherwise must notbe optimized away is set with:

lto_codegen_add_must_preserve_symbol(lto_code_gen_t, const char*)

After all these settings are done, the linker requests that a native object filebe created from the modules with the settings using:

lto_codegen_compile(lto_code_gen_t, size*)

which returns a pointer to a buffer containing the generated native object file.The linker then parses that and links it with the rest of the native objectfiles.

© Copyright 2003-2024, LLVM Project. Last updated on 2024-09-14. Created using Sphinx 7.1.2.

Design and Implementation — LLVM 20.0.0git documentation (2024)
Top Articles
What Is A Good Monthly Retirement Income for a Couple? | SoFi
Understanding margin calls and 4 ways to avoid owing money to your brokerage firm
3 Tick Granite Osrs
Play FETCH GAMES for Free!
Washu Parking
Lifewitceee
Craigslist Vans
Federal Fusion 308 165 Grain Ballistics Chart
Readyset Ochsner.org
Nation Hearing Near Me
Volstate Portal
Daniela Antury Telegram
4Chan Louisville
Inevitable Claymore Wow
VMware’s Partner Connect Program: an evolution of opportunities
Ou Class Nav
50 Shades Darker Movie 123Movies
All Obituaries | Buie's Funeral Home | Raeford NC funeral home and cremation
CANNABIS ONLINE DISPENSARY Promo Code — $100 Off 2024
R Personalfinance
Joan M. Wallace - Baker Swan Funeral Home
Brazos Valley Busted Newspaper
Dark Entreaty Ffxiv
Disputes over ESPN, Disney and DirecTV go to the heart of TV's existential problems
Hctc Speed Test
Jcp Meevo Com
Watertown Ford Quick Lane
Sandals Travel Agent Login
Harrison 911 Cad Log
Big Boobs Indian Photos
Penn State Service Management
The Creator Showtimes Near Baxter Avenue Theatres
Wheeling Matinee Results
What are the 7 Types of Communication with Examples
Loopnet Properties For Sale
Nacogdoches, Texas: Step Back in Time in Texas' Oldest Town
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Robot or human?
Latest Nigerian Music (Next 2020)
2008 DODGE RAM diesel for sale - Gladstone, OR - craigslist
Kelley Blue Book Recalls
Hellgirl000
Conroe Isd Sign In
Taylor University Baseball Roster
Appraisalport Com Dashboard Orders
Hireright Applicant Center Login
Despacito Justin Bieber Lyrics
6576771660
Contico Tuff Box Replacement Locks
Muni Metro Schedule
Ics 400 Test Answers 2022
Lake County Fl Trash Pickup Schedule
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 5742

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.