blob: eadbb410bd5a01f45f50ed54469ea9303d28a8f4 [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"
Yunlian Jiangbd200b92018-04-13 05:03:28 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/Program.h"
36#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000037#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"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000042#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000043#include "llvm/Transforms/Utils/FunctionImportUtils.h"
44#include "llvm/Transforms/Utils/SplitModule.h"
45
46using namespace llvm;
47using namespace lto;
48
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000049LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000050 errs() << "failed to open " << Path << ": " << Msg << '\n';
51 errs().flush();
52 exit(1);
53}
54
Teresa Johnson9ba95f92016-08-11 14:58:12 +000055Error Config::addSaveTemps(std::string OutputFileName,
56 bool UseInputModulePath) {
57 ShouldDiscardValueNames = false;
58
59 std::error_code EC;
60 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000061 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000062 if (EC)
63 return errorCodeToError(EC);
64
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;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000068 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000069 // If the linker's hook returned false, we need to pass that result
70 // through.
71 if (LinkerHook && !LinkerHook(Task, M))
72 return false;
73
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) {
Teresa Johnson81d92072018-05-05 14:37:20 +000079 PathPrefix = OutputFileName;
80 if (Task != (unsigned)-1)
81 PathPrefix += utostr(Task) + ".";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000082 } else
Teresa Johnson81d92072018-05-05 14:37:20 +000083 PathPrefix = M.getModuleIdentifier() + ".";
84 std::string Path = PathPrefix + PathSuffix + ".bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000085 std::error_code EC;
86 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000087 // Because -save-temps is a debugging feature, we report the error
88 // directly and exit.
89 if (EC)
90 reportOpenError(Path, EC.message());
Rafael Espindola6a86e252018-02-14 19:11:32 +000091 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000092 return true;
93 };
94 };
95
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);
102
103 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +0000104 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000105 std::error_code EC;
106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000107 // Because -save-temps is a debugging feature, we report the error
108 // directly and exit.
109 if (EC)
110 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000111 WriteIndexToFile(Index, OS);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000112
113 Path = OutputFileName + "index.dot";
114 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
115 if (EC)
116 reportOpenError(Path, EC.message());
117 Index.exportToDot(OSDot);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000118 return true;
119 };
120
Mehdi Amini41af4302016-11-11 04:28:40 +0000121 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000122}
123
124namespace {
125
126std::unique_ptr<TargetMachine>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000127createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000129 SubtargetFeatures Features;
130 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000131 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000132 Features.AddFeature(A);
133
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000134 Reloc::Model RelocModel;
135 if (Conf.RelocModel)
136 RelocModel = *Conf.RelocModel;
137 else
138 RelocModel =
139 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
140
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000141 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000142 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000143 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000144}
145
Dehao Chen89d32262017-08-02 01:28:31 +0000146static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Teresa Johnson28023db2018-07-19 14:51:32 +0000147 unsigned OptLevel, bool IsThinLTO,
148 ModuleSummaryIndex *ExportSummary,
149 const ModuleSummaryIndex *ImportSummary) {
Dehao Chen89d32262017-08-02 01:28:31 +0000150 Optional<PGOOptions> PGOOpt;
151 if (!Conf.SampleProfile.empty())
152 PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
153
154 PassBuilder PB(TM, PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000155 AAManager AA;
156
157 // Parse a custom AA pipeline if asked to.
Dehao Chen3246dc32017-08-02 03:03:19 +0000158 if (!PB.parseAAPipeline(AA, "default"))
159 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000160
Dehao Chen3246dc32017-08-02 03:03:19 +0000161 LoopAnalysisManager LAM(Conf.DebugPassManager);
162 FunctionAnalysisManager FAM(Conf.DebugPassManager);
163 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
164 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000165
166 // Register the AA manager first so that our version is the one used.
167 FAM.registerPass([&] { return std::move(AA); });
168
169 // Register all the basic analyses with the managers.
170 PB.registerModuleAnalyses(MAM);
171 PB.registerCGSCCAnalyses(CGAM);
172 PB.registerFunctionAnalyses(FAM);
173 PB.registerLoopAnalyses(LAM);
174 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
175
Dehao Chen3246dc32017-08-02 03:03:19 +0000176 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000177 // FIXME (davide): verify the input.
178
179 PassBuilder::OptimizationLevel OL;
180
181 switch (OptLevel) {
182 default:
183 llvm_unreachable("Invalid optimization level");
184 case 0:
185 OL = PassBuilder::O0;
186 break;
187 case 1:
188 OL = PassBuilder::O1;
189 break;
190 case 2:
191 OL = PassBuilder::O2;
192 break;
193 case 3:
194 OL = PassBuilder::O3;
195 break;
196 }
197
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000198 if (IsThinLTO)
Teresa Johnson28023db2018-07-19 14:51:32 +0000199 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
200 ImportSummary);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000201 else
Teresa Johnson28023db2018-07-19 14:51:32 +0000202 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000203 MPM.run(Mod, MAM);
204
205 // FIXME (davide): verify the output.
206}
207
Davide Italianoec9612d2016-09-07 17:46:16 +0000208static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
209 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000210 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000211 bool DisableVerify) {
212 PassBuilder PB(TM);
213 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000214
215 // Parse a custom AA pipeline if asked to.
216 if (!AAPipelineDesc.empty())
217 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
218 report_fatal_error("unable to parse AA pipeline description: " +
219 AAPipelineDesc);
220
Davide Italianoec9612d2016-09-07 17:46:16 +0000221 LoopAnalysisManager LAM;
222 FunctionAnalysisManager FAM;
223 CGSCCAnalysisManager CGAM;
224 ModuleAnalysisManager MAM;
225
226 // Register the AA manager first so that our version is the one used.
227 FAM.registerPass([&] { return std::move(AA); });
228
229 // Register all the basic analyses with the managers.
230 PB.registerModuleAnalyses(MAM);
231 PB.registerCGSCCAnalyses(CGAM);
232 PB.registerFunctionAnalyses(FAM);
233 PB.registerLoopAnalyses(LAM);
234 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
235
236 ModulePassManager MPM;
237
238 // Always verify the input.
239 MPM.addPass(VerifierPass());
240
241 // Now, add all the passes we've been requested to.
242 if (!PB.parsePassPipeline(MPM, PipelineDesc))
243 report_fatal_error("unable to parse pass pipeline description: " +
244 PipelineDesc);
245
246 if (!DisableVerify)
247 MPM.addPass(VerifierPass());
248 MPM.run(Mod, MAM);
249}
250
Davide Italiano24c29b12016-09-07 01:08:31 +0000251static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000252 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
253 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000254 legacy::PassManager passes;
255 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
256
257 PassManagerBuilder PMB;
258 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
259 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000260 PMB.ExportSummary = ExportSummary;
261 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000262 // Unconditionally verify input since it is not verified before this
263 // point and has unknown origin.
264 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000265 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266 PMB.LoopVectorize = true;
267 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000268 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000269 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000270 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000271 PMB.populateThinLTOPassManager(passes);
272 else
273 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000274 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000275}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276
Davide Italiano24c29b12016-09-07 01:08:31 +0000277bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000278 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
279 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000280 // FIXME: Plumb the combined index into the new pass manager.
281 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000282 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
283 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000284 else if (Conf.UseNewPM)
Teresa Johnson28023db2018-07-19 14:51:32 +0000285 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
286 ImportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000287 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000288 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000289 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000290}
291
Peter Collingbourne80186a52016-09-23 21:33:43 +0000292void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000293 unsigned Task, Module &Mod) {
294 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000295 return;
296
Peter Collingbournec5a97652018-05-21 20:26:49 +0000297 std::unique_ptr<ToolOutputFile> DwoOut;
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000298 SmallString<1024> DwoFile(Conf.DwoPath);
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000299 if (!Conf.DwoDir.empty()) {
Peter Collingbournec5a97652018-05-21 20:26:49 +0000300 std::error_code EC;
301 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
302 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
303 EC.message());
304
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000305 DwoFile = Conf.DwoDir;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000306 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000307 }
308
309 if (!DwoFile.empty()) {
310 std::error_code EC;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000311 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
Peter Collingbourne274c4f72018-05-21 20:56:28 +0000312 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000313 if (EC)
314 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000315 }
316
Peter Collingbourne80186a52016-09-23 21:33:43 +0000317 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318 legacy::PassManager CodeGenPasses;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000319 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
320 DwoOut ? &DwoOut->os() : nullptr,
Peter Collingbourne9a451142018-05-21 20:16:41 +0000321 Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000322 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000323 CodeGenPasses.run(Mod);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000324
325 if (DwoOut)
326 DwoOut->keep();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000327}
328
Peter Collingbourne80186a52016-09-23 21:33:43 +0000329void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000330 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000331 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000332 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
333 unsigned ThreadCount = 0;
334 const Target *T = &TM->getTarget();
335
336 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000337 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000338 [&](std::unique_ptr<Module> MPart) {
339 // We want to clone the module in a new context to multi-thread the
340 // codegen. We do it by serializing partition modules to bitcode
341 // (while still on the main thread, in order to avoid data races) and
342 // spinning up new threads which deserialize the partitions into
343 // separate contexts.
344 // FIXME: Provide a more direct way to do this in LLVM.
345 SmallString<0> BC;
346 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000347 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000348
349 // Enqueue the task
350 CodegenThreadPool.async(
351 [&](const SmallString<0> &BC, unsigned ThreadId) {
352 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000353 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000354 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
355 Ctx);
356 if (!MOrErr)
357 report_fatal_error("Failed to read bitcode");
358 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
359
360 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000361 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000362
Peter Collingbourne80186a52016-09-23 21:33:43 +0000363 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364 },
365 // Pass BC using std::move to ensure that it get moved rather than
366 // copied into the thread's context.
367 std::move(BC), ThreadCount++);
368 },
369 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000370
371 // Because the inner lambda (which runs in a worker thread) captures our local
372 // variables, we need to wait for the worker threads to terminate before we
373 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000374 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000375}
376
Davide Italiano24c29b12016-09-07 01:08:31 +0000377Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000378 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000379 Mod.setTargetTriple(C.OverrideTriple);
380 else if (Mod.getTargetTriple().empty())
381 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000382
383 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000384 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000385 if (!T)
386 return make_error<StringError>(Msg, inconvertibleErrorCode());
387 return T;
388}
389
390}
391
Teresa Johnson85cc2982018-05-03 20:24:12 +0000392static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000393finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000394 // Make sure we flush the diagnostic remarks file in case the linker doesn't
395 // call the global destructors before exiting.
396 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000397 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000398 DiagOutputFile->keep();
399 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000400 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000401}
402
Peter Collingbourne80186a52016-09-23 21:33:43 +0000403Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000404 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000405 std::unique_ptr<Module> Mod,
406 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000407 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408 if (!TOrErr)
409 return TOrErr.takeError();
410
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000411 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000412
Davide Italianoebd47192017-02-12 03:31:30 +0000413 // Setup optimization remarks.
414 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000415 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000416 if (!DiagFileOrErr)
417 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000418 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000419
Davide Italiano20a895c2017-02-13 14:39:51 +0000420 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000421 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000422 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
423 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000424 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000426 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000427 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000428 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000429 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000430 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000431 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000432 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433}
434
George Rimareaf51722018-01-29 08:03:30 +0000435static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
436 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000437 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000438 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000439 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000440 if (!Index.isGlobalValueLive(GVS)) {
441 DeadGVs.push_back(&GV);
442 convertToDeclaration(GV);
443 }
George Rimar76c5fae2018-02-02 12:17:33 +0000444
Teresa Johnson791c98e2018-02-06 00:43:39 +0000445 // Now that all dead bodies have been dropped, delete the actual objects
446 // themselves when possible.
447 for (GlobalValue *GV : DeadGVs) {
448 GV->removeDeadConstantUsers();
449 // Might reference something defined in native object (i.e. dropped a
450 // non-prevailing IR def, but we need to keep the declaration).
451 if (GV->use_empty())
452 GV->eraseFromParent();
453 }
George Rimareaf51722018-01-29 08:03:30 +0000454}
455
Peter Collingbourne80186a52016-09-23 21:33:43 +0000456Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000457 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000458 const FunctionImporter::ImportMapTy &ImportList,
459 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000460 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000461 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462 if (!TOrErr)
463 return TOrErr.takeError();
464
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000465 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000466
Teresa Johnson85cc2982018-05-03 20:24:12 +0000467 // Setup optimization remarks.
468 auto DiagFileOrErr = lto::setupOptimizationRemarks(
469 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
470 if (!DiagFileOrErr)
471 return DiagFileOrErr.takeError();
472 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
473
Mehdi Aminid310b472016-08-22 06:25:41 +0000474 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000475 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000476 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000477 }
478
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000479 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000480 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000481
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000482 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000483
George Rimareaf51722018-01-29 08:03:30 +0000484 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
485
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000486 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
487
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000488 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000489 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490
491 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000492 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000494 if (Conf.PostInternalizeModuleHook &&
495 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000496 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000497
498 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000499 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000500 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000501 auto I = ModuleMap.find(Identifier);
502 assert(I != ModuleMap.end());
503 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000504 /*ShouldLazyLoadMetadata=*/true,
505 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000506 };
507
508 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000509 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
510 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000511
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000512 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000513 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000514
Peter Collingbournef7691d82017-03-22 18:22:59 +0000515 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
516 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000517 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518
Peter Collingbourne80186a52016-09-23 21:33:43 +0000519 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000520 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521}