1 //===-LTO.h - LLVM Link Time Optimizer ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares functions and classes used to support LTO. It is intended
11 // to be used both by LTO classes as well as by clients (gold-plugin) that
12 // don't utilize the LTO code generator interfaces.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_LTO_LTO_H
17 #define LLVM_LTO_LTO_H
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/ModuleSummaryIndex.h"
25 #include "llvm/LTO/Config.h"
26 #include "llvm/Linker/IRMover.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/thread.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Transforms/IPO/FunctionImport.h"
38 class MemoryBufferRef;
41 class raw_pwrite_stream;
43 /// Resolve Weak and LinkOnce values in the \p Index. Linkage changes recorded
44 /// in the index and the ThinLTO backends must apply the changes to the Module
45 /// via thinLTOResolveWeakForLinkerModule.
47 /// This is done for correctness (if value exported, ensure we always
48 /// emit a copy), and compile-time optimization (allow drop of duplicates).
49 void thinLTOResolveWeakForLinkerInIndex(
50 ModuleSummaryIndex &Index,
51 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
53 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
56 /// This enum is used for the returned value of the callback passed to
57 /// thinLTOInternalizeAndPromoteInIndex, it indicates if a symbol can be made
58 /// Internal (only referenced from its defining object), Hidden (
59 /// outside the DSO), or Exported (exposed as public API for the DSO).
60 enum SummaryResolution { Internal, Hidden, Exported };
62 /// Update the linkages in the given \p Index to mark exported values
63 /// as external and non-exported values as internal. The ThinLTO backends
64 /// must apply the changes to the Module via thinLTOInternalizeModule.
65 void thinLTOInternalizeAndPromoteInIndex(
66 ModuleSummaryIndex &Index,
67 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported);
71 /// Given the original \p Path to an output file, replace any path
72 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
73 /// resulting directory if it does not yet exist.
74 std::string getThinLTOOutputFile(const std::string &Path,
75 const std::string &OldPrefix,
76 const std::string &NewPrefix);
79 struct SymbolResolution;
80 class ThinBackendProc;
82 /// An input file. This is a wrapper for ModuleSymbolTable that exposes only the
83 /// information that an LTO client should need in order to do symbol resolution.
85 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
87 InputFile() = default;
89 // FIXME: Remove the LLVMContext once we have bitcode symbol tables.
92 std::vector<InputModule> Mods;
93 ModuleSymbolTable SymTab;
95 std::vector<StringRef> Comdats;
96 DenseMap<const Comdat *, unsigned> ComdatMap;
101 /// Create an InputFile.
102 static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object);
104 class symbol_iterator;
106 /// This is a wrapper for ArrayRef<ModuleSymbolTable::Symbol>::iterator that
107 /// exposes only the information that an LTO client should need in order to do
108 /// symbol resolution.
110 /// This object is ephemeral; it is only valid as long as an iterator obtained
111 /// from symbols() refers to it.
113 friend symbol_iterator;
116 ArrayRef<ModuleSymbolTable::Symbol>::iterator I;
117 const ModuleSymbolTable &SymTab;
118 const InputFile *File;
120 SmallString<64> Name;
123 return !(Flags & object::BasicSymbolRef::SF_Global) ||
124 (Flags & object::BasicSymbolRef::SF_FormatSpecific);
128 ArrayRef<ModuleSymbolTable::Symbol>::iterator E = SymTab.symbols().end();
130 Flags = SymTab.getSymbolFlags(*I);
140 raw_svector_ostream OS(Name);
141 SymTab.printSymbolName(OS, *I);
145 bool isGV() const { return I->is<GlobalValue *>(); }
146 GlobalValue *getGV() const { return I->get<GlobalValue *>(); }
149 Symbol(ArrayRef<ModuleSymbolTable::Symbol>::iterator I,
150 const ModuleSymbolTable &SymTab, const InputFile *File)
151 : I(I), SymTab(SymTab), File(File) {
155 /// For COFF weak externals, returns the name of the symbol that is used
156 /// as a fallback if the weak external remains undefined.
157 std::string getCOFFWeakExternalFallback() const {
158 assert((Flags & object::BasicSymbolRef::SF_Weak) &&
159 (Flags & object::BasicSymbolRef::SF_Indirect) &&
160 "symbol is not a weak external");
162 raw_string_ostream OS(Name);
163 SymTab.printSymbolName(
166 cast<GlobalAlias>(getGV())->getAliasee()->stripPointerCasts()));
171 /// Returns the mangled name of the global.
172 StringRef getName() const { return Name; }
174 uint32_t getFlags() const { return Flags; }
175 GlobalValue::VisibilityTypes getVisibility() const {
177 return getGV()->getVisibility();
178 return GlobalValue::DefaultVisibility;
180 bool canBeOmittedFromSymbolTable() const {
181 return isGV() && llvm::canBeOmittedFromSymbolTable(getGV());
184 // FIXME: Expose a thread-local flag for module asm symbols.
185 return isGV() && getGV()->isThreadLocal();
188 // Returns the index of the comdat this symbol is in or -1 if the symbol
189 // is not in a comdat.
190 // FIXME: We have to return Expected<int> because aliases point to an
191 // arbitrary ConstantExpr and that might not actually be a constant. That
192 // means we might not be able to find what an alias is aliased to and
193 // so find its comdat.
194 Expected<int> getComdatIndex() const;
196 uint64_t getCommonSize() const {
197 assert(Flags & object::BasicSymbolRef::SF_Common);
200 return getGV()->getParent()->getDataLayout().getTypeAllocSize(
201 getGV()->getType()->getElementType());
203 unsigned getCommonAlignment() const {
204 assert(Flags & object::BasicSymbolRef::SF_Common);
207 return getGV()->getAlignment();
211 class symbol_iterator {
215 symbol_iterator(ArrayRef<ModuleSymbolTable::Symbol>::iterator I,
216 const ModuleSymbolTable &SymTab, const InputFile *File)
217 : Sym(I, SymTab, File) {}
219 symbol_iterator &operator++() {
225 symbol_iterator operator++(int) {
226 symbol_iterator I = *this;
231 const Symbol &operator*() const { return Sym; }
232 const Symbol *operator->() const { return &Sym; }
234 bool operator!=(const symbol_iterator &Other) const {
235 return Sym.I != Other.Sym.I;
239 /// A range over the symbols in this InputFile.
240 iterator_range<symbol_iterator> symbols() {
241 return llvm::make_range(
242 symbol_iterator(SymTab.symbols().begin(), SymTab, this),
243 symbol_iterator(SymTab.symbols().end(), SymTab, this));
246 /// Returns linker options specified in the input file.
247 Expected<std::string> getLinkerOpts();
249 /// Returns the path to the InputFile.
250 StringRef getName() const;
252 /// Returns the source file path specified at compile time.
253 StringRef getSourceFileName() const;
255 // Returns a table with all the comdats used by this file.
256 ArrayRef<StringRef> getComdatTable() const { return Comdats; }
259 iterator_range<symbol_iterator> module_symbols(InputModule &IM);
262 /// This class wraps an output stream for a native object. Most clients should
263 /// just be able to return an instance of this base class from the stream
264 /// callback, but if a client needs to perform some action after the stream is
265 /// written to, that can be done by deriving from this class and overriding the
267 class NativeObjectStream {
269 NativeObjectStream(std::unique_ptr<raw_pwrite_stream> OS) : OS(std::move(OS)) {}
270 std::unique_ptr<raw_pwrite_stream> OS;
271 virtual ~NativeObjectStream() = default;
274 /// This type defines the callback to add a native object that is generated on
277 /// Stream callbacks must be thread safe.
278 typedef std::function<std::unique_ptr<NativeObjectStream>(unsigned Task)>
281 /// This is the type of a native object cache. To request an item from the
282 /// cache, pass a unique string as the Key. For hits, the cached file will be
283 /// added to the link and this function will return AddStreamFn(). For misses,
284 /// the cache will return a stream callback which must be called at most once to
285 /// produce content for the stream. The native object stream produced by the
286 /// stream callback will add the file to the link after the stream is written
289 /// Clients generally look like this:
291 /// if (AddStreamFn AddStream = Cache(Task, Key))
292 /// ProduceContent(AddStream);
293 typedef std::function<AddStreamFn(unsigned Task, StringRef Key)>
296 /// A ThinBackend defines what happens after the thin-link phase during ThinLTO.
297 /// The details of this type definition aren't important; clients can only
298 /// create a ThinBackend using one of the create*ThinBackend() functions below.
299 typedef std::function<std::unique_ptr<ThinBackendProc>(
300 Config &C, ModuleSummaryIndex &CombinedIndex,
301 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
302 AddStreamFn AddStream, NativeObjectCache Cache)>
305 /// This ThinBackend runs the individual backend jobs in-process.
306 ThinBackend createInProcessThinBackend(unsigned ParallelismLevel);
308 /// This ThinBackend writes individual module indexes to files, instead of
309 /// running the individual backend jobs. This backend is for distributed builds
310 /// where separate processes will invoke the real backends.
312 /// To find the path to write the index to, the backend checks if the path has a
313 /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
314 /// appends ".thinlto.bc" and writes the index to that path. If
315 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a
316 /// similar path with ".imports" appended instead.
317 ThinBackend createWriteIndexesThinBackend(std::string OldPrefix,
318 std::string NewPrefix,
319 bool ShouldEmitImportsFiles,
320 std::string LinkedObjectsFile);
322 /// This class implements a resolution-based interface to LLVM's LTO
323 /// functionality. It supports regular LTO, parallel LTO code generation and
324 /// ThinLTO. You can use it from a linker in the following way:
325 /// - Set hooks and code generation options (see lto::Config struct defined in
326 /// Config.h), and use the lto::Config object to create an lto::LTO object.
327 /// - Create lto::InputFile objects using lto::InputFile::create(), then use
328 /// the symbols() function to enumerate its symbols and compute a resolution
329 /// for each symbol (see SymbolResolution below).
330 /// - After the linker has visited each input file (and each regular object
331 /// file) and computed a resolution for each symbol, take each lto::InputFile
332 /// and pass it and an array of symbol resolutions to the add() function.
333 /// - Call the getMaxTasks() function to get an upper bound on the number of
334 /// native object files that LTO may add to the link.
335 /// - Call the run() function. This function will use the supplied AddStream
336 /// and Cache functions to add up to getMaxTasks() native object files to
342 /// Create an LTO object. A default constructed LTO object has a reasonable
343 /// production configuration, but you can customize it by passing arguments to
344 /// this constructor.
345 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
346 /// Until that is fixed, a Config argument is required.
347 LTO(Config Conf, ThinBackend Backend = nullptr,
348 unsigned ParallelCodeGenParallelismLevel = 1);
351 /// Add an input file to the LTO link, using the provided symbol resolutions.
352 /// The symbol resolutions must appear in the enumeration order given by
353 /// InputFile::symbols().
354 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
356 /// Returns an upper bound on the number of tasks that the client may expect.
357 /// This may only be called after all IR object files have been added. For a
358 /// full description of tasks see LTOBackend.h.
359 unsigned getMaxTasks() const;
361 /// Runs the LTO pipeline. This function calls the supplied AddStream
362 /// function to add native object files to the link.
364 /// The Cache parameter is optional. If supplied, it will be used to cache
365 /// native object files and add them to the link.
367 /// The client will receive at most one callback (via either AddStream or
368 /// Cache) for each task identifier.
369 Error run(AddStreamFn AddStream, NativeObjectCache Cache = nullptr);
374 struct RegularLTOState {
375 RegularLTOState(unsigned ParallelCodeGenParallelismLevel, Config &Conf);
376 struct CommonResolution {
379 /// Record if at least one instance of the common was marked as prevailing
380 bool Prevailing = false;
382 std::map<std::string, CommonResolution> Commons;
384 unsigned ParallelCodeGenParallelismLevel;
386 bool HasModule = false;
387 std::unique_ptr<Module> CombinedModule;
388 std::unique_ptr<IRMover> Mover;
391 struct ThinLTOState {
392 ThinLTOState(ThinBackend Backend);
395 ModuleSummaryIndex CombinedIndex;
396 MapVector<StringRef, BitcodeModule> ModuleMap;
397 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
400 // The global resolution for a particular (mangled) symbol name. This is in
401 // particular necessary to track whether each symbol can be internalized.
402 // Because any input file may introduce a new cross-partition reference, we
403 // cannot make any final internalization decisions until all input files have
404 // been added and the client has called run(). During run() we apply
405 // internalization decisions either directly to the module (for regular LTO)
406 // or to the combined index (for ThinLTO).
407 struct GlobalResolution {
408 /// The unmangled name of the global.
411 /// Keep track if the symbol is visible outside of ThinLTO (i.e. in
412 /// either a regular object or the regular LTO partition).
413 bool VisibleOutsideThinLTO = false;
415 bool UnnamedAddr = true;
417 /// This field keeps track of the partition number of this global. The
418 /// regular LTO object is partition 0, while each ThinLTO object has its own
419 /// partition number from 1 onwards.
421 /// Any global that is defined or used by more than one partition, or that
422 /// is referenced externally, may not be internalized.
424 /// Partitions generally have a one-to-one correspondence with tasks, except
425 /// that we use partition 0 for all parallel LTO code generation partitions.
426 /// Any partitioning of the combined LTO object is done internally by the
428 unsigned Partition = Unknown;
430 /// Special partition numbers.
432 /// A partition number has not yet been assigned to this global.
435 /// This global is either used by more than one partition or has an
436 /// external reference, and therefore cannot be internalized.
439 /// The RegularLTO partition
444 // Global mapping from mangled symbol names to resolutions.
445 StringMap<GlobalResolution> GlobalResolutions;
447 void addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
448 const InputFile::Symbol &Sym, SymbolResolution Res,
451 // These functions take a range of symbol resolutions [ResI, ResE) and consume
452 // the resolutions used by a single input module by incrementing ResI. After
453 // these functions return, [ResI, ResE) will refer to the resolution range for
454 // the remaining modules in the InputFile.
455 Error addModule(InputFile &Input, InputFile::InputModule &IM,
456 const SymbolResolution *&ResI, const SymbolResolution *ResE);
457 Error addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
458 const SymbolResolution *ResE);
459 Error addThinLTO(BitcodeModule BM, Module &M,
460 iterator_range<InputFile::symbol_iterator> Syms,
461 const SymbolResolution *&ResI, const SymbolResolution *ResE);
463 Error runRegularLTO(AddStreamFn AddStream);
464 Error runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
467 mutable bool CalledGetMaxTasks = false;
470 /// The resolution for a symbol. The linker must provide a SymbolResolution for
471 /// each global symbol based on its internal resolution of that symbol.
472 struct SymbolResolution {
474 : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0) {
476 /// The linker has chosen this definition of the symbol.
477 unsigned Prevailing : 1;
479 /// The definition of this symbol is unpreemptable at runtime and is known to
480 /// be in this linkage unit.
481 unsigned FinalDefinitionInLinkageUnit : 1;
483 /// The definition of this symbol is visible outside of the LTO unit.
484 unsigned VisibleToRegularObj : 1;