1 //===-LTO.cpp - 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 implements functions and classes used to support LTO. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/LTO/LTO.h" 14 #include "llvm/ADT/Statistic.h" 15 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 16 #include "llvm/Analysis/StackSafetyAnalysis.h" 17 #include "llvm/Analysis/TargetLibraryInfo.h" 18 #include "llvm/Analysis/TargetTransformInfo.h" 19 #include "llvm/Bitcode/BitcodeReader.h" 20 #include "llvm/Bitcode/BitcodeWriter.h" 21 #include "llvm/CodeGen/Analysis.h" 22 #include "llvm/Config/llvm-config.h" 23 #include "llvm/IR/AutoUpgrade.h" 24 #include "llvm/IR/DiagnosticPrinter.h" 25 #include "llvm/IR/Intrinsics.h" 26 #include "llvm/IR/LLVMRemarkStreamer.h" 27 #include "llvm/IR/LegacyPassManager.h" 28 #include "llvm/IR/Mangler.h" 29 #include "llvm/IR/Metadata.h" 30 #include "llvm/LTO/LTOBackend.h" 31 #include "llvm/LTO/SummaryBasedOptimizations.h" 32 #include "llvm/Linker/IRMover.h" 33 #include "llvm/Object/IRObjectFile.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Error.h" 36 #include "llvm/Support/ManagedStatic.h" 37 #include "llvm/Support/MemoryBuffer.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/SHA1.h" 40 #include "llvm/Support/SourceMgr.h" 41 #include "llvm/Support/TargetRegistry.h" 42 #include "llvm/Support/ThreadPool.h" 43 #include "llvm/Support/Threading.h" 44 #include "llvm/Support/TimeProfiler.h" 45 #include "llvm/Support/VCSRevision.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include "llvm/Target/TargetOptions.h" 49 #include "llvm/Transforms/IPO.h" 50 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 51 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 52 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 53 #include "llvm/Transforms/Utils/SplitModule.h" 54 55 #include <set> 56 57 using namespace llvm; 58 using namespace lto; 59 using namespace object; 60 61 #define DEBUG_TYPE "lto" 62 63 static cl::opt<bool> 64 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, 65 cl::desc("Dump the SCCs in the ThinLTO index's callgraph")); 66 67 /// Enable global value internalization in LTO. 68 cl::opt<bool> EnableLTOInternalization( 69 "enable-lto-internalization", cl::init(true), cl::Hidden, 70 cl::desc("Enable global value internalization in LTO")); 71 72 // Computes a unique hash for the Module considering the current list of 73 // export/import and other global analysis results. 74 // The hash is produced in \p Key. 75 void llvm::computeLTOCacheKey( 76 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index, 77 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, 78 const FunctionImporter::ExportSetTy &ExportList, 79 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 80 const GVSummaryMapTy &DefinedGlobals, 81 const std::set<GlobalValue::GUID> &CfiFunctionDefs, 82 const std::set<GlobalValue::GUID> &CfiFunctionDecls) { 83 // Compute the unique hash for this entry. 84 // This is based on the current compiler version, the module itself, the 85 // export list, the hash for every single module in the import list, the 86 // list of ResolvedODR for the module, and the list of preserved symbols. 87 SHA1 Hasher; 88 89 // Start with the compiler revision 90 Hasher.update(LLVM_VERSION_STRING); 91 #ifdef LLVM_REVISION 92 Hasher.update(LLVM_REVISION); 93 #endif 94 95 // Include the parts of the LTO configuration that affect code generation. 96 auto AddString = [&](StringRef Str) { 97 Hasher.update(Str); 98 Hasher.update(ArrayRef<uint8_t>{0}); 99 }; 100 auto AddUnsigned = [&](unsigned I) { 101 uint8_t Data[4]; 102 support::endian::write32le(Data, I); 103 Hasher.update(ArrayRef<uint8_t>{Data, 4}); 104 }; 105 auto AddUint64 = [&](uint64_t I) { 106 uint8_t Data[8]; 107 support::endian::write64le(Data, I); 108 Hasher.update(ArrayRef<uint8_t>{Data, 8}); 109 }; 110 AddString(Conf.CPU); 111 // FIXME: Hash more of Options. For now all clients initialize Options from 112 // command-line flags (which is unsupported in production), but may set 113 // RelaxELFRelocations. The clang driver can also pass FunctionSections, 114 // DataSections and DebuggerTuning via command line flags. 115 AddUnsigned(Conf.Options.RelaxELFRelocations); 116 AddUnsigned(Conf.Options.FunctionSections); 117 AddUnsigned(Conf.Options.DataSections); 118 AddUnsigned((unsigned)Conf.Options.DebuggerTuning); 119 for (auto &A : Conf.MAttrs) 120 AddString(A); 121 if (Conf.RelocModel) 122 AddUnsigned(*Conf.RelocModel); 123 else 124 AddUnsigned(-1); 125 if (Conf.CodeModel) 126 AddUnsigned(*Conf.CodeModel); 127 else 128 AddUnsigned(-1); 129 AddUnsigned(Conf.CGOptLevel); 130 AddUnsigned(Conf.CGFileType); 131 AddUnsigned(Conf.OptLevel); 132 AddUnsigned(Conf.UseNewPM); 133 AddUnsigned(Conf.Freestanding); 134 AddString(Conf.OptPipeline); 135 AddString(Conf.AAPipeline); 136 AddString(Conf.OverrideTriple); 137 AddString(Conf.DefaultTriple); 138 AddString(Conf.DwoDir); 139 140 // Include the hash for the current module 141 auto ModHash = Index.getModuleHash(ModuleID); 142 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); 143 144 std::vector<uint64_t> ExportsGUID; 145 ExportsGUID.reserve(ExportList.size()); 146 for (const auto &VI : ExportList) { 147 auto GUID = VI.getGUID(); 148 ExportsGUID.push_back(GUID); 149 } 150 151 // Sort the export list elements GUIDs. 152 llvm::sort(ExportsGUID); 153 for (uint64_t GUID : ExportsGUID) { 154 // The export list can impact the internalization, be conservative here 155 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID))); 156 } 157 158 // Include the hash for every module we import functions from. The set of 159 // imported symbols for each module may affect code generation and is 160 // sensitive to link order, so include that as well. 161 using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator; 162 std::vector<ImportMapIteratorTy> ImportModulesVector; 163 ImportModulesVector.reserve(ImportList.size()); 164 165 for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end(); 166 ++It) { 167 ImportModulesVector.push_back(It); 168 } 169 llvm::sort(ImportModulesVector, 170 [](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs) 171 -> bool { return Lhs->getKey() < Rhs->getKey(); }); 172 for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) { 173 auto ModHash = Index.getModuleHash(EntryIt->first()); 174 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); 175 176 AddUint64(EntryIt->second.size()); 177 for (auto &Fn : EntryIt->second) 178 AddUint64(Fn); 179 } 180 181 // Include the hash for the resolved ODR. 182 for (auto &Entry : ResolvedODR) { 183 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first, 184 sizeof(GlobalValue::GUID))); 185 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second, 186 sizeof(GlobalValue::LinkageTypes))); 187 } 188 189 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or 190 // defined in this module. 191 std::set<GlobalValue::GUID> UsedCfiDefs; 192 std::set<GlobalValue::GUID> UsedCfiDecls; 193 194 // Typeids used in this module. 195 std::set<GlobalValue::GUID> UsedTypeIds; 196 197 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) { 198 if (CfiFunctionDefs.count(ValueGUID)) 199 UsedCfiDefs.insert(ValueGUID); 200 if (CfiFunctionDecls.count(ValueGUID)) 201 UsedCfiDecls.insert(ValueGUID); 202 }; 203 204 auto AddUsedThings = [&](GlobalValueSummary *GS) { 205 if (!GS) return; 206 AddUnsigned(GS->getVisibility()); 207 AddUnsigned(GS->isLive()); 208 AddUnsigned(GS->canAutoHide()); 209 for (const ValueInfo &VI : GS->refs()) { 210 AddUnsigned(VI.isDSOLocal()); 211 AddUsedCfiGlobal(VI.getGUID()); 212 } 213 if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) { 214 AddUnsigned(GVS->maybeReadOnly()); 215 AddUnsigned(GVS->maybeWriteOnly()); 216 } 217 if (auto *FS = dyn_cast<FunctionSummary>(GS)) { 218 for (auto &TT : FS->type_tests()) 219 UsedTypeIds.insert(TT); 220 for (auto &TT : FS->type_test_assume_vcalls()) 221 UsedTypeIds.insert(TT.GUID); 222 for (auto &TT : FS->type_checked_load_vcalls()) 223 UsedTypeIds.insert(TT.GUID); 224 for (auto &TT : FS->type_test_assume_const_vcalls()) 225 UsedTypeIds.insert(TT.VFunc.GUID); 226 for (auto &TT : FS->type_checked_load_const_vcalls()) 227 UsedTypeIds.insert(TT.VFunc.GUID); 228 for (auto &ET : FS->calls()) { 229 AddUnsigned(ET.first.isDSOLocal()); 230 AddUsedCfiGlobal(ET.first.getGUID()); 231 } 232 } 233 }; 234 235 // Include the hash for the linkage type to reflect internalization and weak 236 // resolution, and collect any used type identifier resolutions. 237 for (auto &GS : DefinedGlobals) { 238 GlobalValue::LinkageTypes Linkage = GS.second->linkage(); 239 Hasher.update( 240 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage))); 241 AddUsedCfiGlobal(GS.first); 242 AddUsedThings(GS.second); 243 } 244 245 // Imported functions may introduce new uses of type identifier resolutions, 246 // so we need to collect their used resolutions as well. 247 for (auto &ImpM : ImportList) 248 for (auto &ImpF : ImpM.second) { 249 GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first()); 250 AddUsedThings(S); 251 // If this is an alias, we also care about any types/etc. that the aliasee 252 // may reference. 253 if (auto *AS = dyn_cast_or_null<AliasSummary>(S)) 254 AddUsedThings(AS->getBaseObject()); 255 } 256 257 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) { 258 AddString(TId); 259 260 AddUnsigned(S.TTRes.TheKind); 261 AddUnsigned(S.TTRes.SizeM1BitWidth); 262 263 AddUint64(S.TTRes.AlignLog2); 264 AddUint64(S.TTRes.SizeM1); 265 AddUint64(S.TTRes.BitMask); 266 AddUint64(S.TTRes.InlineBits); 267 268 AddUint64(S.WPDRes.size()); 269 for (auto &WPD : S.WPDRes) { 270 AddUnsigned(WPD.first); 271 AddUnsigned(WPD.second.TheKind); 272 AddString(WPD.second.SingleImplName); 273 274 AddUint64(WPD.second.ResByArg.size()); 275 for (auto &ByArg : WPD.second.ResByArg) { 276 AddUint64(ByArg.first.size()); 277 for (uint64_t Arg : ByArg.first) 278 AddUint64(Arg); 279 AddUnsigned(ByArg.second.TheKind); 280 AddUint64(ByArg.second.Info); 281 AddUnsigned(ByArg.second.Byte); 282 AddUnsigned(ByArg.second.Bit); 283 } 284 } 285 }; 286 287 // Include the hash for all type identifiers used by this module. 288 for (GlobalValue::GUID TId : UsedTypeIds) { 289 auto TidIter = Index.typeIds().equal_range(TId); 290 for (auto It = TidIter.first; It != TidIter.second; ++It) 291 AddTypeIdSummary(It->second.first, It->second.second); 292 } 293 294 AddUnsigned(UsedCfiDefs.size()); 295 for (auto &V : UsedCfiDefs) 296 AddUint64(V); 297 298 AddUnsigned(UsedCfiDecls.size()); 299 for (auto &V : UsedCfiDecls) 300 AddUint64(V); 301 302 if (!Conf.SampleProfile.empty()) { 303 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile); 304 if (FileOrErr) { 305 Hasher.update(FileOrErr.get()->getBuffer()); 306 307 if (!Conf.ProfileRemapping.empty()) { 308 FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping); 309 if (FileOrErr) 310 Hasher.update(FileOrErr.get()->getBuffer()); 311 } 312 } 313 } 314 315 Key = toHex(Hasher.result()); 316 } 317 318 static void thinLTOResolvePrevailingGUID( 319 const Config &C, ValueInfo VI, 320 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias, 321 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 322 isPrevailing, 323 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> 324 recordNewLinkage, 325 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 326 GlobalValue::VisibilityTypes Visibility = 327 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility() 328 : GlobalValue::DefaultVisibility; 329 for (auto &S : VI.getSummaryList()) { 330 GlobalValue::LinkageTypes OriginalLinkage = S->linkage(); 331 // Ignore local and appending linkage values since the linker 332 // doesn't resolve them. 333 if (GlobalValue::isLocalLinkage(OriginalLinkage) || 334 GlobalValue::isAppendingLinkage(S->linkage())) 335 continue; 336 // We need to emit only one of these. The prevailing module will keep it, 337 // but turned into a weak, while the others will drop it when possible. 338 // This is both a compile-time optimization and a correctness 339 // transformation. This is necessary for correctness when we have exported 340 // a reference - we need to convert the linkonce to weak to 341 // ensure a copy is kept to satisfy the exported reference. 342 // FIXME: We may want to split the compile time and correctness 343 // aspects into separate routines. 344 if (isPrevailing(VI.getGUID(), S.get())) { 345 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) { 346 S->setLinkage(GlobalValue::getWeakLinkage( 347 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage))); 348 // The kept copy is eligible for auto-hiding (hidden visibility) if all 349 // copies were (i.e. they were all linkonce_odr global unnamed addr). 350 // If any copy is not (e.g. it was originally weak_odr), then the symbol 351 // must remain externally available (e.g. a weak_odr from an explicitly 352 // instantiated template). Additionally, if it is in the 353 // GUIDPreservedSymbols set, that means that it is visibile outside 354 // the summary (e.g. in a native object or a bitcode file without 355 // summary), and in that case we cannot hide it as it isn't possible to 356 // check all copies. 357 S->setCanAutoHide(VI.canAutoHide() && 358 !GUIDPreservedSymbols.count(VI.getGUID())); 359 } 360 if (C.VisibilityScheme == Config::FromPrevailing) 361 Visibility = S->getVisibility(); 362 } 363 // Alias and aliasee can't be turned into available_externally. 364 else if (!isa<AliasSummary>(S.get()) && 365 !GlobalInvolvedWithAlias.count(S.get())) 366 S->setLinkage(GlobalValue::AvailableExternallyLinkage); 367 368 // For ELF, set visibility to the computed visibility from summaries. We 369 // don't track visibility from declarations so this may be more relaxed than 370 // the most constraining one. 371 if (C.VisibilityScheme == Config::ELF) 372 S->setVisibility(Visibility); 373 374 if (S->linkage() != OriginalLinkage) 375 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage()); 376 } 377 378 if (C.VisibilityScheme == Config::FromPrevailing) { 379 for (auto &S : VI.getSummaryList()) { 380 GlobalValue::LinkageTypes OriginalLinkage = S->linkage(); 381 if (GlobalValue::isLocalLinkage(OriginalLinkage) || 382 GlobalValue::isAppendingLinkage(S->linkage())) 383 continue; 384 S->setVisibility(Visibility); 385 } 386 } 387 } 388 389 /// Resolve linkage for prevailing symbols in the \p Index. 390 // 391 // We'd like to drop these functions if they are no longer referenced in the 392 // current module. However there is a chance that another module is still 393 // referencing them because of the import. We make sure we always emit at least 394 // one copy. 395 void llvm::thinLTOResolvePrevailingInIndex( 396 const Config &C, ModuleSummaryIndex &Index, 397 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 398 isPrevailing, 399 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> 400 recordNewLinkage, 401 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 402 // We won't optimize the globals that are referenced by an alias for now 403 // Ideally we should turn the alias into a global and duplicate the definition 404 // when needed. 405 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias; 406 for (auto &I : Index) 407 for (auto &S : I.second.SummaryList) 408 if (auto AS = dyn_cast<AliasSummary>(S.get())) 409 GlobalInvolvedWithAlias.insert(&AS->getAliasee()); 410 411 for (auto &I : Index) 412 thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I), 413 GlobalInvolvedWithAlias, isPrevailing, 414 recordNewLinkage, GUIDPreservedSymbols); 415 } 416 417 static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) { 418 if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject())) 419 return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() && 420 (VarSummary->linkage() == GlobalValue::WeakODRLinkage || 421 VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage); 422 return false; 423 } 424 425 static void thinLTOInternalizeAndPromoteGUID( 426 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported, 427 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 428 isPrevailing) { 429 for (auto &S : VI.getSummaryList()) { 430 if (isExported(S->modulePath(), VI)) { 431 if (GlobalValue::isLocalLinkage(S->linkage())) 432 S->setLinkage(GlobalValue::ExternalLinkage); 433 } else if (EnableLTOInternalization && 434 // Ignore local and appending linkage values since the linker 435 // doesn't resolve them. 436 !GlobalValue::isLocalLinkage(S->linkage()) && 437 (!GlobalValue::isInterposableLinkage(S->linkage()) || 438 isPrevailing(VI.getGUID(), S.get())) && 439 S->linkage() != GlobalValue::AppendingLinkage && 440 // We can't internalize available_externally globals because this 441 // can break function pointer equality. 442 S->linkage() != GlobalValue::AvailableExternallyLinkage && 443 // Functions and read-only variables with linkonce_odr and 444 // weak_odr linkage can be internalized. We can't internalize 445 // linkonce_odr and weak_odr variables which are both modified 446 // and read somewhere in the program because reads and writes 447 // will become inconsistent. 448 !isWeakObjectWithRWAccess(S.get())) 449 S->setLinkage(GlobalValue::InternalLinkage); 450 } 451 } 452 453 // Update the linkages in the given \p Index to mark exported values 454 // as external and non-exported values as internal. 455 void llvm::thinLTOInternalizeAndPromoteInIndex( 456 ModuleSummaryIndex &Index, 457 function_ref<bool(StringRef, ValueInfo)> isExported, 458 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)> 459 isPrevailing) { 460 for (auto &I : Index) 461 thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported, 462 isPrevailing); 463 } 464 465 // Requires a destructor for std::vector<InputModule>. 466 InputFile::~InputFile() = default; 467 468 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) { 469 std::unique_ptr<InputFile> File(new InputFile); 470 471 Expected<IRSymtabFile> FOrErr = readIRSymtab(Object); 472 if (!FOrErr) 473 return FOrErr.takeError(); 474 475 File->TargetTriple = FOrErr->TheReader.getTargetTriple(); 476 File->SourceFileName = FOrErr->TheReader.getSourceFileName(); 477 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts(); 478 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries(); 479 File->ComdatTable = FOrErr->TheReader.getComdatTable(); 480 481 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) { 482 size_t Begin = File->Symbols.size(); 483 for (const irsymtab::Reader::SymbolRef &Sym : 484 FOrErr->TheReader.module_symbols(I)) 485 // Skip symbols that are irrelevant to LTO. Note that this condition needs 486 // to match the one in Skip() in LTO::addRegularLTO(). 487 if (Sym.isGlobal() && !Sym.isFormatSpecific()) 488 File->Symbols.push_back(Sym); 489 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()}); 490 } 491 492 File->Mods = FOrErr->Mods; 493 File->Strtab = std::move(FOrErr->Strtab); 494 return std::move(File); 495 } 496 497 StringRef InputFile::getName() const { 498 return Mods[0].getModuleIdentifier(); 499 } 500 501 BitcodeModule &InputFile::getSingleBitcodeModule() { 502 assert(Mods.size() == 1 && "Expect only one bitcode module"); 503 return Mods[0]; 504 } 505 506 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel, 507 const Config &Conf) 508 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel), 509 Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)), 510 Mover(std::make_unique<IRMover>(*CombinedModule)) {} 511 512 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) 513 : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) { 514 if (!Backend) 515 this->Backend = 516 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency()); 517 } 518 519 LTO::LTO(Config Conf, ThinBackend Backend, 520 unsigned ParallelCodeGenParallelismLevel) 521 : Conf(std::move(Conf)), 522 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf), 523 ThinLTO(std::move(Backend)) {} 524 525 // Requires a destructor for MapVector<BitcodeModule>. 526 LTO::~LTO() = default; 527 528 // Add the symbols in the given module to the GlobalResolutions map, and resolve 529 // their partitions. 530 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms, 531 ArrayRef<SymbolResolution> Res, 532 unsigned Partition, bool InSummary) { 533 auto *ResI = Res.begin(); 534 auto *ResE = Res.end(); 535 (void)ResE; 536 for (const InputFile::Symbol &Sym : Syms) { 537 assert(ResI != ResE); 538 SymbolResolution Res = *ResI++; 539 540 StringRef Name = Sym.getName(); 541 Triple TT(RegularLTO.CombinedModule->getTargetTriple()); 542 // Strip the __imp_ prefix from COFF dllimport symbols (similar to the 543 // way they are handled by lld), otherwise we can end up with two 544 // global resolutions (one with and one for a copy of the symbol without). 545 if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_")) 546 Name = Name.substr(strlen("__imp_")); 547 auto &GlobalRes = GlobalResolutions[Name]; 548 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr(); 549 if (Res.Prevailing) { 550 assert(!GlobalRes.Prevailing && 551 "Multiple prevailing defs are not allowed"); 552 GlobalRes.Prevailing = true; 553 GlobalRes.IRName = std::string(Sym.getIRName()); 554 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) { 555 // Sometimes it can be two copies of symbol in a module and prevailing 556 // symbol can have no IR name. That might happen if symbol is defined in 557 // module level inline asm block. In case we have multiple modules with 558 // the same symbol we want to use IR name of the prevailing symbol. 559 // Otherwise, if we haven't seen a prevailing symbol, set the name so that 560 // we can later use it to check if there is any prevailing copy in IR. 561 GlobalRes.IRName = std::string(Sym.getIRName()); 562 } 563 564 // Set the partition to external if we know it is re-defined by the linker 565 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a 566 // regular object, is referenced from llvm.compiler_used, or was already 567 // recorded as being referenced from a different partition. 568 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() || 569 (GlobalRes.Partition != GlobalResolution::Unknown && 570 GlobalRes.Partition != Partition)) { 571 GlobalRes.Partition = GlobalResolution::External; 572 } else 573 // First recorded reference, save the current partition. 574 GlobalRes.Partition = Partition; 575 576 // Flag as visible outside of summary if visible from a regular object or 577 // from a module that does not have a summary. 578 GlobalRes.VisibleOutsideSummary |= 579 (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary); 580 } 581 } 582 583 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, 584 ArrayRef<SymbolResolution> Res) { 585 StringRef Path = Input->getName(); 586 OS << Path << '\n'; 587 auto ResI = Res.begin(); 588 for (const InputFile::Symbol &Sym : Input->symbols()) { 589 assert(ResI != Res.end()); 590 SymbolResolution Res = *ResI++; 591 592 OS << "-r=" << Path << ',' << Sym.getName() << ','; 593 if (Res.Prevailing) 594 OS << 'p'; 595 if (Res.FinalDefinitionInLinkageUnit) 596 OS << 'l'; 597 if (Res.VisibleToRegularObj) 598 OS << 'x'; 599 if (Res.LinkerRedefined) 600 OS << 'r'; 601 OS << '\n'; 602 } 603 OS.flush(); 604 assert(ResI == Res.end()); 605 } 606 607 Error LTO::add(std::unique_ptr<InputFile> Input, 608 ArrayRef<SymbolResolution> Res) { 609 assert(!CalledGetMaxTasks); 610 611 if (Conf.ResolutionFile) 612 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res); 613 614 if (RegularLTO.CombinedModule->getTargetTriple().empty()) { 615 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple()); 616 if (Triple(Input->getTargetTriple()).isOSBinFormatELF()) 617 Conf.VisibilityScheme = Config::ELF; 618 } 619 620 const SymbolResolution *ResI = Res.begin(); 621 for (unsigned I = 0; I != Input->Mods.size(); ++I) 622 if (Error Err = addModule(*Input, I, ResI, Res.end())) 623 return Err; 624 625 assert(ResI == Res.end()); 626 return Error::success(); 627 } 628 629 Error LTO::addModule(InputFile &Input, unsigned ModI, 630 const SymbolResolution *&ResI, 631 const SymbolResolution *ResE) { 632 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo(); 633 if (!LTOInfo) 634 return LTOInfo.takeError(); 635 636 if (EnableSplitLTOUnit.hasValue()) { 637 // If only some modules were split, flag this in the index so that 638 // we can skip or error on optimizations that need consistently split 639 // modules (whole program devirt and lower type tests). 640 if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit) 641 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits(); 642 } else 643 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit; 644 645 BitcodeModule BM = Input.Mods[ModI]; 646 auto ModSyms = Input.module_symbols(ModI); 647 addModuleToGlobalRes(ModSyms, {ResI, ResE}, 648 LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0, 649 LTOInfo->HasSummary); 650 651 if (LTOInfo->IsThinLTO) 652 return addThinLTO(BM, ModSyms, ResI, ResE); 653 654 RegularLTO.EmptyCombinedModule = false; 655 Expected<RegularLTOState::AddedModule> ModOrErr = 656 addRegularLTO(BM, ModSyms, ResI, ResE); 657 if (!ModOrErr) 658 return ModOrErr.takeError(); 659 660 if (!LTOInfo->HasSummary) 661 return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false); 662 663 // Regular LTO module summaries are added to a dummy module that represents 664 // the combined regular LTO module. 665 if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull)) 666 return Err; 667 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr)); 668 return Error::success(); 669 } 670 671 // Checks whether the given global value is in a non-prevailing comdat 672 // (comdat containing values the linker indicated were not prevailing, 673 // which we then dropped to available_externally), and if so, removes 674 // it from the comdat. This is called for all global values to ensure the 675 // comdat is empty rather than leaving an incomplete comdat. It is needed for 676 // regular LTO modules, in case we are in a mixed-LTO mode (both regular 677 // and thin LTO modules) compilation. Since the regular LTO module will be 678 // linked first in the final native link, we want to make sure the linker 679 // doesn't select any of these incomplete comdats that would be left 680 // in the regular LTO module without this cleanup. 681 static void 682 handleNonPrevailingComdat(GlobalValue &GV, 683 std::set<const Comdat *> &NonPrevailingComdats) { 684 Comdat *C = GV.getComdat(); 685 if (!C) 686 return; 687 688 if (!NonPrevailingComdats.count(C)) 689 return; 690 691 // Additionally need to drop externally visible global values from the comdat 692 // to available_externally, so that there aren't multiply defined linker 693 // errors. 694 if (!GV.hasLocalLinkage()) 695 GV.setLinkage(GlobalValue::AvailableExternallyLinkage); 696 697 if (auto GO = dyn_cast<GlobalObject>(&GV)) 698 GO->setComdat(nullptr); 699 } 700 701 // Add a regular LTO object to the link. 702 // The resulting module needs to be linked into the combined LTO module with 703 // linkRegularLTO. 704 Expected<LTO::RegularLTOState::AddedModule> 705 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 706 const SymbolResolution *&ResI, 707 const SymbolResolution *ResE) { 708 RegularLTOState::AddedModule Mod; 709 Expected<std::unique_ptr<Module>> MOrErr = 710 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true, 711 /*IsImporting*/ false); 712 if (!MOrErr) 713 return MOrErr.takeError(); 714 Module &M = **MOrErr; 715 Mod.M = std::move(*MOrErr); 716 717 if (Error Err = M.materializeMetadata()) 718 return std::move(Err); 719 UpgradeDebugInfo(M); 720 721 ModuleSymbolTable SymTab; 722 SymTab.addModule(&M); 723 724 for (GlobalVariable &GV : M.globals()) 725 if (GV.hasAppendingLinkage()) 726 Mod.Keep.push_back(&GV); 727 728 DenseSet<GlobalObject *> AliasedGlobals; 729 for (auto &GA : M.aliases()) 730 if (GlobalObject *GO = GA.getBaseObject()) 731 AliasedGlobals.insert(GO); 732 733 // In this function we need IR GlobalValues matching the symbols in Syms 734 // (which is not backed by a module), so we need to enumerate them in the same 735 // order. The symbol enumeration order of a ModuleSymbolTable intentionally 736 // matches the order of an irsymtab, but when we read the irsymtab in 737 // InputFile::create we omit some symbols that are irrelevant to LTO. The 738 // Skip() function skips the same symbols from the module as InputFile does 739 // from the symbol table. 740 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end(); 741 auto Skip = [&]() { 742 while (MsymI != MsymE) { 743 auto Flags = SymTab.getSymbolFlags(*MsymI); 744 if ((Flags & object::BasicSymbolRef::SF_Global) && 745 !(Flags & object::BasicSymbolRef::SF_FormatSpecific)) 746 return; 747 ++MsymI; 748 } 749 }; 750 Skip(); 751 752 std::set<const Comdat *> NonPrevailingComdats; 753 for (const InputFile::Symbol &Sym : Syms) { 754 assert(ResI != ResE); 755 SymbolResolution Res = *ResI++; 756 757 assert(MsymI != MsymE); 758 ModuleSymbolTable::Symbol Msym = *MsymI++; 759 Skip(); 760 761 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) { 762 if (Res.Prevailing) { 763 if (Sym.isUndefined()) 764 continue; 765 Mod.Keep.push_back(GV); 766 // For symbols re-defined with linker -wrap and -defsym options, 767 // set the linkage to weak to inhibit IPO. The linkage will be 768 // restored by the linker. 769 if (Res.LinkerRedefined) 770 GV->setLinkage(GlobalValue::WeakAnyLinkage); 771 772 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage(); 773 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) 774 GV->setLinkage(GlobalValue::getWeakLinkage( 775 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage))); 776 } else if (isa<GlobalObject>(GV) && 777 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() || 778 GV->hasAvailableExternallyLinkage()) && 779 !AliasedGlobals.count(cast<GlobalObject>(GV))) { 780 // Any of the above three types of linkage indicates that the 781 // chosen prevailing symbol will have the same semantics as this copy of 782 // the symbol, so we may be able to link it with available_externally 783 // linkage. We will decide later whether to do that when we link this 784 // module (in linkRegularLTO), based on whether it is undefined. 785 Mod.Keep.push_back(GV); 786 GV->setLinkage(GlobalValue::AvailableExternallyLinkage); 787 if (GV->hasComdat()) 788 NonPrevailingComdats.insert(GV->getComdat()); 789 cast<GlobalObject>(GV)->setComdat(nullptr); 790 } 791 792 // Set the 'local' flag based on the linker resolution for this symbol. 793 if (Res.FinalDefinitionInLinkageUnit) { 794 GV->setDSOLocal(true); 795 if (GV->hasDLLImportStorageClass()) 796 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes:: 797 DefaultStorageClass); 798 } 799 } 800 // Common resolution: collect the maximum size/alignment over all commons. 801 // We also record if we see an instance of a common as prevailing, so that 802 // if none is prevailing we can ignore it later. 803 if (Sym.isCommon()) { 804 // FIXME: We should figure out what to do about commons defined by asm. 805 // For now they aren't reported correctly by ModuleSymbolTable. 806 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())]; 807 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize()); 808 MaybeAlign SymAlign(Sym.getCommonAlignment()); 809 if (SymAlign) 810 CommonRes.Align = max(*SymAlign, CommonRes.Align); 811 CommonRes.Prevailing |= Res.Prevailing; 812 } 813 814 } 815 if (!M.getComdatSymbolTable().empty()) 816 for (GlobalValue &GV : M.global_values()) 817 handleNonPrevailingComdat(GV, NonPrevailingComdats); 818 assert(MsymI == MsymE); 819 return std::move(Mod); 820 } 821 822 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod, 823 bool LivenessFromIndex) { 824 std::vector<GlobalValue *> Keep; 825 for (GlobalValue *GV : Mod.Keep) { 826 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) { 827 if (Function *F = dyn_cast<Function>(GV)) { 828 OptimizationRemarkEmitter ORE(F, nullptr); 829 ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F) 830 << ore::NV("Function", F) 831 << " not added to the combined module "); 832 } 833 continue; 834 } 835 836 if (!GV->hasAvailableExternallyLinkage()) { 837 Keep.push_back(GV); 838 continue; 839 } 840 841 // Only link available_externally definitions if we don't already have a 842 // definition. 843 GlobalValue *CombinedGV = 844 RegularLTO.CombinedModule->getNamedValue(GV->getName()); 845 if (CombinedGV && !CombinedGV->isDeclaration()) 846 continue; 847 848 Keep.push_back(GV); 849 } 850 851 return RegularLTO.Mover->move(std::move(Mod.M), Keep, 852 [](GlobalValue &, IRMover::ValueAdder) {}, 853 /* IsPerformingImport */ false); 854 } 855 856 // Add a ThinLTO module to the link. 857 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms, 858 const SymbolResolution *&ResI, 859 const SymbolResolution *ResE) { 860 if (Error Err = 861 BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(), 862 ThinLTO.ModuleMap.size())) 863 return Err; 864 865 for (const InputFile::Symbol &Sym : Syms) { 866 assert(ResI != ResE); 867 SymbolResolution Res = *ResI++; 868 869 if (!Sym.getIRName().empty()) { 870 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier( 871 Sym.getIRName(), GlobalValue::ExternalLinkage, "")); 872 if (Res.Prevailing) { 873 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier(); 874 875 // For linker redefined symbols (via --wrap or --defsym) we want to 876 // switch the linkage to `weak` to prevent IPOs from happening. 877 // Find the summary in the module for this very GV and record the new 878 // linkage so that we can switch it when we import the GV. 879 if (Res.LinkerRedefined) 880 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule( 881 GUID, BM.getModuleIdentifier())) 882 S->setLinkage(GlobalValue::WeakAnyLinkage); 883 } 884 885 // If the linker resolved the symbol to a local definition then mark it 886 // as local in the summary for the module we are adding. 887 if (Res.FinalDefinitionInLinkageUnit) { 888 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule( 889 GUID, BM.getModuleIdentifier())) { 890 S->setDSOLocal(true); 891 } 892 } 893 } 894 } 895 896 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second) 897 return make_error<StringError>( 898 "Expected at most one ThinLTO module per bitcode file", 899 inconvertibleErrorCode()); 900 901 if (!Conf.ThinLTOModulesToCompile.empty()) { 902 if (!ThinLTO.ModulesToCompile) 903 ThinLTO.ModulesToCompile = ModuleMapType(); 904 // This is a fuzzy name matching where only modules with name containing the 905 // specified switch values are going to be compiled. 906 for (const std::string &Name : Conf.ThinLTOModulesToCompile) { 907 if (BM.getModuleIdentifier().contains(Name)) { 908 ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM}); 909 llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier() 910 << " to compile\n"; 911 } 912 } 913 } 914 915 return Error::success(); 916 } 917 918 unsigned LTO::getMaxTasks() const { 919 CalledGetMaxTasks = true; 920 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size() 921 : ThinLTO.ModuleMap.size(); 922 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount; 923 } 924 925 // If only some of the modules were split, we cannot correctly handle 926 // code that contains type tests or type checked loads. 927 Error LTO::checkPartiallySplit() { 928 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits()) 929 return Error::success(); 930 931 Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction( 932 Intrinsic::getName(Intrinsic::type_test)); 933 Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction( 934 Intrinsic::getName(Intrinsic::type_checked_load)); 935 936 // First check if there are type tests / type checked loads in the 937 // merged regular LTO module IR. 938 if ((TypeTestFunc && !TypeTestFunc->use_empty()) || 939 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty())) 940 return make_error<StringError>( 941 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)", 942 inconvertibleErrorCode()); 943 944 // Otherwise check if there are any recorded in the combined summary from the 945 // ThinLTO modules. 946 for (auto &P : ThinLTO.CombinedIndex) { 947 for (auto &S : P.second.SummaryList) { 948 auto *FS = dyn_cast<FunctionSummary>(S.get()); 949 if (!FS) 950 continue; 951 if (!FS->type_test_assume_vcalls().empty() || 952 !FS->type_checked_load_vcalls().empty() || 953 !FS->type_test_assume_const_vcalls().empty() || 954 !FS->type_checked_load_const_vcalls().empty() || 955 !FS->type_tests().empty()) 956 return make_error<StringError>( 957 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)", 958 inconvertibleErrorCode()); 959 } 960 } 961 return Error::success(); 962 } 963 964 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) { 965 // Compute "dead" symbols, we don't want to import/export these! 966 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols; 967 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions; 968 for (auto &Res : GlobalResolutions) { 969 // Normally resolution have IR name of symbol. We can do nothing here 970 // otherwise. See comments in GlobalResolution struct for more details. 971 if (Res.second.IRName.empty()) 972 continue; 973 974 GlobalValue::GUID GUID = GlobalValue::getGUID( 975 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)); 976 977 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing) 978 GUIDPreservedSymbols.insert(GUID); 979 980 GUIDPrevailingResolutions[GUID] = 981 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No; 982 } 983 984 auto isPrevailing = [&](GlobalValue::GUID G) { 985 auto It = GUIDPrevailingResolutions.find(G); 986 if (It == GUIDPrevailingResolutions.end()) 987 return PrevailingType::Unknown; 988 return It->second; 989 }; 990 computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols, 991 isPrevailing, Conf.OptLevel > 0); 992 993 // Setup output file to emit statistics. 994 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile); 995 if (!StatsFileOrErr) 996 return StatsFileOrErr.takeError(); 997 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get()); 998 999 Error Result = runRegularLTO(AddStream); 1000 if (!Result) 1001 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols); 1002 1003 if (StatsFile) 1004 PrintStatisticsJSON(StatsFile->os()); 1005 1006 return Result; 1007 } 1008 1009 Error LTO::runRegularLTO(AddStreamFn AddStream) { 1010 // Setup optimization remarks. 1011 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks( 1012 RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename, 1013 Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness, 1014 Conf.RemarksHotnessThreshold); 1015 if (!DiagFileOrErr) 1016 return DiagFileOrErr.takeError(); 1017 1018 // Finalize linking of regular LTO modules containing summaries now that 1019 // we have computed liveness information. 1020 for (auto &M : RegularLTO.ModsWithSummaries) 1021 if (Error Err = linkRegularLTO(std::move(M), 1022 /*LivenessFromIndex=*/true)) 1023 return Err; 1024 1025 // Ensure we don't have inconsistently split LTO units with type tests. 1026 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take 1027 // this path both cases but eventually this should be split into two and 1028 // do the ThinLTO checks in `runThinLTO`. 1029 if (Error Err = checkPartiallySplit()) 1030 return Err; 1031 1032 // Make sure commons have the right size/alignment: we kept the largest from 1033 // all the prevailing when adding the inputs, and we apply it here. 1034 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout(); 1035 for (auto &I : RegularLTO.Commons) { 1036 if (!I.second.Prevailing) 1037 // Don't do anything if no instance of this common was prevailing. 1038 continue; 1039 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first); 1040 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) { 1041 // Don't create a new global if the type is already correct, just make 1042 // sure the alignment is correct. 1043 OldGV->setAlignment(I.second.Align); 1044 continue; 1045 } 1046 ArrayType *Ty = 1047 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size); 1048 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false, 1049 GlobalValue::CommonLinkage, 1050 ConstantAggregateZero::get(Ty), ""); 1051 GV->setAlignment(I.second.Align); 1052 if (OldGV) { 1053 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType())); 1054 GV->takeName(OldGV); 1055 OldGV->eraseFromParent(); 1056 } else { 1057 GV->setName(I.first); 1058 } 1059 } 1060 1061 // If allowed, upgrade public vcall visibility metadata to linkage unit 1062 // visibility before whole program devirtualization in the optimizer. 1063 updateVCallVisibilityInModule(*RegularLTO.CombinedModule, 1064 Conf.HasWholeProgramVisibility); 1065 1066 if (Conf.PreOptModuleHook && 1067 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule)) 1068 return Error::success(); 1069 1070 if (!Conf.CodeGenOnly) { 1071 for (const auto &R : GlobalResolutions) { 1072 if (!R.second.isPrevailingIRSymbol()) 1073 continue; 1074 if (R.second.Partition != 0 && 1075 R.second.Partition != GlobalResolution::External) 1076 continue; 1077 1078 GlobalValue *GV = 1079 RegularLTO.CombinedModule->getNamedValue(R.second.IRName); 1080 // Ignore symbols defined in other partitions. 1081 // Also skip declarations, which are not allowed to have internal linkage. 1082 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration()) 1083 continue; 1084 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global 1085 : GlobalValue::UnnamedAddr::None); 1086 if (EnableLTOInternalization && R.second.Partition == 0) 1087 GV->setLinkage(GlobalValue::InternalLinkage); 1088 } 1089 1090 RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1); 1091 1092 if (Conf.PostInternalizeModuleHook && 1093 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule)) 1094 return Error::success(); 1095 } 1096 1097 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) { 1098 if (Error Err = backend( 1099 Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel, 1100 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex)) 1101 return Err; 1102 } 1103 1104 return finalizeOptimizationRemarks(std::move(*DiagFileOrErr)); 1105 } 1106 1107 static const char *libcallRoutineNames[] = { 1108 #define HANDLE_LIBCALL(code, name) name, 1109 #include "llvm/IR/RuntimeLibcalls.def" 1110 #undef HANDLE_LIBCALL 1111 }; 1112 1113 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() { 1114 return makeArrayRef(libcallRoutineNames); 1115 } 1116 1117 /// This class defines the interface to the ThinLTO backend. 1118 class lto::ThinBackendProc { 1119 protected: 1120 const Config &Conf; 1121 ModuleSummaryIndex &CombinedIndex; 1122 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries; 1123 1124 public: 1125 ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, 1126 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) 1127 : Conf(Conf), CombinedIndex(CombinedIndex), 1128 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {} 1129 1130 virtual ~ThinBackendProc() {} 1131 virtual Error start( 1132 unsigned Task, BitcodeModule BM, 1133 const FunctionImporter::ImportMapTy &ImportList, 1134 const FunctionImporter::ExportSetTy &ExportList, 1135 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 1136 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0; 1137 virtual Error wait() = 0; 1138 virtual unsigned getThreadCount() = 0; 1139 }; 1140 1141 namespace { 1142 class InProcessThinBackend : public ThinBackendProc { 1143 ThreadPool BackendThreadPool; 1144 AddStreamFn AddStream; 1145 NativeObjectCache Cache; 1146 std::set<GlobalValue::GUID> CfiFunctionDefs; 1147 std::set<GlobalValue::GUID> CfiFunctionDecls; 1148 1149 Optional<Error> Err; 1150 std::mutex ErrMu; 1151 1152 public: 1153 InProcessThinBackend( 1154 const Config &Conf, ModuleSummaryIndex &CombinedIndex, 1155 ThreadPoolStrategy ThinLTOParallelism, 1156 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 1157 AddStreamFn AddStream, NativeObjectCache Cache) 1158 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries), 1159 BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)), 1160 Cache(std::move(Cache)) { 1161 for (auto &Name : CombinedIndex.cfiFunctionDefs()) 1162 CfiFunctionDefs.insert( 1163 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); 1164 for (auto &Name : CombinedIndex.cfiFunctionDecls()) 1165 CfiFunctionDecls.insert( 1166 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); 1167 } 1168 1169 Error runThinLTOBackendThread( 1170 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task, 1171 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex, 1172 const FunctionImporter::ImportMapTy &ImportList, 1173 const FunctionImporter::ExportSetTy &ExportList, 1174 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 1175 const GVSummaryMapTy &DefinedGlobals, 1176 MapVector<StringRef, BitcodeModule> &ModuleMap) { 1177 auto RunThinBackend = [&](AddStreamFn AddStream) { 1178 LTOLLVMContext BackendContext(Conf); 1179 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext); 1180 if (!MOrErr) 1181 return MOrErr.takeError(); 1182 1183 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex, 1184 ImportList, DefinedGlobals, ModuleMap); 1185 }; 1186 1187 auto ModuleID = BM.getModuleIdentifier(); 1188 1189 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) || 1190 all_of(CombinedIndex.getModuleHash(ModuleID), 1191 [](uint32_t V) { return V == 0; })) 1192 // Cache disabled or no entry for this module in the combined index or 1193 // no module hash. 1194 return RunThinBackend(AddStream); 1195 1196 SmallString<40> Key; 1197 // The module may be cached, this helps handling it. 1198 computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, 1199 ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs, 1200 CfiFunctionDecls); 1201 if (AddStreamFn CacheAddStream = Cache(Task, Key)) 1202 return RunThinBackend(CacheAddStream); 1203 1204 return Error::success(); 1205 } 1206 1207 Error start( 1208 unsigned Task, BitcodeModule BM, 1209 const FunctionImporter::ImportMapTy &ImportList, 1210 const FunctionImporter::ExportSetTy &ExportList, 1211 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 1212 MapVector<StringRef, BitcodeModule> &ModuleMap) override { 1213 StringRef ModulePath = BM.getModuleIdentifier(); 1214 assert(ModuleToDefinedGVSummaries.count(ModulePath)); 1215 const GVSummaryMapTy &DefinedGlobals = 1216 ModuleToDefinedGVSummaries.find(ModulePath)->second; 1217 BackendThreadPool.async( 1218 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex, 1219 const FunctionImporter::ImportMapTy &ImportList, 1220 const FunctionImporter::ExportSetTy &ExportList, 1221 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> 1222 &ResolvedODR, 1223 const GVSummaryMapTy &DefinedGlobals, 1224 MapVector<StringRef, BitcodeModule> &ModuleMap) { 1225 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled) 1226 timeTraceProfilerInitialize(Conf.TimeTraceGranularity, 1227 "thin backend"); 1228 Error E = runThinLTOBackendThread( 1229 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList, 1230 ResolvedODR, DefinedGlobals, ModuleMap); 1231 if (E) { 1232 std::unique_lock<std::mutex> L(ErrMu); 1233 if (Err) 1234 Err = joinErrors(std::move(*Err), std::move(E)); 1235 else 1236 Err = std::move(E); 1237 } 1238 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled) 1239 timeTraceProfilerFinishThread(); 1240 }, 1241 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList), 1242 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap)); 1243 return Error::success(); 1244 } 1245 1246 Error wait() override { 1247 BackendThreadPool.wait(); 1248 if (Err) 1249 return std::move(*Err); 1250 else 1251 return Error::success(); 1252 } 1253 1254 unsigned getThreadCount() override { 1255 return BackendThreadPool.getThreadCount(); 1256 } 1257 }; 1258 } // end anonymous namespace 1259 1260 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism) { 1261 return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex, 1262 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 1263 AddStreamFn AddStream, NativeObjectCache Cache) { 1264 return std::make_unique<InProcessThinBackend>( 1265 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream, 1266 Cache); 1267 }; 1268 } 1269 1270 // Given the original \p Path to an output file, replace any path 1271 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the 1272 // resulting directory if it does not yet exist. 1273 std::string lto::getThinLTOOutputFile(const std::string &Path, 1274 const std::string &OldPrefix, 1275 const std::string &NewPrefix) { 1276 if (OldPrefix.empty() && NewPrefix.empty()) 1277 return Path; 1278 SmallString<128> NewPath(Path); 1279 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix); 1280 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str()); 1281 if (!ParentPath.empty()) { 1282 // Make sure the new directory exists, creating it if necessary. 1283 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath)) 1284 llvm::errs() << "warning: could not create directory '" << ParentPath 1285 << "': " << EC.message() << '\n'; 1286 } 1287 return std::string(NewPath.str()); 1288 } 1289 1290 namespace { 1291 class WriteIndexesThinBackend : public ThinBackendProc { 1292 std::string OldPrefix, NewPrefix; 1293 bool ShouldEmitImportsFiles; 1294 raw_fd_ostream *LinkedObjectsFile; 1295 lto::IndexWriteCallback OnWrite; 1296 1297 public: 1298 WriteIndexesThinBackend( 1299 const Config &Conf, ModuleSummaryIndex &CombinedIndex, 1300 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 1301 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, 1302 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite) 1303 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries), 1304 OldPrefix(OldPrefix), NewPrefix(NewPrefix), 1305 ShouldEmitImportsFiles(ShouldEmitImportsFiles), 1306 LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {} 1307 1308 Error start( 1309 unsigned Task, BitcodeModule BM, 1310 const FunctionImporter::ImportMapTy &ImportList, 1311 const FunctionImporter::ExportSetTy &ExportList, 1312 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 1313 MapVector<StringRef, BitcodeModule> &ModuleMap) override { 1314 StringRef ModulePath = BM.getModuleIdentifier(); 1315 std::string NewModulePath = 1316 getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix); 1317 1318 if (LinkedObjectsFile) 1319 *LinkedObjectsFile << NewModulePath << '\n'; 1320 1321 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex; 1322 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries, 1323 ImportList, ModuleToSummariesForIndex); 1324 1325 std::error_code EC; 1326 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC, 1327 sys::fs::OpenFlags::OF_None); 1328 if (EC) 1329 return errorCodeToError(EC); 1330 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex); 1331 1332 if (ShouldEmitImportsFiles) { 1333 EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports", 1334 ModuleToSummariesForIndex); 1335 if (EC) 1336 return errorCodeToError(EC); 1337 } 1338 1339 if (OnWrite) 1340 OnWrite(std::string(ModulePath)); 1341 return Error::success(); 1342 } 1343 1344 Error wait() override { return Error::success(); } 1345 1346 // WriteIndexesThinBackend should always return 1 to prevent module 1347 // re-ordering and avoid non-determinism in the final link. 1348 unsigned getThreadCount() override { return 1; } 1349 }; 1350 } // end anonymous namespace 1351 1352 ThinBackend lto::createWriteIndexesThinBackend( 1353 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, 1354 raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) { 1355 return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex, 1356 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 1357 AddStreamFn AddStream, NativeObjectCache Cache) { 1358 return std::make_unique<WriteIndexesThinBackend>( 1359 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix, 1360 ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite); 1361 }; 1362 } 1363 1364 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache, 1365 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 1366 if (ThinLTO.ModuleMap.empty()) 1367 return Error::success(); 1368 1369 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) { 1370 llvm::errs() << "warning: [ThinLTO] No module compiled\n"; 1371 return Error::success(); 1372 } 1373 1374 if (Conf.CombinedIndexHook && 1375 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols)) 1376 return Error::success(); 1377 1378 // Collect for each module the list of function it defines (GUID -> 1379 // Summary). 1380 StringMap<GVSummaryMapTy> 1381 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size()); 1382 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule( 1383 ModuleToDefinedGVSummaries); 1384 // Create entries for any modules that didn't have any GV summaries 1385 // (either they didn't have any GVs to start with, or we suppressed 1386 // generation of the summaries because they e.g. had inline assembly 1387 // uses that couldn't be promoted/renamed on export). This is so 1388 // InProcessThinBackend::start can still launch a backend thread, which 1389 // is passed the map of summaries for the module, without any special 1390 // handling for this case. 1391 for (auto &Mod : ThinLTO.ModuleMap) 1392 if (!ModuleToDefinedGVSummaries.count(Mod.first)) 1393 ModuleToDefinedGVSummaries.try_emplace(Mod.first); 1394 1395 // Synthesize entry counts for functions in the CombinedIndex. 1396 computeSyntheticCounts(ThinLTO.CombinedIndex); 1397 1398 StringMap<FunctionImporter::ImportMapTy> ImportLists( 1399 ThinLTO.ModuleMap.size()); 1400 StringMap<FunctionImporter::ExportSetTy> ExportLists( 1401 ThinLTO.ModuleMap.size()); 1402 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 1403 1404 if (DumpThinCGSCCs) 1405 ThinLTO.CombinedIndex.dumpSCCs(outs()); 1406 1407 std::set<GlobalValue::GUID> ExportedGUIDs; 1408 1409 // If allowed, upgrade public vcall visibility to linkage unit visibility in 1410 // the summaries before whole program devirtualization below. 1411 updateVCallVisibilityInIndex(ThinLTO.CombinedIndex, 1412 Conf.HasWholeProgramVisibility); 1413 1414 // Perform index-based WPD. This will return immediately if there are 1415 // no index entries in the typeIdMetadata map (e.g. if we are instead 1416 // performing IR-based WPD in hybrid regular/thin LTO mode). 1417 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap; 1418 runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs, 1419 LocalWPDTargetsMap); 1420 1421 if (Conf.OptLevel > 0) 1422 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, 1423 ImportLists, ExportLists); 1424 1425 // Figure out which symbols need to be internalized. This also needs to happen 1426 // at -O0 because summary-based DCE is implemented using internalization, and 1427 // we must apply DCE consistently with the full LTO module in order to avoid 1428 // undefined references during the final link. 1429 for (auto &Res : GlobalResolutions) { 1430 // If the symbol does not have external references or it is not prevailing, 1431 // then not need to mark it as exported from a ThinLTO partition. 1432 if (Res.second.Partition != GlobalResolution::External || 1433 !Res.second.isPrevailingIRSymbol()) 1434 continue; 1435 auto GUID = GlobalValue::getGUID( 1436 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)); 1437 // Mark exported unless index-based analysis determined it to be dead. 1438 if (ThinLTO.CombinedIndex.isGUIDLive(GUID)) 1439 ExportedGUIDs.insert(GUID); 1440 } 1441 1442 // Any functions referenced by the jump table in the regular LTO object must 1443 // be exported. 1444 for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs()) 1445 ExportedGUIDs.insert( 1446 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def))); 1447 1448 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) { 1449 const auto &ExportList = ExportLists.find(ModuleIdentifier); 1450 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) || 1451 ExportedGUIDs.count(VI.getGUID()); 1452 }; 1453 1454 // Update local devirtualized targets that were exported by cross-module 1455 // importing or by other devirtualizations marked in the ExportedGUIDs set. 1456 updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported, 1457 LocalWPDTargetsMap); 1458 1459 auto isPrevailing = [&](GlobalValue::GUID GUID, 1460 const GlobalValueSummary *S) { 1461 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath(); 1462 }; 1463 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported, 1464 isPrevailing); 1465 1466 auto recordNewLinkage = [&](StringRef ModuleIdentifier, 1467 GlobalValue::GUID GUID, 1468 GlobalValue::LinkageTypes NewLinkage) { 1469 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage; 1470 }; 1471 thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing, 1472 recordNewLinkage, GUIDPreservedSymbols); 1473 1474 generateParamAccessSummary(ThinLTO.CombinedIndex); 1475 1476 std::unique_ptr<ThinBackendProc> BackendProc = 1477 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, 1478 AddStream, Cache); 1479 1480 auto &ModuleMap = 1481 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap; 1482 1483 auto ProcessOneModule = [&](int I) -> Error { 1484 auto &Mod = *(ModuleMap.begin() + I); 1485 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for 1486 // combined module and parallel code generation partitions. 1487 return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I, 1488 Mod.second, ImportLists[Mod.first], 1489 ExportLists[Mod.first], ResolvedODR[Mod.first], 1490 ThinLTO.ModuleMap); 1491 }; 1492 1493 if (BackendProc->getThreadCount() == 1) { 1494 // Process the modules in the order they were provided on the command-line. 1495 // It is important for this codepath to be used for WriteIndexesThinBackend, 1496 // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same 1497 // order as the inputs, which otherwise would affect the final link order. 1498 for (int I = 0, E = ModuleMap.size(); I != E; ++I) 1499 if (Error E = ProcessOneModule(I)) 1500 return E; 1501 } else { 1502 // When executing in parallel, process largest bitsize modules first to 1503 // improve parallelism, and avoid starving the thread pool near the end. 1504 // This saves about 15 sec on a 36-core machine while link `clang.exe` (out 1505 // of 100 sec). 1506 std::vector<BitcodeModule *> ModulesVec; 1507 ModulesVec.reserve(ModuleMap.size()); 1508 for (auto &Mod : ModuleMap) 1509 ModulesVec.push_back(&Mod.second); 1510 for (int I : generateModulesOrdering(ModulesVec)) 1511 if (Error E = ProcessOneModule(I)) 1512 return E; 1513 } 1514 return BackendProc->wait(); 1515 } 1516 1517 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks( 1518 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, 1519 StringRef RemarksFormat, bool RemarksWithHotness, 1520 Optional<uint64_t> RemarksHotnessThreshold, int Count) { 1521 std::string Filename = std::string(RemarksFilename); 1522 // For ThinLTO, file.opt.<format> becomes 1523 // file.opt.<format>.thin.<num>.<format>. 1524 if (!Filename.empty() && Count != -1) 1525 Filename = 1526 (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat) 1527 .str(); 1528 1529 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks( 1530 Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness, 1531 RemarksHotnessThreshold); 1532 if (Error E = ResultOrErr.takeError()) 1533 return std::move(E); 1534 1535 if (*ResultOrErr) 1536 (*ResultOrErr)->keep(); 1537 1538 return ResultOrErr; 1539 } 1540 1541 Expected<std::unique_ptr<ToolOutputFile>> 1542 lto::setupStatsFile(StringRef StatsFilename) { 1543 // Setup output file to emit statistics. 1544 if (StatsFilename.empty()) 1545 return nullptr; 1546 1547 llvm::EnableStatistics(false); 1548 std::error_code EC; 1549 auto StatsFile = 1550 std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None); 1551 if (EC) 1552 return errorCodeToError(EC); 1553 1554 StatsFile->keep(); 1555 return std::move(StatsFile); 1556 } 1557 1558 // Compute the ordering we will process the inputs: the rough heuristic here 1559 // is to sort them per size so that the largest module get schedule as soon as 1560 // possible. This is purely a compile-time optimization. 1561 std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) { 1562 std::vector<int> ModulesOrdering; 1563 ModulesOrdering.resize(R.size()); 1564 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0); 1565 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) { 1566 auto LSize = R[LeftIndex]->getBuffer().size(); 1567 auto RSize = R[RightIndex]->getBuffer().size(); 1568 return LSize > RSize; 1569 }); 1570 return ModulesOrdering; 1571 } 1572