blob: 0ead398994131d3351af13afdda5f226d515cb33 [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
Peter Collingbourne80186a52016-09-23 21:33:43 +0000288void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000289 unsigned Task, Module &Mod) {
290 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000291 return;
292
Peter Collingbournec5a97652018-05-21 20:26:49 +0000293 std::unique_ptr<ToolOutputFile> DwoOut;
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000294 SmallString<1024> DwoFile(Conf.DwoPath);
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000295 if (!Conf.DwoDir.empty()) {
Peter Collingbournec5a97652018-05-21 20:26:49 +0000296 std::error_code EC;
297 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
298 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
299 EC.message());
300
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000301 DwoFile = Conf.DwoDir;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000302 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
Peter Collingbourne3aa30e82018-05-31 18:25:59 +0000303 }
304
305 if (!DwoFile.empty()) {
306 std::error_code EC;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000307 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
Peter Collingbourne274c4f72018-05-21 20:56:28 +0000308 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000309 if (EC)
310 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000311 }
312
Peter Collingbourne80186a52016-09-23 21:33:43 +0000313 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000314 legacy::PassManager CodeGenPasses;
Peter Collingbournec5a97652018-05-21 20:26:49 +0000315 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
316 DwoOut ? &DwoOut->os() : nullptr,
Peter Collingbourne9a451142018-05-21 20:16:41 +0000317 Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000319 CodeGenPasses.run(Mod);
Peter Collingbournec5a97652018-05-21 20:26:49 +0000320
321 if (DwoOut)
322 DwoOut->keep();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000323}
324
Peter Collingbourne80186a52016-09-23 21:33:43 +0000325void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000326 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000327 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000328 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
329 unsigned ThreadCount = 0;
330 const Target *T = &TM->getTarget();
331
332 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000333 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000334 [&](std::unique_ptr<Module> MPart) {
335 // We want to clone the module in a new context to multi-thread the
336 // codegen. We do it by serializing partition modules to bitcode
337 // (while still on the main thread, in order to avoid data races) and
338 // spinning up new threads which deserialize the partitions into
339 // separate contexts.
340 // FIXME: Provide a more direct way to do this in LLVM.
341 SmallString<0> BC;
342 raw_svector_ostream BCOS(BC);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000343 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000344
345 // Enqueue the task
346 CodegenThreadPool.async(
347 [&](const SmallString<0> &BC, unsigned ThreadId) {
348 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000349 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
351 Ctx);
352 if (!MOrErr)
353 report_fatal_error("Failed to read bitcode");
354 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
355
356 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000357 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000358
Peter Collingbourne80186a52016-09-23 21:33:43 +0000359 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000360 },
361 // Pass BC using std::move to ensure that it get moved rather than
362 // copied into the thread's context.
363 std::move(BC), ThreadCount++);
364 },
365 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000366
367 // Because the inner lambda (which runs in a worker thread) captures our local
368 // variables, we need to wait for the worker threads to terminate before we
369 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000370 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371}
372
Davide Italiano24c29b12016-09-07 01:08:31 +0000373Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000375 Mod.setTargetTriple(C.OverrideTriple);
376 else if (Mod.getTargetTriple().empty())
377 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000378
379 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000380 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000381 if (!T)
382 return make_error<StringError>(Msg, inconvertibleErrorCode());
383 return T;
384}
385
386}
387
Teresa Johnson85cc2982018-05-03 20:24:12 +0000388static Error
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000389finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000390 // Make sure we flush the diagnostic remarks file in case the linker doesn't
391 // call the global destructors before exiting.
392 if (!DiagOutputFile)
Teresa Johnson85cc2982018-05-03 20:24:12 +0000393 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000394 DiagOutputFile->keep();
395 DiagOutputFile->os().flush();
Teresa Johnson85cc2982018-05-03 20:24:12 +0000396 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000397}
398
Peter Collingbourne80186a52016-09-23 21:33:43 +0000399Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000401 std::unique_ptr<Module> Mod,
402 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000403 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000404 if (!TOrErr)
405 return TOrErr.takeError();
406
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000407 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408
Davide Italianoebd47192017-02-12 03:31:30 +0000409 // Setup optimization remarks.
410 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000411 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italianoebd47192017-02-12 03:31:30 +0000412 if (!DiagFileOrErr)
413 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000414 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000415
Davide Italiano20a895c2017-02-13 14:39:51 +0000416 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000417 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson85cc2982018-05-03 20:24:12 +0000418 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
419 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano20a895c2017-02-13 14:39:51 +0000420 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000421
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000422 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000423 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000424 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000425 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000426 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000427 }
Teresa Johnson85cc2982018-05-03 20:24:12 +0000428 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000429}
430
George Rimareaf51722018-01-29 08:03:30 +0000431static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
432 const ModuleSummaryIndex &Index) {
Teresa Johnson791c98e2018-02-06 00:43:39 +0000433 std::vector<GlobalValue*> DeadGVs;
Teresa Johnson5a95c472018-02-05 15:44:27 +0000434 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000435 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson791c98e2018-02-06 00:43:39 +0000436 if (!Index.isGlobalValueLive(GVS)) {
437 DeadGVs.push_back(&GV);
438 convertToDeclaration(GV);
439 }
George Rimar76c5fae2018-02-02 12:17:33 +0000440
Teresa Johnson791c98e2018-02-06 00:43:39 +0000441 // Now that all dead bodies have been dropped, delete the actual objects
442 // themselves when possible.
443 for (GlobalValue *GV : DeadGVs) {
444 GV->removeDeadConstantUsers();
445 // Might reference something defined in native object (i.e. dropped a
446 // non-prevailing IR def, but we need to keep the declaration).
447 if (GV->use_empty())
448 GV->eraseFromParent();
449 }
George Rimareaf51722018-01-29 08:03:30 +0000450}
451
Peter Collingbourne80186a52016-09-23 21:33:43 +0000452Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000453 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000454 const FunctionImporter::ImportMapTy &ImportList,
455 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000456 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000457 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000458 if (!TOrErr)
459 return TOrErr.takeError();
460
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000461 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462
Teresa Johnson85cc2982018-05-03 20:24:12 +0000463 // Setup optimization remarks.
464 auto DiagFileOrErr = lto::setupOptimizationRemarks(
465 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
466 if (!DiagFileOrErr)
467 return DiagFileOrErr.takeError();
468 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
469
Mehdi Aminid310b472016-08-22 06:25:41 +0000470 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000471 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000472 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Aminid310b472016-08-22 06:25:41 +0000473 }
474
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000475 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000476 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000477
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000478 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000479
George Rimareaf51722018-01-29 08:03:30 +0000480 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
481
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000482 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
483
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000484 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000485 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000486
487 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000488 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000489
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000490 if (Conf.PostInternalizeModuleHook &&
491 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000492 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493
494 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000495 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000496 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000497 auto I = ModuleMap.find(Identifier);
498 assert(I != ModuleMap.end());
499 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000500 /*ShouldLazyLoadMetadata=*/true,
501 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000502 };
503
504 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000505 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
506 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000507
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000508 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000509 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000510
Peter Collingbournef7691d82017-03-22 18:22:59 +0000511 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
512 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson85cc2982018-05-03 20:24:12 +0000513 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000514
Peter Collingbourne80186a52016-09-23 21:33:43 +0000515 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson85cc2982018-05-03 20:24:12 +0000516 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517}