blob: 668667a53562561e422470b9317302f9ed58e17a [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
Davide Italiano0dd200e2017-01-24 00:58:24 +000045static cl::opt<bool>
46 LTOUseNewPM("lto-use-new-pm",
47 cl::desc("Run LTO passes using the new pass manager"),
48 cl::init(false), cl::Hidden);
49
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000050LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000051 errs() << "failed to open " << Path << ": " << Msg << '\n';
52 errs().flush();
53 exit(1);
54}
55
Teresa Johnson9ba95f92016-08-11 14:58:12 +000056Error Config::addSaveTemps(std::string OutputFileName,
57 bool UseInputModulePath) {
58 ShouldDiscardValueNames = false;
59
60 std::error_code EC;
61 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000062 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000063 if (EC)
64 return errorCodeToError(EC);
65
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;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000069 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000070 // If the linker's hook returned false, we need to pass that result
71 // through.
72 if (LinkerHook && !LinkerHook(Task, M))
73 return false;
74
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) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000080 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000081 } else
82 PathPrefix = M.getModuleIdentifier();
83 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
84 std::error_code EC;
85 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000086 // Because -save-temps is a debugging feature, we report the error
87 // directly and exit.
88 if (EC)
89 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +000090 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
91 return true;
92 };
93 };
94
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);
101
102 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +0000103 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000104 std::error_code EC;
105 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000106 // Because -save-temps is a debugging feature, we report the error
107 // directly and exit.
108 if (EC)
109 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000110 WriteIndexToFile(Index, OS);
111 return true;
112 };
113
Mehdi Amini41af4302016-11-11 04:28:40 +0000114 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000115}
116
117namespace {
118
119std::unique_ptr<TargetMachine>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000120createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
121 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000122 SubtargetFeatures Features;
123 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000124 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000125 Features.AddFeature(A);
126
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000127 Reloc::Model RelocModel;
128 if (Conf.RelocModel)
129 RelocModel = *Conf.RelocModel;
130 else
131 RelocModel =
132 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
133
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000134 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000135 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000136 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000137}
138
Davide Italiano0dd200e2017-01-24 00:58:24 +0000139static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel) {
140 PassBuilder PB(TM);
141 AAManager AA;
142
143 // Parse a custom AA pipeline if asked to.
144 assert(PB.parseAAPipeline(AA, "default"));
145
146 LoopAnalysisManager LAM;
147 FunctionAnalysisManager FAM;
148 CGSCCAnalysisManager CGAM;
149 ModuleAnalysisManager MAM;
150
151 // Register the AA manager first so that our version is the one used.
152 FAM.registerPass([&] { return std::move(AA); });
153
154 // Register all the basic analyses with the managers.
155 PB.registerModuleAnalyses(MAM);
156 PB.registerCGSCCAnalyses(CGAM);
157 PB.registerFunctionAnalyses(FAM);
158 PB.registerLoopAnalyses(LAM);
159 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
160
161 ModulePassManager MPM;
162 // FIXME (davide): verify the input.
163
164 PassBuilder::OptimizationLevel OL;
165
166 switch (OptLevel) {
167 default:
168 llvm_unreachable("Invalid optimization level");
169 case 0:
170 OL = PassBuilder::O0;
171 break;
172 case 1:
173 OL = PassBuilder::O1;
174 break;
175 case 2:
176 OL = PassBuilder::O2;
177 break;
178 case 3:
179 OL = PassBuilder::O3;
180 break;
181 }
182
183 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */);
184 MPM.run(Mod, MAM);
185
186 // FIXME (davide): verify the output.
187}
188
Davide Italianoec9612d2016-09-07 17:46:16 +0000189static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
190 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000191 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000192 bool DisableVerify) {
193 PassBuilder PB(TM);
194 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000195
196 // Parse a custom AA pipeline if asked to.
197 if (!AAPipelineDesc.empty())
198 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
199 report_fatal_error("unable to parse AA pipeline description: " +
200 AAPipelineDesc);
201
Davide Italianoec9612d2016-09-07 17:46:16 +0000202 LoopAnalysisManager LAM;
203 FunctionAnalysisManager FAM;
204 CGSCCAnalysisManager CGAM;
205 ModuleAnalysisManager MAM;
206
207 // Register the AA manager first so that our version is the one used.
208 FAM.registerPass([&] { return std::move(AA); });
209
210 // Register all the basic analyses with the managers.
211 PB.registerModuleAnalyses(MAM);
212 PB.registerCGSCCAnalyses(CGAM);
213 PB.registerFunctionAnalyses(FAM);
214 PB.registerLoopAnalyses(LAM);
215 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
216
217 ModulePassManager MPM;
218
219 // Always verify the input.
220 MPM.addPass(VerifierPass());
221
222 // Now, add all the passes we've been requested to.
223 if (!PB.parsePassPipeline(MPM, PipelineDesc))
224 report_fatal_error("unable to parse pass pipeline description: " +
225 PipelineDesc);
226
227 if (!DisableVerify)
228 MPM.addPass(VerifierPass());
229 MPM.run(Mod, MAM);
230}
231
Davide Italiano24c29b12016-09-07 01:08:31 +0000232static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000233 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
234 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000235 legacy::PassManager passes;
236 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
237
238 PassManagerBuilder PMB;
239 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
240 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000241 PMB.ExportSummary = ExportSummary;
242 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000243 // Unconditionally verify input since it is not verified before this
244 // point and has unknown origin.
245 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000246 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000247 PMB.LoopVectorize = true;
248 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000249 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000250 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000251 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000252 PMB.populateThinLTOPassManager(passes);
253 else
254 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000255 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000256}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257
Davide Italiano24c29b12016-09-07 01:08:31 +0000258bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000259 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
260 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000261 // There's still no ThinLTO pipeline hooked up in the new pass manager,
262 // once there is one, we can just remove this.
263 if (LTOUseNewPM && IsThinLTO)
264 report_fatal_error("ThinLTO not supported with the new PM yet!");
265
266 // FIXME: Plumb the combined index into the new pass manager.
267 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000268 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
269 Conf.DisableVerify);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000270 else if (LTOUseNewPM)
271 runNewPMPasses(Mod, TM, Conf.OptLevel);
272 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000273 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000274 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000275}
276
Peter Collingbourne80186a52016-09-23 21:33:43 +0000277void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000278 unsigned Task, Module &Mod) {
279 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000280 return;
281
Peter Collingbourne80186a52016-09-23 21:33:43 +0000282 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000283 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000284 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000285 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000286 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000287}
288
Peter Collingbourne80186a52016-09-23 21:33:43 +0000289void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000290 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000291 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
293 unsigned ThreadCount = 0;
294 const Target *T = &TM->getTarget();
295
296 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000297 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000298 [&](std::unique_ptr<Module> MPart) {
299 // We want to clone the module in a new context to multi-thread the
300 // codegen. We do it by serializing partition modules to bitcode
301 // (while still on the main thread, in order to avoid data races) and
302 // spinning up new threads which deserialize the partitions into
303 // separate contexts.
304 // FIXME: Provide a more direct way to do this in LLVM.
305 SmallString<0> BC;
306 raw_svector_ostream BCOS(BC);
307 WriteBitcodeToFile(MPart.get(), BCOS);
308
309 // Enqueue the task
310 CodegenThreadPool.async(
311 [&](const SmallString<0> &BC, unsigned ThreadId) {
312 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000313 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000314 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
315 Ctx);
316 if (!MOrErr)
317 report_fatal_error("Failed to read bitcode");
318 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
319
320 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000321 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000322
Peter Collingbourne80186a52016-09-23 21:33:43 +0000323 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000324 },
325 // Pass BC using std::move to ensure that it get moved rather than
326 // copied into the thread's context.
327 std::move(BC), ThreadCount++);
328 },
329 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000330
331 // Because the inner lambda (which runs in a worker thread) captures our local
332 // variables, we need to wait for the worker threads to terminate before we
333 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000334 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000335}
336
Davide Italiano24c29b12016-09-07 01:08:31 +0000337Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000338 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000339 Mod.setTargetTriple(C.OverrideTriple);
340 else if (Mod.getTargetTriple().empty())
341 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000342
343 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000344 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000345 if (!T)
346 return make_error<StringError>(Msg, inconvertibleErrorCode());
347 return T;
348}
349
350}
351
Davide Italiano20a895c2017-02-13 14:39:51 +0000352static void
353finalizeOptimizationRemarks(std::unique_ptr<tool_output_file> DiagOutputFile) {
354 // Make sure we flush the diagnostic remarks file in case the linker doesn't
355 // call the global destructors before exiting.
356 if (!DiagOutputFile)
357 return;
358 DiagOutputFile->keep();
359 DiagOutputFile->os().flush();
360}
361
Peter Collingbourne80186a52016-09-23 21:33:43 +0000362Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000363 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000364 std::unique_ptr<Module> Mod,
365 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000366 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000367 if (!TOrErr)
368 return TOrErr.takeError();
369
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000370 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371
Davide Italianoebd47192017-02-12 03:31:30 +0000372 // Setup optimization remarks.
373 auto DiagFileOrErr = lto::setupOptimizationRemarks(
374 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
375 if (!DiagFileOrErr)
376 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000377 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000378
Davide Italiano20a895c2017-02-13 14:39:51 +0000379 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000380 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
381 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000382 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000383 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000384 }
385 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000386
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000387 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000388 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000389 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000390 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000391 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000392 }
Davide Italiano20a895c2017-02-13 14:39:51 +0000393 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000394 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000395}
396
Peter Collingbourne80186a52016-09-23 21:33:43 +0000397Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000398 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000399 const FunctionImporter::ImportMapTy &ImportList,
400 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000401 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000402 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000403 if (!TOrErr)
404 return TOrErr.takeError();
405
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000406 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407
Mehdi Aminid310b472016-08-22 06:25:41 +0000408 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000409 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000410 return Error::success();
Mehdi Aminid310b472016-08-22 06:25:41 +0000411 }
412
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000413 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000414 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000415
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000416 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000417
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000418 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
419
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000420 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000421 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422
423 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000424 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000426 if (Conf.PostInternalizeModuleHook &&
427 !Conf.PostInternalizeModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000428 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000429
430 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000431 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000432 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000433 auto I = ModuleMap.find(Identifier);
434 assert(I != ModuleMap.end());
435 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000436 /*ShouldLazyLoadMetadata=*/true,
437 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000438 };
439
440 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000441 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
442 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000444 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000445 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446
Peter Collingbournef7691d82017-03-22 18:22:59 +0000447 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
448 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000449 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000450
Peter Collingbourne80186a52016-09-23 21:33:43 +0000451 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000452 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000453}