blob: 3f72e446cdf2e81b47602ef62dc32c10f6bc6132 [file] [log] [blame]
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/LTO/LTOBackend.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/CGSCCPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
21#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000022#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000024#include "llvm/IR/LegacyPassManager.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000025#include "llvm/IR/PassManager.h"
26#include "llvm/IR/Verifier.h"
Mehdi Amini970800e2016-08-17 06:23:09 +000027#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/MC/SubtargetFeature.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000029#include "llvm/Object/ModuleSymbolTable.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000030#include "llvm/Passes/PassBuilder.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#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"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000038#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#include "llvm/Transforms/Utils/FunctionImportUtils.h"
40#include "llvm/Transforms/Utils/SplitModule.h"
41
42using namespace llvm;
43using namespace lto;
44
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000045LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000046 errs() << "failed to open " << Path << ": " << Msg << '\n';
47 errs().flush();
48 exit(1);
49}
50
Teresa Johnson9ba95f92016-08-11 14:58:12 +000051Error Config::addSaveTemps(std::string OutputFileName,
52 bool UseInputModulePath) {
53 ShouldDiscardValueNames = false;
54
55 std::error_code EC;
56 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000057 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000058 if (EC)
59 return errorCodeToError(EC);
60
61 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
62 // Keep track of the hook provided by the linker, which also needs to run.
63 ModuleHookFn LinkerHook = Hook;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000064 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000065 // If the linker's hook returned false, we need to pass that result
66 // through.
67 if (LinkerHook && !LinkerHook(Task, M))
68 return false;
69
70 std::string PathPrefix;
71 // If this is the combined module (not a ThinLTO backend compile) or the
72 // user hasn't requested using the input module's path, emit to a file
73 // named from the provided OutputFileName with the Task ID appended.
74 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000075 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000076 } else
77 PathPrefix = M.getModuleIdentifier();
78 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
79 std::error_code EC;
80 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000081 // Because -save-temps is a debugging feature, we report the error
82 // directly and exit.
83 if (EC)
84 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +000085 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
86 return true;
87 };
88 };
89
90 setHook("0.preopt", PreOptModuleHook);
91 setHook("1.promote", PostPromoteModuleHook);
92 setHook("2.internalize", PostInternalizeModuleHook);
93 setHook("3.import", PostImportModuleHook);
94 setHook("4.opt", PostOptModuleHook);
95 setHook("5.precodegen", PreCodeGenModuleHook);
96
97 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000098 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000099 std::error_code EC;
100 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000101 // Because -save-temps is a debugging feature, we report the error
102 // directly and exit.
103 if (EC)
104 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000105 WriteIndexToFile(Index, OS);
106 return true;
107 };
108
Mehdi Amini41af4302016-11-11 04:28:40 +0000109 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000110}
111
112namespace {
113
114std::unique_ptr<TargetMachine>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000115createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
116 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000117 SubtargetFeatures Features;
118 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000119 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000120 Features.AddFeature(A);
121
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000122 Reloc::Model RelocModel;
123 if (Conf.RelocModel)
124 RelocModel = *Conf.RelocModel;
125 else
126 RelocModel =
127 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
128
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000129 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000130 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000131 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000132}
133
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000134static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel,
135 bool IsThinLTO) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000136 PassBuilder PB(TM);
137 AAManager AA;
138
139 // Parse a custom AA pipeline if asked to.
140 assert(PB.parseAAPipeline(AA, "default"));
141
142 LoopAnalysisManager LAM;
143 FunctionAnalysisManager FAM;
144 CGSCCAnalysisManager CGAM;
145 ModuleAnalysisManager MAM;
146
147 // Register the AA manager first so that our version is the one used.
148 FAM.registerPass([&] { return std::move(AA); });
149
150 // Register all the basic analyses with the managers.
151 PB.registerModuleAnalyses(MAM);
152 PB.registerCGSCCAnalyses(CGAM);
153 PB.registerFunctionAnalyses(FAM);
154 PB.registerLoopAnalyses(LAM);
155 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
156
157 ModulePassManager MPM;
158 // FIXME (davide): verify the input.
159
160 PassBuilder::OptimizationLevel OL;
161
162 switch (OptLevel) {
163 default:
164 llvm_unreachable("Invalid optimization level");
165 case 0:
166 OL = PassBuilder::O0;
167 break;
168 case 1:
169 OL = PassBuilder::O1;
170 break;
171 case 2:
172 OL = PassBuilder::O2;
173 break;
174 case 3:
175 OL = PassBuilder::O3;
176 break;
177 }
178
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000179 if (IsThinLTO)
180 MPM = PB.buildThinLTODefaultPipeline(OL, false /* DebugLogging */);
181 else
182 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000183 MPM.run(Mod, MAM);
184
185 // FIXME (davide): verify the output.
186}
187
Davide Italianoec9612d2016-09-07 17:46:16 +0000188static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
189 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000190 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000191 bool DisableVerify) {
192 PassBuilder PB(TM);
193 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000194
195 // Parse a custom AA pipeline if asked to.
196 if (!AAPipelineDesc.empty())
197 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
198 report_fatal_error("unable to parse AA pipeline description: " +
199 AAPipelineDesc);
200
Davide Italianoec9612d2016-09-07 17:46:16 +0000201 LoopAnalysisManager LAM;
202 FunctionAnalysisManager FAM;
203 CGSCCAnalysisManager CGAM;
204 ModuleAnalysisManager MAM;
205
206 // Register the AA manager first so that our version is the one used.
207 FAM.registerPass([&] { return std::move(AA); });
208
209 // Register all the basic analyses with the managers.
210 PB.registerModuleAnalyses(MAM);
211 PB.registerCGSCCAnalyses(CGAM);
212 PB.registerFunctionAnalyses(FAM);
213 PB.registerLoopAnalyses(LAM);
214 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
215
216 ModulePassManager MPM;
217
218 // Always verify the input.
219 MPM.addPass(VerifierPass());
220
221 // Now, add all the passes we've been requested to.
222 if (!PB.parsePassPipeline(MPM, PipelineDesc))
223 report_fatal_error("unable to parse pass pipeline description: " +
224 PipelineDesc);
225
226 if (!DisableVerify)
227 MPM.addPass(VerifierPass());
228 MPM.run(Mod, MAM);
229}
230
Davide Italiano24c29b12016-09-07 01:08:31 +0000231static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000232 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
233 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234 legacy::PassManager passes;
235 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
236
237 PassManagerBuilder PMB;
238 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
239 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000240 PMB.ExportSummary = ExportSummary;
241 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000242 // Unconditionally verify input since it is not verified before this
243 // point and has unknown origin.
244 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000245 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000246 PMB.LoopVectorize = true;
247 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000248 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000249 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000250 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000251 PMB.populateThinLTOPassManager(passes);
252 else
253 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000254 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000255}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000256
Davide Italiano24c29b12016-09-07 01:08:31 +0000257bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000258 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
259 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000260 // FIXME: Plumb the combined index into the new pass manager.
261 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000262 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
263 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000264 else if (Conf.UseNewPM)
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000265 runNewPMPasses(Mod, TM, Conf.OptLevel, IsThinLTO);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000266 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000267 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000268 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000269}
270
Peter Collingbourne80186a52016-09-23 21:33:43 +0000271void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000272 unsigned Task, Module &Mod) {
273 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 return;
275
Peter Collingbourne80186a52016-09-23 21:33:43 +0000276 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000278 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000280 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000281}
282
Peter Collingbourne80186a52016-09-23 21:33:43 +0000283void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000284 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000285 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000286 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
287 unsigned ThreadCount = 0;
288 const Target *T = &TM->getTarget();
289
290 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000291 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292 [&](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.
299 SmallString<0> BC;
300 raw_svector_ostream BCOS(BC);
301 WriteBitcodeToFile(MPart.get(), BCOS);
302
303 // Enqueue the task
304 CodegenThreadPool.async(
305 [&](const SmallString<0> &BC, unsigned ThreadId) {
306 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000307 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000308 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
309 Ctx);
310 if (!MOrErr)
311 report_fatal_error("Failed to read bitcode");
312 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
313
314 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000315 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000316
Peter Collingbourne80186a52016-09-23 21:33:43 +0000317 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318 },
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++);
322 },
323 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000324
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.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000328 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000329}
330
Davide Italiano24c29b12016-09-07 01:08:31 +0000331Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000332 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000333 Mod.setTargetTriple(C.OverrideTriple);
334 else if (Mod.getTargetTriple().empty())
335 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336
337 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000338 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000339 if (!T)
340 return make_error<StringError>(Msg, inconvertibleErrorCode());
341 return T;
342}
343
344}
345
Davide Italiano20a895c2017-02-13 14:39:51 +0000346static void
347finalizeOptimizationRemarks(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.
350 if (!DiagOutputFile)
351 return;
352 DiagOutputFile->keep();
353 DiagOutputFile->os().flush();
354}
355
Peter Collingbourne80186a52016-09-23 21:33:43 +0000356Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000358 std::unique_ptr<Module> Mod,
359 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000360 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361 if (!TOrErr)
362 return TOrErr.takeError();
363
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000364 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000365
Davide Italianoebd47192017-02-12 03:31:30 +0000366 // Setup optimization remarks.
367 auto DiagFileOrErr = lto::setupOptimizationRemarks(
368 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
369 if (!DiagFileOrErr)
370 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000371 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000372
Davide Italiano20a895c2017-02-13 14:39:51 +0000373 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000374 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
375 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000376 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000377 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000378 }
379 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000381 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000382 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000383 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000384 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000385 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000386 }
Davide Italiano20a895c2017-02-13 14:39:51 +0000387 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000388 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000389}
390
Peter Collingbourne80186a52016-09-23 21:33:43 +0000391Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000392 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000393 const FunctionImporter::ImportMapTy &ImportList,
394 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000395 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000396 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000397 if (!TOrErr)
398 return TOrErr.takeError();
399
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000400 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000401
Mehdi Aminid310b472016-08-22 06:25:41 +0000402 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000403 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000404 return Error::success();
Mehdi Aminid310b472016-08-22 06:25:41 +0000405 }
406
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000407 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000408 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000410 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000411
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000412 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
413
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000414 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000415 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416
417 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000418 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000420 if (Conf.PostInternalizeModuleHook &&
421 !Conf.PostInternalizeModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000422 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423
424 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000425 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000426 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000427 auto I = ModuleMap.find(Identifier);
428 assert(I != ModuleMap.end());
429 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000430 /*ShouldLazyLoadMetadata=*/true,
431 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000432 };
433
434 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000435 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
436 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000437
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000438 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000439 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000440
Peter Collingbournef7691d82017-03-22 18:22:59 +0000441 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
442 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000443 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444
Peter Collingbourne80186a52016-09-23 21:33:43 +0000445 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000446 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447}