1 //===-LTO.h - LLVM Link Time Optimizer ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares functions and classes used to support LTO. It is intended
11 // to be used both by LTO classes as well as by clients (gold-plugin) that
12 // don't utilize the LTO code generator interfaces.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_LTO_LTO_H
17 #define LLVM_LTO_LTO_H
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/ModuleSummaryIndex.h"
24 #include "llvm/LTO/Config.h"
25 #include "llvm/Linker/IRMover.h"
26 #include "llvm/Object/IRSymtab.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 #include "llvm/Support/thread.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Transforms/IPO/FunctionImport.h"
38 class MemoryBufferRef;
41 class raw_pwrite_stream;
43 /// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
44 /// recorded in the index and the ThinLTO backends must apply the changes to
45 /// the module via thinLTOResolvePrevailingInModule.
47 /// This is done for correctness (if value exported, ensure we always
48 /// emit a copy), and compile-time optimization (allow drop of duplicates).
49 void thinLTOResolvePrevailingInIndex(
50 ModuleSummaryIndex &Index,
51 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
53 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
56 /// Update the linkages in the given \p Index to mark exported values
57 /// as external and non-exported values as internal. The ThinLTO backends
58 /// must apply the changes to the Module via thinLTOInternalizeModule.
59 void thinLTOInternalizeAndPromoteInIndex(
60 ModuleSummaryIndex &Index,
61 function_ref<bool(StringRef, GlobalValue::GUID)> isExported);
63 /// Computes a unique hash for the Module considering the current list of
64 /// export/import and other global analysis results.
65 /// The hash is produced in \p Key.
66 void computeLTOCacheKey(
67 SmallString<40> &Key, const lto::Config &Conf,
68 const ModuleSummaryIndex &Index, StringRef ModuleID,
69 const FunctionImporter::ImportMapTy &ImportList,
70 const FunctionImporter::ExportSetTy &ExportList,
71 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
72 const GVSummaryMapTy &DefinedGlobals,
73 const std::set<GlobalValue::GUID> &CfiFunctionDefs = {},
74 const std::set<GlobalValue::GUID> &CfiFunctionDecls = {});
78 /// Given the original \p Path to an output file, replace any path
79 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
80 /// resulting directory if it does not yet exist.
81 std::string getThinLTOOutputFile(const std::string &Path,
82 const std::string &OldPrefix,
83 const std::string &NewPrefix);
85 /// Setup optimization remarks.
86 Expected<std::unique_ptr<ToolOutputFile>>
87 setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename,
88 bool LTOPassRemarksWithHotness, int Count = -1);
91 struct SymbolResolution;
92 class ThinBackendProc;
94 /// An input file. This is a symbol table wrapper that only exposes the
95 /// information that an LTO client should need in order to do symbol resolution.
101 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
103 InputFile() = default;
105 std::vector<BitcodeModule> Mods;
106 SmallVector<char, 0> Strtab;
107 std::vector<Symbol> Symbols;
109 // [begin, end) for each module
110 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
112 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
113 std::vector<StringRef> ComdatTable;
118 /// Create an InputFile.
119 static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object);
121 /// The purpose of this class is to only expose the symbol information that an
122 /// LTO client should need in order to do symbol resolution.
123 class Symbol : irsymtab::Symbol {
127 Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {}
129 using irsymtab::Symbol::isUndefined;
130 using irsymtab::Symbol::isCommon;
131 using irsymtab::Symbol::isWeak;
132 using irsymtab::Symbol::isIndirect;
133 using irsymtab::Symbol::getName;
134 using irsymtab::Symbol::getVisibility;
135 using irsymtab::Symbol::canBeOmittedFromSymbolTable;
136 using irsymtab::Symbol::isTLS;
137 using irsymtab::Symbol::getComdatIndex;
138 using irsymtab::Symbol::getCommonSize;
139 using irsymtab::Symbol::getCommonAlignment;
140 using irsymtab::Symbol::getCOFFWeakExternalFallback;
141 using irsymtab::Symbol::getSectionName;
142 using irsymtab::Symbol::isExecutable;
145 /// A range over the symbols in this InputFile.
146 ArrayRef<Symbol> symbols() const { return Symbols; }
148 /// Returns linker options specified in the input file.
149 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
151 /// Returns the path to the InputFile.
152 StringRef getName() const;
154 /// Returns the input file's target triple.
155 StringRef getTargetTriple() const { return TargetTriple; }
157 /// Returns the source file path specified at compile time.
158 StringRef getSourceFileName() const { return SourceFileName; }
160 // Returns a table with all the comdats used by this file.
161 ArrayRef<StringRef> getComdatTable() const { return ComdatTable; }
164 ArrayRef<Symbol> module_symbols(unsigned I) const {
165 const auto &Indices = ModuleSymIndices[I];
166 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
170 /// This class wraps an output stream for a native object. Most clients should
171 /// just be able to return an instance of this base class from the stream
172 /// callback, but if a client needs to perform some action after the stream is
173 /// written to, that can be done by deriving from this class and overriding the
175 class NativeObjectStream {
177 NativeObjectStream(std::unique_ptr<raw_pwrite_stream> OS) : OS(std::move(OS)) {}
178 std::unique_ptr<raw_pwrite_stream> OS;
179 virtual ~NativeObjectStream() = default;
182 /// This type defines the callback to add a native object that is generated on
185 /// Stream callbacks must be thread safe.
186 typedef std::function<std::unique_ptr<NativeObjectStream>(unsigned Task)>
189 /// This is the type of a native object cache. To request an item from the
190 /// cache, pass a unique string as the Key. For hits, the cached file will be
191 /// added to the link and this function will return AddStreamFn(). For misses,
192 /// the cache will return a stream callback which must be called at most once to
193 /// produce content for the stream. The native object stream produced by the
194 /// stream callback will add the file to the link after the stream is written
197 /// Clients generally look like this:
199 /// if (AddStreamFn AddStream = Cache(Task, Key))
200 /// ProduceContent(AddStream);
201 typedef std::function<AddStreamFn(unsigned Task, StringRef Key)>
204 /// A ThinBackend defines what happens after the thin-link phase during ThinLTO.
205 /// The details of this type definition aren't important; clients can only
206 /// create a ThinBackend using one of the create*ThinBackend() functions below.
207 typedef std::function<std::unique_ptr<ThinBackendProc>(
208 Config &C, ModuleSummaryIndex &CombinedIndex,
209 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
210 AddStreamFn AddStream, NativeObjectCache Cache)>
213 /// This ThinBackend runs the individual backend jobs in-process.
214 ThinBackend createInProcessThinBackend(unsigned ParallelismLevel);
216 /// This ThinBackend writes individual module indexes to files, instead of
217 /// running the individual backend jobs. This backend is for distributed builds
218 /// where separate processes will invoke the real backends.
220 /// To find the path to write the index to, the backend checks if the path has a
221 /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
222 /// appends ".thinlto.bc" and writes the index to that path. If
223 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a
224 /// similar path with ".imports" appended instead.
225 /// LinkedObjectsFile is an output stream to write the list of object files for
226 /// the final ThinLTO linking. Can be nullptr.
227 /// OnWrite is callback which receives module identifier and notifies LTO user
228 /// that index file for the module (and optionally imports file) was created.
229 using IndexWriteCallback = std::function<void(const std::string &)>;
230 ThinBackend createWriteIndexesThinBackend(std::string OldPrefix,
231 std::string NewPrefix,
232 bool ShouldEmitImportsFiles,
233 raw_fd_ostream *LinkedObjectsFile,
234 IndexWriteCallback OnWrite);
236 /// This class implements a resolution-based interface to LLVM's LTO
237 /// functionality. It supports regular LTO, parallel LTO code generation and
238 /// ThinLTO. You can use it from a linker in the following way:
239 /// - Set hooks and code generation options (see lto::Config struct defined in
240 /// Config.h), and use the lto::Config object to create an lto::LTO object.
241 /// - Create lto::InputFile objects using lto::InputFile::create(), then use
242 /// the symbols() function to enumerate its symbols and compute a resolution
243 /// for each symbol (see SymbolResolution below).
244 /// - After the linker has visited each input file (and each regular object
245 /// file) and computed a resolution for each symbol, take each lto::InputFile
246 /// and pass it and an array of symbol resolutions to the add() function.
247 /// - Call the getMaxTasks() function to get an upper bound on the number of
248 /// native object files that LTO may add to the link.
249 /// - Call the run() function. This function will use the supplied AddStream
250 /// and Cache functions to add up to getMaxTasks() native object files to
256 /// Create an LTO object. A default constructed LTO object has a reasonable
257 /// production configuration, but you can customize it by passing arguments to
258 /// this constructor.
259 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
260 /// Until that is fixed, a Config argument is required.
261 LTO(Config Conf, ThinBackend Backend = nullptr,
262 unsigned ParallelCodeGenParallelismLevel = 1);
265 /// Add an input file to the LTO link, using the provided symbol resolutions.
266 /// The symbol resolutions must appear in the enumeration order given by
267 /// InputFile::symbols().
268 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
270 /// Returns an upper bound on the number of tasks that the client may expect.
271 /// This may only be called after all IR object files have been added. For a
272 /// full description of tasks see LTOBackend.h.
273 unsigned getMaxTasks() const;
275 /// Runs the LTO pipeline. This function calls the supplied AddStream
276 /// function to add native object files to the link.
278 /// The Cache parameter is optional. If supplied, it will be used to cache
279 /// native object files and add them to the link.
281 /// The client will receive at most one callback (via either AddStream or
282 /// Cache) for each task identifier.
283 Error run(AddStreamFn AddStream, NativeObjectCache Cache = nullptr);
288 struct RegularLTOState {
289 RegularLTOState(unsigned ParallelCodeGenParallelismLevel, Config &Conf);
290 struct CommonResolution {
293 /// Record if at least one instance of the common was marked as prevailing
294 bool Prevailing = false;
296 std::map<std::string, CommonResolution> Commons;
298 unsigned ParallelCodeGenParallelismLevel;
300 std::unique_ptr<Module> CombinedModule;
301 std::unique_ptr<IRMover> Mover;
303 // This stores the information about a regular LTO module that we have added
304 // to the link. It will either be linked immediately (for modules without
305 // summaries) or after summary-based dead stripping (for modules with
308 std::unique_ptr<Module> M;
309 std::vector<GlobalValue *> Keep;
311 std::vector<AddedModule> ModsWithSummaries;
314 struct ThinLTOState {
315 ThinLTOState(ThinBackend Backend);
318 ModuleSummaryIndex CombinedIndex;
319 MapVector<StringRef, BitcodeModule> ModuleMap;
320 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
323 // The global resolution for a particular (mangled) symbol name. This is in
324 // particular necessary to track whether each symbol can be internalized.
325 // Because any input file may introduce a new cross-partition reference, we
326 // cannot make any final internalization decisions until all input files have
327 // been added and the client has called run(). During run() we apply
328 // internalization decisions either directly to the module (for regular LTO)
329 // or to the combined index (for ThinLTO).
330 struct GlobalResolution {
331 /// The unmangled name of the global.
334 /// Keep track if the symbol is visible outside of a module with a summary
335 /// (i.e. in either a regular object or a regular LTO module without a
337 bool VisibleOutsideSummary = false;
339 bool UnnamedAddr = true;
341 /// True if module contains the prevailing definition.
342 bool Prevailing = false;
344 /// Returns true if module contains the prevailing definition and symbol is
345 /// an IR symbol. For example when module-level inline asm block is used,
346 /// symbol can be prevailing in module but have no IR name.
347 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
349 /// This field keeps track of the partition number of this global. The
350 /// regular LTO object is partition 0, while each ThinLTO object has its own
351 /// partition number from 1 onwards.
353 /// Any global that is defined or used by more than one partition, or that
354 /// is referenced externally, may not be internalized.
356 /// Partitions generally have a one-to-one correspondence with tasks, except
357 /// that we use partition 0 for all parallel LTO code generation partitions.
358 /// Any partitioning of the combined LTO object is done internally by the
360 unsigned Partition = Unknown;
362 /// Special partition numbers.
364 /// A partition number has not yet been assigned to this global.
367 /// This global is either used by more than one partition or has an
368 /// external reference, and therefore cannot be internalized.
371 /// The RegularLTO partition
376 // Global mapping from mangled symbol names to resolutions.
377 StringMap<GlobalResolution> GlobalResolutions;
379 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
380 ArrayRef<SymbolResolution> Res, unsigned Partition,
383 // These functions take a range of symbol resolutions [ResI, ResE) and consume
384 // the resolutions used by a single input module by incrementing ResI. After
385 // these functions return, [ResI, ResE) will refer to the resolution range for
386 // the remaining modules in the InputFile.
387 Error addModule(InputFile &Input, unsigned ModI,
388 const SymbolResolution *&ResI, const SymbolResolution *ResE);
390 Expected<RegularLTOState::AddedModule>
391 addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
392 const SymbolResolution *&ResI, const SymbolResolution *ResE);
393 Error linkRegularLTO(RegularLTOState::AddedModule Mod,
394 bool LivenessFromIndex);
396 Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
397 const SymbolResolution *&ResI, const SymbolResolution *ResE);
399 Error runRegularLTO(AddStreamFn AddStream);
400 Error runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache);
402 mutable bool CalledGetMaxTasks = false;
404 // Use Optional to distinguish false from not yet initialized.
405 Optional<bool> EnableSplitLTOUnit;
408 /// The resolution for a symbol. The linker must provide a SymbolResolution for
409 /// each global symbol based on its internal resolution of that symbol.
410 struct SymbolResolution {
412 : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0),
413 LinkerRedefined(0) {}
415 /// The linker has chosen this definition of the symbol.
416 unsigned Prevailing : 1;
418 /// The definition of this symbol is unpreemptable at runtime and is known to
419 /// be in this linkage unit.
420 unsigned FinalDefinitionInLinkageUnit : 1;
422 /// The definition of this symbol is visible outside of the LTO unit.
423 unsigned VisibleToRegularObj : 1;
425 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
427 unsigned LinkerRedefined : 1;