1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===// 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 the "backend" phase of LTO, i.e. it performs 10 // optimization and code generation on a loaded module. It is generally used 11 // internally by the LTO class but can also be used independently, for example 12 // to implement a standalone ThinLTO backend. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/LTO/LTOBackend.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/CGSCCPassManager.h" 19 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeReader.h" 23 #include "llvm/Bitcode/BitcodeWriter.h" 24 #include "llvm/IR/LLVMRemarkStreamer.h" 25 #include "llvm/IR/LegacyPassManager.h" 26 #include "llvm/IR/PassManager.h" 27 #include "llvm/IR/Verifier.h" 28 #include "llvm/LTO/LTO.h" 29 #include "llvm/MC/SubtargetFeature.h" 30 #include "llvm/Object/ModuleSymbolTable.h" 31 #include "llvm/Passes/PassBuilder.h" 32 #include "llvm/Passes/PassPlugin.h" 33 #include "llvm/Passes/StandardInstrumentations.h" 34 #include "llvm/Support/Error.h" 35 #include "llvm/Support/FileSystem.h" 36 #include "llvm/Support/MemoryBuffer.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/Program.h" 39 #include "llvm/Support/SmallVectorMemoryBuffer.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/ThreadPool.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Target/TargetMachine.h" 44 #include "llvm/Transforms/IPO.h" 45 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 46 #include "llvm/Transforms/Scalar/LoopPassManager.h" 47 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 48 #include "llvm/Transforms/Utils/SplitModule.h" 49 50 using namespace llvm; 51 using namespace lto; 52 53 #define DEBUG_TYPE "lto-backend" 54 55 enum class LTOBitcodeEmbedding { 56 DoNotEmbed = 0, 57 EmbedOptimized = 1, 58 EmbedPostMergePreOptimized = 2 59 }; 60 61 static cl::opt<LTOBitcodeEmbedding> EmbedBitcode( 62 "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), 63 cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", 64 "Do not embed"), 65 clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", 66 "Embed after all optimization passes"), 67 clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, 68 "post-merge-pre-opt", 69 "Embed post merge, but before optimizations")), 70 cl::desc("Embed LLVM bitcode in object files produced by LTO")); 71 72 static cl::opt<bool> ThinLTOAssumeMerged( 73 "thinlto-assume-merged", cl::init(false), 74 cl::desc("Assume the input has already undergone ThinLTO function " 75 "importing and the other pre-optimization pipeline changes.")); 76 77 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) { 78 errs() << "failed to open " << Path << ": " << Msg << '\n'; 79 errs().flush(); 80 exit(1); 81 } 82 83 Error Config::addSaveTemps(std::string OutputFileName, 84 bool UseInputModulePath) { 85 ShouldDiscardValueNames = false; 86 87 std::error_code EC; 88 ResolutionFile = std::make_unique<raw_fd_ostream>( 89 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text); 90 if (EC) { 91 ResolutionFile.reset(); 92 return errorCodeToError(EC); 93 } 94 95 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) { 96 // Keep track of the hook provided by the linker, which also needs to run. 97 ModuleHookFn LinkerHook = Hook; 98 Hook = [=](unsigned Task, const Module &M) { 99 // If the linker's hook returned false, we need to pass that result 100 // through. 101 if (LinkerHook && !LinkerHook(Task, M)) 102 return false; 103 104 std::string PathPrefix; 105 // If this is the combined module (not a ThinLTO backend compile) or the 106 // user hasn't requested using the input module's path, emit to a file 107 // named from the provided OutputFileName with the Task ID appended. 108 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) { 109 PathPrefix = OutputFileName; 110 if (Task != (unsigned)-1) 111 PathPrefix += utostr(Task) + "."; 112 } else 113 PathPrefix = M.getModuleIdentifier() + "."; 114 std::string Path = PathPrefix + PathSuffix + ".bc"; 115 std::error_code EC; 116 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None); 117 // Because -save-temps is a debugging feature, we report the error 118 // directly and exit. 119 if (EC) 120 reportOpenError(Path, EC.message()); 121 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false); 122 return true; 123 }; 124 }; 125 126 setHook("0.preopt", PreOptModuleHook); 127 setHook("1.promote", PostPromoteModuleHook); 128 setHook("2.internalize", PostInternalizeModuleHook); 129 setHook("3.import", PostImportModuleHook); 130 setHook("4.opt", PostOptModuleHook); 131 setHook("5.precodegen", PreCodeGenModuleHook); 132 133 CombinedIndexHook = 134 [=](const ModuleSummaryIndex &Index, 135 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 136 std::string Path = OutputFileName + "index.bc"; 137 std::error_code EC; 138 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None); 139 // Because -save-temps is a debugging feature, we report the error 140 // directly and exit. 141 if (EC) 142 reportOpenError(Path, EC.message()); 143 WriteIndexToFile(Index, OS); 144 145 Path = OutputFileName + "index.dot"; 146 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None); 147 if (EC) 148 reportOpenError(Path, EC.message()); 149 Index.exportToDot(OSDot, GUIDPreservedSymbols); 150 return true; 151 }; 152 153 return Error::success(); 154 } 155 156 #define HANDLE_EXTENSION(Ext) \ 157 llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); 158 #include "llvm/Support/Extension.def" 159 160 static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins, 161 PassBuilder &PB) { 162 #define HANDLE_EXTENSION(Ext) \ 163 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 164 #include "llvm/Support/Extension.def" 165 166 // Load requested pass plugins and let them register pass builder callbacks 167 for (auto &PluginFN : PassPlugins) { 168 auto PassPlugin = PassPlugin::Load(PluginFN); 169 if (!PassPlugin) { 170 errs() << "Failed to load passes from '" << PluginFN 171 << "'. Request ignored.\n"; 172 continue; 173 } 174 175 PassPlugin->registerPassBuilderCallbacks(PB); 176 } 177 } 178 179 static std::unique_ptr<TargetMachine> 180 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) { 181 StringRef TheTriple = M.getTargetTriple(); 182 SubtargetFeatures Features; 183 Features.getDefaultSubtargetFeatures(Triple(TheTriple)); 184 for (const std::string &A : Conf.MAttrs) 185 Features.AddFeature(A); 186 187 Reloc::Model RelocModel; 188 if (Conf.RelocModel) 189 RelocModel = *Conf.RelocModel; 190 else 191 RelocModel = 192 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_; 193 194 Optional<CodeModel::Model> CodeModel; 195 if (Conf.CodeModel) 196 CodeModel = *Conf.CodeModel; 197 else 198 CodeModel = M.getCodeModel(); 199 200 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine( 201 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel, 202 CodeModel, Conf.CGOptLevel)); 203 assert(TM && "Failed to create target machine"); 204 return TM; 205 } 206 207 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, 208 unsigned OptLevel, bool IsThinLTO, 209 ModuleSummaryIndex *ExportSummary, 210 const ModuleSummaryIndex *ImportSummary) { 211 Optional<PGOOptions> PGOOpt; 212 if (!Conf.SampleProfile.empty()) 213 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping, 214 PGOOptions::SampleUse, PGOOptions::NoCSAction, true); 215 else if (Conf.RunCSIRInstr) { 216 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping, 217 PGOOptions::IRUse, PGOOptions::CSIRInstr); 218 } else if (!Conf.CSIRProfile.empty()) { 219 PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping, 220 PGOOptions::IRUse, PGOOptions::CSIRUse); 221 } 222 223 PassInstrumentationCallbacks PIC; 224 StandardInstrumentations SI(Conf.DebugPassManager); 225 SI.registerCallbacks(PIC); 226 PassBuilder PB(Conf.DebugPassManager, TM, Conf.PTO, PGOOpt, &PIC); 227 AAManager AA; 228 229 // Parse a custom AA pipeline if asked to. 230 if (auto Err = PB.parseAAPipeline(AA, "default")) 231 report_fatal_error("Error parsing default AA pipeline"); 232 233 RegisterPassPlugins(Conf.PassPlugins, PB); 234 235 LoopAnalysisManager LAM(Conf.DebugPassManager); 236 FunctionAnalysisManager FAM(Conf.DebugPassManager); 237 CGSCCAnalysisManager CGAM(Conf.DebugPassManager); 238 ModuleAnalysisManager MAM(Conf.DebugPassManager); 239 240 // Register the AA manager first so that our version is the one used. 241 FAM.registerPass([&] { return std::move(AA); }); 242 243 // Register all the basic analyses with the managers. 244 PB.registerModuleAnalyses(MAM); 245 PB.registerCGSCCAnalyses(CGAM); 246 PB.registerFunctionAnalyses(FAM); 247 PB.registerLoopAnalyses(LAM); 248 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 249 250 ModulePassManager MPM(Conf.DebugPassManager); 251 252 if (!Conf.DisableVerify) 253 MPM.addPass(VerifierPass()); 254 255 PassBuilder::OptimizationLevel OL; 256 257 switch (OptLevel) { 258 default: 259 llvm_unreachable("Invalid optimization level"); 260 case 0: 261 OL = PassBuilder::OptimizationLevel::O0; 262 break; 263 case 1: 264 OL = PassBuilder::OptimizationLevel::O1; 265 break; 266 case 2: 267 OL = PassBuilder::OptimizationLevel::O2; 268 break; 269 case 3: 270 OL = PassBuilder::OptimizationLevel::O3; 271 break; 272 } 273 274 if (IsThinLTO) 275 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary)); 276 else 277 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary)); 278 279 if (!Conf.DisableVerify) 280 MPM.addPass(VerifierPass()); 281 282 MPM.run(Mod, MAM); 283 } 284 285 static void runNewPMCustomPasses(const Config &Conf, Module &Mod, 286 TargetMachine *TM, std::string PipelineDesc, 287 std::string AAPipelineDesc, 288 bool DisableVerify) { 289 PassBuilder PB(Conf.DebugPassManager, TM); 290 AAManager AA; 291 292 // Parse a custom AA pipeline if asked to. 293 if (!AAPipelineDesc.empty()) 294 if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc)) 295 report_fatal_error("unable to parse AA pipeline description '" + 296 AAPipelineDesc + "': " + toString(std::move(Err))); 297 298 RegisterPassPlugins(Conf.PassPlugins, PB); 299 300 LoopAnalysisManager LAM; 301 FunctionAnalysisManager FAM; 302 CGSCCAnalysisManager CGAM; 303 ModuleAnalysisManager MAM; 304 305 // Register the AA manager first so that our version is the one used. 306 FAM.registerPass([&] { return std::move(AA); }); 307 308 // Register all the basic analyses with the managers. 309 PB.registerModuleAnalyses(MAM); 310 PB.registerCGSCCAnalyses(CGAM); 311 PB.registerFunctionAnalyses(FAM); 312 PB.registerLoopAnalyses(LAM); 313 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 314 315 ModulePassManager MPM; 316 317 // Always verify the input. 318 MPM.addPass(VerifierPass()); 319 320 // Now, add all the passes we've been requested to. 321 if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc)) 322 report_fatal_error("unable to parse pass pipeline description '" + 323 PipelineDesc + "': " + toString(std::move(Err))); 324 325 if (!DisableVerify) 326 MPM.addPass(VerifierPass()); 327 MPM.run(Mod, MAM); 328 } 329 330 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, 331 bool IsThinLTO, ModuleSummaryIndex *ExportSummary, 332 const ModuleSummaryIndex *ImportSummary) { 333 legacy::PassManager passes; 334 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 335 336 PassManagerBuilder PMB; 337 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())); 338 PMB.Inliner = createFunctionInliningPass(); 339 PMB.ExportSummary = ExportSummary; 340 PMB.ImportSummary = ImportSummary; 341 // Unconditionally verify input since it is not verified before this 342 // point and has unknown origin. 343 PMB.VerifyInput = true; 344 PMB.VerifyOutput = !Conf.DisableVerify; 345 PMB.LoopVectorize = true; 346 PMB.SLPVectorize = true; 347 PMB.OptLevel = Conf.OptLevel; 348 PMB.PGOSampleUse = Conf.SampleProfile; 349 PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr; 350 if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) { 351 PMB.EnablePGOCSInstrUse = true; 352 PMB.PGOInstrUse = Conf.CSIRProfile; 353 } 354 if (IsThinLTO) 355 PMB.populateThinLTOPassManager(passes); 356 else 357 PMB.populateLTOPassManager(passes); 358 passes.run(Mod); 359 } 360 361 bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, 362 bool IsThinLTO, ModuleSummaryIndex *ExportSummary, 363 const ModuleSummaryIndex *ImportSummary, 364 const std::vector<uint8_t> &CmdArgs) { 365 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) { 366 // FIXME: the motivation for capturing post-merge bitcode and command line 367 // is replicating the compilation environment from bitcode, without needing 368 // to understand the dependencies (the functions to be imported). This 369 // assumes a clang - based invocation, case in which we have the command 370 // line. 371 // It's not very clear how the above motivation would map in the 372 // linker-based case, so we currently don't plumb the command line args in 373 // that case. 374 if (CmdArgs.empty()) 375 LLVM_DEBUG( 376 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but " 377 "command line arguments are not available"); 378 llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(), 379 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true, 380 /*Cmdline*/ CmdArgs); 381 } 382 // FIXME: Plumb the combined index into the new pass manager. 383 if (!Conf.OptPipeline.empty()) 384 runNewPMCustomPasses(Conf, Mod, TM, Conf.OptPipeline, Conf.AAPipeline, 385 Conf.DisableVerify); 386 else if (Conf.UseNewPM) 387 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary, 388 ImportSummary); 389 else 390 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary); 391 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod); 392 } 393 394 static void codegen(const Config &Conf, TargetMachine *TM, 395 AddStreamFn AddStream, unsigned Task, Module &Mod, 396 const ModuleSummaryIndex &CombinedIndex) { 397 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod)) 398 return; 399 400 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized) 401 llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(), 402 /*EmbedBitcode*/ true, 403 /*EmbedCmdline*/ false, 404 /*CmdArgs*/ std::vector<uint8_t>()); 405 406 std::unique_ptr<ToolOutputFile> DwoOut; 407 SmallString<1024> DwoFile(Conf.SplitDwarfOutput); 408 if (!Conf.DwoDir.empty()) { 409 std::error_code EC; 410 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir)) 411 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " + 412 EC.message()); 413 414 DwoFile = Conf.DwoDir; 415 sys::path::append(DwoFile, std::to_string(Task) + ".dwo"); 416 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile); 417 } else 418 TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile; 419 420 if (!DwoFile.empty()) { 421 std::error_code EC; 422 DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None); 423 if (EC) 424 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message()); 425 } 426 427 auto Stream = AddStream(Task); 428 legacy::PassManager CodeGenPasses; 429 CodeGenPasses.add( 430 createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex)); 431 if (Conf.PreCodeGenPassesHook) 432 Conf.PreCodeGenPassesHook(CodeGenPasses); 433 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, 434 DwoOut ? &DwoOut->os() : nullptr, 435 Conf.CGFileType)) 436 report_fatal_error("Failed to setup codegen"); 437 CodeGenPasses.run(Mod); 438 439 if (DwoOut) 440 DwoOut->keep(); 441 } 442 443 static void splitCodeGen(const Config &C, TargetMachine *TM, 444 AddStreamFn AddStream, 445 unsigned ParallelCodeGenParallelismLevel, 446 std::unique_ptr<Module> Mod, 447 const ModuleSummaryIndex &CombinedIndex) { 448 ThreadPool CodegenThreadPool( 449 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel)); 450 unsigned ThreadCount = 0; 451 const Target *T = &TM->getTarget(); 452 453 SplitModule( 454 std::move(Mod), ParallelCodeGenParallelismLevel, 455 [&](std::unique_ptr<Module> MPart) { 456 // We want to clone the module in a new context to multi-thread the 457 // codegen. We do it by serializing partition modules to bitcode 458 // (while still on the main thread, in order to avoid data races) and 459 // spinning up new threads which deserialize the partitions into 460 // separate contexts. 461 // FIXME: Provide a more direct way to do this in LLVM. 462 SmallString<0> BC; 463 raw_svector_ostream BCOS(BC); 464 WriteBitcodeToFile(*MPart, BCOS); 465 466 // Enqueue the task 467 CodegenThreadPool.async( 468 [&](const SmallString<0> &BC, unsigned ThreadId) { 469 LTOLLVMContext Ctx(C); 470 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile( 471 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"), 472 Ctx); 473 if (!MOrErr) 474 report_fatal_error("Failed to read bitcode"); 475 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get()); 476 477 std::unique_ptr<TargetMachine> TM = 478 createTargetMachine(C, T, *MPartInCtx); 479 480 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx, 481 CombinedIndex); 482 }, 483 // Pass BC using std::move to ensure that it get moved rather than 484 // copied into the thread's context. 485 std::move(BC), ThreadCount++); 486 }, 487 false); 488 489 // Because the inner lambda (which runs in a worker thread) captures our local 490 // variables, we need to wait for the worker threads to terminate before we 491 // can leave the function scope. 492 CodegenThreadPool.wait(); 493 } 494 495 static Expected<const Target *> initAndLookupTarget(const Config &C, 496 Module &Mod) { 497 if (!C.OverrideTriple.empty()) 498 Mod.setTargetTriple(C.OverrideTriple); 499 else if (Mod.getTargetTriple().empty()) 500 Mod.setTargetTriple(C.DefaultTriple); 501 502 std::string Msg; 503 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg); 504 if (!T) 505 return make_error<StringError>(Msg, inconvertibleErrorCode()); 506 return T; 507 } 508 509 Error lto::finalizeOptimizationRemarks( 510 std::unique_ptr<ToolOutputFile> DiagOutputFile) { 511 // Make sure we flush the diagnostic remarks file in case the linker doesn't 512 // call the global destructors before exiting. 513 if (!DiagOutputFile) 514 return Error::success(); 515 DiagOutputFile->keep(); 516 DiagOutputFile->os().flush(); 517 return Error::success(); 518 } 519 520 Error lto::backend(const Config &C, AddStreamFn AddStream, 521 unsigned ParallelCodeGenParallelismLevel, 522 std::unique_ptr<Module> Mod, 523 ModuleSummaryIndex &CombinedIndex) { 524 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod); 525 if (!TOrErr) 526 return TOrErr.takeError(); 527 528 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod); 529 530 if (!C.CodeGenOnly) { 531 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false, 532 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr, 533 /*CmdArgs*/ std::vector<uint8_t>())) 534 return Error::success(); 535 } 536 537 if (ParallelCodeGenParallelismLevel == 1) { 538 codegen(C, TM.get(), AddStream, 0, *Mod, CombinedIndex); 539 } else { 540 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, 541 std::move(Mod), CombinedIndex); 542 } 543 return Error::success(); 544 } 545 546 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, 547 const ModuleSummaryIndex &Index) { 548 std::vector<GlobalValue*> DeadGVs; 549 for (auto &GV : Mod.global_values()) 550 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID())) 551 if (!Index.isGlobalValueLive(GVS)) { 552 DeadGVs.push_back(&GV); 553 convertToDeclaration(GV); 554 } 555 556 // Now that all dead bodies have been dropped, delete the actual objects 557 // themselves when possible. 558 for (GlobalValue *GV : DeadGVs) { 559 GV->removeDeadConstantUsers(); 560 // Might reference something defined in native object (i.e. dropped a 561 // non-prevailing IR def, but we need to keep the declaration). 562 if (GV->use_empty()) 563 GV->eraseFromParent(); 564 } 565 } 566 567 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream, 568 Module &Mod, const ModuleSummaryIndex &CombinedIndex, 569 const FunctionImporter::ImportMapTy &ImportList, 570 const GVSummaryMapTy &DefinedGlobals, 571 MapVector<StringRef, BitcodeModule> &ModuleMap, 572 const std::vector<uint8_t> &CmdArgs) { 573 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod); 574 if (!TOrErr) 575 return TOrErr.takeError(); 576 577 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod); 578 579 // Setup optimization remarks. 580 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks( 581 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses, 582 Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold, 583 Task); 584 if (!DiagFileOrErr) 585 return DiagFileOrErr.takeError(); 586 auto DiagnosticOutputFile = std::move(*DiagFileOrErr); 587 588 // Set the partial sample profile ratio in the profile summary module flag of 589 // the module, if applicable. 590 Mod.setPartialSampleProfileRatio(CombinedIndex); 591 592 if (Conf.CodeGenOnly) { 593 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex); 594 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 595 } 596 597 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod)) 598 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 599 600 auto OptimizeAndCodegen = 601 [&](Module &Mod, TargetMachine *TM, 602 std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) { 603 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true, 604 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex, 605 CmdArgs)) 606 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 607 608 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex); 609 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 610 }; 611 612 if (ThinLTOAssumeMerged) 613 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile)); 614 615 // When linking an ELF shared object, dso_local should be dropped. We 616 // conservatively do this for -fpic. 617 bool ClearDSOLocalOnDeclarations = 618 TM->getTargetTriple().isOSBinFormatELF() && 619 TM->getRelocationModel() != Reloc::Static && 620 Mod.getPIELevel() == PIELevel::Default; 621 renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations); 622 623 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex); 624 625 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals); 626 627 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod)) 628 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 629 630 if (!DefinedGlobals.empty()) 631 thinLTOInternalizeModule(Mod, DefinedGlobals); 632 633 if (Conf.PostInternalizeModuleHook && 634 !Conf.PostInternalizeModuleHook(Task, Mod)) 635 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 636 637 auto ModuleLoader = [&](StringRef Identifier) { 638 assert(Mod.getContext().isODRUniquingDebugTypes() && 639 "ODR Type uniquing should be enabled on the context"); 640 auto I = ModuleMap.find(Identifier); 641 assert(I != ModuleMap.end()); 642 return I->second.getLazyModule(Mod.getContext(), 643 /*ShouldLazyLoadMetadata=*/true, 644 /*IsImporting*/ true); 645 }; 646 647 FunctionImporter Importer(CombinedIndex, ModuleLoader, 648 ClearDSOLocalOnDeclarations); 649 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError()) 650 return Err; 651 652 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod)) 653 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile)); 654 655 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile)); 656 } 657 658 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) { 659 if (ThinLTOAssumeMerged && BMs.size() == 1) 660 return BMs.begin(); 661 662 for (BitcodeModule &BM : BMs) { 663 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo(); 664 if (LTOInfo && LTOInfo->IsThinLTO) 665 return &BM; 666 } 667 return nullptr; 668 } 669 670 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) { 671 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 672 if (!BMsOrErr) 673 return BMsOrErr.takeError(); 674 675 // The bitcode file may contain multiple modules, we want the one that is 676 // marked as being the ThinLTO module. 677 if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr)) 678 return *Bm; 679 680 return make_error<StringError>("Could not find module summary", 681 inconvertibleErrorCode()); 682 } 683 684 bool lto::loadReferencedModules( 685 const Module &M, const ModuleSummaryIndex &CombinedIndex, 686 FunctionImporter::ImportMapTy &ImportList, 687 MapVector<llvm::StringRef, llvm::BitcodeModule> &ModuleMap, 688 std::vector<std::unique_ptr<llvm::MemoryBuffer>> 689 &OwnedImportsLifetimeManager) { 690 if (ThinLTOAssumeMerged) 691 return true; 692 // We can simply import the values mentioned in the combined index, since 693 // we should only invoke this using the individual indexes written out 694 // via a WriteIndexesThinBackend. 695 for (const auto &GlobalList : CombinedIndex) { 696 // Ignore entries for undefined references. 697 if (GlobalList.second.SummaryList.empty()) 698 continue; 699 700 auto GUID = GlobalList.first; 701 for (const auto &Summary : GlobalList.second.SummaryList) { 702 // Skip the summaries for the importing module. These are included to 703 // e.g. record required linkage changes. 704 if (Summary->modulePath() == M.getModuleIdentifier()) 705 continue; 706 // Add an entry to provoke importing by thinBackend. 707 ImportList[Summary->modulePath()].insert(GUID); 708 } 709 } 710 711 for (auto &I : ImportList) { 712 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr = 713 llvm::MemoryBuffer::getFile(I.first()); 714 if (!MBOrErr) { 715 errs() << "Error loading imported file '" << I.first() 716 << "': " << MBOrErr.getError().message() << "\n"; 717 return false; 718 } 719 720 Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr); 721 if (!BMOrErr) { 722 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { 723 errs() << "Error loading imported file '" << I.first() 724 << "': " << EIB.message() << '\n'; 725 }); 726 return false; 727 } 728 ModuleMap.insert({I.first(), *BMOrErr}); 729 OwnedImportsLifetimeManager.push_back(std::move(*MBOrErr)); 730 } 731 return true; 732 } 733