blob: 1879b40808ac0d6231827af2beff42c10ffb4efd [file] [log] [blame]
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Teresa Johnson9ba95f92016-08-11 14:58:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the "backend" phase of LTO, i.e. it performs
10// optimization and code generation on a loaded module. It is generally used
11// internally by the LTO class but can also be used independently, for example
12// to implement a standalone ThinLTO backend.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/LTO/LTOBackend.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000017#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/CGSCCPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000021#include "llvm/Bitcode/BitcodeReader.h"
22#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000023#include "llvm/IR/LegacyPassManager.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000024#include "llvm/IR/PassManager.h"
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +000025#include "llvm/IR/RemarkStreamer.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000026#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"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000036#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/ThreadPool.h"
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +000038#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#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>(
Fangrui Songd9b948b2019-08-05 05:43:48 +000061 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_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;
Fangrui Songd9b948b2019-08-05 05:43:48 +000086 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_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;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_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";
Fangrui Songd9b948b2019-08-05 05:43:48 +0000114 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000115 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
Caroline Tice3dea3f92018-09-21 18:41:31 +0000141 Optional<CodeModel::Model> CodeModel;
142 if (Conf.CodeModel)
143 CodeModel = *Conf.CodeModel;
144 else
145 CodeModel = M.getCodeModel();
146
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000147 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000148 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Caroline Tice3dea3f92018-09-21 18:41:31 +0000149 CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000150}
151
Dehao Chen89d32262017-08-02 01:28:31 +0000152static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Teresa Johnson28023db2018-07-19 14:51:32 +0000153 unsigned OptLevel, bool IsThinLTO,
154 ModuleSummaryIndex *ExportSummary,
155 const ModuleSummaryIndex *ImportSummary) {
Dehao Chen89d32262017-08-02 01:28:31 +0000156 Optional<PGOOptions> PGOOpt;
157 if (!Conf.SampleProfile.empty())
Rong Xudb29a3a2019-03-04 20:21:27 +0000158 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
159 PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
160 else if (Conf.RunCSIRInstr) {
161 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
162 PGOOptions::IRUse, PGOOptions::CSIRInstr);
163 } else if (!Conf.CSIRProfile.empty()) {
164 PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
165 PGOOptions::IRUse, PGOOptions::CSIRUse);
166 }
Dehao Chen89d32262017-08-02 01:28:31 +0000167
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000168 PassBuilder PB(TM, PipelineTuningOptions(), PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000169 AAManager AA;
170
171 // Parse a custom AA pipeline if asked to.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000172 if (auto Err = PB.parseAAPipeline(AA, "default"))
Dehao Chen3246dc32017-08-02 03:03:19 +0000173 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000174
Dehao Chen3246dc32017-08-02 03:03:19 +0000175 LoopAnalysisManager LAM(Conf.DebugPassManager);
176 FunctionAnalysisManager FAM(Conf.DebugPassManager);
177 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
178 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000179
180 // Register the AA manager first so that our version is the one used.
181 FAM.registerPass([&] { return std::move(AA); });
182
183 // Register all the basic analyses with the managers.
184 PB.registerModuleAnalyses(MAM);
185 PB.registerCGSCCAnalyses(CGAM);
186 PB.registerFunctionAnalyses(FAM);
187 PB.registerLoopAnalyses(LAM);
188 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
189
Dehao Chen3246dc32017-08-02 03:03:19 +0000190 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000191 // FIXME (davide): verify the input.
192
193 PassBuilder::OptimizationLevel OL;
194
195 switch (OptLevel) {
196 default:
197 llvm_unreachable("Invalid optimization level");
198 case 0:
199 OL = PassBuilder::O0;
200 break;
201 case 1:
202 OL = PassBuilder::O1;
203 break;
204 case 2:
205 OL = PassBuilder::O2;
206 break;
207 case 3:
208 OL = PassBuilder::O3;
209 break;
210 }
211
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000212 if (IsThinLTO)
Teresa Johnson28023db2018-07-19 14:51:32 +0000213 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
214 ImportSummary);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000215 else
Teresa Johnson28023db2018-07-19 14:51:32 +0000216 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000217 MPM.run(Mod, MAM);
218
219 // FIXME (davide): verify the output.
220}
221
Davide Italianoec9612d2016-09-07 17:46:16 +0000222static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
223 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000224 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000225 bool DisableVerify) {
226 PassBuilder PB(TM);
227 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000228
229 // Parse a custom AA pipeline if asked to.
230 if (!AAPipelineDesc.empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000231 if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
232 report_fatal_error("unable to parse AA pipeline description '" +
233 AAPipelineDesc + "': " + toString(std::move(Err)));
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000234
Davide Italianoec9612d2016-09-07 17:46:16 +0000235 LoopAnalysisManager LAM;
236 FunctionAnalysisManager FAM;
237 CGSCCAnalysisManager CGAM;
238 ModuleAnalysisManager MAM;
239
240 // Register the AA manager first so that our version is the one used.
241 FAM.registerPass([&] { return std::move(AA); });
242
243 // Register all the basic analyses with the managers.
244 PB.registerModuleAnalyses(MAM);
245 PB.registerCGSCCAnalyses(CGAM);
246 PB.registerFunctionAnalyses(FAM);
247 PB.registerLoopAnalyses(LAM);
248 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
249
250 ModulePassManager MPM;
251
252 // Always verify the input.
253 MPM.addPass(VerifierPass());
254
255 // Now, add all the passes we've been requested to.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000256 if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
257 report_fatal_error("unable to parse pass pipeline description '" +
258 PipelineDesc + "': " + toString(std::move(Err)));
Davide Italianoec9612d2016-09-07 17:46:16 +0000259
260 if (!DisableVerify)
261 MPM.addPass(VerifierPass());
262 MPM.run(Mod, MAM);
263}
264
Davide Italiano24c29b12016-09-07 01:08:31 +0000265static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000266 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
267 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000268 legacy::PassManager passes;
269 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
270
271 PassManagerBuilder PMB;
272 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
273 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000274 PMB.ExportSummary = ExportSummary;
275 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276 // Unconditionally verify input since it is not verified before this
277 // point and has unknown origin.
278 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000279 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000280 PMB.LoopVectorize = true;
281 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000282 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000283 PMB.PGOSampleUse = Conf.SampleProfile;
Rong Xudb29a3a2019-03-04 20:21:27 +0000284 PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
285 if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
286 PMB.EnablePGOCSInstrUse = true;
287 PMB.PGOInstrUse = Conf.CSIRProfile;
288 }
Davide Italiano8812f282016-11-24 00:23:09 +0000289 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000290 PMB.populateThinLTOPassManager(passes);
291 else
292 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000293 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000294}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000295
Davide Italiano24c29b12016-09-07 01:08:31 +0000296bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000297 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
298 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000299 // FIXME: Plumb the combined index into the new pass manager.
300 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000301 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
302 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000303 else if (Conf.UseNewPM)
Teresa Johnson28023db2018-07-19 14:51:32 +0000304 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
305 ImportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000306 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000307 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000308 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000309}
310
Peter Collingbourne80186a52016-09-23 21:33:43 +0000311void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000312 unsigned Task, Module &Mod) {
313 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000314 return;
315
Peter Collingbournec5a97652018-05-21 20:26:49 +0000316 std::unique_ptr<ToolOutputFile> DwoOut;
Aaron Pucherte1dc4952019-06-15 15:38:51 +0000317 SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000318 if (!Conf.DwoDir.empty()) {
Peter Collingbournec5a97652018-05-21 20:26:49 +0000319 std::error_code EC;
320 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
321 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
322 EC.message());
323
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000324 DwoFile = Conf.DwoDir;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000325 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
Aaron Pucherte1dc4952019-06-15 15:38:51 +0000326 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
327 } else
328 TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000329
330 if (!DwoFile.empty()) {
331 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000332 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000333 if (EC)
334 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000335 }
336
Peter Collingbourne80186a52016-09-23 21:33:43 +0000337 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000338 legacy::PassManager CodeGenPasses;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000339 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
340 DwoOut ? &DwoOut->os() : nullptr,
Peter Collingbourne9a451142018-05-21 20:16:41 +0000341 Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000342 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000343 CodeGenPasses.run(Mod);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000344
345 if (DwoOut)
346 DwoOut->keep();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347}
348
Peter Collingbourne80186a52016-09-23 21:33:43 +0000349void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000351 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000352 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
353 unsigned ThreadCount = 0;
354 const Target *T = &TM->getTarget();
355
356 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000357 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000358 [&](std::unique_ptr<Module> MPart) {
359 // We want to clone the module in a new context to multi-thread the
360 // codegen. We do it by serializing partition modules to bitcode
361 // (while still on the main thread, in order to avoid data races) and
362 // spinning up new threads which deserialize the partitions into
363 // separate contexts.
364 // FIXME: Provide a more direct way to do this in LLVM.
365 SmallString<0> BC;
366 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000367 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368
369 // Enqueue the task
370 CodegenThreadPool.async(
371 [&](const SmallString<0> &BC, unsigned ThreadId) {
372 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000373 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
375 Ctx);
376 if (!MOrErr)
377 report_fatal_error("Failed to read bitcode");
378 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
379
380 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000381 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000382
Peter Collingbourne80186a52016-09-23 21:33:43 +0000383 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000384 },
385 // Pass BC using std::move to ensure that it get moved rather than
386 // copied into the thread's context.
387 std::move(BC), ThreadCount++);
388 },
389 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000390
391 // Because the inner lambda (which runs in a worker thread) captures our local
392 // variables, we need to wait for the worker threads to terminate before we
393 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000394 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000395}
396
Davide Italiano24c29b12016-09-07 01:08:31 +0000397Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000398 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000399 Mod.setTargetTriple(C.OverrideTriple);
400 else if (Mod.getTargetTriple().empty())
401 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402
403 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000404 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405 if (!T)
406 return make_error<StringError>(Msg, inconvertibleErrorCode());
407 return T;
408}
409
410}
411
Teresa Johnson85cc2982018-05-03 20:24:12 +0000412static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000413finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000414 // Make sure we flush the diagnostic remarks file in case the linker doesn't
415 // call the global destructors before exiting.
416 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000417 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000418 DiagOutputFile->keep();
419 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000420 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000421}
422
Peter Collingbourne80186a52016-09-23 21:33:43 +0000423Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000424 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000425 std::unique_ptr<Module> Mod,
426 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000427 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000428 if (!TOrErr)
429 return TOrErr.takeError();
430
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000431 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000432
Davide Italianoebd47192017-02-12 03:31:30 +0000433 // Setup optimization remarks.
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000434 auto DiagFileOrErr = lto::setupOptimizationRemarks(
435 Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
436 C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000437 if (!DiagFileOrErr)
438 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000439 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000440
Davide Italiano20a895c2017-02-13 14:39:51 +0000441 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000442 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000443 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
444 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000445 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000447 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000448 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000449 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000450 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000451 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000452 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000453 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000454}
455
George Rimareaf51722018-01-29 08:03:30 +0000456static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
457 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000458 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000459 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000460 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000461 if (!Index.isGlobalValueLive(GVS)) {
462 DeadGVs.push_back(&GV);
463 convertToDeclaration(GV);
464 }
George Rimar76c5fae2018-02-02 12:17:33 +0000465
Teresa Johnson791c98e2018-02-06 00:43:39 +0000466 // Now that all dead bodies have been dropped, delete the actual objects
467 // themselves when possible.
468 for (GlobalValue *GV : DeadGVs) {
469 GV->removeDeadConstantUsers();
470 // Might reference something defined in native object (i.e. dropped a
471 // non-prevailing IR def, but we need to keep the declaration).
472 if (GV->use_empty())
473 GV->eraseFromParent();
474 }
George Rimareaf51722018-01-29 08:03:30 +0000475}
476
Peter Collingbourne80186a52016-09-23 21:33:43 +0000477Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000478 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000479 const FunctionImporter::ImportMapTy &ImportList,
480 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000481 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000482 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000483 if (!TOrErr)
484 return TOrErr.takeError();
485
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000486 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000487
Teresa Johnson85cc2982018-05-03 20:24:12 +0000488 // Setup optimization remarks.
489 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +0000490 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000491 Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000492 if (!DiagFileOrErr)
493 return DiagFileOrErr.takeError();
494 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
495
Mehdi Aminid310b472016-08-22 06:25:41 +0000496 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000497 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000498 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000499 }
500
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000501 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000502 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000503
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000504 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000505
George Rimareaf51722018-01-29 08:03:30 +0000506 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
507
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000508 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000509
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000510 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000511 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000512
513 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000514 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000516 if (Conf.PostInternalizeModuleHook &&
517 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000518 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519
520 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000521 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000522 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000523 auto I = ModuleMap.find(Identifier);
524 assert(I != ModuleMap.end());
525 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000526 /*ShouldLazyLoadMetadata=*/true,
527 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000528 };
529
530 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000531 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
532 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000533
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000534 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000535 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000536
Peter Collingbournef7691d82017-03-22 18:22:59 +0000537 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
538 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000539 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000540
Peter Collingbourne80186a52016-09-23 21:33:43 +0000541 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000542 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543}