blob: 0595771bd008f72cd860a61c739edb0abbdbbd7a [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"
25#include "llvm/IR/Verifier.h"
Mehdi Amini970800e2016-08-17 06:23:09 +000026#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000027#include "llvm/MC/SubtargetFeature.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000028#include "llvm/Object/ModuleSymbolTable.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000029#include "llvm/Passes/PassBuilder.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include "llvm/Support/Error.h"
31#include "llvm/Support/FileSystem.h"
Yunlian Jiangbd200b92018-04-13 05:03:28 +000032#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/Program.h"
35#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000036#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/ThreadPool.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Transforms/IPO.h"
40#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000041#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000042#include "llvm/Transforms/Utils/FunctionImportUtils.h"
43#include "llvm/Transforms/Utils/SplitModule.h"
44
45using namespace llvm;
46using namespace lto;
47
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000048LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000049 errs() << "failed to open " << Path << ": " << Msg << '\n';
50 errs().flush();
51 exit(1);
52}
53
Teresa Johnson9ba95f92016-08-11 14:58:12 +000054Error Config::addSaveTemps(std::string OutputFileName,
55 bool UseInputModulePath) {
56 ShouldDiscardValueNames = false;
57
58 std::error_code EC;
59 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000060 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000061 if (EC)
62 return errorCodeToError(EC);
63
64 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
65 // Keep track of the hook provided by the linker, which also needs to run.
66 ModuleHookFn LinkerHook = Hook;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000067 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000068 // If the linker's hook returned false, we need to pass that result
69 // through.
70 if (LinkerHook && !LinkerHook(Task, M))
71 return false;
72
73 std::string PathPrefix;
74 // If this is the combined module (not a ThinLTO backend compile) or the
75 // user hasn't requested using the input module's path, emit to a file
76 // named from the provided OutputFileName with the Task ID appended.
77 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
Teresa Johnson81d92072018-05-05 14:37:20 +000078 PathPrefix = OutputFileName;
79 if (Task != (unsigned)-1)
80 PathPrefix += utostr(Task) + ".";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000081 } else
Teresa Johnson81d92072018-05-05 14:37:20 +000082 PathPrefix = M.getModuleIdentifier() + ".";
83 std::string Path = PathPrefix + PathSuffix + ".bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000084 std::error_code EC;
85 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000086 // Because -save-temps is a debugging feature, we report the error
87 // directly and exit.
88 if (EC)
89 reportOpenError(Path, EC.message());
Rafael Espindola6a86e252018-02-14 19:11:32 +000090 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000091 return true;
92 };
93 };
94
95 setHook("0.preopt", PreOptModuleHook);
96 setHook("1.promote", PostPromoteModuleHook);
97 setHook("2.internalize", PostInternalizeModuleHook);
98 setHook("3.import", PostImportModuleHook);
99 setHook("4.opt", PostOptModuleHook);
100 setHook("5.precodegen", PreCodeGenModuleHook);
101
102 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +0000103 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000104 std::error_code EC;
105 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000106 // Because -save-temps is a debugging feature, we report the error
107 // directly and exit.
108 if (EC)
109 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000110 WriteIndexToFile(Index, OS);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000111
112 Path = OutputFileName + "index.dot";
113 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
114 if (EC)
115 reportOpenError(Path, EC.message());
116 Index.exportToDot(OSDot);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000117 return true;
118 };
119
Mehdi Amini41af4302016-11-11 04:28:40 +0000120 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000121}
122
123namespace {
124
125std::unique_ptr<TargetMachine>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000126createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
127 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000128 SubtargetFeatures Features;
129 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000130 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000131 Features.AddFeature(A);
132
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000133 Reloc::Model RelocModel;
134 if (Conf.RelocModel)
135 RelocModel = *Conf.RelocModel;
136 else
137 RelocModel =
138 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
139
Caroline Tice3dea3f92018-09-21 18:41:31 +0000140 Optional<CodeModel::Model> CodeModel;
141 if (Conf.CodeModel)
142 CodeModel = *Conf.CodeModel;
143 else
144 CodeModel = M.getCodeModel();
145
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000146 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000147 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Caroline Tice3dea3f92018-09-21 18:41:31 +0000148 CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000149}
150
Dehao Chen89d32262017-08-02 01:28:31 +0000151static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Teresa Johnson28023db2018-07-19 14:51:32 +0000152 unsigned OptLevel, bool IsThinLTO,
153 ModuleSummaryIndex *ExportSummary,
154 const ModuleSummaryIndex *ImportSummary) {
Dehao Chen89d32262017-08-02 01:28:31 +0000155 Optional<PGOOptions> PGOOpt;
156 if (!Conf.SampleProfile.empty())
Rong Xudb29a3a2019-03-04 20:21:27 +0000157 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
158 PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
159 else if (Conf.RunCSIRInstr) {
160 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
161 PGOOptions::IRUse, PGOOptions::CSIRInstr);
162 } else if (!Conf.CSIRProfile.empty()) {
163 PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
164 PGOOptions::IRUse, PGOOptions::CSIRUse);
165 }
Dehao Chen89d32262017-08-02 01:28:31 +0000166
167 PassBuilder PB(TM, PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000168 AAManager AA;
169
170 // Parse a custom AA pipeline if asked to.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000171 if (auto Err = PB.parseAAPipeline(AA, "default"))
Dehao Chen3246dc32017-08-02 03:03:19 +0000172 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000173
Dehao Chen3246dc32017-08-02 03:03:19 +0000174 LoopAnalysisManager LAM(Conf.DebugPassManager);
175 FunctionAnalysisManager FAM(Conf.DebugPassManager);
176 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
177 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000178
179 // Register the AA manager first so that our version is the one used.
180 FAM.registerPass([&] { return std::move(AA); });
181
182 // Register all the basic analyses with the managers.
183 PB.registerModuleAnalyses(MAM);
184 PB.registerCGSCCAnalyses(CGAM);
185 PB.registerFunctionAnalyses(FAM);
186 PB.registerLoopAnalyses(LAM);
187 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
188
Dehao Chen3246dc32017-08-02 03:03:19 +0000189 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000190 // FIXME (davide): verify the input.
191
192 PassBuilder::OptimizationLevel OL;
193
194 switch (OptLevel) {
195 default:
196 llvm_unreachable("Invalid optimization level");
197 case 0:
198 OL = PassBuilder::O0;
199 break;
200 case 1:
201 OL = PassBuilder::O1;
202 break;
203 case 2:
204 OL = PassBuilder::O2;
205 break;
206 case 3:
207 OL = PassBuilder::O3;
208 break;
209 }
210
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000211 if (IsThinLTO)
Teresa Johnson28023db2018-07-19 14:51:32 +0000212 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
213 ImportSummary);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000214 else
Teresa Johnson28023db2018-07-19 14:51:32 +0000215 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000216 MPM.run(Mod, MAM);
217
218 // FIXME (davide): verify the output.
219}
220
Davide Italianoec9612d2016-09-07 17:46:16 +0000221static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
222 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000223 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000224 bool DisableVerify) {
225 PassBuilder PB(TM);
226 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000227
228 // Parse a custom AA pipeline if asked to.
229 if (!AAPipelineDesc.empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000230 if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
231 report_fatal_error("unable to parse AA pipeline description '" +
232 AAPipelineDesc + "': " + toString(std::move(Err)));
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000233
Davide Italianoec9612d2016-09-07 17:46:16 +0000234 LoopAnalysisManager LAM;
235 FunctionAnalysisManager FAM;
236 CGSCCAnalysisManager CGAM;
237 ModuleAnalysisManager MAM;
238
239 // Register the AA manager first so that our version is the one used.
240 FAM.registerPass([&] { return std::move(AA); });
241
242 // Register all the basic analyses with the managers.
243 PB.registerModuleAnalyses(MAM);
244 PB.registerCGSCCAnalyses(CGAM);
245 PB.registerFunctionAnalyses(FAM);
246 PB.registerLoopAnalyses(LAM);
247 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
248
249 ModulePassManager MPM;
250
251 // Always verify the input.
252 MPM.addPass(VerifierPass());
253
254 // Now, add all the passes we've been requested to.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +0000255 if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
256 report_fatal_error("unable to parse pass pipeline description '" +
257 PipelineDesc + "': " + toString(std::move(Err)));
Davide Italianoec9612d2016-09-07 17:46:16 +0000258
259 if (!DisableVerify)
260 MPM.addPass(VerifierPass());
261 MPM.run(Mod, MAM);
262}
263
Davide Italiano24c29b12016-09-07 01:08:31 +0000264static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000265 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
266 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000267 legacy::PassManager passes;
268 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
269
270 PassManagerBuilder PMB;
271 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
272 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000273 PMB.ExportSummary = ExportSummary;
274 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000275 // Unconditionally verify input since it is not verified before this
276 // point and has unknown origin.
277 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000278 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 PMB.LoopVectorize = true;
280 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000281 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000282 PMB.PGOSampleUse = Conf.SampleProfile;
Rong Xudb29a3a2019-03-04 20:21:27 +0000283 PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
284 if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
285 PMB.EnablePGOCSInstrUse = true;
286 PMB.PGOInstrUse = Conf.CSIRProfile;
287 }
Davide Italiano8812f282016-11-24 00:23:09 +0000288 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000289 PMB.populateThinLTOPassManager(passes);
290 else
291 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000292 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000293}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000294
Davide Italiano24c29b12016-09-07 01:08:31 +0000295bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000296 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
297 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000298 // FIXME: Plumb the combined index into the new pass manager.
299 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000300 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
301 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000302 else if (Conf.UseNewPM)
Teresa Johnson28023db2018-07-19 14:51:32 +0000303 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
304 ImportSummary);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000305 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000306 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000307 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000308}
309
Peter Collingbourne80186a52016-09-23 21:33:43 +0000310void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000311 unsigned Task, Module &Mod) {
312 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000313 return;
314
Peter Collingbournec5a97652018-05-21 20:26:49 +0000315 std::unique_ptr<ToolOutputFile> DwoOut;
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000316 SmallString<1024> DwoFile(Conf.DwoPath);
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000317 if (!Conf.DwoDir.empty()) {
Peter Collingbournec5a97652018-05-21 20:26:49 +0000318 std::error_code EC;
319 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
320 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
321 EC.message());
322
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000323 DwoFile = Conf.DwoDir;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000324 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000325 }
326
327 if (!DwoFile.empty()) {
328 std::error_code EC;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000329 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
Peter Collingbourne274c4f72018-05-21 20:56:28 +0000330 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000331 if (EC)
332 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000333 }
334
Peter Collingbourne80186a52016-09-23 21:33:43 +0000335 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336 legacy::PassManager CodeGenPasses;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000337 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
338 DwoOut ? &DwoOut->os() : nullptr,
Peter Collingbourne9a451142018-05-21 20:16:41 +0000339 Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000340 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000341 CodeGenPasses.run(Mod);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000342
343 if (DwoOut)
344 DwoOut->keep();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000345}
346
Peter Collingbourne80186a52016-09-23 21:33:43 +0000347void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000348 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000349 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
351 unsigned ThreadCount = 0;
352 const Target *T = &TM->getTarget();
353
354 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000355 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000356 [&](std::unique_ptr<Module> MPart) {
357 // We want to clone the module in a new context to multi-thread the
358 // codegen. We do it by serializing partition modules to bitcode
359 // (while still on the main thread, in order to avoid data races) and
360 // spinning up new threads which deserialize the partitions into
361 // separate contexts.
362 // FIXME: Provide a more direct way to do this in LLVM.
363 SmallString<0> BC;
364 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000365 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000366
367 // Enqueue the task
368 CodegenThreadPool.async(
369 [&](const SmallString<0> &BC, unsigned ThreadId) {
370 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000371 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
373 Ctx);
374 if (!MOrErr)
375 report_fatal_error("Failed to read bitcode");
376 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
377
378 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000379 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000380
Peter Collingbourne80186a52016-09-23 21:33:43 +0000381 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000382 },
383 // Pass BC using std::move to ensure that it get moved rather than
384 // copied into the thread's context.
385 std::move(BC), ThreadCount++);
386 },
387 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000388
389 // Because the inner lambda (which runs in a worker thread) captures our local
390 // variables, we need to wait for the worker threads to terminate before we
391 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000392 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000393}
394
Davide Italiano24c29b12016-09-07 01:08:31 +0000395Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000397 Mod.setTargetTriple(C.OverrideTriple);
398 else if (Mod.getTargetTriple().empty())
399 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400
401 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000402 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000403 if (!T)
404 return make_error<StringError>(Msg, inconvertibleErrorCode());
405 return T;
406}
407
408}
409
Teresa Johnson85cc2982018-05-03 20:24:12 +0000410static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000411finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000412 // Make sure we flush the diagnostic remarks file in case the linker doesn't
413 // call the global destructors before exiting.
414 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000415 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000416 DiagOutputFile->keep();
417 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000418 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000419}
420
Peter Collingbourne80186a52016-09-23 21:33:43 +0000421Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000423 std::unique_ptr<Module> Mod,
424 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000425 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000426 if (!TOrErr)
427 return TOrErr.takeError();
428
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000429 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000430
Davide Italianoebd47192017-02-12 03:31:30 +0000431 // Setup optimization remarks.
432 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000433 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000434 if (!DiagFileOrErr)
435 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000436 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000437
Davide Italiano20a895c2017-02-13 14:39:51 +0000438 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000439 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000440 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
441 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000442 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000444 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000445 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000446 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000447 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000448 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000449 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000450 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000451}
452
George Rimareaf51722018-01-29 08:03:30 +0000453static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
454 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000455 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000456 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000457 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000458 if (!Index.isGlobalValueLive(GVS)) {
459 DeadGVs.push_back(&GV);
460 convertToDeclaration(GV);
461 }
George Rimar76c5fae2018-02-02 12:17:33 +0000462
Teresa Johnson791c98e2018-02-06 00:43:39 +0000463 // Now that all dead bodies have been dropped, delete the actual objects
464 // themselves when possible.
465 for (GlobalValue *GV : DeadGVs) {
466 GV->removeDeadConstantUsers();
467 // Might reference something defined in native object (i.e. dropped a
468 // non-prevailing IR def, but we need to keep the declaration).
469 if (GV->use_empty())
470 GV->eraseFromParent();
471 }
George Rimareaf51722018-01-29 08:03:30 +0000472}
473
Peter Collingbourne80186a52016-09-23 21:33:43 +0000474Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000475 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000476 const FunctionImporter::ImportMapTy &ImportList,
477 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000478 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000479 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480 if (!TOrErr)
481 return TOrErr.takeError();
482
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000483 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000484
Teresa Johnson85cc2982018-05-03 20:24:12 +0000485 // Setup optimization remarks.
486 auto DiagFileOrErr = lto::setupOptimizationRemarks(
487 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
488 if (!DiagFileOrErr)
489 return DiagFileOrErr.takeError();
490 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
491
Mehdi Aminid310b472016-08-22 06:25:41 +0000492 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000493 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000494 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000495 }
496
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000497 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000498 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000499
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000500 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000501
George Rimareaf51722018-01-29 08:03:30 +0000502 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
503
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000504 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000505
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000506 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000507 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000508
509 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000510 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000511
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000512 if (Conf.PostInternalizeModuleHook &&
513 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000514 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515
516 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000517 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000518 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000519 auto I = ModuleMap.find(Identifier);
520 assert(I != ModuleMap.end());
521 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000522 /*ShouldLazyLoadMetadata=*/true,
523 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524 };
525
526 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000527 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
528 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000530 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000531 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532
Peter Collingbournef7691d82017-03-22 18:22:59 +0000533 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
534 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000535 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000536
Peter Collingbourne80186a52016-09-23 21:33:43 +0000537 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000538 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000539}