blob: 6367aac11f371078cb6324ee1abef9300e549108 [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,
147 unsigned OptLevel, bool IsThinLTO) {
148 Optional<PGOOptions> PGOOpt;
149 if (!Conf.SampleProfile.empty())
150 PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
151
152 PassBuilder PB(TM, PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000153 AAManager AA;
154
155 // Parse a custom AA pipeline if asked to.
Dehao Chen3246dc32017-08-02 03:03:19 +0000156 if (!PB.parseAAPipeline(AA, "default"))
157 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000158
Dehao Chen3246dc32017-08-02 03:03:19 +0000159 LoopAnalysisManager LAM(Conf.DebugPassManager);
160 FunctionAnalysisManager FAM(Conf.DebugPassManager);
161 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
162 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000163
164 // Register the AA manager first so that our version is the one used.
165 FAM.registerPass([&] { return std::move(AA); });
166
167 // Register all the basic analyses with the managers.
168 PB.registerModuleAnalyses(MAM);
169 PB.registerCGSCCAnalyses(CGAM);
170 PB.registerFunctionAnalyses(FAM);
171 PB.registerLoopAnalyses(LAM);
172 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
173
Dehao Chen3246dc32017-08-02 03:03:19 +0000174 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000175 // FIXME (davide): verify the input.
176
177 PassBuilder::OptimizationLevel OL;
178
179 switch (OptLevel) {
180 default:
181 llvm_unreachable("Invalid optimization level");
182 case 0:
183 OL = PassBuilder::O0;
184 break;
185 case 1:
186 OL = PassBuilder::O1;
187 break;
188 case 2:
189 OL = PassBuilder::O2;
190 break;
191 case 3:
192 OL = PassBuilder::O3;
193 break;
194 }
195
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000196 if (IsThinLTO)
Dehao Chen3246dc32017-08-02 03:03:19 +0000197 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000198 else
Dehao Chen3246dc32017-08-02 03:03:19 +0000199 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000200 MPM.run(Mod, MAM);
201
202 // FIXME (davide): verify the output.
203}
204
Davide Italianoec9612d2016-09-07 17:46:16 +0000205static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
206 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000207 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000208 bool DisableVerify) {
209 PassBuilder PB(TM);
210 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000211
212 // Parse a custom AA pipeline if asked to.
213 if (!AAPipelineDesc.empty())
214 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
215 report_fatal_error("unable to parse AA pipeline description: " +
216 AAPipelineDesc);
217
Davide Italianoec9612d2016-09-07 17:46:16 +0000218 LoopAnalysisManager LAM;
219 FunctionAnalysisManager FAM;
220 CGSCCAnalysisManager CGAM;
221 ModuleAnalysisManager MAM;
222
223 // Register the AA manager first so that our version is the one used.
224 FAM.registerPass([&] { return std::move(AA); });
225
226 // Register all the basic analyses with the managers.
227 PB.registerModuleAnalyses(MAM);
228 PB.registerCGSCCAnalyses(CGAM);
229 PB.registerFunctionAnalyses(FAM);
230 PB.registerLoopAnalyses(LAM);
231 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
232
233 ModulePassManager MPM;
234
235 // Always verify the input.
236 MPM.addPass(VerifierPass());
237
238 // Now, add all the passes we've been requested to.
239 if (!PB.parsePassPipeline(MPM, PipelineDesc))
240 report_fatal_error("unable to parse pass pipeline description: " +
241 PipelineDesc);
242
243 if (!DisableVerify)
244 MPM.addPass(VerifierPass());
245 MPM.run(Mod, MAM);
246}
247
Davide Italiano24c29b12016-09-07 01:08:31 +0000248static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000249 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
250 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000251 legacy::PassManager passes;
252 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
253
254 PassManagerBuilder PMB;
255 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
256 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000257 PMB.ExportSummary = ExportSummary;
258 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000259 // Unconditionally verify input since it is not verified before this
260 // point and has unknown origin.
261 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000262 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000263 PMB.LoopVectorize = true;
264 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000265 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000266 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000267 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000268 PMB.populateThinLTOPassManager(passes);
269 else
270 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000271 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000272}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273
Davide Italiano24c29b12016-09-07 01:08:31 +0000274bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000275 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
276 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000277 // FIXME: Plumb the combined index into the new pass manager.
278 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000279 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
280 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000281 else if (Conf.UseNewPM)
Dehao Chen89d32262017-08-02 01:28:31 +0000282 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000283 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000284 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000285 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000286}
287
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000288void codegenWithSplitDwarf(Config &Conf, TargetMachine *TM,
289 AddStreamFn AddStream, unsigned Task, Module &Mod) {
290 SmallString<128> TempFile;
291 int FD = -1;
292 if (auto EC =
293 sys::fs::createTemporaryFile("lto-llvm-fission", "o", FD, TempFile))
294 report_fatal_error("Could not create temporary file " +
295 TempFile.str() + ": " + EC.message());
296 llvm::raw_fd_ostream OS(FD, true);
297 SmallString<1024> DwarfFile(Conf.DwoDir);
298 std::string DwoName = sys::path::filename(Mod.getModuleIdentifier()).str() +
299 "-" + std::to_string(Task) + "-";
300 size_t index = TempFile.str().rfind("lto-llvm-fission");
301 StringRef TempID = TempFile.str().substr(index + 17, 6);
302 DwoName += TempID.str() + ".dwo";
303 sys::path::append(DwarfFile, DwoName);
304 TM->Options.MCOptions.SplitDwarfFile = DwarfFile.str().str();
305
306 legacy::PassManager CodeGenPasses;
307 if (TM->addPassesToEmitFile(CodeGenPasses, OS, Conf.CGFileType))
308 report_fatal_error("Failed to setup codegen");
309 CodeGenPasses.run(Mod);
310
311 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
312 report_fatal_error("Failed to create directory " +
313 Conf.DwoDir + ": " + EC.message());
314
315 SmallVector<const char*, 5> ExtractArgs, StripArgs;
316 ExtractArgs.push_back(Conf.Objcopy.c_str());
317 ExtractArgs.push_back("--extract-dwo");
318 ExtractArgs.push_back(TempFile.c_str());
319 ExtractArgs.push_back(TM->Options.MCOptions.SplitDwarfFile.c_str());
320 ExtractArgs.push_back(nullptr);
321 StripArgs.push_back(Conf.Objcopy.c_str());
322 StripArgs.push_back("--strip-dwo");
323 StripArgs.push_back(TempFile.c_str());
324 StripArgs.push_back(nullptr);
325
326 if (auto Ret = sys::ExecuteAndWait(Conf.Objcopy, ExtractArgs.data())) {
327 report_fatal_error("Failed to extract dwo from " + TempFile.str() +
328 ". Exit code " + std::to_string(Ret));
329 }
330 if (auto Ret = sys::ExecuteAndWait(Conf.Objcopy, StripArgs.data())) {
331 report_fatal_error("Failed to strip dwo from " + TempFile.str() +
332 ". Exit code " + std::to_string(Ret));
333 }
334
335 auto Stream = AddStream(Task);
336 auto Buffer = MemoryBuffer::getFile(TempFile);
337 if (auto EC = Buffer.getError())
338 report_fatal_error("Failed to load file " +
339 TempFile.str() + ": " + EC.message());
340 *Stream->OS << Buffer.get()->getBuffer();
341 if (auto EC = sys::fs::remove(TempFile))
342 report_fatal_error("Failed to delete file " +
343 TempFile.str() + ": " + EC.message());
344}
345
Peter Collingbourne80186a52016-09-23 21:33:43 +0000346void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000347 unsigned Task, Module &Mod) {
348 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 return;
350
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000351 if (!Conf.DwoDir.empty()) {
352 codegenWithSplitDwarf(Conf, TM, AddStream, Task, Mod);
353 return;
354 }
355
Peter Collingbourne80186a52016-09-23 21:33:43 +0000356 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000358 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000360 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361}
362
Peter Collingbourne80186a52016-09-23 21:33:43 +0000363void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000365 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000366 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
367 unsigned ThreadCount = 0;
368 const Target *T = &TM->getTarget();
369
370 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000371 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372 [&](std::unique_ptr<Module> MPart) {
373 // We want to clone the module in a new context to multi-thread the
374 // codegen. We do it by serializing partition modules to bitcode
375 // (while still on the main thread, in order to avoid data races) and
376 // spinning up new threads which deserialize the partitions into
377 // separate contexts.
378 // FIXME: Provide a more direct way to do this in LLVM.
379 SmallString<0> BC;
380 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000381 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000382
383 // Enqueue the task
384 CodegenThreadPool.async(
385 [&](const SmallString<0> &BC, unsigned ThreadId) {
386 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000387 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000388 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
389 Ctx);
390 if (!MOrErr)
391 report_fatal_error("Failed to read bitcode");
392 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
393
394 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000395 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000396
Peter Collingbourne80186a52016-09-23 21:33:43 +0000397 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000398 },
399 // Pass BC using std::move to ensure that it get moved rather than
400 // copied into the thread's context.
401 std::move(BC), ThreadCount++);
402 },
403 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000404
405 // Because the inner lambda (which runs in a worker thread) captures our local
406 // variables, we need to wait for the worker threads to terminate before we
407 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000408 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409}
410
Davide Italiano24c29b12016-09-07 01:08:31 +0000411Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000412 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000413 Mod.setTargetTriple(C.OverrideTriple);
414 else if (Mod.getTargetTriple().empty())
415 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416
417 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000418 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419 if (!T)
420 return make_error<StringError>(Msg, inconvertibleErrorCode());
421 return T;
422}
423
424}
425
Teresa Johnson85cc2982018-05-03 20:24:12 +0000426static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000427finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000428 // Make sure we flush the diagnostic remarks file in case the linker doesn't
429 // call the global destructors before exiting.
430 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000431 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000432 DiagOutputFile->keep();
433 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000434 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000435}
436
Peter Collingbourne80186a52016-09-23 21:33:43 +0000437Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000438 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000439 std::unique_ptr<Module> Mod,
440 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000441 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000442 if (!TOrErr)
443 return TOrErr.takeError();
444
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000445 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446
Davide Italianoebd47192017-02-12 03:31:30 +0000447 // Setup optimization remarks.
448 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000449 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000450 if (!DiagFileOrErr)
451 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000452 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000453
Davide Italiano20a895c2017-02-13 14:39:51 +0000454 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000455 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000456 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
457 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000458 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000460 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000461 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000462 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000463 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000464 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000465 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000466 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000467}
468
George Rimareaf51722018-01-29 08:03:30 +0000469static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
470 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000471 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000472 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000473 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000474 if (!Index.isGlobalValueLive(GVS)) {
475 DeadGVs.push_back(&GV);
476 convertToDeclaration(GV);
477 }
George Rimar76c5fae2018-02-02 12:17:33 +0000478
Teresa Johnson791c98e2018-02-06 00:43:39 +0000479 // Now that all dead bodies have been dropped, delete the actual objects
480 // themselves when possible.
481 for (GlobalValue *GV : DeadGVs) {
482 GV->removeDeadConstantUsers();
483 // Might reference something defined in native object (i.e. dropped a
484 // non-prevailing IR def, but we need to keep the declaration).
485 if (GV->use_empty())
486 GV->eraseFromParent();
487 }
George Rimareaf51722018-01-29 08:03:30 +0000488}
489
Peter Collingbourne80186a52016-09-23 21:33:43 +0000490Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000491 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 const FunctionImporter::ImportMapTy &ImportList,
493 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000494 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000495 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496 if (!TOrErr)
497 return TOrErr.takeError();
498
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000499 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000500
Teresa Johnson85cc2982018-05-03 20:24:12 +0000501 // Setup optimization remarks.
502 auto DiagFileOrErr = lto::setupOptimizationRemarks(
503 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
504 if (!DiagFileOrErr)
505 return DiagFileOrErr.takeError();
506 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
507
Mehdi Aminid310b472016-08-22 06:25:41 +0000508 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000509 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000510 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000511 }
512
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000513 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000514 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000516 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517
George Rimareaf51722018-01-29 08:03:30 +0000518 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
519
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000520 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
521
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000522 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000523 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524
525 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000526 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000528 if (Conf.PostInternalizeModuleHook &&
529 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000530 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000531
532 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000533 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000534 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000535 auto I = ModuleMap.find(Identifier);
536 assert(I != ModuleMap.end());
537 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000538 /*ShouldLazyLoadMetadata=*/true,
539 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000540 };
541
542 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000543 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
544 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000545
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000546 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000547 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000548
Peter Collingbournef7691d82017-03-22 18:22:59 +0000549 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
550 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000551 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000552
Peter Collingbourne80186a52016-09-23 21:33:43 +0000553 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000554 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000555}