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