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
108class LTO;
109struct SymbolResolution;
110
111/// An input file. This is a symbol table wrapper that only exposes the
112/// information that an LTO client should need in order to do symbol resolution.
113class InputFile {
114public:
115 struct Symbol;
116
117private:
118 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
119 friend LTO;
120 InputFile() = default;
121
122 std::vector<BitcodeModule> Mods;
124 std::vector<Symbol> Symbols;
125
126 // [begin, end) for each module
127 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
128
129 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
130 std::vector<StringRef> DependentLibraries;
131 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
132
133 MemoryBufferRef MbRef;
134 bool IsMemberOfArchive = false;
135 bool IsThinLTO = false;
136 StringRef ArchivePath;
137 StringRef MemberName;
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 // Returns the memory buffer reference for this input file.
198 MemoryBufferRef getFileBuffer() const { return MbRef; }
199 // Returns true if this input file is a member of an archive.
200 bool isMemberOfArchive() const { return IsMemberOfArchive; }
201 // Mark this input file as a member of archive.
202 void memberOfArchive(bool MA) { IsMemberOfArchive = MA; }
203
204 // Returns true if bitcode is ThinLTO.
205 bool isThinLTO() const { return IsThinLTO; }
206
207 // Store an archive path and a member name.
209 ArchivePath = Path;
210 MemberName = Name;
211 }
212 StringRef getArchivePath() const { return ArchivePath; }
213 StringRef getMemberName() const { return MemberName; }
214
215private:
216 ArrayRef<Symbol> module_symbols(unsigned I) const {
217 const auto &Indices = ModuleSymIndices[I];
218 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
219 }
220};
221
222using IndexWriteCallback = std::function<void(const std::string &)>;
223
225
226/// This class defines the interface to the ThinLTO backend.
228protected:
229 const Config &Conf;
235 std::optional<Error> Err;
236 std::mutex ErrMu;
237
238public:
248
249 virtual ~ThinBackendProc() = default;
250 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
251 Triple Triple) {}
252 virtual Error start(
253 unsigned Task, BitcodeModule BM,
254 const FunctionImporter::ImportMapTy &ImportList,
255 const FunctionImporter::ExportSetTy &ExportList,
256 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
258 virtual Error wait() {
259 BackendThreadPool.wait();
260 if (Err)
261 return std::move(*Err);
262 return Error::success();
263 }
264 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
265 virtual bool isSensitiveToInputOrder() { return false; }
266
267 // Write sharded indices and (optionally) imports to disk
269 StringRef ModulePath,
270 const std::string &NewModulePath) const;
271
272 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
273 // (optionally) record imports in ImportsFiles.
275 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
276 const std::string &NewModulePath, StringRef SummaryPath,
277 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
278 const;
279};
280
281/// This callable defines the behavior of a ThinLTO backend after the thin-link
282/// phase. It accepts a configuration \p C, a combined module summary index
283/// \p CombinedIndex, a map of module identifiers to global variable summaries
284/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
285/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
286/// ThinBackendProc, which can be used to launch backends in parallel.
287using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
288 const Config &C, ModuleSummaryIndex &CombinedIndex,
289 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
290 AddStreamFn AddStream, FileCache Cache)>;
291
292/// This type defines the behavior following the thin-link phase during ThinLTO.
293/// It encapsulates a backend function and a strategy for thread pool
294/// parallelism. Clients should use one of the provided create*ThinBackend()
295/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
296/// strategy to be used for processing.
299 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
300 ThinBackend() = default;
301
302 std::unique_ptr<ThinBackendProc> operator()(
303 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
304 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
305 AddStreamFn AddStream, FileCache Cache) {
306 assert(isValid() && "Invalid backend function");
307 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
308 std::move(AddStream), std::move(Cache));
309 }
310 ThreadPoolStrategy getParallelism() const { return Parallelism; }
311 bool isValid() const { return static_cast<bool>(Func); }
312
313private:
314 ThinBackendFunction Func = nullptr;
315 ThreadPoolStrategy Parallelism;
316};
317
318/// This ThinBackend runs the individual backend jobs in-process.
319/// The default value means to use one job per hardware core (not hyper-thread).
320/// OnWrite is callback which receives module identifier and notifies LTO user
321/// that index file for the module (and optionally imports file) was created.
322/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
323/// to the same path as the input module, with suffix ".thinlto.bc"
324/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
325/// similar path with ".imports" appended instead.
327 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
328 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
329
330/// This ThinBackend generates the index shards and then runs the individual
331/// backend jobs via an external process. It takes the same parameters as the
332/// InProcessThinBackend; however, these parameters only control the behavior
333/// when generating the index files for the modules. Additionally:
334/// LinkerOutputFile is a string that should identify this LTO invocation in
335/// the context of a wider build. It's used for naming to aid the user in
336/// identifying activity related to a specific LTO invocation.
337/// Distributor specifies the path to a process to invoke to manage the backend
338/// job execution.
339/// DistributorArgs specifies a list of arguments to be applied to the
340/// distributor.
341/// RemoteCompiler specifies the path to a Clang executable to be invoked for
342/// the backend jobs.
343/// RemoteCompilerPrependArgs specifies a list of prepend arguments to be
344/// applied to the backend compilations.
345/// RemoteCompilerArgs specifies a list of arguments to be applied to the
346/// backend compilations.
347/// SaveTemps is a debugging tool that prevents temporary files created by this
348/// backend from being cleaned up.
350 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
351 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
352 StringRef LinkerOutputFile, StringRef Distributor,
353 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
354 ArrayRef<StringRef> RemoteCompilerPrependArgs,
355 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps);
356
357/// This ThinBackend writes individual module indexes to files, instead of
358/// running the individual backend jobs. This backend is for distributed builds
359/// where separate processes will invoke the real backends.
360///
361/// To find the path to write the index to, the backend checks if the path has a
362/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
363/// appends ".thinlto.bc" and writes the index to that path. If
364/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
365/// similar path with ".imports" appended instead.
366/// LinkedObjectsFile is an output stream to write the list of object files for
367/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
368/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
369/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
370/// callback which receives module identifier and notifies LTO user that index
371/// file for the module (and optionally imports file) was created.
373 ThreadPoolStrategy Parallelism, std::string OldPrefix,
374 std::string NewPrefix, std::string NativeObjectPrefix,
375 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
376 IndexWriteCallback OnWrite);
377
378/// This class implements a resolution-based interface to LLVM's LTO
379/// functionality. It supports regular LTO, parallel LTO code generation and
380/// ThinLTO. You can use it from a linker in the following way:
381/// - Set hooks and code generation options (see lto::Config struct defined in
382/// Config.h), and use the lto::Config object to create an lto::LTO object.
383/// - Create lto::InputFile objects using lto::InputFile::create(), then use
384/// the symbols() function to enumerate its symbols and compute a resolution
385/// for each symbol (see SymbolResolution below).
386/// - After the linker has visited each input file (and each regular object
387/// file) and computed a resolution for each symbol, take each lto::InputFile
388/// and pass it and an array of symbol resolutions to the add() function.
389/// - Call the getMaxTasks() function to get an upper bound on the number of
390/// native object files that LTO may add to the link.
391/// - Call the run() function. This function will use the supplied AddStream
392/// and Cache functions to add up to getMaxTasks() native object files to
393/// the link.
394class LTO {
395 friend InputFile;
396
397public:
398 /// Unified LTO modes
399 enum LTOKind {
400 /// Any LTO mode without Unified LTO. The default mode.
402
403 /// Regular LTO, with Unified LTO enabled.
405
406 /// ThinLTO, with Unified LTO enabled.
408 };
409
410 /// Create an LTO object. A default constructed LTO object has a reasonable
411 /// production configuration, but you can customize it by passing arguments to
412 /// this constructor.
413 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
414 /// Until that is fixed, a Config argument is required.
415 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
416 unsigned ParallelCodeGenParallelismLevel = 1,
417 LTOKind LTOMode = LTOK_Default);
418 LLVM_ABI virtual ~LTO();
419
420 /// Add an input file to the LTO link, using the provided symbol resolutions.
421 /// The symbol resolutions must appear in the enumeration order given by
422 /// InputFile::symbols().
423 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
425
426 /// Returns an upper bound on the number of tasks that the client may expect.
427 /// This may only be called after all IR object files have been added. For a
428 /// full description of tasks see LTOBackend.h.
429 LLVM_ABI unsigned getMaxTasks() const;
430
431 /// Runs the LTO pipeline. This function calls the supplied AddStream
432 /// function to add native object files to the link.
433 ///
434 /// The Cache parameter is optional. If supplied, it will be used to cache
435 /// native object files and add them to the link.
436 ///
437 /// The client will receive at most one callback (via either AddStream or
438 /// Cache) for each task identifier.
439 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
440
441 /// Static method that returns a list of libcall symbols that can be generated
442 /// by LTO but might not be visible from bitcode symbol table.
445
446private:
447 Config Conf;
448
449 struct RegularLTOState {
450 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
451 const Config &Conf);
455 /// Record if at least one instance of the common was marked as prevailing
456 bool Prevailing = false;
457 };
458 std::map<std::string, CommonResolution> Commons;
459
460 unsigned ParallelCodeGenParallelismLevel;
461 LTOLLVMContext Ctx;
462 std::unique_ptr<Module> CombinedModule;
463 std::unique_ptr<IRMover> Mover;
464
465 // This stores the information about a regular LTO module that we have added
466 // to the link. It will either be linked immediately (for modules without
467 // summaries) or after summary-based dead stripping (for modules with
468 // summaries).
469 struct AddedModule {
470 std::unique_ptr<Module> M;
471 std::vector<GlobalValue *> Keep;
472 };
473 std::vector<AddedModule> ModsWithSummaries;
474 bool EmptyCombinedModule = true;
475 } RegularLTO;
476
477 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
478
479 struct ThinLTOState {
480 LLVM_ABI ThinLTOState(ThinBackend Backend);
481
482 ThinBackend Backend;
483 ModuleSummaryIndex CombinedIndex;
484 // The full set of bitcode modules in input order.
485 ModuleMapType ModuleMap;
486 // The bitcode modules to compile, if specified by the LTO Config.
487 std::optional<ModuleMapType> ModulesToCompile;
488
489 void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) {
490 PrevailingModuleForGUID[GUID] = Module;
491 }
492 bool isPrevailingModuleForGUID(GlobalValue::GUID GUID,
493 StringRef Module) const {
494 auto It = PrevailingModuleForGUID.find(GUID);
495 return It != PrevailingModuleForGUID.end() && It->second == Module;
496 }
497
498 private:
499 // Make this private so all accesses must go through above accessor methods
500 // to avoid inadvertently creating new entries on lookups.
501 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
502 } ThinLTO;
503
504 // The global resolution for a particular (mangled) symbol name. This is in
505 // particular necessary to track whether each symbol can be internalized.
506 // Because any input file may introduce a new cross-partition reference, we
507 // cannot make any final internalization decisions until all input files have
508 // been added and the client has called run(). During run() we apply
509 // internalization decisions either directly to the module (for regular LTO)
510 // or to the combined index (for ThinLTO).
511 struct GlobalResolution {
512 /// The unmangled name of the global.
513 std::string IRName;
514
515 /// Keep track if the symbol is visible outside of a module with a summary
516 /// (i.e. in either a regular object or a regular LTO module without a
517 /// summary).
518 bool VisibleOutsideSummary = false;
519
520 /// The symbol was exported dynamically, and therefore could be referenced
521 /// by a shared library not visible to the linker.
522 bool ExportDynamic = false;
523
524 bool UnnamedAddr = true;
525
526 /// True if module contains the prevailing definition.
527 bool Prevailing = false;
528
529 /// Returns true if module contains the prevailing definition and symbol is
530 /// an IR symbol. For example when module-level inline asm block is used,
531 /// symbol can be prevailing in module but have no IR name.
532 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
533
534 /// This field keeps track of the partition number of this global. The
535 /// regular LTO object is partition 0, while each ThinLTO object has its own
536 /// partition number from 1 onwards.
537 ///
538 /// Any global that is defined or used by more than one partition, or that
539 /// is referenced externally, may not be internalized.
540 ///
541 /// Partitions generally have a one-to-one correspondence with tasks, except
542 /// that we use partition 0 for all parallel LTO code generation partitions.
543 /// Any partitioning of the combined LTO object is done internally by the
544 /// LTO backend.
545 unsigned Partition = Unknown;
546
547 /// Special partition numbers.
548 enum : unsigned {
549 /// A partition number has not yet been assigned to this global.
550 Unknown = -1u,
551
552 /// This global is either used by more than one partition or has an
553 /// external reference, and therefore cannot be internalized.
554 External = -2u,
555
556 /// The RegularLTO partition
557 RegularLTO = 0,
558 };
559 };
560
561 // GlobalResolutionSymbolSaver allocator.
562 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
563
564 // Symbol saver for global resolution map.
565 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
566
567 // Global mapping from mangled symbol names to resolutions.
568 // Make this an unique_ptr to guard against accessing after it has been reset
569 // (to reduce memory after we're done with it).
570 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
571 GlobalResolutions;
572
573 void releaseGlobalResolutionsMemory();
574
575 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
576 ArrayRef<SymbolResolution> Res, unsigned Partition,
577 bool InSummary);
578
579 // These functions take a range of symbol resolutions and consume the
580 // resolutions used by a single input module. Functions return ranges refering
581 // to the resolutions for the remaining modules in the InputFile.
582 Expected<ArrayRef<SymbolResolution>>
583 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
584 unsigned ModI, ArrayRef<SymbolResolution> Res);
585
586 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
587 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
588 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
591 bool LivenessFromIndex);
592
593 Expected<ArrayRef<SymbolResolution>>
594 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
596
597 Error runRegularLTO(AddStreamFn AddStream);
598 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
599 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
600
601 Error checkPartiallySplit();
602
603 mutable bool CalledGetMaxTasks = false;
604
605 // LTO mode when using Unified LTO.
606 LTOKind LTOMode;
607
608 // Use Optional to distinguish false from not yet initialized.
609 std::optional<bool> EnableSplitLTOUnit;
610
611 // Identify symbols exported dynamically, and that therefore could be
612 // referenced by a shared library not visible to the linker.
613 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
614
615 // Diagnostic optimization remarks file
616 LLVMRemarkFileHandle DiagnosticOutputFile;
617
618public:
619 virtual Expected<std::shared_ptr<lto::InputFile>>
620 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
621 return std::shared_ptr<lto::InputFile>(InputPtr.release());
622 }
623
625};
626
627/// The resolution for a symbol. The linker must provide a SymbolResolution for
628/// each global symbol based on its internal resolution of that symbol.
633
634 /// The linker has chosen this definition of the symbol.
635 unsigned Prevailing : 1;
636
637 /// The definition of this symbol is unpreemptable at runtime and is known to
638 /// be in this linkage unit.
640
641 /// The definition of this symbol is visible outside of the LTO unit.
643
644 /// The symbol was exported dynamically, and therefore could be referenced
645 /// by a shared library not visible to the linker.
646 unsigned ExportDynamic : 1;
647
648 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
649 /// linker option.
650 unsigned LinkerRedefined : 1;
651};
652
653} // namespace lto
654} // namespace llvm
655
656#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:57
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:40
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.
MemoryBufferRef getFileBuffer() const
Definition LTO.h:198
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:569
void memberOfArchive(bool MA)
Definition LTO.h:202
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
StringRef getArchivePath() const
Definition LTO.h:212
StringRef getMemberName() const
Definition LTO.h:213
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:600
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:604
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:188
bool isThinLTO() const
Definition LTO.h:205
bool isMemberOfArchive() const
Definition LTO.h:200
void setArchivePathAndName(StringRef Path, StringRef Name)
Definition LTO.h:208
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:394
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:622
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:743
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:1412
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:620
virtual llvm::Error handleArchiveInputs()
Definition LTO.h:624
LTOKind
Unified LTO modes.
Definition LTO.h:399
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:404
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:401
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:407
virtual 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:1166
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1217
DefaultThreadPool BackendThreadPool
Definition LTO.h:234
const Config & Conf
Definition LTO.h:229
std::optional< Error > Err
Definition LTO.h:235
virtual bool isSensitiveToInputOrder()
Definition LTO.h:265
unsigned getThreadCount()
Definition LTO.h:264
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:231
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1425
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:239
virtual Error wait()
Definition LTO.h:258
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:230
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:250
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:232
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:1775
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:1809
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1791
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2189
LLVM_ABI ThinBackend createOutOfProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles, StringRef LinkerOutputFile, StringRef Distributor, ArrayRef< StringRef > DistributorArgs, StringRef RemoteCompiler, ArrayRef< StringRef > RemoteCompilerPrependArgs, ArrayRef< StringRef > RemoteCompilerArgs, bool SaveTemps)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
Definition LTO.cpp:2657
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:222
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:1895
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:2164
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2208
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:224
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:287
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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:554
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:355
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:449
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:262
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:1915
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:104
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:58
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:84
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:305
std::vector< GlobalValue * > Keep
Definition LTO.h:471
std::unique_ptr< Module > M
Definition LTO.h:470
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:456
The resolution for a symbol.
Definition LTO.h:629
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:639
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:646
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:635
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:650
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:642
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:297
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition LTO.h:302
bool isValid() const
Definition LTO.h:311
ThreadPoolStrategy getParallelism() const
Definition LTO.h:310
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:298