blob: e55da169962c0c8bfbb78fbc8ae1cbfb972a5d3e [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) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000079 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000080 } else
81 PathPrefix = M.getModuleIdentifier();
82 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
83 std::error_code EC;
84 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000085 // Because -save-temps is a debugging feature, we report the error
86 // directly and exit.
87 if (EC)
88 reportOpenError(Path, EC.message());
Rafael Espindola6a86e252018-02-14 19:11:32 +000089 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000090 return true;
91 };
92 };
93
94 setHook("0.preopt", PreOptModuleHook);
95 setHook("1.promote", PostPromoteModuleHook);
96 setHook("2.internalize", PostInternalizeModuleHook);
97 setHook("3.import", PostImportModuleHook);
98 setHook("4.opt", PostOptModuleHook);
99 setHook("5.precodegen", PreCodeGenModuleHook);
100
101 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +0000102 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000103 std::error_code EC;
104 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000105 // Because -save-temps is a debugging feature, we report the error
106 // directly and exit.
107 if (EC)
108 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000109 WriteIndexToFile(Index, OS);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000110
111 Path = OutputFileName + "index.dot";
112 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
113 if (EC)
114 reportOpenError(Path, EC.message());
115 Index.exportToDot(OSDot);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000116 return true;
117 };
118
Mehdi Amini41af4302016-11-11 04:28:40 +0000119 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000120}
121
122namespace {
123
124std::unique_ptr<TargetMachine>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000125createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
126 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000127 SubtargetFeatures Features;
128 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000129 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000130 Features.AddFeature(A);
131
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000132 Reloc::Model RelocModel;
133 if (Conf.RelocModel)
134 RelocModel = *Conf.RelocModel;
135 else
136 RelocModel =
137 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
138
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000139 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000140 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000141 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000142}
143
Dehao Chen89d32262017-08-02 01:28:31 +0000144static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
145 unsigned OptLevel, bool IsThinLTO) {
146 Optional<PGOOptions> PGOOpt;
147 if (!Conf.SampleProfile.empty())
148 PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
149
150 PassBuilder PB(TM, PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000151 AAManager AA;
152
153 // Parse a custom AA pipeline if asked to.
Dehao Chen3246dc32017-08-02 03:03:19 +0000154 if (!PB.parseAAPipeline(AA, "default"))
155 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000156
Dehao Chen3246dc32017-08-02 03:03:19 +0000157 LoopAnalysisManager LAM(Conf.DebugPassManager);
158 FunctionAnalysisManager FAM(Conf.DebugPassManager);
159 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
160 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000161
162 // Register the AA manager first so that our version is the one used.
163 FAM.registerPass([&] { return std::move(AA); });
164
165 // Register all the basic analyses with the managers.
166 PB.registerModuleAnalyses(MAM);
167 PB.registerCGSCCAnalyses(CGAM);
168 PB.registerFunctionAnalyses(FAM);
169 PB.registerLoopAnalyses(LAM);
170 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
171
Dehao Chen3246dc32017-08-02 03:03:19 +0000172 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000173 // FIXME (davide): verify the input.
174
175 PassBuilder::OptimizationLevel OL;
176
177 switch (OptLevel) {
178 default:
179 llvm_unreachable("Invalid optimization level");
180 case 0:
181 OL = PassBuilder::O0;
182 break;
183 case 1:
184 OL = PassBuilder::O1;
185 break;
186 case 2:
187 OL = PassBuilder::O2;
188 break;
189 case 3:
190 OL = PassBuilder::O3;
191 break;
192 }
193
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000194 if (IsThinLTO)
Dehao Chen3246dc32017-08-02 03:03:19 +0000195 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000196 else
Dehao Chen3246dc32017-08-02 03:03:19 +0000197 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000198 MPM.run(Mod, MAM);
199
200 // FIXME (davide): verify the output.
201}
202
Davide Italianoec9612d2016-09-07 17:46:16 +0000203static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
204 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000205 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000206 bool DisableVerify) {
207 PassBuilder PB(TM);
208 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000209
210 // Parse a custom AA pipeline if asked to.
211 if (!AAPipelineDesc.empty())
212 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
213 report_fatal_error("unable to parse AA pipeline description: " +
214 AAPipelineDesc);
215
Davide Italianoec9612d2016-09-07 17:46:16 +0000216 LoopAnalysisManager LAM;
217 FunctionAnalysisManager FAM;
218 CGSCCAnalysisManager CGAM;
219 ModuleAnalysisManager MAM;
220
221 // Register the AA manager first so that our version is the one used.
222 FAM.registerPass([&] { return std::move(AA); });
223
224 // Register all the basic analyses with the managers.
225 PB.registerModuleAnalyses(MAM);
226 PB.registerCGSCCAnalyses(CGAM);
227 PB.registerFunctionAnalyses(FAM);
228 PB.registerLoopAnalyses(LAM);
229 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
230
231 ModulePassManager MPM;
232
233 // Always verify the input.
234 MPM.addPass(VerifierPass());
235
236 // Now, add all the passes we've been requested to.
237 if (!PB.parsePassPipeline(MPM, PipelineDesc))
238 report_fatal_error("unable to parse pass pipeline description: " +
239 PipelineDesc);
240
241 if (!DisableVerify)
242 MPM.addPass(VerifierPass());
243 MPM.run(Mod, MAM);
244}
245
Davide Italiano24c29b12016-09-07 01:08:31 +0000246static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000247 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
248 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000249 legacy::PassManager passes;
250 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
251
252 PassManagerBuilder PMB;
253 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
254 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000255 PMB.ExportSummary = ExportSummary;
256 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257 // Unconditionally verify input since it is not verified before this
258 // point and has unknown origin.
259 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000260 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000261 PMB.LoopVectorize = true;
262 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000263 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000264 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000265 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266 PMB.populateThinLTOPassManager(passes);
267 else
268 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000269 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000270}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000271
Davide Italiano24c29b12016-09-07 01:08:31 +0000272bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000273 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
274 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000275 // FIXME: Plumb the combined index into the new pass manager.
276 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000277 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
278 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000279 else if (Conf.UseNewPM)
Dehao Chen89d32262017-08-02 01:28:31 +0000280 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000281 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000282 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000283 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000284}
285
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000286void codegenWithSplitDwarf(Config &Conf, TargetMachine *TM,
287 AddStreamFn AddStream, unsigned Task, Module &Mod) {
288 SmallString<128> TempFile;
289 int FD = -1;
290 if (auto EC =
291 sys::fs::createTemporaryFile("lto-llvm-fission", "o", FD, TempFile))
292 report_fatal_error("Could not create temporary file " +
293 TempFile.str() + ": " + EC.message());
294 llvm::raw_fd_ostream OS(FD, true);
295 SmallString<1024> DwarfFile(Conf.DwoDir);
296 std::string DwoName = sys::path::filename(Mod.getModuleIdentifier()).str() +
297 "-" + std::to_string(Task) + "-";
298 size_t index = TempFile.str().rfind("lto-llvm-fission");
299 StringRef TempID = TempFile.str().substr(index + 17, 6);
300 DwoName += TempID.str() + ".dwo";
301 sys::path::append(DwarfFile, DwoName);
302 TM->Options.MCOptions.SplitDwarfFile = DwarfFile.str().str();
303
304 legacy::PassManager CodeGenPasses;
305 if (TM->addPassesToEmitFile(CodeGenPasses, OS, Conf.CGFileType))
306 report_fatal_error("Failed to setup codegen");
307 CodeGenPasses.run(Mod);
308
309 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
310 report_fatal_error("Failed to create directory " +
311 Conf.DwoDir + ": " + EC.message());
312
313 SmallVector<const char*, 5> ExtractArgs, StripArgs;
314 ExtractArgs.push_back(Conf.Objcopy.c_str());
315 ExtractArgs.push_back("--extract-dwo");
316 ExtractArgs.push_back(TempFile.c_str());
317 ExtractArgs.push_back(TM->Options.MCOptions.SplitDwarfFile.c_str());
318 ExtractArgs.push_back(nullptr);
319 StripArgs.push_back(Conf.Objcopy.c_str());
320 StripArgs.push_back("--strip-dwo");
321 StripArgs.push_back(TempFile.c_str());
322 StripArgs.push_back(nullptr);
323
324 if (auto Ret = sys::ExecuteAndWait(Conf.Objcopy, ExtractArgs.data())) {
325 report_fatal_error("Failed to extract dwo from " + TempFile.str() +
326 ". Exit code " + std::to_string(Ret));
327 }
328 if (auto Ret = sys::ExecuteAndWait(Conf.Objcopy, StripArgs.data())) {
329 report_fatal_error("Failed to strip dwo from " + TempFile.str() +
330 ". Exit code " + std::to_string(Ret));
331 }
332
333 auto Stream = AddStream(Task);
334 auto Buffer = MemoryBuffer::getFile(TempFile);
335 if (auto EC = Buffer.getError())
336 report_fatal_error("Failed to load file " +
337 TempFile.str() + ": " + EC.message());
338 *Stream->OS << Buffer.get()->getBuffer();
339 if (auto EC = sys::fs::remove(TempFile))
340 report_fatal_error("Failed to delete file " +
341 TempFile.str() + ": " + EC.message());
342}
343
Peter Collingbourne80186a52016-09-23 21:33:43 +0000344void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000345 unsigned Task, Module &Mod) {
346 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 return;
348
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000349 if (!Conf.DwoDir.empty()) {
350 codegenWithSplitDwarf(Conf, TM, AddStream, Task, Mod);
351 return;
352 }
353
Peter Collingbourne80186a52016-09-23 21:33:43 +0000354 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000356 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000358 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359}
360
Peter Collingbourne80186a52016-09-23 21:33:43 +0000361void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000362 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000363 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
365 unsigned ThreadCount = 0;
366 const Target *T = &TM->getTarget();
367
368 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000369 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000370 [&](std::unique_ptr<Module> MPart) {
371 // We want to clone the module in a new context to multi-thread the
372 // codegen. We do it by serializing partition modules to bitcode
373 // (while still on the main thread, in order to avoid data races) and
374 // spinning up new threads which deserialize the partitions into
375 // separate contexts.
376 // FIXME: Provide a more direct way to do this in LLVM.
377 SmallString<0> BC;
378 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000379 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380
381 // Enqueue the task
382 CodegenThreadPool.async(
383 [&](const SmallString<0> &BC, unsigned ThreadId) {
384 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000385 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000386 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
387 Ctx);
388 if (!MOrErr)
389 report_fatal_error("Failed to read bitcode");
390 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
391
392 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000393 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000394
Peter Collingbourne80186a52016-09-23 21:33:43 +0000395 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396 },
397 // Pass BC using std::move to ensure that it get moved rather than
398 // copied into the thread's context.
399 std::move(BC), ThreadCount++);
400 },
401 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000402
403 // Because the inner lambda (which runs in a worker thread) captures our local
404 // variables, we need to wait for the worker threads to terminate before we
405 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000406 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407}
408
Davide Italiano24c29b12016-09-07 01:08:31 +0000409Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000410 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000411 Mod.setTargetTriple(C.OverrideTriple);
412 else if (Mod.getTargetTriple().empty())
413 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414
415 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000416 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000417 if (!T)
418 return make_error<StringError>(Msg, inconvertibleErrorCode());
419 return T;
420}
421
422}
423
Teresa Johnson85cc2982018-05-03 20:24:12 +0000424static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000425finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000426 // Make sure we flush the diagnostic remarks file in case the linker doesn't
427 // call the global destructors before exiting.
428 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000429 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000430 DiagOutputFile->keep();
431 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000432 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000433}
434
Peter Collingbourne80186a52016-09-23 21:33:43 +0000435Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000436 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000437 std::unique_ptr<Module> Mod,
438 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000439 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000440 if (!TOrErr)
441 return TOrErr.takeError();
442
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000443 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444
Davide Italianoebd47192017-02-12 03:31:30 +0000445 // Setup optimization remarks.
446 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000447 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000448 if (!DiagFileOrErr)
449 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000450 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000451
Davide Italiano20a895c2017-02-13 14:39:51 +0000452 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000453 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000454 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
455 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000456 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000458 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000459 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000460 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000461 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000462 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000463 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000464 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465}
466
George Rimareaf51722018-01-29 08:03:30 +0000467static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
468 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000469 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000470 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000471 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000472 if (!Index.isGlobalValueLive(GVS)) {
473 DeadGVs.push_back(&GV);
474 convertToDeclaration(GV);
475 }
George Rimar76c5fae2018-02-02 12:17:33 +0000476
Teresa Johnson791c98e2018-02-06 00:43:39 +0000477 // Now that all dead bodies have been dropped, delete the actual objects
478 // themselves when possible.
479 for (GlobalValue *GV : DeadGVs) {
480 GV->removeDeadConstantUsers();
481 // Might reference something defined in native object (i.e. dropped a
482 // non-prevailing IR def, but we need to keep the declaration).
483 if (GV->use_empty())
484 GV->eraseFromParent();
485 }
George Rimareaf51722018-01-29 08:03:30 +0000486}
487
Peter Collingbourne80186a52016-09-23 21:33:43 +0000488Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000489 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490 const FunctionImporter::ImportMapTy &ImportList,
491 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000492 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000493 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000494 if (!TOrErr)
495 return TOrErr.takeError();
496
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000497 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000498
Teresa Johnson85cc2982018-05-03 20:24:12 +0000499 // Setup optimization remarks.
500 auto DiagFileOrErr = lto::setupOptimizationRemarks(
501 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
502 if (!DiagFileOrErr)
503 return DiagFileOrErr.takeError();
504 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
505
Mehdi Aminid310b472016-08-22 06:25:41 +0000506 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000507 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000508 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000509 }
510
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000511 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000512 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000513
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000514 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515
George Rimareaf51722018-01-29 08:03:30 +0000516 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
517
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000518 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
519
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000520 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000521 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000522
523 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000524 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000525
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000526 if (Conf.PostInternalizeModuleHook &&
527 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000528 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529
530 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000531 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000532 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000533 auto I = ModuleMap.find(Identifier);
534 assert(I != ModuleMap.end());
535 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000536 /*ShouldLazyLoadMetadata=*/true,
537 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000538 };
539
540 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000541 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
542 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000544 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000545 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000546
Peter Collingbournef7691d82017-03-22 18:22:59 +0000547 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
548 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000549 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000550
Peter Collingbourne80186a52016-09-23 21:33:43 +0000551 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000552 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000553}