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/TargetRegistry.h"
34 #include "llvm/Support/ThreadPool.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO.h"
37 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38 #include "llvm/Transforms/Scalar/LoopPassManager.h"
39 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
40 #include "llvm/Transforms/Utils/SplitModule.h"
46 LTOUseNewPM("lto-use-new-pm",
47 cl::desc("Run LTO passes using the new pass manager"),
48 cl::init(false), cl::Hidden);
50 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
51 errs() << "failed to open " << Path << ": " << Msg << '\n';
56 Error Config::addSaveTemps(std::string OutputFileName,
57 bool UseInputModulePath) {
58 ShouldDiscardValueNames = false;
61 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
62 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
64 return errorCodeToError(EC);
66 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
67 // Keep track of the hook provided by the linker, which also needs to run.
68 ModuleHookFn LinkerHook = Hook;
69 Hook = [=](unsigned Task, const Module &M) {
70 // If the linker's hook returned false, we need to pass that result
72 if (LinkerHook && !LinkerHook(Task, M))
75 std::string PathPrefix;
76 // If this is the combined module (not a ThinLTO backend compile) or the
77 // user hasn't requested using the input module's path, emit to a file
78 // named from the provided OutputFileName with the Task ID appended.
79 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
80 PathPrefix = OutputFileName + utostr(Task);
82 PathPrefix = M.getModuleIdentifier();
83 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
85 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
86 // Because -save-temps is a debugging feature, we report the error
89 reportOpenError(Path, EC.message());
90 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
95 setHook("0.preopt", PreOptModuleHook);
96 setHook("1.promote", PostPromoteModuleHook);
97 setHook("2.internalize", PostInternalizeModuleHook);
98 setHook("3.import", PostImportModuleHook);
99 setHook("4.opt", PostOptModuleHook);
100 setHook("5.precodegen", PreCodeGenModuleHook);
102 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
103 std::string Path = OutputFileName + "index.bc";
105 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
106 // Because -save-temps is a debugging feature, we report the error
107 // directly and exit.
109 reportOpenError(Path, EC.message());
110 WriteIndexToFile(Index, OS);
114 return Error::success();
119 std::unique_ptr<TargetMachine>
120 createTargetMachine(Config &Conf, StringRef TheTriple,
121 const Target *TheTarget) {
122 SubtargetFeatures Features;
123 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
124 for (const std::string &A : Conf.MAttrs)
125 Features.AddFeature(A);
127 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
128 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
129 Conf.CodeModel, Conf.CGOptLevel));
132 static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel) {
136 // Parse a custom AA pipeline if asked to.
137 assert(PB.parseAAPipeline(AA, "default"));
139 LoopAnalysisManager LAM;
140 FunctionAnalysisManager FAM;
141 CGSCCAnalysisManager CGAM;
142 ModuleAnalysisManager MAM;
144 // Register the AA manager first so that our version is the one used.
145 FAM.registerPass([&] { return std::move(AA); });
147 // Register all the basic analyses with the managers.
148 PB.registerModuleAnalyses(MAM);
149 PB.registerCGSCCAnalyses(CGAM);
150 PB.registerFunctionAnalyses(FAM);
151 PB.registerLoopAnalyses(LAM);
152 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
154 ModulePassManager MPM;
155 // FIXME (davide): verify the input.
157 PassBuilder::OptimizationLevel OL;
161 llvm_unreachable("Invalid optimization level");
163 OL = PassBuilder::O0;
166 OL = PassBuilder::O1;
169 OL = PassBuilder::O2;
172 OL = PassBuilder::O3;
176 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */);
179 // FIXME (davide): verify the output.
182 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
183 std::string PipelineDesc,
184 std::string AAPipelineDesc,
185 bool DisableVerify) {
189 // Parse a custom AA pipeline if asked to.
190 if (!AAPipelineDesc.empty())
191 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
192 report_fatal_error("unable to parse AA pipeline description: " +
195 LoopAnalysisManager LAM;
196 FunctionAnalysisManager FAM;
197 CGSCCAnalysisManager CGAM;
198 ModuleAnalysisManager MAM;
200 // Register the AA manager first so that our version is the one used.
201 FAM.registerPass([&] { return std::move(AA); });
203 // Register all the basic analyses with the managers.
204 PB.registerModuleAnalyses(MAM);
205 PB.registerCGSCCAnalyses(CGAM);
206 PB.registerFunctionAnalyses(FAM);
207 PB.registerLoopAnalyses(LAM);
208 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
210 ModulePassManager MPM;
212 // Always verify the input.
213 MPM.addPass(VerifierPass());
215 // Now, add all the passes we've been requested to.
216 if (!PB.parsePassPipeline(MPM, PipelineDesc))
217 report_fatal_error("unable to parse pass pipeline description: " +
221 MPM.addPass(VerifierPass());
225 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
226 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
227 const ModuleSummaryIndex *ImportSummary) {
228 legacy::PassManager passes;
229 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
231 PassManagerBuilder PMB;
232 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
233 PMB.Inliner = createFunctionInliningPass();
234 PMB.ExportSummary = ExportSummary;
235 PMB.ImportSummary = ImportSummary;
236 // Unconditionally verify input since it is not verified before this
237 // point and has unknown origin.
238 PMB.VerifyInput = true;
239 PMB.VerifyOutput = !Conf.DisableVerify;
240 PMB.LoopVectorize = true;
241 PMB.SLPVectorize = true;
242 PMB.OptLevel = Conf.OptLevel;
243 PMB.PGOSampleUse = Conf.SampleProfile;
245 PMB.populateThinLTOPassManager(passes);
247 PMB.populateLTOPassManager(passes);
251 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
252 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
253 const ModuleSummaryIndex *ImportSummary) {
254 // There's still no ThinLTO pipeline hooked up in the new pass manager,
255 // once there is one, we can just remove this.
256 if (LTOUseNewPM && IsThinLTO)
257 report_fatal_error("ThinLTO not supported with the new PM yet!");
259 // FIXME: Plumb the combined index into the new pass manager.
260 if (!Conf.OptPipeline.empty())
261 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
263 else if (LTOUseNewPM)
264 runNewPMPasses(Mod, TM, Conf.OptLevel);
266 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
267 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
270 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
271 unsigned Task, Module &Mod) {
272 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
275 auto Stream = AddStream(Task);
276 legacy::PassManager CodeGenPasses;
277 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
278 report_fatal_error("Failed to setup codegen");
279 CodeGenPasses.run(Mod);
282 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
283 unsigned ParallelCodeGenParallelismLevel,
284 std::unique_ptr<Module> Mod) {
285 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
286 unsigned ThreadCount = 0;
287 const Target *T = &TM->getTarget();
290 std::move(Mod), ParallelCodeGenParallelismLevel,
291 [&](std::unique_ptr<Module> MPart) {
292 // We want to clone the module in a new context to multi-thread the
293 // codegen. We do it by serializing partition modules to bitcode
294 // (while still on the main thread, in order to avoid data races) and
295 // spinning up new threads which deserialize the partitions into
296 // separate contexts.
297 // FIXME: Provide a more direct way to do this in LLVM.
299 raw_svector_ostream BCOS(BC);
300 WriteBitcodeToFile(MPart.get(), BCOS);
303 CodegenThreadPool.async(
304 [&](const SmallString<0> &BC, unsigned ThreadId) {
305 LTOLLVMContext Ctx(C);
306 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
307 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
310 report_fatal_error("Failed to read bitcode");
311 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
313 std::unique_ptr<TargetMachine> TM =
314 createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
316 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
318 // Pass BC using std::move to ensure that it get moved rather than
319 // copied into the thread's context.
320 std::move(BC), ThreadCount++);
324 // Because the inner lambda (which runs in a worker thread) captures our local
325 // variables, we need to wait for the worker threads to terminate before we
326 // can leave the function scope.
327 CodegenThreadPool.wait();
330 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
331 if (!C.OverrideTriple.empty())
332 Mod.setTargetTriple(C.OverrideTriple);
333 else if (Mod.getTargetTriple().empty())
334 Mod.setTargetTriple(C.DefaultTriple);
337 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
339 return make_error<StringError>(Msg, inconvertibleErrorCode());
346 finalizeOptimizationRemarks(std::unique_ptr<tool_output_file> DiagOutputFile) {
347 // Make sure we flush the diagnostic remarks file in case the linker doesn't
348 // call the global destructors before exiting.
351 DiagOutputFile->keep();
352 DiagOutputFile->os().flush();
355 Error lto::backend(Config &C, AddStreamFn AddStream,
356 unsigned ParallelCodeGenParallelismLevel,
357 std::unique_ptr<Module> Mod,
358 ModuleSummaryIndex &CombinedIndex) {
359 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
361 return TOrErr.takeError();
363 std::unique_ptr<TargetMachine> TM =
364 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
366 // Setup optimization remarks.
367 auto DiagFileOrErr = lto::setupOptimizationRemarks(
368 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
370 return DiagFileOrErr.takeError();
371 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
373 if (!C.CodeGenOnly) {
374 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
375 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
376 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
377 return Error::success();
381 if (ParallelCodeGenParallelismLevel == 1) {
382 codegen(C, TM.get(), AddStream, 0, *Mod);
384 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
387 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
388 return Error::success();
391 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
392 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
393 const FunctionImporter::ImportMapTy &ImportList,
394 const GVSummaryMapTy &DefinedGlobals,
395 MapVector<StringRef, BitcodeModule> &ModuleMap) {
396 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
398 return TOrErr.takeError();
400 std::unique_ptr<TargetMachine> TM =
401 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
403 if (Conf.CodeGenOnly) {
404 codegen(Conf, TM.get(), AddStream, Task, Mod);
405 return Error::success();
408 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
409 return Error::success();
411 renameModuleForThinLTO(Mod, CombinedIndex);
413 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
415 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
416 return Error::success();
418 if (!DefinedGlobals.empty())
419 thinLTOInternalizeModule(Mod, DefinedGlobals);
421 if (Conf.PostInternalizeModuleHook &&
422 !Conf.PostInternalizeModuleHook(Task, Mod))
423 return Error::success();
425 auto ModuleLoader = [&](StringRef Identifier) {
426 assert(Mod.getContext().isODRUniquingDebugTypes() &&
427 "ODR Type uniquing should be enabled on the context");
428 auto I = ModuleMap.find(Identifier);
429 assert(I != ModuleMap.end());
430 return I->second.getLazyModule(Mod.getContext(),
431 /*ShouldLazyLoadMetadata=*/true,
432 /*IsImporting*/ true);
435 FunctionImporter Importer(CombinedIndex, ModuleLoader);
436 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
439 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
440 return Error::success();
442 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
443 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
444 return Error::success();
446 codegen(Conf, TM.get(), AddStream, Task, Mod);
447 return Error::success();