LLVM 20.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
18#include <memory>
19
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/MapVector.h"
24#include "llvm/LTO/Config.h"
27#include "llvm/Support/Error.h"
30#include "llvm/Support/thread.h"
33
34namespace llvm {
35
36class Error;
37class IRMover;
38class LLVMContext;
39class MemoryBufferRef;
40class Module;
41class raw_pwrite_stream;
42class ToolOutputFile;
43
44/// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
45/// recorded in the index and the ThinLTO backends must apply the changes to
46/// the module via thinLTOFinalizeInModule.
47///
48/// This is done for correctness (if value exported, ensure we always
49/// emit a copy), and compile-time optimization (allow drop of duplicates).
51 const lto::Config &C, ModuleSummaryIndex &Index,
52 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
53 isPrevailing,
54 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
55 recordNewLinkage,
56 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
57
58/// Update the linkages in the given \p Index to mark exported values
59/// as external and non-exported values as internal. The ThinLTO backends
60/// must apply the changes to the Module via thinLTOInternalizeModule.
62 ModuleSummaryIndex &Index,
63 function_ref<bool(StringRef, ValueInfo)> isExported,
64 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
65 isPrevailing);
66
67/// Computes a unique hash for the Module considering the current list of
68/// export/import and other global analysis results.
69std::string computeLTOCacheKey(
70 const lto::Config &Conf, const ModuleSummaryIndex &Index,
71 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
72 const FunctionImporter::ExportSetTy &ExportList,
73 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
74 const GVSummaryMapTy &DefinedGlobals,
75 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs = {},
76 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls = {});
77
78/// Recomputes the LTO cache key for a given key with an extra identifier.
79std::string recomputeLTOCacheKey(const std::string &Key, StringRef ExtraID);
80
81namespace lto {
82
83StringLiteral getThinLTODefaultCPU(const Triple &TheTriple);
84
85/// Given the original \p Path to an output file, replace any path
86/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
87/// resulting directory if it does not yet exist.
88std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
89 StringRef NewPrefix);
90
91/// Setup optimization remarks.
92Expected<std::unique_ptr<ToolOutputFile>> setupLLVMOptimizationRemarks(
93 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
94 StringRef RemarksFormat, bool RemarksWithHotness,
95 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
96
97/// Setups the output file for saving statistics.
98Expected<std::unique_ptr<ToolOutputFile>>
99setupStatsFile(StringRef StatsFilename);
100
101/// Produces a container ordering for optimal multi-threaded processing. Returns
102/// ordered indices to elements in the input array.
103std::vector<int> generateModulesOrdering(ArrayRef<BitcodeModule *> R);
104
105/// Updates MemProf attributes (and metadata) based on whether the index
106/// has recorded that we are linking with allocation libraries containing
107/// the necessary APIs for downstream transformations.
108void updateMemProfAttributes(Module &Mod, const ModuleSummaryIndex &Index);
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.
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
135public:
137
138 /// Create an InputFile.
140
141 /// The purpose of this struct is to only expose the symbol information that
142 /// an LTO client should need in order to do symbol resolution.
144 friend LTO;
145
146 public:
147 Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {}
148
165 };
166
167 /// A range over the symbols in this InputFile.
168 ArrayRef<Symbol> symbols() const { return Symbols; }
169
170 /// Returns linker options specified in the input file.
171 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
172
173 /// Returns dependent library specifiers from the input file.
174 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
175
176 /// Returns the path to the InputFile.
177 StringRef getName() const;
178
179 /// Returns the input file's target triple.
180 StringRef getTargetTriple() const { return TargetTriple; }
181
182 /// Returns the source file path specified at compile time.
183 StringRef getSourceFileName() const { return SourceFileName; }
184
185 // Returns a table with all the comdats used by this file.
187 return ComdatTable;
188 }
189
190 // Returns the only BitcodeModule from InputFile.
192
193private:
194 ArrayRef<Symbol> module_symbols(unsigned I) const {
195 const auto &Indices = ModuleSymIndices[I];
196 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
197 }
198};
199
200using IndexWriteCallback = std::function<void(const std::string &)>;
201
202/// This class defines the interface to the ThinLTO backend.
204protected:
205 const Config &Conf;
211 std::optional<Error> Err;
212 std::mutex ErrMu;
213
214public:
219 ThreadPoolStrategy ThinLTOParallelism)
223 BackendThreadPool(ThinLTOParallelism) {}
224
225 virtual ~ThinBackendProc() = default;
226 virtual Error start(
227 unsigned Task, BitcodeModule BM,
228 const FunctionImporter::ImportMapTy &ImportList,
229 const FunctionImporter::ExportSetTy &ExportList,
230 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
234 if (Err)
235 return std::move(*Err);
236 return Error::success();
237 }
239 virtual bool isSensitiveToInputOrder() { return false; }
240
241 // Write sharded indices and (optionally) imports to disk
243 llvm::StringRef ModulePath,
244 const std::string &NewModulePath) const;
245};
246
247/// This callable defines the behavior of a ThinLTO backend after the thin-link
248/// phase. It accepts a configuration \p C, a combined module summary index
249/// \p CombinedIndex, a map of module identifiers to global variable summaries
250/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
251/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
252/// ThinBackendProc, which can be used to launch backends in parallel.
253using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
254 const Config &C, ModuleSummaryIndex &CombinedIndex,
255 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
256 AddStreamFn AddStream, FileCache Cache)>;
257
258/// This type defines the behavior following the thin-link phase during ThinLTO.
259/// It encapsulates a backend function and a strategy for thread pool
260/// parallelism. Clients should use one of the provided create*ThinBackend()
261/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
262/// strategy to be used for processing.
265 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
266 ThinBackend() = default;
267
268 std::unique_ptr<ThinBackendProc> operator()(
269 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
270 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
271 AddStreamFn AddStream, FileCache Cache) {
272 assert(isValid() && "Invalid backend function");
273 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
274 std::move(AddStream), std::move(Cache));
275 }
276 ThreadPoolStrategy getParallelism() const { return Parallelism; }
277 bool isValid() const { return static_cast<bool>(Func); }
278
279private:
280 ThinBackendFunction Func = nullptr;
281 ThreadPoolStrategy Parallelism;
282};
283
284/// This ThinBackend runs the individual backend jobs in-process.
285/// The default value means to use one job per hardware core (not hyper-thread).
286/// OnWrite is callback which receives module identifier and notifies LTO user
287/// that index file for the module (and optionally imports file) was created.
288/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
289/// to the same path as the input module, with suffix ".thinlto.bc"
290/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
291/// similar path with ".imports" appended instead.
292ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism,
293 IndexWriteCallback OnWrite = nullptr,
294 bool ShouldEmitIndexFiles = false,
295 bool ShouldEmitImportsFiles = false);
296
297/// This ThinBackend writes individual module indexes to files, instead of
298/// running the individual backend jobs. This backend is for distributed builds
299/// where separate processes will invoke the real backends.
300///
301/// To find the path to write the index to, the backend checks if the path has a
302/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
303/// appends ".thinlto.bc" and writes the index to that path. If
304/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
305/// similar path with ".imports" appended instead.
306/// LinkedObjectsFile is an output stream to write the list of object files for
307/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
308/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
309/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
310/// callback which receives module identifier and notifies LTO user that index
311/// file for the module (and optionally imports file) was created.
313 std::string OldPrefix,
314 std::string NewPrefix,
315 std::string NativeObjectPrefix,
316 bool ShouldEmitImportsFiles,
317 raw_fd_ostream *LinkedObjectsFile,
318 IndexWriteCallback OnWrite);
319
320/// This class implements a resolution-based interface to LLVM's LTO
321/// functionality. It supports regular LTO, parallel LTO code generation and
322/// ThinLTO. You can use it from a linker in the following way:
323/// - Set hooks and code generation options (see lto::Config struct defined in
324/// Config.h), and use the lto::Config object to create an lto::LTO object.
325/// - Create lto::InputFile objects using lto::InputFile::create(), then use
326/// the symbols() function to enumerate its symbols and compute a resolution
327/// for each symbol (see SymbolResolution below).
328/// - After the linker has visited each input file (and each regular object
329/// file) and computed a resolution for each symbol, take each lto::InputFile
330/// and pass it and an array of symbol resolutions to the add() function.
331/// - Call the getMaxTasks() function to get an upper bound on the number of
332/// native object files that LTO may add to the link.
333/// - Call the run() function. This function will use the supplied AddStream
334/// and Cache functions to add up to getMaxTasks() native object files to
335/// the link.
336class LTO {
337 friend InputFile;
338
339public:
340 /// Unified LTO modes
341 enum LTOKind {
342 /// Any LTO mode without Unified LTO. The default mode.
344
345 /// Regular LTO, with Unified LTO enabled.
347
348 /// ThinLTO, with Unified LTO enabled.
350 };
351
352 /// Create an LTO object. A default constructed LTO object has a reasonable
353 /// production configuration, but you can customize it by passing arguments to
354 /// this constructor.
355 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
356 /// Until that is fixed, a Config argument is required.
357 LTO(Config Conf, ThinBackend Backend = {},
358 unsigned ParallelCodeGenParallelismLevel = 1,
359 LTOKind LTOMode = LTOK_Default);
361
362 /// Add an input file to the LTO link, using the provided symbol resolutions.
363 /// The symbol resolutions must appear in the enumeration order given by
364 /// InputFile::symbols().
365 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
366
367 /// Returns an upper bound on the number of tasks that the client may expect.
368 /// This may only be called after all IR object files have been added. For a
369 /// full description of tasks see LTOBackend.h.
370 unsigned getMaxTasks() const;
371
372 /// Runs the LTO pipeline. This function calls the supplied AddStream
373 /// function to add native object files to the link.
374 ///
375 /// The Cache parameter is optional. If supplied, it will be used to cache
376 /// native object files and add them to the link.
377 ///
378 /// The client will receive at most one callback (via either AddStream or
379 /// Cache) for each task identifier.
380 Error run(AddStreamFn AddStream, FileCache Cache = {});
381
382 /// Static method that returns a list of libcall symbols that can be generated
383 /// by LTO but might not be visible from bitcode symbol table.
385
386private:
387 Config Conf;
388
389 struct RegularLTOState {
390 RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
391 const Config &Conf);
395 /// Record if at least one instance of the common was marked as prevailing
396 bool Prevailing = false;
397 };
398 std::map<std::string, CommonResolution> Commons;
399
400 unsigned ParallelCodeGenParallelismLevel;
401 LTOLLVMContext Ctx;
402 std::unique_ptr<Module> CombinedModule;
403 std::unique_ptr<IRMover> Mover;
404
405 // This stores the information about a regular LTO module that we have added
406 // to the link. It will either be linked immediately (for modules without
407 // summaries) or after summary-based dead stripping (for modules with
408 // summaries).
409 struct AddedModule {
410 std::unique_ptr<Module> M;
411 std::vector<GlobalValue *> Keep;
412 };
413 std::vector<AddedModule> ModsWithSummaries;
414 bool EmptyCombinedModule = true;
415 } RegularLTO;
416
418
419 struct ThinLTOState {
420 ThinLTOState(ThinBackend Backend);
421
422 ThinBackend Backend;
423 ModuleSummaryIndex CombinedIndex;
424 // The full set of bitcode modules in input order.
425 ModuleMapType ModuleMap;
426 // The bitcode modules to compile, if specified by the LTO Config.
427 std::optional<ModuleMapType> ModulesToCompile;
428 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
429 } ThinLTO;
430
431 // The global resolution for a particular (mangled) symbol name. This is in
432 // particular necessary to track whether each symbol can be internalized.
433 // Because any input file may introduce a new cross-partition reference, we
434 // cannot make any final internalization decisions until all input files have
435 // been added and the client has called run(). During run() we apply
436 // internalization decisions either directly to the module (for regular LTO)
437 // or to the combined index (for ThinLTO).
438 struct GlobalResolution {
439 /// The unmangled name of the global.
440 std::string IRName;
441
442 /// Keep track if the symbol is visible outside of a module with a summary
443 /// (i.e. in either a regular object or a regular LTO module without a
444 /// summary).
445 bool VisibleOutsideSummary = false;
446
447 /// The symbol was exported dynamically, and therefore could be referenced
448 /// by a shared library not visible to the linker.
449 bool ExportDynamic = false;
450
451 bool UnnamedAddr = true;
452
453 /// True if module contains the prevailing definition.
454 bool Prevailing = false;
455
456 /// Returns true if module contains the prevailing definition and symbol is
457 /// an IR symbol. For example when module-level inline asm block is used,
458 /// symbol can be prevailing in module but have no IR name.
459 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
460
461 /// This field keeps track of the partition number of this global. The
462 /// regular LTO object is partition 0, while each ThinLTO object has its own
463 /// partition number from 1 onwards.
464 ///
465 /// Any global that is defined or used by more than one partition, or that
466 /// is referenced externally, may not be internalized.
467 ///
468 /// Partitions generally have a one-to-one correspondence with tasks, except
469 /// that we use partition 0 for all parallel LTO code generation partitions.
470 /// Any partitioning of the combined LTO object is done internally by the
471 /// LTO backend.
472 unsigned Partition = Unknown;
473
474 /// Special partition numbers.
475 enum : unsigned {
476 /// A partition number has not yet been assigned to this global.
477 Unknown = -1u,
478
479 /// This global is either used by more than one partition or has an
480 /// external reference, and therefore cannot be internalized.
481 External = -2u,
482
483 /// The RegularLTO partition
484 RegularLTO = 0,
485 };
486 };
487
488 // GlobalResolutionSymbolSaver allocator.
489 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
490
491 // Symbol saver for global resolution map.
492 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
493
494 // Global mapping from mangled symbol names to resolutions.
495 // Make this an unique_ptr to guard against accessing after it has been reset
496 // (to reduce memory after we're done with it).
497 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
498 GlobalResolutions;
499
500 void releaseGlobalResolutionsMemory();
501
502 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
503 ArrayRef<SymbolResolution> Res, unsigned Partition,
504 bool InSummary);
505
506 // These functions take a range of symbol resolutions [ResI, ResE) and consume
507 // the resolutions used by a single input module by incrementing ResI. After
508 // these functions return, [ResI, ResE) will refer to the resolution range for
509 // the remaining modules in the InputFile.
510 Error addModule(InputFile &Input, unsigned ModI,
511 const SymbolResolution *&ResI, const SymbolResolution *ResE);
512
513 Expected<RegularLTOState::AddedModule>
514 addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
515 const SymbolResolution *&ResI, const SymbolResolution *ResE);
516 Error linkRegularLTO(RegularLTOState::AddedModule Mod,
517 bool LivenessFromIndex);
518
519 Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
520 const SymbolResolution *&ResI, const SymbolResolution *ResE);
521
522 Error runRegularLTO(AddStreamFn AddStream);
523 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
524 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
525
526 Error checkPartiallySplit();
527
528 mutable bool CalledGetMaxTasks = false;
529
530 // LTO mode when using Unified LTO.
531 LTOKind LTOMode;
532
533 // Use Optional to distinguish false from not yet initialized.
534 std::optional<bool> EnableSplitLTOUnit;
535
536 // Identify symbols exported dynamically, and that therefore could be
537 // referenced by a shared library not visible to the linker.
538 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
539
540 // Diagnostic optimization remarks file
541 std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
542};
543
544/// The resolution for a symbol. The linker must provide a SymbolResolution for
545/// each global symbol based on its internal resolution of that symbol.
550
551 /// The linker has chosen this definition of the symbol.
552 unsigned Prevailing : 1;
553
554 /// The definition of this symbol is unpreemptable at runtime and is known to
555 /// be in this linkage unit.
557
558 /// The definition of this symbol is visible outside of the LTO unit.
560
561 /// The symbol was exported dynamically, and therefore could be referenced
562 /// by a shared library not visible to the linker.
563 unsigned ExportDynamic : 1;
564
565 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
566 /// linker option.
567 unsigned LinkerRedefined : 1;
568};
569
570} // namespace lto
571} // namespace llvm
572
573#endif
This file defines the DenseMap class.
uint32_t Index
Provides passes for computing function attributes based on interprocedural analyses.
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:278
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
The map maintains the list of imports.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:587
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
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 non-threaded implementation.
Definition: ThreadPool.h:218
void wait() override
Blocking wait for all the tasks to execute first.
Definition: ThreadPool.cpp:201
unsigned getMaxConcurrency() const override
Returns always 1: there is no concurrency.
Definition: ThreadPool.h:233
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
This tells how a thread pool will be used.
Definition: Threading.h:116
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
An input file.
Definition: LTO.h:115
static Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition: LTO.cpp:554
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition: LTO.h:168
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition: LTO.h:171
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition: LTO.h:174
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition: LTO.h:186
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition: LTO.h:180
StringRef getName() const
Returns the path to the InputFile.
Definition: LTO.cpp:583
BitcodeModule & getSingleBitcodeModule()
Definition: LTO.cpp:587
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition: LTO.h:183
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition: LTO.h:336
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:728
static 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:1382
LTOKind
Unified LTO modes.
Definition: LTO.h:341
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition: LTO.h:346
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition: LTO.h:343
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition: LTO.h:349
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition: LTO.cpp:1110
Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition: LTO.cpp:1161
This class defines the interface to the ThinLTO backend.
Definition: LTO.h:203
DefaultThreadPool BackendThreadPool
Definition: LTO.h:210
const Config & Conf
Definition: LTO.h:205
Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, llvm::StringRef ModulePath, const std::string &NewModulePath) const
Definition: LTO.cpp:1390
std::optional< Error > Err
Definition: LTO.h:211
virtual bool isSensitiveToInputOrder()
Definition: LTO.h:239
unsigned getThreadCount()
Definition: LTO.h:238
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition: LTO.h:207
std::mutex ErrMu
Definition: LTO.h:212
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition: LTO.h:215
ModuleSummaryIndex & CombinedIndex
Definition: LTO.h:206
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:208
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
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:1705
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:1739
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:256
std::function< void(const std::string &)> IndexWriteCallback
Definition: LTO.h:200
StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition: LTO.cpp:1721
Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition: LTO.cpp:2116
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:1825
std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition: LTO.cpp:2135
Expected< std::unique_ptr< ToolOutputFile > > 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:2091
void updateMemProfAttributes(Module &Mod, const ModuleSummaryIndex &Index)
Updates MemProf attributes (and metadata) based on whether the index has recorded that we are linking...
Definition: LTO.cpp:1219
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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"))
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:42
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:541
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:349
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"))
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:440
@ Mod
The access may modify the value stored in memory.
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:1873
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)
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:99
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
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:67
This represents a symbol that has been read from a storage::Symbol and possibly a storage::Uncommon.
Definition: IRSymtab.h:170
StringRef getName() const
Returns the mangled symbol name.
Definition: IRSymtab.h:183
bool canBeOmittedFromSymbolTable() const
Definition: IRSymtab.h:206
bool isUsed() const
Definition: IRSymtab.h:203
StringRef getSectionName() const
Definition: IRSymtab.h:232
bool isTLS() const
Definition: IRSymtab.h:204
bool isWeak() const
Definition: IRSymtab.h:200
bool isIndirect() const
Definition: IRSymtab.h:202
bool isCommon() const
Definition: IRSymtab.h:201
uint32_t getCommonAlignment() const
Definition: IRSymtab.h:220
bool isExecutable() const
Definition: IRSymtab.h:213
uint64_t getCommonSize() const
Definition: IRSymtab.h:215
int getComdatIndex() const
Returns the index into the comdat table (see Reader::getComdatTable()), or -1 if not a comdat member.
Definition: IRSymtab.h:191
GlobalValue::VisibilityTypes getVisibility() const
Definition: IRSymtab.h:195
bool isUndefined() const
Definition: IRSymtab.h:199
StringRef getIRName() const
Returns the unmangled symbol name, or the empty string if this is not an IR symbol.
Definition: IRSymtab.h:187
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:227
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
Definition: IRSymtab.h:91
LTO configuration.
Definition: Config.h:41
The purpose of this struct is to only expose the symbol information that an LTO client should need in...
Definition: LTO.h:143
Symbol(const irsymtab::Symbol &S)
Definition: LTO.h:147
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition: Config.h:299
std::vector< GlobalValue * > Keep
Definition: LTO.h:411
std::unique_ptr< Module > M
Definition: LTO.h:410
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition: LTO.h:396
The resolution for a symbol.
Definition: LTO.h:546
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition: LTO.h:556
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition: LTO.h:563
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition: LTO.h:552
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition: LTO.h:567
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition: LTO.h:559
This type defines the behavior following the thin-link phase during ThinLTO.
Definition: LTO.h:263
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition: LTO.h:268
bool isValid() const
Definition: LTO.h:277
ThreadPoolStrategy getParallelism() const
Definition: LTO.h:276
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition: LTO.h:264