Thanks to visit codestin.com
Credit goes to llvm.org

LLVM 22.0.0git
LTO.h
Go to the documentation of this file.
1//===-LTO.h - LLVM Link Time Optimizer ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file declares functions and classes used to support LTO. It is intended
10// to be used both by LTO classes as well as by clients (gold-plugin) that
11// don't utilize the LTO code generator interfaces.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LTO_LTO_H
16#define LLVM_LTO_LTO_H
17
20#include <memory>
21
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/MapVector.h"
26#include "llvm/LTO/Config.h"
29#include "llvm/Support/Error.h"
32#include "llvm/Support/thread.h"
35
36namespace llvm {
37
38class Error;
39class IRMover;
40class LLVMContext;
41class MemoryBufferRef;
42class Module;
44class ToolOutputFile;
45
46/// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
47/// recorded in the index and the ThinLTO backends must apply the changes to
48/// the module via thinLTOFinalizeInModule.
49///
50/// This is done for correctness (if value exported, ensure we always
51/// emit a copy), and compile-time optimization (allow drop of duplicates).
53 const lto::Config &C, ModuleSummaryIndex &Index,
55 isPrevailing,
57 recordNewLinkage,
58 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
59
60/// Update the linkages in the given \p Index to mark exported values
61/// as external and non-exported values as internal. The ThinLTO backends
62/// must apply the changes to the Module via thinLTOInternalizeModule.
64 ModuleSummaryIndex &Index,
65 function_ref<bool(StringRef, ValueInfo)> isExported,
67 isPrevailing);
68
69/// Computes a unique hash for the Module considering the current list of
70/// export/import and other global analysis results.
72 const lto::Config &Conf, const ModuleSummaryIndex &Index,
73 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
74 const FunctionImporter::ExportSetTy &ExportList,
75 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
76 const GVSummaryMapTy &DefinedGlobals,
77 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs = {},
78 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls = {});
79
80/// Recomputes the LTO cache key for a given key with an extra identifier.
81LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key,
82 StringRef ExtraID);
83
84namespace lto {
85
86LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple);
87
88/// Given the original \p Path to an output file, replace any path
89/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
90/// resulting directory if it does not yet exist.
91LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
92 StringRef NewPrefix);
93
94/// Setup optimization remarks.
95LLVM_ABI Expected<LLVMRemarkFileHandle> setupLLVMOptimizationRemarks(
96 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
97 StringRef RemarksFormat, bool RemarksWithHotness,
98 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
99
100/// Setups the output file for saving statistics.
101LLVM_ABI Expected<std::unique_ptr<ToolOutputFile>>
102setupStatsFile(StringRef StatsFilename);
103
104/// Produces a container ordering for optimal multi-threaded processing. Returns
105/// ordered indices to elements in the input array.
107
108/// Updates MemProf attributes (and metadata) based on whether the index
109/// has recorded that we are linking with allocation libraries containing
110/// the necessary APIs for downstream transformations.
112 const ModuleSummaryIndex &Index);
113
114class LTO;
115struct SymbolResolution;
116
117/// An input file. This is a symbol table wrapper that only exposes the
118/// information that an LTO client should need in order to do symbol resolution.
119class InputFile {
120public:
121 struct Symbol;
122
123private:
124 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
125 friend LTO;
126 InputFile() = default;
127
128 std::vector<BitcodeModule> Mods;
130 std::vector<Symbol> Symbols;
131
132 // [begin, end) for each module
133 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
134
135 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
136 std::vector<StringRef> DependentLibraries;
137 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
138
139public:
141
142 /// Create an InputFile.
144 create(MemoryBufferRef Object);
145
146 /// The purpose of this struct is to only expose the symbol information that
147 /// an LTO client should need in order to do symbol resolution.
171
172 /// A range over the symbols in this InputFile.
173 ArrayRef<Symbol> symbols() const { return Symbols; }
174
175 /// Returns linker options specified in the input file.
176 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
177
178 /// Returns dependent library specifiers from the input file.
179 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
180
181 /// Returns the path to the InputFile.
182 LLVM_ABI StringRef getName() const;
183
184 /// Returns the input file's target triple.
185 StringRef getTargetTriple() const { return TargetTriple; }
186
187 /// Returns the source file path specified at compile time.
188 StringRef getSourceFileName() const { return SourceFileName; }
189
190 // Returns a table with all the comdats used by this file.
194
195 // Returns the only BitcodeModule from InputFile.
197
198private:
199 ArrayRef<Symbol> module_symbols(unsigned I) const {
200 const auto &Indices = ModuleSymIndices[I];
201 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
202 }
203};
204
205using IndexWriteCallback = std::function<void(const std::string &)>;
206
208
209/// This class defines the interface to the ThinLTO backend.
211protected:
212 const Config &Conf;
218 std::optional<Error> Err;
219 std::mutex ErrMu;
220
221public:
231
232 virtual ~ThinBackendProc() = default;
233 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
234 Triple Triple) {}
235 virtual Error start(
236 unsigned Task, BitcodeModule BM,
237 const FunctionImporter::ImportMapTy &ImportList,
238 const FunctionImporter::ExportSetTy &ExportList,
239 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
241 virtual Error wait() {
242 BackendThreadPool.wait();
243 if (Err)
244 return std::move(*Err);
245 return Error::success();
246 }
247 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
248 virtual bool isSensitiveToInputOrder() { return false; }
249
250 // Write sharded indices and (optionally) imports to disk
252 StringRef ModulePath,
253 const std::string &NewModulePath) const;
254
255 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
256 // (optionally) record imports in ImportsFiles.
258 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
259 const std::string &NewModulePath, StringRef SummaryPath,
260 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
261 const;
262};
263
264/// This callable defines the behavior of a ThinLTO backend after the thin-link
265/// phase. It accepts a configuration \p C, a combined module summary index
266/// \p CombinedIndex, a map of module identifiers to global variable summaries
267/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
268/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
269/// ThinBackendProc, which can be used to launch backends in parallel.
270using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
271 const Config &C, ModuleSummaryIndex &CombinedIndex,
272 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
273 AddStreamFn AddStream, FileCache Cache)>;
274
275/// This type defines the behavior following the thin-link phase during ThinLTO.
276/// It encapsulates a backend function and a strategy for thread pool
277/// parallelism. Clients should use one of the provided create*ThinBackend()
278/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
279/// strategy to be used for processing.
282 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
283 ThinBackend() = default;
284
285 std::unique_ptr<ThinBackendProc> operator()(
286 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
287 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
288 AddStreamFn AddStream, FileCache Cache) {
289 assert(isValid() && "Invalid backend function");
290 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
291 std::move(AddStream), std::move(Cache));
292 }
293 ThreadPoolStrategy getParallelism() const { return Parallelism; }
294 bool isValid() const { return static_cast<bool>(Func); }
295
296private:
297 ThinBackendFunction Func = nullptr;
298 ThreadPoolStrategy Parallelism;
299};
300
301/// This ThinBackend runs the individual backend jobs in-process.
302/// The default value means to use one job per hardware core (not hyper-thread).
303/// OnWrite is callback which receives module identifier and notifies LTO user
304/// that index file for the module (and optionally imports file) was created.
305/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
306/// to the same path as the input module, with suffix ".thinlto.bc"
307/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
308/// similar path with ".imports" appended instead.
310 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
311 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
312
313/// This ThinBackend generates the index shards and then runs the individual
314/// backend jobs via an external process. It takes the same parameters as the
315/// InProcessThinBackend; however, these parameters only control the behavior
316/// when generating the index files for the modules. Additionally:
317/// LinkerOutputFile is a string that should identify this LTO invocation in
318/// the context of a wider build. It's used for naming to aid the user in
319/// identifying activity related to a specific LTO invocation.
320/// Distributor specifies the path to a process to invoke to manage the backend
321/// job execution.
322/// DistributorArgs specifies a list of arguments to be applied to the
323/// distributor.
324/// RemoteCompiler specifies the path to a Clang executable to be invoked for
325/// the backend jobs.
326/// RemoteCompilerArgs specifies a list of arguments to be applied to the
327/// backend compilations.
328/// SaveTemps is a debugging tool that prevents temporary files created by this
329/// backend from being cleaned up.
331 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
332 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
333 StringRef LinkerOutputFile, StringRef Distributor,
334 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
335 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps);
336
337/// This ThinBackend writes individual module indexes to files, instead of
338/// running the individual backend jobs. This backend is for distributed builds
339/// where separate processes will invoke the real backends.
340///
341/// To find the path to write the index to, the backend checks if the path has a
342/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
343/// appends ".thinlto.bc" and writes the index to that path. If
344/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
345/// similar path with ".imports" appended instead.
346/// LinkedObjectsFile is an output stream to write the list of object files for
347/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
348/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
349/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
350/// callback which receives module identifier and notifies LTO user that index
351/// file for the module (and optionally imports file) was created.
353 ThreadPoolStrategy Parallelism, std::string OldPrefix,
354 std::string NewPrefix, std::string NativeObjectPrefix,
355 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
356 IndexWriteCallback OnWrite);
357
358/// This class implements a resolution-based interface to LLVM's LTO
359/// functionality. It supports regular LTO, parallel LTO code generation and
360/// ThinLTO. You can use it from a linker in the following way:
361/// - Set hooks and code generation options (see lto::Config struct defined in
362/// Config.h), and use the lto::Config object to create an lto::LTO object.
363/// - Create lto::InputFile objects using lto::InputFile::create(), then use
364/// the symbols() function to enumerate its symbols and compute a resolution
365/// for each symbol (see SymbolResolution below).
366/// - After the linker has visited each input file (and each regular object
367/// file) and computed a resolution for each symbol, take each lto::InputFile
368/// and pass it and an array of symbol resolutions to the add() function.
369/// - Call the getMaxTasks() function to get an upper bound on the number of
370/// native object files that LTO may add to the link.
371/// - Call the run() function. This function will use the supplied AddStream
372/// and Cache functions to add up to getMaxTasks() native object files to
373/// the link.
374class LTO {
375 friend InputFile;
376
377public:
378 /// Unified LTO modes
379 enum LTOKind {
380 /// Any LTO mode without Unified LTO. The default mode.
382
383 /// Regular LTO, with Unified LTO enabled.
385
386 /// ThinLTO, with Unified LTO enabled.
388 };
389
390 /// Create an LTO object. A default constructed LTO object has a reasonable
391 /// production configuration, but you can customize it by passing arguments to
392 /// this constructor.
393 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
394 /// Until that is fixed, a Config argument is required.
395 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
396 unsigned ParallelCodeGenParallelismLevel = 1,
397 LTOKind LTOMode = LTOK_Default);
399
400 /// Add an input file to the LTO link, using the provided symbol resolutions.
401 /// The symbol resolutions must appear in the enumeration order given by
402 /// InputFile::symbols().
403 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
405
406 /// Returns an upper bound on the number of tasks that the client may expect.
407 /// This may only be called after all IR object files have been added. For a
408 /// full description of tasks see LTOBackend.h.
409 LLVM_ABI unsigned getMaxTasks() const;
410
411 /// Runs the LTO pipeline. This function calls the supplied AddStream
412 /// function to add native object files to the link.
413 ///
414 /// The Cache parameter is optional. If supplied, it will be used to cache
415 /// native object files and add them to the link.
416 ///
417 /// The client will receive at most one callback (via either AddStream or
418 /// Cache) for each task identifier.
419 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
420
421 /// Static method that returns a list of libcall symbols that can be generated
422 /// by LTO but might not be visible from bitcode symbol table.
425
426private:
427 Config Conf;
428
429 struct RegularLTOState {
430 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
431 const Config &Conf);
435 /// Record if at least one instance of the common was marked as prevailing
436 bool Prevailing = false;
437 };
438 std::map<std::string, CommonResolution> Commons;
439
440 unsigned ParallelCodeGenParallelismLevel;
441 LTOLLVMContext Ctx;
442 std::unique_ptr<Module> CombinedModule;
443 std::unique_ptr<IRMover> Mover;
444
445 // This stores the information about a regular LTO module that we have added
446 // to the link. It will either be linked immediately (for modules without
447 // summaries) or after summary-based dead stripping (for modules with
448 // summaries).
449 struct AddedModule {
450 std::unique_ptr<Module> M;
451 std::vector<GlobalValue *> Keep;
452 };
453 std::vector<AddedModule> ModsWithSummaries;
454 bool EmptyCombinedModule = true;
455 } RegularLTO;
456
457 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
458
459 struct ThinLTOState {
460 LLVM_ABI ThinLTOState(ThinBackend Backend);
461
462 ThinBackend Backend;
463 ModuleSummaryIndex CombinedIndex;
464 // The full set of bitcode modules in input order.
465 ModuleMapType ModuleMap;
466 // The bitcode modules to compile, if specified by the LTO Config.
467 std::optional<ModuleMapType> ModulesToCompile;
468 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
469 } ThinLTO;
470
471 // The global resolution for a particular (mangled) symbol name. This is in
472 // particular necessary to track whether each symbol can be internalized.
473 // Because any input file may introduce a new cross-partition reference, we
474 // cannot make any final internalization decisions until all input files have
475 // been added and the client has called run(). During run() we apply
476 // internalization decisions either directly to the module (for regular LTO)
477 // or to the combined index (for ThinLTO).
478 struct GlobalResolution {
479 /// The unmangled name of the global.
480 std::string IRName;
481
482 /// Keep track if the symbol is visible outside of a module with a summary
483 /// (i.e. in either a regular object or a regular LTO module without a
484 /// summary).
485 bool VisibleOutsideSummary = false;
486
487 /// The symbol was exported dynamically, and therefore could be referenced
488 /// by a shared library not visible to the linker.
489 bool ExportDynamic = false;
490
491 bool UnnamedAddr = true;
492
493 /// True if module contains the prevailing definition.
494 bool Prevailing = false;
495
496 /// Returns true if module contains the prevailing definition and symbol is
497 /// an IR symbol. For example when module-level inline asm block is used,
498 /// symbol can be prevailing in module but have no IR name.
499 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
500
501 /// This field keeps track of the partition number of this global. The
502 /// regular LTO object is partition 0, while each ThinLTO object has its own
503 /// partition number from 1 onwards.
504 ///
505 /// Any global that is defined or used by more than one partition, or that
506 /// is referenced externally, may not be internalized.
507 ///
508 /// Partitions generally have a one-to-one correspondence with tasks, except
509 /// that we use partition 0 for all parallel LTO code generation partitions.
510 /// Any partitioning of the combined LTO object is done internally by the
511 /// LTO backend.
512 unsigned Partition = Unknown;
513
514 /// Special partition numbers.
515 enum : unsigned {
516 /// A partition number has not yet been assigned to this global.
517 Unknown = -1u,
518
519 /// This global is either used by more than one partition or has an
520 /// external reference, and therefore cannot be internalized.
521 External = -2u,
522
523 /// The RegularLTO partition
524 RegularLTO = 0,
525 };
526 };
527
528 // GlobalResolutionSymbolSaver allocator.
529 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
530
531 // Symbol saver for global resolution map.
532 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
533
534 // Global mapping from mangled symbol names to resolutions.
535 // Make this an unique_ptr to guard against accessing after it has been reset
536 // (to reduce memory after we're done with it).
537 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
538 GlobalResolutions;
539
540 void releaseGlobalResolutionsMemory();
541
542 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
543 ArrayRef<SymbolResolution> Res, unsigned Partition,
544 bool InSummary);
545
546 // These functions take a range of symbol resolutions and consume the
547 // resolutions used by a single input module. Functions return ranges refering
548 // to the resolutions for the remaining modules in the InputFile.
549 Expected<ArrayRef<SymbolResolution>>
550 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
551 unsigned ModI, ArrayRef<SymbolResolution> Res);
552
553 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
554 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
555 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
558 bool LivenessFromIndex);
559
560 Expected<ArrayRef<SymbolResolution>>
561 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
563
564 Error runRegularLTO(AddStreamFn AddStream);
565 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
566 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
567
568 Error checkPartiallySplit();
569
570 mutable bool CalledGetMaxTasks = false;
571
572 // LTO mode when using Unified LTO.
573 LTOKind LTOMode;
574
575 // Use Optional to distinguish false from not yet initialized.
576 std::optional<bool> EnableSplitLTOUnit;
577
578 // Identify symbols exported dynamically, and that therefore could be
579 // referenced by a shared library not visible to the linker.
580 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
581
582 // Diagnostic optimization remarks file
583 LLVMRemarkFileHandle DiagnosticOutputFile;
584};
585
586/// The resolution for a symbol. The linker must provide a SymbolResolution for
587/// each global symbol based on its internal resolution of that symbol.
592
593 /// The linker has chosen this definition of the symbol.
594 unsigned Prevailing : 1;
595
596 /// The definition of this symbol is unpreemptable at runtime and is known to
597 /// be in this linkage unit.
599
600 /// The definition of this symbol is visible outside of the LTO unit.
602
603 /// The symbol was exported dynamically, and therefore could be referenced
604 /// by a shared library not visible to the linker.
605 unsigned ExportDynamic : 1;
606
607 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
608 /// linker option.
609 unsigned LinkerRedefined : 1;
610};
611
612} // namespace lto
613} // namespace llvm
614
615#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseMap class.
Provides passes for computing function attributes based on interprocedural analyses.
#define I(x, y, z)
Definition MD5.cpp:58
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
Represents a module in a bitcode file.
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
The map maintains the list of imports.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This tells how a thread pool will be used.
Definition Threading.h:115
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
An efficient, type-erasing, non-owning reference to a callable.
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:561
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:173
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:176
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:179
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:191
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:185
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:590
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:594
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:188
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:374
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:612
LLVM_ABI Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
Definition LTO.cpp:733
static LLVM_ABI SmallVector< const char * > getRuntimeLibcallSymbols(const Triple &TT)
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
Definition LTO.cpp:1427
LTOKind
Unified LTO modes.
Definition LTO.h:379
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:384
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:381
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:387
LLVM_ABI ~LTO()
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1150
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1201
DefaultThreadPool BackendThreadPool
Definition LTO.h:217
const Config & Conf
Definition LTO.h:212
std::optional< Error > Err
Definition LTO.h:218
virtual bool isSensitiveToInputOrder()
Definition LTO.h:248
unsigned getThreadCount()
Definition LTO.h:247
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:214
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1441
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:222
virtual Error wait()
Definition LTO.h:241
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:213
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:233
virtual ~ThinBackendProc()=default
virtual Error start(unsigned Task, BitcodeModule BM, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, MapVector< StringRef, BitcodeModule > &ModuleMap)=0
IndexWriteCallback OnWrite
Definition LTO.h:215
A raw_ostream that writes to a file descriptor.
An abstract base class for streams implementations that also support a pwrite operation.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite=nullptr, bool ShouldEmitIndexFiles=false, bool ShouldEmitImportsFiles=false)
This ThinBackend runs the individual backend jobs in-process.
Definition LTO.cpp:1791
LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix, StringRef NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix.
Definition LTO.cpp:1825
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1807
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2205
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:205
LLVM_ABI ThinBackend createWriteIndexesThinBackend(ThreadPoolStrategy Parallelism, std::string OldPrefix, std::string NewPrefix, std::string NativeObjectPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
Definition LTO.cpp:1911
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition LTO.cpp:2180
LLVM_ABI ThinBackend createOutOfProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles, StringRef LinkerOutputFile, StringRef Distributor, ArrayRef< StringRef > DistributorArgs, StringRef RemoteCompiler, ArrayRef< StringRef > RemoteCompilerArgs, bool SaveTemps)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
Definition LTO.cpp:2542
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2224
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:207
std::function< std::unique_ptr< ThinBackendProc >( const Config &C, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)> ThinBackendFunction
This callable defines the behavior of a ThinLTO backend after the thin-link phase.
Definition LTO.h:270
LLVM_ABI void updateMemProfAttributes(Module &Mod, const ModuleSummaryIndex &Index)
Updates MemProf attributes (and metadata) based on whether the index has recorded that we are linking...
Definition LTO.cpp:1259
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:548
LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key, StringRef ExtraID)
Recomputes the LTO cache key for a given key with an extra identifier.
Definition LTO.cpp:353
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
LLVM_ABI void thinLTOResolvePrevailingInIndex(const lto::Config &C, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
Definition LTO.cpp:447
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:250
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1847
cl::opt< std::optional< uint64_t >, false, remarks::HotnessThresholdParser > RemarksHotnessThreshold("lto-pass-remarks-hotness-threshold", cl::desc("Minimum profile count required for an " "optimization remark to be output." " Use 'auto' to apply the threshold from profile summary."), cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden)
LLVM_ABI std::string computeLTOCacheKey(const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const DenseSet< GlobalValue::GUID > &CfiFunctionDefs={}, const DenseSet< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
Definition LTO.cpp:103
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:59
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This type represents a file cache system that manages caching of files.
Definition Caching.h:85
Struct that holds a reference to a particular GUID in a global value summary.
This represents a symbol that has been read from a storage::Symbol and possibly a storage::Uncommon.
Definition IRSymtab.h:172
StringRef getName() const
Returns the mangled symbol name.
Definition IRSymtab.h:185
bool canBeOmittedFromSymbolTable() const
Definition IRSymtab.h:208
bool isUsed() const
Definition IRSymtab.h:205
StringRef getSectionName() const
Definition IRSymtab.h:234
bool isTLS() const
Definition IRSymtab.h:206
bool isWeak() const
Definition IRSymtab.h:202
bool isIndirect() const
Definition IRSymtab.h:204
bool isCommon() const
Definition IRSymtab.h:203
uint32_t getCommonAlignment() const
Definition IRSymtab.h:222
bool isExecutable() const
Definition IRSymtab.h:215
uint64_t getCommonSize() const
Definition IRSymtab.h:217
storage::Symbol S
Definition IRSymtab.h:195
int getComdatIndex() const
Returns the index into the comdat table (see Reader::getComdatTable()), or -1 if not a comdat member.
Definition IRSymtab.h:193
GlobalValue::VisibilityTypes getVisibility() const
Definition IRSymtab.h:197
bool isUndefined() const
Definition IRSymtab.h:201
StringRef getIRName() const
Returns the unmangled symbol name, or the empty string if this is not an IR symbol.
Definition IRSymtab.h:189
StringRef getCOFFWeakExternalFallback() const
COFF-specific: for weak externals, returns the name of the symbol that is used as a fallback if the w...
Definition IRSymtab.h:229
LTO configuration.
Definition Config.h:42
The purpose of this struct is to only expose the symbol information that an LTO client should need in...
Definition LTO.h:148
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:152
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:300
std::vector< GlobalValue * > Keep
Definition LTO.h:451
std::unique_ptr< Module > M
Definition LTO.h:450
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:436
The resolution for a symbol.
Definition LTO.h:588
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:598
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:605
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:594
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:609
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:601
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:280
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition LTO.h:285
bool isValid() const
Definition LTO.h:294
ThreadPoolStrategy getParallelism() const
Definition LTO.h:293
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:281