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 "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/Bitcode/BitcodeReader.h" 21 #include "llvm/IR/ModuleSummaryIndex.h" 22 #include "llvm/LTO/Config.h" 23 #include "llvm/Object/IRSymtab.h" 24 #include "llvm/Support/Caching.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/thread.h" 27 #include "llvm/Transforms/IPO/FunctionAttrs.h" 28 #include "llvm/Transforms/IPO/FunctionImport.h" 29 30 namespace llvm { 31 32 class Error; 33 class IRMover; 34 class LLVMContext; 35 class MemoryBufferRef; 36 class Module; 37 class raw_pwrite_stream; 38 class Target; 39 class ToolOutputFile; 40 41 /// Resolve linkage for prevailing symbols in the \p Index. Linkage changes 42 /// recorded in the index and the ThinLTO backends must apply the changes to 43 /// the module via thinLTOFinalizeInModule. 44 /// 45 /// This is done for correctness (if value exported, ensure we always 46 /// emit a copy), and compile-time optimization (allow drop of duplicates). 47 void thinLTOResolvePrevailingInIndex( 48 const lto::Config &C, ModuleSummaryIndex &Index, 49 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 50 isPrevailing, 51 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> 52 recordNewLinkage, 53 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols); 54 55 /// Update the linkages in the given \p Index to mark exported values 56 /// as external and non-exported values as internal. The ThinLTO backends 57 /// must apply the changes to the Module via thinLTOInternalizeModule. 58 void thinLTOInternalizeAndPromoteInIndex( 59 ModuleSummaryIndex &Index, 60 function_ref<bool(StringRef, ValueInfo)> isExported, 61 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 62 isPrevailing); 63 64 /// Computes a unique hash for the Module considering the current list of 65 /// export/import and other global analysis results. 66 /// The hash is produced in \p Key. 67 void computeLTOCacheKey( 68 SmallString<40> &Key, const lto::Config &Conf, 69 const ModuleSummaryIndex &Index, StringRef ModuleID, 70 const FunctionImporter::ImportMapTy &ImportList, 71 const FunctionImporter::ExportSetTy &ExportList, 72 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 73 const GVSummaryMapTy &DefinedGlobals, 74 const std::set<GlobalValue::GUID> &CfiFunctionDefs = {}, 75 const std::set<GlobalValue::GUID> &CfiFunctionDecls = {}); 76 77 namespace lto { 78 79 /// Given the original \p Path to an output file, replace any path 80 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the 81 /// resulting directory if it does not yet exist. 82 std::string getThinLTOOutputFile(const std::string &Path, 83 const std::string &OldPrefix, 84 const std::string &NewPrefix); 85 86 /// Setup optimization remarks. 87 Expected<std::unique_ptr<ToolOutputFile>> setupLLVMOptimizationRemarks( 88 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, 89 StringRef RemarksFormat, bool RemarksWithHotness, 90 Optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1); 91 92 /// Setups the output file for saving statistics. 93 Expected<std::unique_ptr<ToolOutputFile>> 94 setupStatsFile(StringRef StatsFilename); 95 96 /// Produces a container ordering for optimal multi-threaded processing. Returns 97 /// ordered indices to elements in the input array. 98 std::vector<int> generateModulesOrdering(ArrayRef<BitcodeModule *> R); 99 100 class LTO; 101 struct SymbolResolution; 102 class ThinBackendProc; 103 104 /// An input file. This is a symbol table wrapper that only exposes the 105 /// information that an LTO client should need in order to do symbol resolution. 106 class InputFile { 107 public: 108 class Symbol; 109 110 private: 111 // FIXME: Remove LTO class friendship once we have bitcode symbol tables. 112 friend LTO; 113 InputFile() = default; 114 115 std::vector<BitcodeModule> Mods; 116 SmallVector<char, 0> Strtab; 117 std::vector<Symbol> Symbols; 118 119 // [begin, end) for each module 120 std::vector<std::pair<size_t, size_t>> ModuleSymIndices; 121 122 StringRef TargetTriple, SourceFileName, COFFLinkerOpts; 123 std::vector<StringRef> DependentLibraries; 124 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable; 125 126 public: 127 ~InputFile(); 128 129 /// Create an InputFile. 130 static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object); 131 132 /// The purpose of this class is to only expose the symbol information that an 133 /// LTO client should need in order to do symbol resolution. 134 class Symbol : irsymtab::Symbol { 135 friend LTO; 136 137 public: 138 Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {} 139 140 using irsymtab::Symbol::isUndefined; 141 using irsymtab::Symbol::isCommon; 142 using irsymtab::Symbol::isWeak; 143 using irsymtab::Symbol::isIndirect; 144 using irsymtab::Symbol::getName; 145 using irsymtab::Symbol::getIRName; 146 using irsymtab::Symbol::getVisibility; 147 using irsymtab::Symbol::canBeOmittedFromSymbolTable; 148 using irsymtab::Symbol::isTLS; 149 using irsymtab::Symbol::getComdatIndex; 150 using irsymtab::Symbol::getCommonSize; 151 using irsymtab::Symbol::getCommonAlignment; 152 using irsymtab::Symbol::getCOFFWeakExternalFallback; 153 using irsymtab::Symbol::getSectionName; 154 using irsymtab::Symbol::isExecutable; 155 using irsymtab::Symbol::isUsed; 156 }; 157 158 /// A range over the symbols in this InputFile. 159 ArrayRef<Symbol> symbols() const { return Symbols; } 160 161 /// Returns linker options specified in the input file. 162 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; } 163 164 /// Returns dependent library specifiers from the input file. 165 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; } 166 167 /// Returns the path to the InputFile. 168 StringRef getName() const; 169 170 /// Returns the input file's target triple. 171 StringRef getTargetTriple() const { return TargetTriple; } 172 173 /// Returns the source file path specified at compile time. 174 StringRef getSourceFileName() const { return SourceFileName; } 175 176 // Returns a table with all the comdats used by this file. 177 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> getComdatTable() const { 178 return ComdatTable; 179 } 180 181 // Returns the only BitcodeModule from InputFile. 182 BitcodeModule &getSingleBitcodeModule(); 183 184 private: 185 ArrayRef<Symbol> module_symbols(unsigned I) const { 186 const auto &Indices = ModuleSymIndices[I]; 187 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second}; 188 } 189 }; 190 191 /// A ThinBackend defines what happens after the thin-link phase during ThinLTO. 192 /// The details of this type definition aren't important; clients can only 193 /// create a ThinBackend using one of the create*ThinBackend() functions below. 194 using ThinBackend = std::function<std::unique_ptr<ThinBackendProc>( 195 const Config &C, ModuleSummaryIndex &CombinedIndex, 196 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 197 AddStreamFn AddStream, FileCache Cache)>; 198 199 /// This ThinBackend runs the individual backend jobs in-process. 200 /// The default value means to use one job per hardware core (not hyper-thread). 201 ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism); 202 203 /// This ThinBackend writes individual module indexes to files, instead of 204 /// running the individual backend jobs. This backend is for distributed builds 205 /// where separate processes will invoke the real backends. 206 /// 207 /// To find the path to write the index to, the backend checks if the path has a 208 /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then 209 /// appends ".thinlto.bc" and writes the index to that path. If 210 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a 211 /// similar path with ".imports" appended instead. 212 /// LinkedObjectsFile is an output stream to write the list of object files for 213 /// the final ThinLTO linking. Can be nullptr. 214 /// OnWrite is callback which receives module identifier and notifies LTO user 215 /// that index file for the module (and optionally imports file) was created. 216 using IndexWriteCallback = std::function<void(const std::string &)>; 217 ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, 218 std::string NewPrefix, 219 bool ShouldEmitImportsFiles, 220 raw_fd_ostream *LinkedObjectsFile, 221 IndexWriteCallback OnWrite); 222 223 /// This class implements a resolution-based interface to LLVM's LTO 224 /// functionality. It supports regular LTO, parallel LTO code generation and 225 /// ThinLTO. You can use it from a linker in the following way: 226 /// - Set hooks and code generation options (see lto::Config struct defined in 227 /// Config.h), and use the lto::Config object to create an lto::LTO object. 228 /// - Create lto::InputFile objects using lto::InputFile::create(), then use 229 /// the symbols() function to enumerate its symbols and compute a resolution 230 /// for each symbol (see SymbolResolution below). 231 /// - After the linker has visited each input file (and each regular object 232 /// file) and computed a resolution for each symbol, take each lto::InputFile 233 /// and pass it and an array of symbol resolutions to the add() function. 234 /// - Call the getMaxTasks() function to get an upper bound on the number of 235 /// native object files that LTO may add to the link. 236 /// - Call the run() function. This function will use the supplied AddStream 237 /// and Cache functions to add up to getMaxTasks() native object files to 238 /// the link. 239 class LTO { 240 friend InputFile; 241 242 public: 243 /// Create an LTO object. A default constructed LTO object has a reasonable 244 /// production configuration, but you can customize it by passing arguments to 245 /// this constructor. 246 /// FIXME: We do currently require the DiagHandler field to be set in Conf. 247 /// Until that is fixed, a Config argument is required. 248 LTO(Config Conf, ThinBackend Backend = nullptr, 249 unsigned ParallelCodeGenParallelismLevel = 1); 250 ~LTO(); 251 252 /// Add an input file to the LTO link, using the provided symbol resolutions. 253 /// The symbol resolutions must appear in the enumeration order given by 254 /// InputFile::symbols(). 255 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res); 256 257 /// Returns an upper bound on the number of tasks that the client may expect. 258 /// This may only be called after all IR object files have been added. For a 259 /// full description of tasks see LTOBackend.h. 260 unsigned getMaxTasks() const; 261 262 /// Runs the LTO pipeline. This function calls the supplied AddStream 263 /// function to add native object files to the link. 264 /// 265 /// The Cache parameter is optional. If supplied, it will be used to cache 266 /// native object files and add them to the link. 267 /// 268 /// The client will receive at most one callback (via either AddStream or 269 /// Cache) for each task identifier. 270 Error run(AddStreamFn AddStream, FileCache Cache = nullptr); 271 272 /// Static method that returns a list of libcall symbols that can be generated 273 /// by LTO but might not be visible from bitcode symbol table. 274 static ArrayRef<const char*> getRuntimeLibcallSymbols(); 275 276 private: 277 Config Conf; 278 279 struct RegularLTOState { 280 RegularLTOState(unsigned ParallelCodeGenParallelismLevel, 281 const Config &Conf); 282 struct CommonResolution { 283 uint64_t Size = 0; 284 MaybeAlign Align; 285 /// Record if at least one instance of the common was marked as prevailing 286 bool Prevailing = false; 287 }; 288 std::map<std::string, CommonResolution> Commons; 289 290 unsigned ParallelCodeGenParallelismLevel; 291 LTOLLVMContext Ctx; 292 std::unique_ptr<Module> CombinedModule; 293 std::unique_ptr<IRMover> Mover; 294 295 // This stores the information about a regular LTO module that we have added 296 // to the link. It will either be linked immediately (for modules without 297 // summaries) or after summary-based dead stripping (for modules with 298 // summaries). 299 struct AddedModule { 300 std::unique_ptr<Module> M; 301 std::vector<GlobalValue *> Keep; 302 }; 303 std::vector<AddedModule> ModsWithSummaries; 304 bool EmptyCombinedModule = true; 305 } RegularLTO; 306 307 using ModuleMapType = MapVector<StringRef, BitcodeModule>; 308 309 struct ThinLTOState { 310 ThinLTOState(ThinBackend Backend); 311 312 ThinBackend Backend; 313 ModuleSummaryIndex CombinedIndex; 314 // The full set of bitcode modules in input order. 315 ModuleMapType ModuleMap; 316 // The bitcode modules to compile, if specified by the LTO Config. 317 Optional<ModuleMapType> ModulesToCompile; 318 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID; 319 } ThinLTO; 320 321 // The global resolution for a particular (mangled) symbol name. This is in 322 // particular necessary to track whether each symbol can be internalized. 323 // Because any input file may introduce a new cross-partition reference, we 324 // cannot make any final internalization decisions until all input files have 325 // been added and the client has called run(). During run() we apply 326 // internalization decisions either directly to the module (for regular LTO) 327 // or to the combined index (for ThinLTO). 328 struct GlobalResolution { 329 /// The unmangled name of the global. 330 std::string IRName; 331 332 /// Keep track if the symbol is visible outside of a module with a summary 333 /// (i.e. in either a regular object or a regular LTO module without a 334 /// summary). 335 bool VisibleOutsideSummary = false; 336 337 /// The symbol was exported dynamically, and therefore could be referenced 338 /// by a shared library not visible to the linker. 339 bool ExportDynamic = false; 340 341 bool UnnamedAddr = true; 342 343 /// True if module contains the prevailing definition. 344 bool Prevailing = false; 345 346 /// Returns true if module contains the prevailing definition and symbol is 347 /// an IR symbol. For example when module-level inline asm block is used, 348 /// symbol can be prevailing in module but have no IR name. 349 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); } 350 351 /// This field keeps track of the partition number of this global. The 352 /// regular LTO object is partition 0, while each ThinLTO object has its own 353 /// partition number from 1 onwards. 354 /// 355 /// Any global that is defined or used by more than one partition, or that 356 /// is referenced externally, may not be internalized. 357 /// 358 /// Partitions generally have a one-to-one correspondence with tasks, except 359 /// that we use partition 0 for all parallel LTO code generation partitions. 360 /// Any partitioning of the combined LTO object is done internally by the 361 /// LTO backend. 362 unsigned Partition = Unknown; 363 364 /// Special partition numbers. 365 enum : unsigned { 366 /// A partition number has not yet been assigned to this global. 367 Unknown = -1u, 368 369 /// This global is either used by more than one partition or has an 370 /// external reference, and therefore cannot be internalized. 371 External = -2u, 372 373 /// The RegularLTO partition 374 RegularLTO = 0, 375 }; 376 }; 377 378 // Global mapping from mangled symbol names to resolutions. 379 StringMap<GlobalResolution> GlobalResolutions; 380 381 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms, 382 ArrayRef<SymbolResolution> Res, unsigned Partition, 383 bool InSummary); 384 385 // These functions take a range of symbol resolutions [ResI, ResE) and consume 386 // the resolutions used by a single input module by incrementing ResI. After 387 // these functions return, [ResI, ResE) will refer to the resolution range for 388 // the remaining modules in the InputFile. 389 Error addModule(InputFile &Input, unsigned ModI, 390 const SymbolResolution *&ResI, const SymbolResolution *ResE); 391 392 Expected<RegularLTOState::AddedModule> 393 addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 394 const SymbolResolution *&ResI, const SymbolResolution *ResE); 395 Error linkRegularLTO(RegularLTOState::AddedModule Mod, 396 bool LivenessFromIndex); 397 398 Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 399 const SymbolResolution *&ResI, const SymbolResolution *ResE); 400 401 Error runRegularLTO(AddStreamFn AddStream); 402 Error runThinLTO(AddStreamFn AddStream, FileCache Cache, 403 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols); 404 405 Error checkPartiallySplit(); 406 407 mutable bool CalledGetMaxTasks = false; 408 409 // Use Optional to distinguish false from not yet initialized. 410 Optional<bool> EnableSplitLTOUnit; 411 412 // Identify symbols exported dynamically, and that therefore could be 413 // referenced by a shared library not visible to the linker. 414 DenseSet<GlobalValue::GUID> DynamicExportSymbols; 415 416 // Diagnostic optimization remarks file 417 std::unique_ptr<ToolOutputFile> DiagnosticOutputFile; 418 }; 419 420 /// The resolution for a symbol. The linker must provide a SymbolResolution for 421 /// each global symbol based on its internal resolution of that symbol. 422 struct SymbolResolution { 423 SymbolResolution() 424 : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0), 425 ExportDynamic(0), LinkerRedefined(0) {} 426 427 /// The linker has chosen this definition of the symbol. 428 unsigned Prevailing : 1; 429 430 /// The definition of this symbol is unpreemptable at runtime and is known to 431 /// be in this linkage unit. 432 unsigned FinalDefinitionInLinkageUnit : 1; 433 434 /// The definition of this symbol is visible outside of the LTO unit. 435 unsigned VisibleToRegularObj : 1; 436 437 /// The symbol was exported dynamically, and therefore could be referenced 438 /// by a shared library not visible to the linker. 439 unsigned ExportDynamic : 1; 440 441 /// Linker redefined version of the symbol which appeared in -wrap or -defsym 442 /// linker option. 443 unsigned LinkerRedefined : 1; 444 }; 445 446 } // namespace lto 447 } // namespace llvm 448 449 #endif 450