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
21#include <memory>
22
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/MapVector.h"
27#include "llvm/LTO/Config.h"
30#include "llvm/Support/Error.h"
33#include "llvm/Support/thread.h"
36
37namespace llvm {
38
39class Error;
40class IRMover;
41class LLVMContext;
42class MemoryBufferRef;
43class Module;
45class ToolOutputFile;
46
47/// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
48/// recorded in the index and the ThinLTO backends must apply the changes to
49/// the module via thinLTOFinalizeInModule.
50///
51/// This is done for correctness (if value exported, ensure we always
52/// emit a copy), and compile-time optimization (allow drop of duplicates).
54 const lto::Config &C, ModuleSummaryIndex &Index,
56 isPrevailing,
58 recordNewLinkage,
59 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
60
61/// Update the linkages in the given \p Index to mark exported values
62/// as external and non-exported values as internal. The ThinLTO backends
63/// must apply the changes to the Module via thinLTOInternalizeModule.
65 ModuleSummaryIndex &Index,
66 function_ref<bool(StringRef, ValueInfo)> isExported,
68 isPrevailing,
69 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr = nullptr);
70
71/// Computes a unique hash for the Module considering the current list of
72/// export/import and other global analysis results.
74 const lto::Config &Conf, const ModuleSummaryIndex &Index,
75 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
76 const FunctionImporter::ExportSetTy &ExportList,
77 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
78 const GVSummaryMapTy &DefinedGlobals,
79 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs = {},
80 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls = {});
81
82/// Recomputes the LTO cache key for a given key with an extra identifier.
83LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key,
84 StringRef ExtraID);
85
86namespace lto {
87
88LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple);
89
90/// Given the original \p Path to an output file, replace any path
91/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
92/// resulting directory if it does not yet exist.
93LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
94 StringRef NewPrefix);
95
96/// Setup optimization remarks.
97LLVM_ABI Expected<LLVMRemarkFileHandle> setupLLVMOptimizationRemarks(
98 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
99 StringRef RemarksFormat, bool RemarksWithHotness,
100 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
101
102/// Setups the output file for saving statistics.
103LLVM_ABI Expected<std::unique_ptr<ToolOutputFile>>
104setupStatsFile(StringRef StatsFilename);
105
106/// Produces a container ordering for optimal multi-threaded processing. Returns
107/// ordered indices to elements in the input array.
109
110class LTO;
111struct SymbolResolution;
112
113/// An input file. This is a symbol table wrapper that only exposes the
114/// information that an LTO client should need in order to do symbol resolution.
115class InputFile {
116public:
117 struct Symbol;
118
119private:
120 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
121 friend LTO;
122 InputFile() = default;
123
124 std::vector<BitcodeModule> Mods;
126 std::vector<Symbol> Symbols;
127
128 // [begin, end) for each module
129 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
130
131 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
132 std::vector<StringRef> DependentLibraries;
133 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
134
135 MemoryBufferRef MbRef;
136 bool IsFatLTOObject = false;
137 // For distributed compilation, each input must exist as an individual bitcode
138 // file on disk and be identified by its ModuleID. Archive members and FatLTO
139 // objects violate this. So, in these cases we flag that the bitcode must be
140 // written out to a new standalone file.
141 bool SerializeForDistribution = false;
142 bool IsThinLTO = false;
143 StringRef ArchivePath;
144 StringRef MemberName;
145
146public:
148
149 /// Create an InputFile.
151 create(MemoryBufferRef Object);
152
153 /// The purpose of this struct is to only expose the symbol information that
154 /// an LTO client should need in order to do symbol resolution.
156 friend LTO;
157
158 public:
160
177
178 // Returns whether this symbol is a library call that LTO code generation
179 // may emit references to. Such symbols must be considered external, as
180 // removing them or modifying their interfaces would invalidate the code
181 // generator's knowledge about them.
182 bool isLibcall(const RTLIB::RuntimeLibcallsInfo &Libcalls) const;
183 };
184
185 /// A range over the symbols in this InputFile.
186 ArrayRef<Symbol> symbols() const { return Symbols; }
187
188 /// Returns linker options specified in the input file.
189 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
190
191 /// Returns dependent library specifiers from the input file.
192 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
193
194 /// Returns the path to the InputFile.
195 LLVM_ABI StringRef getName() const;
196
197 /// Returns the input file's target triple.
198 StringRef getTargetTriple() const { return TargetTriple; }
199
200 /// Returns the source file path specified at compile time.
201 StringRef getSourceFileName() const { return SourceFileName; }
202
203 // Returns a table with all the comdats used by this file.
207
208 // Returns the only BitcodeModule from InputFile.
210 // Returns the primary BitcodeModule from InputFile.
212 // Returns the memory buffer reference for this input file.
213 MemoryBufferRef getFileBuffer() const { return MbRef; }
214 // Returns true if this input should be serialized to disk for distribution.
215 // See the comment on SerializeForDistribution for details.
216 bool getSerializeForDistribution() const { return SerializeForDistribution; }
217 // Mark whether this input should be serialized to disk for distribution.
218 // See the comment on SerializeForDistribution for details.
219 void setSerializeForDistribution(bool SFD) { SerializeForDistribution = SFD; }
220 // Returns true if this bitcode came from a FatLTO object.
221 bool isFatLTOObject() const { return IsFatLTOObject; }
222 // Mark this bitcode as coming from a FatLTO object.
223 void fatLTOObject(bool FO) { IsFatLTOObject = FO; }
224
225 // Returns true if bitcode is ThinLTO.
226 bool isThinLTO() const { return IsThinLTO; }
227
228 // Store an archive path and a member name.
230 ArchivePath = Path;
231 MemberName = Name;
232 }
233 StringRef getArchivePath() const { return ArchivePath; }
234 StringRef getMemberName() const { return MemberName; }
235
236private:
237 ArrayRef<Symbol> module_symbols(unsigned I) const {
238 const auto &Indices = ModuleSymIndices[I];
239 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
240 }
241};
242
243using IndexWriteCallback = std::function<void(const std::string &)>;
244
246
247/// This class defines the interface to the ThinLTO backend.
249protected:
250 const Config &Conf;
256 std::optional<Error> Err;
257 std::mutex ErrMu;
258
259public:
269
270 virtual ~ThinBackendProc() = default;
271 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
272 Triple Triple) {}
273 virtual Error start(
274 unsigned Task, BitcodeModule BM,
275 const FunctionImporter::ImportMapTy &ImportList,
276 const FunctionImporter::ExportSetTy &ExportList,
277 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
279 virtual Error wait() {
280 BackendThreadPool.wait();
281 if (Err)
282 return std::move(*Err);
283 return Error::success();
284 }
285 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
286 virtual bool isSensitiveToInputOrder() { return false; }
287
288 // Write sharded indices and (optionally) imports to disk
290 StringRef ModulePath,
291 const std::string &NewModulePath) const;
292
293 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
294 // (optionally) record imports in ImportsFiles.
296 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
297 const std::string &NewModulePath, StringRef SummaryPath,
298 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
299 const;
300};
301
302/// This callable defines the behavior of a ThinLTO backend after the thin-link
303/// phase. It accepts a configuration \p C, a combined module summary index
304/// \p CombinedIndex, a map of module identifiers to global variable summaries
305/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
306/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
307/// ThinBackendProc, which can be used to launch backends in parallel.
308using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
309 const Config &C, ModuleSummaryIndex &CombinedIndex,
310 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
311 AddStreamFn AddStream, FileCache Cache)>;
312
313/// This type defines the behavior following the thin-link phase during ThinLTO.
314/// It encapsulates a backend function and a strategy for thread pool
315/// parallelism. Clients should use one of the provided create*ThinBackend()
316/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
317/// strategy to be used for processing.
320 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
321 ThinBackend() = default;
322
323 std::unique_ptr<ThinBackendProc> operator()(
324 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
325 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
326 AddStreamFn AddStream, FileCache Cache) {
327 assert(isValid() && "Invalid backend function");
328 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
329 std::move(AddStream), std::move(Cache));
330 }
331 ThreadPoolStrategy getParallelism() const { return Parallelism; }
332 bool isValid() const { return static_cast<bool>(Func); }
333
334private:
335 ThinBackendFunction Func = nullptr;
336 ThreadPoolStrategy Parallelism;
337};
338
339/// This ThinBackend runs the individual backend jobs in-process.
340/// The default value means to use one job per hardware core (not hyper-thread).
341/// OnWrite is callback which receives module identifier and notifies LTO user
342/// that index file for the module (and optionally imports file) was created.
343/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
344/// to the same path as the input module, with suffix ".thinlto.bc"
345/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
346/// similar path with ".imports" appended instead.
348 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
349 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
350
351/// This ThinBackend generates the index shards and then runs the individual
352/// backend jobs via an external process. It takes the same parameters as the
353/// InProcessThinBackend; however, these parameters only control the behavior
354/// when generating the index files for the modules. Additionally:
355/// LinkerOutputFile is a string that should identify this LTO invocation in
356/// the context of a wider build. It's used for naming to aid the user in
357/// identifying activity related to a specific LTO invocation.
358/// Distributor specifies the path to a process to invoke to manage the backend
359/// job execution.
360/// DistributorArgs specifies a list of arguments to be applied to the
361/// distributor.
362/// RemoteCompiler specifies the path to a Clang executable to be invoked for
363/// the backend jobs.
364/// RemoteCompilerPrependArgs specifies a list of prepend arguments to be
365/// applied to the backend compilations.
366/// RemoteCompilerArgs specifies a list of arguments to be applied to the
367/// backend compilations.
368/// SaveTemps is a debugging tool that prevents temporary files created by this
369/// backend from being cleaned up.
371 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
372 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
373 StringRef LinkerOutputFile, StringRef Distributor,
374 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
375 ArrayRef<StringRef> RemoteCompilerPrependArgs,
376 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps);
377
378/// This ThinBackend writes individual module indexes to files, instead of
379/// running the individual backend jobs. This backend is for distributed builds
380/// where separate processes will invoke the real backends.
381///
382/// To find the path to write the index to, the backend checks if the path has a
383/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
384/// appends ".thinlto.bc" and writes the index to that path. If
385/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
386/// similar path with ".imports" appended instead.
387/// LinkedObjectsFile is an output stream to write the list of object files for
388/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
389/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
390/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
391/// callback which receives module identifier and notifies LTO user that index
392/// file for the module (and optionally imports file) was created.
394 ThreadPoolStrategy Parallelism, std::string OldPrefix,
395 std::string NewPrefix, std::string NativeObjectPrefix,
396 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
397 IndexWriteCallback OnWrite);
398
399/// This class implements a resolution-based interface to LLVM's LTO
400/// functionality. It supports regular LTO, parallel LTO code generation and
401/// ThinLTO. You can use it from a linker in the following way:
402/// - Set hooks and code generation options (see lto::Config struct defined in
403/// Config.h), and use the lto::Config object to create an lto::LTO object.
404/// - Create lto::InputFile objects using lto::InputFile::create(), then use
405/// the symbols() function to enumerate its symbols and compute a resolution
406/// for each symbol (see SymbolResolution below).
407/// - After the linker has visited each input file (and each regular object
408/// file) and computed a resolution for each symbol, take each lto::InputFile
409/// and pass it and an array of symbol resolutions to the add() function.
410/// - Call the getMaxTasks() function to get an upper bound on the number of
411/// native object files that LTO may add to the link.
412/// - Call the run() function. This function will use the supplied AddStream
413/// and Cache functions to add up to getMaxTasks() native object files to
414/// the link.
415class LTO {
416 friend InputFile;
417
418public:
419 /// Unified LTO modes
420 enum LTOKind {
421 /// Any LTO mode without Unified LTO. The default mode.
423
424 /// Regular LTO, with Unified LTO enabled.
426
427 /// ThinLTO, with Unified LTO enabled.
429 };
430
431 /// Create an LTO object. A default constructed LTO object has a reasonable
432 /// production configuration, but you can customize it by passing arguments to
433 /// this constructor.
434 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
435 /// Until that is fixed, a Config argument is required.
436 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
437 unsigned ParallelCodeGenParallelismLevel = 1,
438 LTOKind LTOMode = LTOK_Default);
439 LLVM_ABI virtual ~LTO();
440
441 /// Add an input file to the LTO link, using the provided symbol resolutions.
442 /// The symbol resolutions must appear in the enumeration order given by
443 /// InputFile::symbols().
444 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
446
447 /// Returns an upper bound on the number of tasks that the client may expect.
448 /// This may only be called after all IR object files have been added. For a
449 /// full description of tasks see LTOBackend.h.
450 LLVM_ABI unsigned getMaxTasks() const;
451
452 /// Runs the LTO pipeline. This function calls the supplied AddStream
453 /// function to add native object files to the link.
454 ///
455 /// The Cache parameter is optional. If supplied, it will be used to cache
456 /// native object files and add them to the link.
457 ///
458 /// The client will receive at most one callback (via either AddStream or
459 /// Cache) for each task identifier.
460 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
461
462 /// Static method that returns a list of libcall symbols that can be generated
463 /// by LTO but might not be visible from bitcode symbol table.
466
467protected:
468 // Called at the start of run().
470
471 // Called before returning from run().
472 virtual void cleanup();
473
474private:
475 Config Conf;
476
477 struct RegularLTOState {
478 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
479 const Config &Conf);
483 /// Record if at least one instance of the common was marked as prevailing
484 bool Prevailing = false;
485 };
486 std::map<std::string, CommonResolution> Commons;
487
488 unsigned ParallelCodeGenParallelismLevel;
489 LTOLLVMContext Ctx;
490 std::unique_ptr<Module> CombinedModule;
491 std::unique_ptr<IRMover> Mover;
492
493 // This stores the information about a regular LTO module that we have added
494 // to the link. It will either be linked immediately (for modules without
495 // summaries) or after summary-based dead stripping (for modules with
496 // summaries).
497 struct AddedModule {
498 std::unique_ptr<Module> M;
499 std::vector<GlobalValue *> Keep;
500 };
501 std::vector<AddedModule> ModsWithSummaries;
502 bool EmptyCombinedModule = true;
503 } RegularLTO;
504
505 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
506
507 struct ThinLTOState {
508 LLVM_ABI ThinLTOState(ThinBackend Backend);
509
510 ThinBackend Backend;
511 ModuleSummaryIndex CombinedIndex;
512 // The full set of bitcode modules in input order.
513 ModuleMapType ModuleMap;
514 // The bitcode modules to compile, if specified by the LTO Config.
515 std::optional<ModuleMapType> ModulesToCompile;
516
517 void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) {
518 PrevailingModuleForGUID[GUID] = Module;
519 }
520 bool isPrevailingModuleForGUID(GlobalValue::GUID GUID,
521 StringRef Module) const {
522 auto It = PrevailingModuleForGUID.find(GUID);
523 return It != PrevailingModuleForGUID.end() && It->second == Module;
524 }
525
526 private:
527 // Make this private so all accesses must go through above accessor methods
528 // to avoid inadvertently creating new entries on lookups.
529 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
530 } ThinLTO;
531
532 // The global resolution for a particular (mangled) symbol name. This is in
533 // particular necessary to track whether each symbol can be internalized.
534 // Because any input file may introduce a new cross-partition reference, we
535 // cannot make any final internalization decisions until all input files have
536 // been added and the client has called run(). During run() we apply
537 // internalization decisions either directly to the module (for regular LTO)
538 // or to the combined index (for ThinLTO).
539 struct GlobalResolution {
540 /// The unmangled name of the global.
541 std::string IRName;
542
543 /// Keep track if the symbol is visible outside of a module with a summary
544 /// (i.e. in either a regular object or a regular LTO module without a
545 /// summary).
546 bool VisibleOutsideSummary = false;
547
548 /// The symbol was exported dynamically, and therefore could be referenced
549 /// by a shared library not visible to the linker.
550 bool ExportDynamic = false;
551
552 bool UnnamedAddr = true;
553
554 /// True if module contains the prevailing definition.
555 bool Prevailing = false;
556
557 /// Returns true if module contains the prevailing definition and symbol is
558 /// an IR symbol. For example when module-level inline asm block is used,
559 /// symbol can be prevailing in module but have no IR name.
560 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
561
562 /// This field keeps track of the partition number of this global. The
563 /// regular LTO object is partition 0, while each ThinLTO object has its own
564 /// partition number from 1 onwards.
565 ///
566 /// Any global that is defined or used by more than one partition, or that
567 /// is referenced externally, may not be internalized.
568 ///
569 /// Partitions generally have a one-to-one correspondence with tasks, except
570 /// that we use partition 0 for all parallel LTO code generation partitions.
571 /// Any partitioning of the combined LTO object is done internally by the
572 /// LTO backend.
573 unsigned Partition = Unknown;
574
575 /// Special partition numbers.
576 enum : unsigned {
577 /// A partition number has not yet been assigned to this global.
578 Unknown = -1u,
579
580 /// This global is either used by more than one partition or has an
581 /// external reference, and therefore cannot be internalized.
582 External = -2u,
583
584 /// The RegularLTO partition
585 RegularLTO = 0,
586 };
587 };
588
589 // GlobalResolutionSymbolSaver allocator.
590 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
591
592 // Symbol saver for global resolution map.
593 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
594
595 // Global mapping from mangled symbol names to resolutions.
596 // Make this an unique_ptr to guard against accessing after it has been reset
597 // (to reduce memory after we're done with it).
598 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
599 GlobalResolutions;
600
601 void releaseGlobalResolutionsMemory();
602
603 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
604 ArrayRef<SymbolResolution> Res, unsigned Partition,
605 bool InSummary, const Triple &TT);
606
607 // These functions take a range of symbol resolutions and consume the
608 // resolutions used by a single input module. Functions return ranges refering
609 // to the resolutions for the remaining modules in the InputFile.
610 Expected<ArrayRef<SymbolResolution>>
611 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
612 unsigned ModI, ArrayRef<SymbolResolution> Res);
613
614 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
615 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
616 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
619 bool LivenessFromIndex);
620
621 Expected<ArrayRef<SymbolResolution>>
622 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
624
625 Error runRegularLTO(AddStreamFn AddStream);
626 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
627 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
628
629 Error checkPartiallySplit();
630
631 mutable bool CalledGetMaxTasks = false;
632
633 // LTO mode when using Unified LTO.
634 LTOKind LTOMode;
635
636 // Use Optional to distinguish false from not yet initialized.
637 std::optional<bool> EnableSplitLTOUnit;
638
639 // Identify symbols exported dynamically, and that therefore could be
640 // referenced by a shared library not visible to the linker.
641 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
642
643 // Diagnostic optimization remarks file
644 LLVMRemarkFileHandle DiagnosticOutputFile;
645
646 // A dummy module to host the dummy function.
647 std::unique_ptr<Module> DummyModule;
648
649 // A dummy function created in a private module to provide a context for
650 // LTO-link optimization remarks. This is needed for ThinLTO where we
651 // may not have any IR functions available, because the optimization remark
652 // handling requires a function.
653 Function *LinkerRemarkFunction = nullptr;
654
655 // Setup optimization remarks according to the provided configuration.
656 Error setupOptimizationRemarks();
657
658public:
659 /// Helper to emit an optimization remark during the LTO link when outside of
660 /// the standard optimization pass pipeline.
661 void emitRemark(OptimizationRemark &Remark);
662
663 virtual Expected<std::shared_ptr<lto::InputFile>>
664 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
665 return std::shared_ptr<lto::InputFile>(InputPtr.release());
666 }
667};
668
669/// The resolution for a symbol. The linker must provide a SymbolResolution for
670/// each global symbol based on its internal resolution of that symbol.
675
676 /// The linker has chosen this definition of the symbol.
677 unsigned Prevailing : 1;
678
679 /// The definition of this symbol is unpreemptable at runtime and is known to
680 /// be in this linkage unit.
682
683 /// The definition of this symbol is visible outside of the LTO unit.
685
686 /// The symbol was exported dynamically, and therefore could be referenced
687 /// by a shared library not visible to the linker.
688 unsigned ExportDynamic : 1;
689
690 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
691 /// linker option.
692 unsigned LinkerRedefined : 1;
693};
694
695} // namespace lto
696} // namespace llvm
697
698#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:669
MemoryBufferRef getFileBuffer() const
Definition LTO.h:213
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:624
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:186
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:189
bool isFatLTOObject() const
Definition LTO.h:221
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:192
StringRef getArchivePath() const
Definition LTO.h:233
StringRef getMemberName() const
Definition LTO.h:234
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:204
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:198
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:660
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:664
void setSerializeForDistribution(bool SFD)
Definition LTO.h:219
bool getSerializeForDistribution() const
Definition LTO.h:216
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:201
bool isThinLTO() const
Definition LTO.h:226
void fatLTOObject(bool FO)
Definition LTO.h:223
void setArchivePathAndName(StringRef Path, StringRef Name)
Definition LTO.h:229
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:415
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:684
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:816
virtual void cleanup()
Definition LTO.cpp:701
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:1481
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:664
virtual Error serializeInputsForDistribution()
Definition LTO.h:469
LTOKind
Unified LTO modes.
Definition LTO.h:420
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:425
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:422
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:428
virtual LLVM_ABI ~LTO()
void emitRemark(OptimizationRemark &Remark)
Helper to emit an optimization remark during the LTO link when outside of the standard optimization p...
Definition LTO.cpp:101
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1238
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1289
DefaultThreadPool BackendThreadPool
Definition LTO.h:255
const Config & Conf
Definition LTO.h:250
std::optional< Error > Err
Definition LTO.h:256
virtual bool isSensitiveToInputOrder()
Definition LTO.h:286
unsigned getThreadCount()
Definition LTO.h:285
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:252
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1494
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:260
virtual Error wait()
Definition LTO.h:279
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:251
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:271
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:253
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:1844
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:1878
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1860
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2293
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:2761
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:243
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:1964
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:2268
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2312
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:245
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:308
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 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:388
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:488
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:1917
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:137
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
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:606
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
A simple container for information about the supported runtime calls.
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:155
bool isLibcall(const RTLIB::RuntimeLibcallsInfo &Libcalls) const
Definition LTO.cpp:655
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:159
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:499
std::unique_ptr< Module > M
Definition LTO.h:498
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:484
The resolution for a symbol.
Definition LTO.h:671
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:681
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:688
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:677
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:692
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:684
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:318
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition LTO.h:323
bool isValid() const
Definition LTO.h:332
ThreadPoolStrategy getParallelism() const
Definition LTO.h:331
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:319