1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the "backend" phase of LTO, i.e. it performs
11 // optimization and code generation on a loaded module. It is generally used
12 // internally by the LTO class but can also be used independently, for example
13 // to implement a standalone ThinLTO backend.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/LTO/LTOBackend.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/CGSCCPassManager.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/LegacyPassManager.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Object/ModuleSymbolTable.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/ThreadPool.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
42 #include "llvm/Transforms/Scalar/LoopPassManager.h"
43 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
44 #include "llvm/Transforms/Utils/SplitModule.h"
49 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
50 errs() << "failed to open " << Path << ": " << Msg << '\n';
55 Error Config::addSaveTemps(std::string OutputFileName,
56 bool UseInputModulePath) {
57 ShouldDiscardValueNames = false;
60 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
61 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
63 return errorCodeToError(EC);
65 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
66 // Keep track of the hook provided by the linker, which also needs to run.
67 ModuleHookFn LinkerHook = Hook;
68 Hook = [=](unsigned Task, const Module &M) {
69 // If the linker's hook returned false, we need to pass that result
71 if (LinkerHook && !LinkerHook(Task, M))
74 std::string PathPrefix;
75 // If this is the combined module (not a ThinLTO backend compile) or the
76 // user hasn't requested using the input module's path, emit to a file
77 // named from the provided OutputFileName with the Task ID appended.
78 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
79 PathPrefix = OutputFileName;
80 if (Task != (unsigned)-1)
81 PathPrefix += utostr(Task) + ".";
83 PathPrefix = M.getModuleIdentifier() + ".";
84 std::string Path = PathPrefix + PathSuffix + ".bc";
86 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
87 // Because -save-temps is a debugging feature, we report the error
90 reportOpenError(Path, EC.message());
91 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
96 setHook("0.preopt", PreOptModuleHook);
97 setHook("1.promote", PostPromoteModuleHook);
98 setHook("2.internalize", PostInternalizeModuleHook);
99 setHook("3.import", PostImportModuleHook);
100 setHook("4.opt", PostOptModuleHook);
101 setHook("5.precodegen", PreCodeGenModuleHook);
103 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
104 std::string Path = OutputFileName + "index.bc";
106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
107 // Because -save-temps is a debugging feature, we report the error
108 // directly and exit.
110 reportOpenError(Path, EC.message());
111 WriteIndexToFile(Index, OS);
113 Path = OutputFileName + "index.dot";
114 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
116 reportOpenError(Path, EC.message());
117 Index.exportToDot(OSDot);
121 return Error::success();
126 std::unique_ptr<TargetMachine>
127 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128 StringRef TheTriple = M.getTargetTriple();
129 SubtargetFeatures Features;
130 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
131 for (const std::string &A : Conf.MAttrs)
132 Features.AddFeature(A);
134 Reloc::Model RelocModel;
136 RelocModel = *Conf.RelocModel;
139 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
141 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
142 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
143 Conf.CodeModel, Conf.CGOptLevel));
146 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
147 unsigned OptLevel, bool IsThinLTO) {
148 Optional<PGOOptions> PGOOpt;
149 if (!Conf.SampleProfile.empty())
150 PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
152 PassBuilder PB(TM, PGOOpt);
155 // Parse a custom AA pipeline if asked to.
156 if (!PB.parseAAPipeline(AA, "default"))
157 report_fatal_error("Error parsing default AA pipeline");
159 LoopAnalysisManager LAM(Conf.DebugPassManager);
160 FunctionAnalysisManager FAM(Conf.DebugPassManager);
161 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
162 ModuleAnalysisManager MAM(Conf.DebugPassManager);
164 // Register the AA manager first so that our version is the one used.
165 FAM.registerPass([&] { return std::move(AA); });
167 // Register all the basic analyses with the managers.
168 PB.registerModuleAnalyses(MAM);
169 PB.registerCGSCCAnalyses(CGAM);
170 PB.registerFunctionAnalyses(FAM);
171 PB.registerLoopAnalyses(LAM);
172 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
174 ModulePassManager MPM(Conf.DebugPassManager);
175 // FIXME (davide): verify the input.
177 PassBuilder::OptimizationLevel OL;
181 llvm_unreachable("Invalid optimization level");
183 OL = PassBuilder::O0;
186 OL = PassBuilder::O1;
189 OL = PassBuilder::O2;
192 OL = PassBuilder::O3;
197 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager);
199 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager);
202 // FIXME (davide): verify the output.
205 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
206 std::string PipelineDesc,
207 std::string AAPipelineDesc,
208 bool DisableVerify) {
212 // Parse a custom AA pipeline if asked to.
213 if (!AAPipelineDesc.empty())
214 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
215 report_fatal_error("unable to parse AA pipeline description: " +
218 LoopAnalysisManager LAM;
219 FunctionAnalysisManager FAM;
220 CGSCCAnalysisManager CGAM;
221 ModuleAnalysisManager MAM;
223 // Register the AA manager first so that our version is the one used.
224 FAM.registerPass([&] { return std::move(AA); });
226 // Register all the basic analyses with the managers.
227 PB.registerModuleAnalyses(MAM);
228 PB.registerCGSCCAnalyses(CGAM);
229 PB.registerFunctionAnalyses(FAM);
230 PB.registerLoopAnalyses(LAM);
231 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
233 ModulePassManager MPM;
235 // Always verify the input.
236 MPM.addPass(VerifierPass());
238 // Now, add all the passes we've been requested to.
239 if (!PB.parsePassPipeline(MPM, PipelineDesc))
240 report_fatal_error("unable to parse pass pipeline description: " +
244 MPM.addPass(VerifierPass());
248 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
249 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
250 const ModuleSummaryIndex *ImportSummary) {
251 legacy::PassManager passes;
252 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
254 PassManagerBuilder PMB;
255 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
256 PMB.Inliner = createFunctionInliningPass();
257 PMB.ExportSummary = ExportSummary;
258 PMB.ImportSummary = ImportSummary;
259 // Unconditionally verify input since it is not verified before this
260 // point and has unknown origin.
261 PMB.VerifyInput = true;
262 PMB.VerifyOutput = !Conf.DisableVerify;
263 PMB.LoopVectorize = true;
264 PMB.SLPVectorize = true;
265 PMB.OptLevel = Conf.OptLevel;
266 PMB.PGOSampleUse = Conf.SampleProfile;
268 PMB.populateThinLTOPassManager(passes);
270 PMB.populateLTOPassManager(passes);
274 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
275 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
276 const ModuleSummaryIndex *ImportSummary) {
277 // FIXME: Plumb the combined index into the new pass manager.
278 if (!Conf.OptPipeline.empty())
279 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
281 else if (Conf.UseNewPM)
282 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO);
284 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
285 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
288 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
289 unsigned Task, Module &Mod) {
290 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
293 std::unique_ptr<ToolOutputFile> DwoOut;
294 if (!Conf.DwoDir.empty()) {
296 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
297 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
300 SmallString<1024> DwoFile(Conf.DwoDir);
301 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
302 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
303 DwoOut = make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
305 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
308 auto Stream = AddStream(Task);
309 legacy::PassManager CodeGenPasses;
310 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
311 DwoOut ? &DwoOut->os() : nullptr,
313 report_fatal_error("Failed to setup codegen");
314 CodeGenPasses.run(Mod);
320 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
321 unsigned ParallelCodeGenParallelismLevel,
322 std::unique_ptr<Module> Mod) {
323 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
324 unsigned ThreadCount = 0;
325 const Target *T = &TM->getTarget();
328 std::move(Mod), ParallelCodeGenParallelismLevel,
329 [&](std::unique_ptr<Module> MPart) {
330 // We want to clone the module in a new context to multi-thread the
331 // codegen. We do it by serializing partition modules to bitcode
332 // (while still on the main thread, in order to avoid data races) and
333 // spinning up new threads which deserialize the partitions into
334 // separate contexts.
335 // FIXME: Provide a more direct way to do this in LLVM.
337 raw_svector_ostream BCOS(BC);
338 WriteBitcodeToFile(*MPart, BCOS);
341 CodegenThreadPool.async(
342 [&](const SmallString<0> &BC, unsigned ThreadId) {
343 LTOLLVMContext Ctx(C);
344 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
345 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
348 report_fatal_error("Failed to read bitcode");
349 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
351 std::unique_ptr<TargetMachine> TM =
352 createTargetMachine(C, T, *MPartInCtx);
354 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
356 // Pass BC using std::move to ensure that it get moved rather than
357 // copied into the thread's context.
358 std::move(BC), ThreadCount++);
362 // Because the inner lambda (which runs in a worker thread) captures our local
363 // variables, we need to wait for the worker threads to terminate before we
364 // can leave the function scope.
365 CodegenThreadPool.wait();
368 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
369 if (!C.OverrideTriple.empty())
370 Mod.setTargetTriple(C.OverrideTriple);
371 else if (Mod.getTargetTriple().empty())
372 Mod.setTargetTriple(C.DefaultTriple);
375 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
377 return make_error<StringError>(Msg, inconvertibleErrorCode());
384 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
385 // Make sure we flush the diagnostic remarks file in case the linker doesn't
386 // call the global destructors before exiting.
388 return Error::success();
389 DiagOutputFile->keep();
390 DiagOutputFile->os().flush();
391 return Error::success();
394 Error lto::backend(Config &C, AddStreamFn AddStream,
395 unsigned ParallelCodeGenParallelismLevel,
396 std::unique_ptr<Module> Mod,
397 ModuleSummaryIndex &CombinedIndex) {
398 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
400 return TOrErr.takeError();
402 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
404 // Setup optimization remarks.
405 auto DiagFileOrErr = lto::setupOptimizationRemarks(
406 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
408 return DiagFileOrErr.takeError();
409 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
411 if (!C.CodeGenOnly) {
412 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
413 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
414 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
417 if (ParallelCodeGenParallelismLevel == 1) {
418 codegen(C, TM.get(), AddStream, 0, *Mod);
420 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
423 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
426 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
427 const ModuleSummaryIndex &Index) {
428 std::vector<GlobalValue*> DeadGVs;
429 for (auto &GV : Mod.global_values())
430 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
431 if (!Index.isGlobalValueLive(GVS)) {
432 DeadGVs.push_back(&GV);
433 convertToDeclaration(GV);
436 // Now that all dead bodies have been dropped, delete the actual objects
437 // themselves when possible.
438 for (GlobalValue *GV : DeadGVs) {
439 GV->removeDeadConstantUsers();
440 // Might reference something defined in native object (i.e. dropped a
441 // non-prevailing IR def, but we need to keep the declaration).
443 GV->eraseFromParent();
447 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
448 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
449 const FunctionImporter::ImportMapTy &ImportList,
450 const GVSummaryMapTy &DefinedGlobals,
451 MapVector<StringRef, BitcodeModule> &ModuleMap) {
452 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
454 return TOrErr.takeError();
456 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
458 // Setup optimization remarks.
459 auto DiagFileOrErr = lto::setupOptimizationRemarks(
460 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
462 return DiagFileOrErr.takeError();
463 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
465 if (Conf.CodeGenOnly) {
466 codegen(Conf, TM.get(), AddStream, Task, Mod);
467 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
470 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
471 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
473 renameModuleForThinLTO(Mod, CombinedIndex);
475 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
477 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
479 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
480 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
482 if (!DefinedGlobals.empty())
483 thinLTOInternalizeModule(Mod, DefinedGlobals);
485 if (Conf.PostInternalizeModuleHook &&
486 !Conf.PostInternalizeModuleHook(Task, Mod))
487 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
489 auto ModuleLoader = [&](StringRef Identifier) {
490 assert(Mod.getContext().isODRUniquingDebugTypes() &&
491 "ODR Type uniquing should be enabled on the context");
492 auto I = ModuleMap.find(Identifier);
493 assert(I != ModuleMap.end());
494 return I->second.getLazyModule(Mod.getContext(),
495 /*ShouldLazyLoadMetadata=*/true,
496 /*IsImporting*/ true);
499 FunctionImporter Importer(CombinedIndex, ModuleLoader);
500 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
503 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
504 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
506 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
507 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
508 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
510 codegen(Conf, TM.get(), AddStream, Task, Mod);
511 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));