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
133public:
135
136 /// Create an InputFile.
138 create(MemoryBufferRef Object);
139
140 /// The purpose of this struct is to only expose the symbol information that
141 /// an LTO client should need in order to do symbol resolution.
165
166 /// A range over the symbols in this InputFile.
167 ArrayRef<Symbol> symbols() const { return Symbols; }
168
169 /// Returns linker options specified in the input file.
170 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
171
172 /// Returns dependent library specifiers from the input file.
173 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
174
175 /// Returns the path to the InputFile.
176 LLVM_ABI StringRef getName() const;
177
178 /// Returns the input file's target triple.
179 StringRef getTargetTriple() const { return TargetTriple; }
180
181 /// Returns the source file path specified at compile time.
182 StringRef getSourceFileName() const { return SourceFileName; }
183
184 // Returns a table with all the comdats used by this file.
188
189 // Returns the only BitcodeModule from InputFile.
191
192private:
193 ArrayRef<Symbol> module_symbols(unsigned I) const {
194 const auto &Indices = ModuleSymIndices[I];
195 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
196 }
197};
198
199using IndexWriteCallback = std::function<void(const std::string &)>;
200
202
203/// This class defines the interface to the ThinLTO backend.
205protected:
206 const Config &Conf;
212 std::optional<Error> Err;
213 std::mutex ErrMu;
214
215public:
225
226 virtual ~ThinBackendProc() = default;
227 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
228 Triple Triple) {}
229 virtual Error start(
230 unsigned Task, BitcodeModule BM,
231 const FunctionImporter::ImportMapTy &ImportList,
232 const FunctionImporter::ExportSetTy &ExportList,
233 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
235 virtual Error wait() {
236 BackendThreadPool.wait();
237 if (Err)
238 return std::move(*Err);
239 return Error::success();
240 }
241 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
242 virtual bool isSensitiveToInputOrder() { return false; }
243
244 // Write sharded indices and (optionally) imports to disk
246 StringRef ModulePath,
247 const std::string &NewModulePath) const;
248
249 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
250 // (optionally) record imports in ImportsFiles.
252 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
253 const std::string &NewModulePath, StringRef SummaryPath,
254 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
255 const;
256};
257
258/// This callable defines the behavior of a ThinLTO backend after the thin-link
259/// phase. It accepts a configuration \p C, a combined module summary index
260/// \p CombinedIndex, a map of module identifiers to global variable summaries
261/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
262/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
263/// ThinBackendProc, which can be used to launch backends in parallel.
264using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
265 const Config &C, ModuleSummaryIndex &CombinedIndex,
266 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
267 AddStreamFn AddStream, FileCache Cache)>;
268
269/// This type defines the behavior following the thin-link phase during ThinLTO.
270/// It encapsulates a backend function and a strategy for thread pool
271/// parallelism. Clients should use one of the provided create*ThinBackend()
272/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
273/// strategy to be used for processing.
276 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
277 ThinBackend() = default;
278
279 std::unique_ptr<ThinBackendProc> operator()(
280 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
281 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
282 AddStreamFn AddStream, FileCache Cache) {
283 assert(isValid() && "Invalid backend function");
284 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
285 std::move(AddStream), std::move(Cache));
286 }
287 ThreadPoolStrategy getParallelism() const { return Parallelism; }
288 bool isValid() const { return static_cast<bool>(Func); }
289
290private:
291 ThinBackendFunction Func = nullptr;
292 ThreadPoolStrategy Parallelism;
293};
294
295/// This ThinBackend runs the individual backend jobs in-process.
296/// The default value means to use one job per hardware core (not hyper-thread).
297/// OnWrite is callback which receives module identifier and notifies LTO user
298/// that index file for the module (and optionally imports file) was created.
299/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
300/// to the same path as the input module, with suffix ".thinlto.bc"
301/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
302/// similar path with ".imports" appended instead.
304 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
305 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
306
307/// This ThinBackend generates the index shards and then runs the individual
308/// backend jobs via an external process. It takes the same parameters as the
309/// InProcessThinBackend; however, these parameters only control the behavior
310/// when generating the index files for the modules. Additionally:
311/// LinkerOutputFile is a string that should identify this LTO invocation in
312/// the context of a wider build. It's used for naming to aid the user in
313/// identifying activity related to a specific LTO invocation.
314/// Distributor specifies the path to a process to invoke to manage the backend
315/// job execution.
316/// DistributorArgs specifies a list of arguments to be applied to the
317/// distributor.
318/// RemoteCompiler specifies the path to a Clang executable to be invoked for
319/// the backend jobs.
320/// RemoteCompilerPrependArgs specifies a list of prepend arguments to be
321/// applied to the backend compilations.
322/// RemoteCompilerArgs specifies a list of arguments to be applied to the
323/// backend compilations.
324/// SaveTemps is a debugging tool that prevents temporary files created by this
325/// backend from being cleaned up.
327 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
328 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
329 StringRef LinkerOutputFile, StringRef Distributor,
330 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
331 ArrayRef<StringRef> RemoteCompilerPrependArgs,
332 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps);
333
334/// This ThinBackend writes individual module indexes to files, instead of
335/// running the individual backend jobs. This backend is for distributed builds
336/// where separate processes will invoke the real backends.
337///
338/// To find the path to write the index to, the backend checks if the path has a
339/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
340/// appends ".thinlto.bc" and writes the index to that path. If
341/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
342/// similar path with ".imports" appended instead.
343/// LinkedObjectsFile is an output stream to write the list of object files for
344/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
345/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
346/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
347/// callback which receives module identifier and notifies LTO user that index
348/// file for the module (and optionally imports file) was created.
350 ThreadPoolStrategy Parallelism, std::string OldPrefix,
351 std::string NewPrefix, std::string NativeObjectPrefix,
352 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
353 IndexWriteCallback OnWrite);
354
355/// This class implements a resolution-based interface to LLVM's LTO
356/// functionality. It supports regular LTO, parallel LTO code generation and
357/// ThinLTO. You can use it from a linker in the following way:
358/// - Set hooks and code generation options (see lto::Config struct defined in
359/// Config.h), and use the lto::Config object to create an lto::LTO object.
360/// - Create lto::InputFile objects using lto::InputFile::create(), then use
361/// the symbols() function to enumerate its symbols and compute a resolution
362/// for each symbol (see SymbolResolution below).
363/// - After the linker has visited each input file (and each regular object
364/// file) and computed a resolution for each symbol, take each lto::InputFile
365/// and pass it and an array of symbol resolutions to the add() function.
366/// - Call the getMaxTasks() function to get an upper bound on the number of
367/// native object files that LTO may add to the link.
368/// - Call the run() function. This function will use the supplied AddStream
369/// and Cache functions to add up to getMaxTasks() native object files to
370/// the link.
371class LTO {
372 friend InputFile;
373
374public:
375 /// Unified LTO modes
376 enum LTOKind {
377 /// Any LTO mode without Unified LTO. The default mode.
379
380 /// Regular LTO, with Unified LTO enabled.
382
383 /// ThinLTO, with Unified LTO enabled.
385 };
386
387 /// Create an LTO object. A default constructed LTO object has a reasonable
388 /// production configuration, but you can customize it by passing arguments to
389 /// this constructor.
390 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
391 /// Until that is fixed, a Config argument is required.
392 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
393 unsigned ParallelCodeGenParallelismLevel = 1,
394 LTOKind LTOMode = LTOK_Default);
396
397 /// Add an input file to the LTO link, using the provided symbol resolutions.
398 /// The symbol resolutions must appear in the enumeration order given by
399 /// InputFile::symbols().
400 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
402
403 /// Returns an upper bound on the number of tasks that the client may expect.
404 /// This may only be called after all IR object files have been added. For a
405 /// full description of tasks see LTOBackend.h.
406 LLVM_ABI unsigned getMaxTasks() const;
407
408 /// Runs the LTO pipeline. This function calls the supplied AddStream
409 /// function to add native object files to the link.
410 ///
411 /// The Cache parameter is optional. If supplied, it will be used to cache
412 /// native object files and add them to the link.
413 ///
414 /// The client will receive at most one callback (via either AddStream or
415 /// Cache) for each task identifier.
416 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
417
418 /// Static method that returns a list of libcall symbols that can be generated
419 /// by LTO but might not be visible from bitcode symbol table.
422
423private:
424 Config Conf;
425
426 struct RegularLTOState {
427 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
428 const Config &Conf);
432 /// Record if at least one instance of the common was marked as prevailing
433 bool Prevailing = false;
434 };
435 std::map<std::string, CommonResolution> Commons;
436
437 unsigned ParallelCodeGenParallelismLevel;
438 LTOLLVMContext Ctx;
439 std::unique_ptr<Module> CombinedModule;
440 std::unique_ptr<IRMover> Mover;
441
442 // This stores the information about a regular LTO module that we have added
443 // to the link. It will either be linked immediately (for modules without
444 // summaries) or after summary-based dead stripping (for modules with
445 // summaries).
446 struct AddedModule {
447 std::unique_ptr<Module> M;
448 std::vector<GlobalValue *> Keep;
449 };
450 std::vector<AddedModule> ModsWithSummaries;
451 bool EmptyCombinedModule = true;
452 } RegularLTO;
453
454 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
455
456 struct ThinLTOState {
457 LLVM_ABI ThinLTOState(ThinBackend Backend);
458
459 ThinBackend Backend;
460 ModuleSummaryIndex CombinedIndex;
461 // The full set of bitcode modules in input order.
462 ModuleMapType ModuleMap;
463 // The bitcode modules to compile, if specified by the LTO Config.
464 std::optional<ModuleMapType> ModulesToCompile;
465
466 void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) {
467 PrevailingModuleForGUID[GUID] = Module;
468 }
469 bool isPrevailingModuleForGUID(GlobalValue::GUID GUID,
470 StringRef Module) const {
471 auto It = PrevailingModuleForGUID.find(GUID);
472 return It != PrevailingModuleForGUID.end() && It->second == Module;
473 }
474
475 private:
476 // Make this private so all accesses must go through above accessor methods
477 // to avoid inadvertently creating new entries on lookups.
478 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
479 } ThinLTO;
480
481 // The global resolution for a particular (mangled) symbol name. This is in
482 // particular necessary to track whether each symbol can be internalized.
483 // Because any input file may introduce a new cross-partition reference, we
484 // cannot make any final internalization decisions until all input files have
485 // been added and the client has called run(). During run() we apply
486 // internalization decisions either directly to the module (for regular LTO)
487 // or to the combined index (for ThinLTO).
488 struct GlobalResolution {
489 /// The unmangled name of the global.
490 std::string IRName;
491
492 /// Keep track if the symbol is visible outside of a module with a summary
493 /// (i.e. in either a regular object or a regular LTO module without a
494 /// summary).
495 bool VisibleOutsideSummary = false;
496
497 /// The symbol was exported dynamically, and therefore could be referenced
498 /// by a shared library not visible to the linker.
499 bool ExportDynamic = false;
500
501 bool UnnamedAddr = true;
502
503 /// True if module contains the prevailing definition.
504 bool Prevailing = false;
505
506 /// Returns true if module contains the prevailing definition and symbol is
507 /// an IR symbol. For example when module-level inline asm block is used,
508 /// symbol can be prevailing in module but have no IR name.
509 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
510
511 /// This field keeps track of the partition number of this global. The
512 /// regular LTO object is partition 0, while each ThinLTO object has its own
513 /// partition number from 1 onwards.
514 ///
515 /// Any global that is defined or used by more than one partition, or that
516 /// is referenced externally, may not be internalized.
517 ///
518 /// Partitions generally have a one-to-one correspondence with tasks, except
519 /// that we use partition 0 for all parallel LTO code generation partitions.
520 /// Any partitioning of the combined LTO object is done internally by the
521 /// LTO backend.
522 unsigned Partition = Unknown;
523
524 /// Special partition numbers.
525 enum : unsigned {
526 /// A partition number has not yet been assigned to this global.
527 Unknown = -1u,
528
529 /// This global is either used by more than one partition or has an
530 /// external reference, and therefore cannot be internalized.
531 External = -2u,
532
533 /// The RegularLTO partition
534 RegularLTO = 0,
535 };
536 };
537
538 // GlobalResolutionSymbolSaver allocator.
539 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
540
541 // Symbol saver for global resolution map.
542 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
543
544 // Global mapping from mangled symbol names to resolutions.
545 // Make this an unique_ptr to guard against accessing after it has been reset
546 // (to reduce memory after we're done with it).
547 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
548 GlobalResolutions;
549
550 void releaseGlobalResolutionsMemory();
551
552 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
553 ArrayRef<SymbolResolution> Res, unsigned Partition,
554 bool InSummary);
555
556 // These functions take a range of symbol resolutions and consume the
557 // resolutions used by a single input module. Functions return ranges refering
558 // to the resolutions for the remaining modules in the InputFile.
559 Expected<ArrayRef<SymbolResolution>>
560 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
561 unsigned ModI, ArrayRef<SymbolResolution> Res);
562
563 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
564 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
565 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
568 bool LivenessFromIndex);
569
570 Expected<ArrayRef<SymbolResolution>>
571 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
573
574 Error runRegularLTO(AddStreamFn AddStream);
575 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
576 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
577
578 Error checkPartiallySplit();
579
580 mutable bool CalledGetMaxTasks = false;
581
582 // LTO mode when using Unified LTO.
583 LTOKind LTOMode;
584
585 // Use Optional to distinguish false from not yet initialized.
586 std::optional<bool> EnableSplitLTOUnit;
587
588 // Identify symbols exported dynamically, and that therefore could be
589 // referenced by a shared library not visible to the linker.
590 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
591
592 // Diagnostic optimization remarks file
593 LLVMRemarkFileHandle DiagnosticOutputFile;
594};
595
596/// The resolution for a symbol. The linker must provide a SymbolResolution for
597/// each global symbol based on its internal resolution of that symbol.
602
603 /// The linker has chosen this definition of the symbol.
604 unsigned Prevailing : 1;
605
606 /// The definition of this symbol is unpreemptable at runtime and is known to
607 /// be in this linkage unit.
609
610 /// The definition of this symbol is visible outside of the LTO unit.
612
613 /// The symbol was exported dynamically, and therefore could be referenced
614 /// by a shared library not visible to the linker.
615 unsigned ExportDynamic : 1;
616
617 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
618 /// linker option.
619 unsigned LinkerRedefined : 1;
620};
621
622} // namespace lto
623} // namespace llvm
624
625#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseMap class.
Provides passes for computing function attributes based on interprocedural analyses.
#define I(x, y, z)
Definition MD5.cpp:58
This file implements a map that provides insertion order iteration.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
Represents a module in a bitcode file.
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
The map maintains the list of imports.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This tells how a thread pool will be used.
Definition Threading.h:115
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
An efficient, type-erasing, non-owning reference to a callable.
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:568
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:167
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:170
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:173
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:185
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:179
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:597
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:601
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:182
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:371
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:619
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:740
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:1400
LTOKind
Unified LTO modes.
Definition LTO.h:376
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:381
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:378
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:384
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:1157
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1208
DefaultThreadPool BackendThreadPool
Definition LTO.h:211
const Config & Conf
Definition LTO.h:206
std::optional< Error > Err
Definition LTO.h:212
virtual bool isSensitiveToInputOrder()
Definition LTO.h:242
unsigned getThreadCount()
Definition LTO.h:241
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:208
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1414
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:216
virtual Error wait()
Definition LTO.h:235
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:207
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:227
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:209
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:1764
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:1798
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1780
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2178
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:2523
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:199
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:1884
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:2153
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2197
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:201
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:264
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:553
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:354
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:448
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:254
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:1867
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:867
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:142
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:146
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:300
std::vector< GlobalValue * > Keep
Definition LTO.h:448
std::unique_ptr< Module > M
Definition LTO.h:447
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:433
The resolution for a symbol.
Definition LTO.h:598
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:608
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:615
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:604
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:619
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:611
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:274
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition LTO.h:279
bool isValid() const
Definition LTO.h:288
ThreadPoolStrategy getParallelism() const
Definition LTO.h:287
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:275