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/LTO/legacy/UpdateCompilerUsed.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Object/ModuleSymbolTable.h"
31 #include "llvm/Passes/PassBuilder.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/ThreadPool.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/IPO.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Scalar/LoopPassManager.h"
40 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
41 #include "llvm/Transforms/Utils/SplitModule.h"
47 LTOUseNewPM("lto-use-new-pm",
48 cl::desc("Run LTO passes using the new pass manager"),
49 cl::init(false), cl::Hidden);
51 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
52 errs() << "failed to open " << Path << ": " << Msg << '\n';
57 Error Config::addSaveTemps(std::string OutputFileName,
58 bool UseInputModulePath) {
59 ShouldDiscardValueNames = false;
62 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
63 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
65 return errorCodeToError(EC);
67 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
68 // Keep track of the hook provided by the linker, which also needs to run.
69 ModuleHookFn LinkerHook = Hook;
70 Hook = [=](unsigned Task, const Module &M) {
71 // If the linker's hook returned false, we need to pass that result
73 if (LinkerHook && !LinkerHook(Task, M))
76 std::string PathPrefix;
77 // If this is the combined module (not a ThinLTO backend compile) or the
78 // user hasn't requested using the input module's path, emit to a file
79 // named from the provided OutputFileName with the Task ID appended.
80 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
81 PathPrefix = OutputFileName + 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);
115 return Error::success();
120 std::unique_ptr<TargetMachine>
121 createTargetMachine(Config &Conf, StringRef TheTriple,
122 const Target *TheTarget) {
123 SubtargetFeatures Features;
124 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
125 for (const std::string &A : Conf.MAttrs)
126 Features.AddFeature(A);
128 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
129 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
130 Conf.CodeModel, Conf.CGOptLevel));
133 static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel) {
137 // Parse a custom AA pipeline if asked to.
138 assert(PB.parseAAPipeline(AA, "default"));
140 LoopAnalysisManager LAM;
141 FunctionAnalysisManager FAM;
142 CGSCCAnalysisManager CGAM;
143 ModuleAnalysisManager MAM;
145 // Register the AA manager first so that our version is the one used.
146 FAM.registerPass([&] { return std::move(AA); });
148 // Register all the basic analyses with the managers.
149 PB.registerModuleAnalyses(MAM);
150 PB.registerCGSCCAnalyses(CGAM);
151 PB.registerFunctionAnalyses(FAM);
152 PB.registerLoopAnalyses(LAM);
153 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
155 ModulePassManager MPM;
156 // FIXME (davide): verify the input.
158 PassBuilder::OptimizationLevel OL;
162 llvm_unreachable("Invalid optimization level");
164 OL = PassBuilder::O0;
167 OL = PassBuilder::O1;
170 OL = PassBuilder::O2;
173 OL = PassBuilder::O3;
177 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */);
180 // FIXME (davide): verify the output.
183 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
184 std::string PipelineDesc,
185 std::string AAPipelineDesc,
186 bool DisableVerify) {
190 // Parse a custom AA pipeline if asked to.
191 if (!AAPipelineDesc.empty())
192 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
193 report_fatal_error("unable to parse AA pipeline description: " +
196 LoopAnalysisManager LAM;
197 FunctionAnalysisManager FAM;
198 CGSCCAnalysisManager CGAM;
199 ModuleAnalysisManager MAM;
201 // Register the AA manager first so that our version is the one used.
202 FAM.registerPass([&] { return std::move(AA); });
204 // Register all the basic analyses with the managers.
205 PB.registerModuleAnalyses(MAM);
206 PB.registerCGSCCAnalyses(CGAM);
207 PB.registerFunctionAnalyses(FAM);
208 PB.registerLoopAnalyses(LAM);
209 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
211 ModulePassManager MPM;
213 // Always verify the input.
214 MPM.addPass(VerifierPass());
216 // Now, add all the passes we've been requested to.
217 if (!PB.parsePassPipeline(MPM, PipelineDesc))
218 report_fatal_error("unable to parse pass pipeline description: " +
222 MPM.addPass(VerifierPass());
226 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
227 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
228 const ModuleSummaryIndex *ImportSummary) {
229 legacy::PassManager passes;
230 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
232 PassManagerBuilder PMB;
233 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
234 PMB.Inliner = createFunctionInliningPass();
235 PMB.ExportSummary = ExportSummary;
236 PMB.ImportSummary = ImportSummary;
237 // Unconditionally verify input since it is not verified before this
238 // point and has unknown origin.
239 PMB.VerifyInput = true;
240 PMB.VerifyOutput = !Conf.DisableVerify;
241 PMB.LoopVectorize = true;
242 PMB.SLPVectorize = true;
243 PMB.OptLevel = Conf.OptLevel;
244 PMB.PGOSampleUse = Conf.SampleProfile;
246 PMB.populateThinLTOPassManager(passes);
248 PMB.populateLTOPassManager(passes);
252 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
253 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
254 const ModuleSummaryIndex *ImportSummary) {
255 // There's still no ThinLTO pipeline hooked up in the new pass manager,
256 // once there is one, we can just remove this.
257 if (LTOUseNewPM && IsThinLTO)
258 report_fatal_error("ThinLTO not supported with the new PM yet!");
260 // FIXME: Plumb the combined index into the new pass manager.
261 if (!Conf.OptPipeline.empty())
262 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
264 else if (LTOUseNewPM)
265 runNewPMPasses(Mod, TM, Conf.OptLevel);
267 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
268 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
271 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
272 unsigned Task, Module &Mod) {
273 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
276 auto Stream = AddStream(Task);
277 legacy::PassManager CodeGenPasses;
278 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
279 report_fatal_error("Failed to setup codegen");
280 CodeGenPasses.run(Mod);
283 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
284 unsigned ParallelCodeGenParallelismLevel,
285 std::unique_ptr<Module> Mod) {
286 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
287 unsigned ThreadCount = 0;
288 const Target *T = &TM->getTarget();
291 std::move(Mod), ParallelCodeGenParallelismLevel,
292 [&](std::unique_ptr<Module> MPart) {
293 // We want to clone the module in a new context to multi-thread the
294 // codegen. We do it by serializing partition modules to bitcode
295 // (while still on the main thread, in order to avoid data races) and
296 // spinning up new threads which deserialize the partitions into
297 // separate contexts.
298 // FIXME: Provide a more direct way to do this in LLVM.
300 raw_svector_ostream BCOS(BC);
301 WriteBitcodeToFile(MPart.get(), BCOS);
304 CodegenThreadPool.async(
305 [&](const SmallString<0> &BC, unsigned ThreadId) {
306 LTOLLVMContext Ctx(C);
307 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
308 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
311 report_fatal_error("Failed to read bitcode");
312 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
314 std::unique_ptr<TargetMachine> TM =
315 createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
317 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
319 // Pass BC using std::move to ensure that it get moved rather than
320 // copied into the thread's context.
321 std::move(BC), ThreadCount++);
325 // Because the inner lambda (which runs in a worker thread) captures our local
326 // variables, we need to wait for the worker threads to terminate before we
327 // can leave the function scope.
328 CodegenThreadPool.wait();
331 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
332 if (!C.OverrideTriple.empty())
333 Mod.setTargetTriple(C.OverrideTriple);
334 else if (Mod.getTargetTriple().empty())
335 Mod.setTargetTriple(C.DefaultTriple);
338 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
340 return make_error<StringError>(Msg, inconvertibleErrorCode());
347 finalizeOptimizationRemarks(std::unique_ptr<tool_output_file> DiagOutputFile) {
348 // Make sure we flush the diagnostic remarks file in case the linker doesn't
349 // call the global destructors before exiting.
352 DiagOutputFile->keep();
353 DiagOutputFile->os().flush();
356 static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) {
357 // Collect the list of undefined symbols used in asm and update
358 // llvm.compiler.used to prevent optimization to drop these from the output.
359 StringSet<> AsmUndefinedRefs;
360 ModuleSymbolTable::CollectAsmSymbols(
362 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
363 if (Flags & object::BasicSymbolRef::SF_Undefined)
364 AsmUndefinedRefs.insert(Name);
366 updateCompilerUsed(Mod, TM, AsmUndefinedRefs);
369 Error lto::backend(Config &C, AddStreamFn AddStream,
370 unsigned ParallelCodeGenParallelismLevel,
371 std::unique_ptr<Module> Mod,
372 ModuleSummaryIndex &CombinedIndex) {
373 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
375 return TOrErr.takeError();
377 std::unique_ptr<TargetMachine> TM =
378 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
380 handleAsmUndefinedRefs(*Mod, *TM);
382 // Setup optimization remarks.
383 auto DiagFileOrErr = lto::setupOptimizationRemarks(
384 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
386 return DiagFileOrErr.takeError();
387 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
389 if (!C.CodeGenOnly) {
390 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
391 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
392 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
393 return Error::success();
397 if (ParallelCodeGenParallelismLevel == 1) {
398 codegen(C, TM.get(), AddStream, 0, *Mod);
400 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
403 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
404 return Error::success();
407 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
408 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
409 const FunctionImporter::ImportMapTy &ImportList,
410 const GVSummaryMapTy &DefinedGlobals,
411 MapVector<StringRef, BitcodeModule> &ModuleMap) {
412 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
414 return TOrErr.takeError();
416 std::unique_ptr<TargetMachine> TM =
417 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
419 handleAsmUndefinedRefs(Mod, *TM);
421 if (Conf.CodeGenOnly) {
422 codegen(Conf, TM.get(), AddStream, Task, Mod);
423 return Error::success();
426 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
427 return Error::success();
429 renameModuleForThinLTO(Mod, CombinedIndex);
431 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
433 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
434 return Error::success();
436 if (!DefinedGlobals.empty())
437 thinLTOInternalizeModule(Mod, DefinedGlobals);
439 if (Conf.PostInternalizeModuleHook &&
440 !Conf.PostInternalizeModuleHook(Task, Mod))
441 return Error::success();
443 auto ModuleLoader = [&](StringRef Identifier) {
444 assert(Mod.getContext().isODRUniquingDebugTypes() &&
445 "ODR Type uniquing should be enabled on the context");
446 auto I = ModuleMap.find(Identifier);
447 assert(I != ModuleMap.end());
448 return I->second.getLazyModule(Mod.getContext(),
449 /*ShouldLazyLoadMetadata=*/true,
450 /*IsImporting*/ true);
453 FunctionImporter Importer(CombinedIndex, ModuleLoader);
454 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
457 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
458 return Error::success();
460 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
461 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
462 return Error::success();
464 codegen(Conf, TM.get(), AddStream, Task, Mod);
465 return Error::success();