blob: 395988c0ebfdbfd1e48396f4b948ee1598ab6c82 [file] [log] [blame]
Peter Collingbourne4e380b02013-09-19 22:15:52 +00001//===-- llvm-lto: a simple command-line program to link modules with LTO --===//
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 program takes in a list of bitcode files, links them, performs link-time
11// optimization, and outputs an object file.
12//
13//===----------------------------------------------------------------------===//
14
Rafael Espindola282a4702013-10-31 20:51:58 +000015#include "llvm/ADT/StringSet.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000016#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000017#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000018#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000019#include "llvm/IR/LLVMContext.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000020#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/IRReader/IRReader.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000022#include "llvm/LTO/LTOCodeGenerator.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000023#include "llvm/LTO/LTOModule.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000024#include "llvm/LTO/ThinLTOCodeGenerator.h"
25#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000026#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000027#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000028#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/PrettyStackTrace.h"
30#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000031#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000032#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000033#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000034#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000035#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000036
37using namespace llvm;
38
Peter Collingbourne070843d2015-03-19 22:01:00 +000039static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000040 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
41 "(default = '-O2')"),
42 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000043
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000044static cl::opt<bool> DisableVerify(
45 "disable-verify", cl::init(false),
46 cl::desc("Do not run the verifier during the optimization pipeline"));
47
Davide Italianob10e8932016-04-13 21:41:35 +000048static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
49 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000050
51static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000052 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
53 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000054
Davide Italianob10e8932016-04-13 21:41:35 +000055static cl::opt<bool> DisableLTOVectorization(
56 "disable-lto-vectorization", cl::init(false),
57 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000058
Davide Italianob10e8932016-04-13 21:41:35 +000059static cl::opt<bool> UseDiagnosticHandler(
60 "use-diagnostic-handler", cl::init(false),
61 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000062
Teresa Johnsonf72278f2015-11-02 18:02:11 +000063static cl::opt<bool>
64 ThinLTO("thinlto", cl::init(false),
65 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000066
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000067enum ThinLTOModes {
68 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000069 THINDISTRIBUTE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000070 THINPROMOTE,
71 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000072 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073 THINOPT,
74 THINCODEGEN,
75 THINALL
76};
77
78cl::opt<ThinLTOModes> ThinLTOMode(
79 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
80 cl::values(
81 clEnumValN(
82 THINLINK, "thinlink",
83 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000084 clEnumValN(THINDISTRIBUTE, "distributedindexes",
85 "Produces individual indexes for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000086 clEnumValN(THINPROMOTE, "promote",
87 "Perform pre-import promotion (requires -thinlto-index)."),
88 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
89 "cross-module importing (requires "
90 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +000091 clEnumValN(THININTERNALIZE, "internalize",
92 "Perform internalization driven by -exported-symbol "
93 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000094 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
95 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
96 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end"),
97 clEnumValEnd));
98
99static cl::opt<std::string>
100 ThinLTOIndex("thinlto-index",
101 cl::desc("Provide the index produced by a ThinLink, required "
102 "to perform the promotion and/or importing."));
103
Mehdi Amini03abce92016-05-05 16:33:51 +0000104static cl::opt<std::string> ThinLTOModuleId(
105 "thinlto-module-id",
106 cl::desc("For the module ID for the file to process, useful to "
107 "match what is in the index."));
108
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000109static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000110 SaveModuleFile("save-merged-module", cl::init(false),
111 cl::desc("Write merged LTO module to file before CodeGen"));
112
113static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
114 cl::desc("<input bitcode files>"));
115
116static cl::opt<std::string> OutputFilename("o", cl::init(""),
117 cl::desc("Override output filename"),
118 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000119
Mehdi Amini059464f2016-04-24 03:18:01 +0000120static cl::list<std::string> ExportedSymbols(
121 "exported-symbol",
122 cl::desc("List of symbols to export from the resulting object file"),
123 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000124
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000125static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000126 DSOSymbols("dso-symbol",
127 cl::desc("Symbol to put in the symtab in the resulting dso"),
128 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000129
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000130static cl::opt<bool> ListSymbolsOnly(
131 "list-symbols-only", cl::init(false),
132 cl::desc("Instead of running LTO, list the symbols in each IR file"));
133
Manman Ren6487ce92015-02-24 00:45:56 +0000134static cl::opt<bool> SetMergedModule(
135 "set-merged-module", cl::init(false),
136 cl::desc("Use the first input module as the merged module"));
137
Peter Collingbournec269ed52015-08-27 23:37:36 +0000138static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
139 cl::desc("Number of backend threads"));
140
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000141static cl::opt<bool> RestoreGlobalsLinkage(
142 "restore-linkage", cl::init(false),
143 cl::desc("Restore original linkage of globals prior to CodeGen"));
144
Rafael Espindola282a4702013-10-31 20:51:58 +0000145namespace {
146struct ModuleInfo {
147 std::vector<bool> CanBeHidden;
148};
149}
150
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000151static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
152 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000153 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000154 switch (Severity) {
155 case LTO_DS_NOTE:
156 errs() << "note: ";
157 break;
158 case LTO_DS_REMARK:
159 errs() << "remark: ";
160 break;
161 case LTO_DS_ERROR:
162 errs() << "error: ";
163 break;
164 case LTO_DS_WARNING:
165 errs() << "warning: ";
166 break;
167 }
168 errs() << Msg << "\n";
169}
170
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000171static std::string CurrentActivity;
Mehdi Amini354f5202015-11-19 05:52:29 +0000172static void diagnosticHandler(const DiagnosticInfo &DI) {
173 raw_ostream &OS = errs();
174 OS << "llvm-lto: ";
175 switch (DI.getSeverity()) {
176 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000177 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000178 break;
179 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000180 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000181 break;
182 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000183 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000184 break;
185 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000186 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000187 break;
188 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000189 if (!CurrentActivity.empty())
190 OS << ' ' << CurrentActivity;
191 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000192
193 DiagnosticPrinterRawOStream DP(OS);
194 DI.print(DP);
195 OS << '\n';
196
197 if (DI.getSeverity() == DS_Error)
198 exit(1);
199}
200
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000201static void diagnosticHandlerWithContext(const DiagnosticInfo &DI,
202 void *Context) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000203 diagnosticHandler(DI);
204}
205
Rafael Espindola5e128db2015-12-04 00:45:57 +0000206static void error(const Twine &Msg) {
207 errs() << "llvm-lto: " << Msg << '\n';
208 exit(1);
209}
210
211static void error(std::error_code EC, const Twine &Prefix) {
212 if (EC)
213 error(Prefix + ": " + EC.message());
214}
215
216template <typename T>
217static void error(const ErrorOr<T> &V, const Twine &Prefix) {
218 error(V.getError(), Prefix);
219}
220
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000221static void maybeVerifyModule(const Module &Mod) {
222 if (!DisableVerify && verifyModule(Mod))
223 error("Broken Module");
224}
225
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000226static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000227getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000228 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000229 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
230 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000231 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000232 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000233 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000234 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
235 Context->setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000236 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000237 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
238 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000239 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000240 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000241 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000242}
243
244/// \brief List symbols in each IR file.
245///
246/// The main point here is to provide lit-testable coverage for the LTOModule
247/// functionality that's exposed by the C API to list symbols. Moreover, this
248/// provides testing coverage for modules that have been created in their own
249/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000250static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000251 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000252 std::unique_ptr<MemoryBuffer> Buffer;
253 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000254 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000255
256 // List the symbols.
257 outs() << Filename << ":\n";
258 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
259 outs() << Module->getSymbolName(I) << "\n";
260 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000261}
262
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000263/// Create a combined index file from the input IR files and write it.
264///
265/// This is meant to enable testing of ThinLTO combined index generation,
266/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000267static void createCombinedModuleSummaryIndex() {
268 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000269 uint64_t NextModuleId = 0;
270 for (auto &Filename : InputFilenames) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000271 CurrentActivity = "loading file '" + Filename + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000272 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
273 llvm::getModuleSummaryIndexForFile(Filename, diagnosticHandler);
Mehdi Amini155da5b2016-03-19 00:17:32 +0000274 error(IndexOrErr, "error " + CurrentActivity);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000275 std::unique_ptr<ModuleSummaryIndex> Index = std::move(IndexOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000276 CurrentActivity = "";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000277 // Skip files without a module summary.
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000278 if (!Index)
279 continue;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000280 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
281 }
282 std::error_code EC;
283 assert(!OutputFilename.empty());
284 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
285 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000286 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000287 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000288 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000289}
290
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000291namespace thinlto {
292
293std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000294loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000295 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
296
Mehdi Amini385cf282016-03-26 03:35:38 +0000297 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000298 const auto &Filename = ModPath.first();
299 auto CurrentActivity = "loading file '" + Filename + "'";
300 auto InputOrErr = MemoryBuffer::getFile(Filename);
301 error(InputOrErr, "error " + CurrentActivity);
302 InputBuffers.push_back(std::move(*InputOrErr));
303 }
304 return InputBuffers;
305}
306
Teresa Johnson26ab5772016-03-15 00:04:37 +0000307std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000308 if (ThinLTOIndex.empty())
309 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
310 auto CurrentActivity = "loading file '" + ThinLTOIndex + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000311 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
312 llvm::getModuleSummaryIndexForFile(ThinLTOIndex, diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000313 error(IndexOrErr, "error " + CurrentActivity);
314 return std::move(IndexOrErr.get());
315}
316
317static std::unique_ptr<Module> loadModule(StringRef Filename,
318 LLVMContext &Ctx) {
319 SMDiagnostic Err;
320 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
321 if (!M) {
322 Err.print("llvm-lto", errs());
323 report_fatal_error("Can't load module for file " + Filename);
324 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000325 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000326
327 if (ThinLTOModuleId.getNumOccurrences()) {
328 if (InputFilenames.size() != 1)
329 report_fatal_error("Can't override the module id for multiple files");
330 M->setModuleIdentifier(ThinLTOModuleId);
331 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000332 return M;
333}
334
335static void writeModuleToFile(Module &TheModule, StringRef Filename) {
336 std::error_code EC;
337 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
338 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000339 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000340 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000341}
342
343class ThinLTOProcessing {
344public:
345 ThinLTOCodeGenerator ThinGenerator;
346
347 ThinLTOProcessing(const TargetOptions &Options) {
348 ThinGenerator.setCodePICModel(RelocModel);
349 ThinGenerator.setTargetOptions(Options);
Mehdi Amini059464f2016-04-24 03:18:01 +0000350
351 // Add all the exported symbols to the table of symbols to preserve.
352 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
353 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000354 }
355
356 void run() {
357 switch (ThinLTOMode) {
358 case THINLINK:
359 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000360 case THINDISTRIBUTE:
361 return distributedIndexes();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000362 case THINPROMOTE:
363 return promote();
364 case THINIMPORT:
365 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000366 case THININTERNALIZE:
367 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000368 case THINOPT:
369 return optimize();
370 case THINCODEGEN:
371 return codegen();
372 case THINALL:
373 return runAll();
374 }
375 }
376
377private:
378 /// Load the input files, create the combined index, and write it out.
379 void thinLink() {
380 // Perform "ThinLink": just produce the index
381 if (OutputFilename.empty())
382 report_fatal_error(
383 "OutputFilename is necessary to store the combined index.\n");
384
385 LLVMContext Ctx;
386 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
387 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
388 auto &Filename = InputFilenames[i];
389 StringRef CurrentActivity = "loading file '" + Filename + "'";
390 auto InputOrErr = MemoryBuffer::getFile(Filename);
391 error(InputOrErr, "error " + CurrentActivity);
392 InputBuffers.push_back(std::move(*InputOrErr));
393 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
394 }
395
396 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
397 std::error_code EC;
398 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
399 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000400 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000401 return;
402 }
403
Teresa Johnson84174c32016-05-10 13:48:23 +0000404 /// Load the combined index from disk, then compute and generate
405 /// individual index files suitable for ThinLTO distributed backend builds
406 /// on the files mentioned on the command line (these must match the index
407 /// content).
408 void distributedIndexes() {
409 if (InputFilenames.size() != 1 && !OutputFilename.empty())
410 report_fatal_error("Can't handle a single output filename and multiple "
411 "input files, do not provide an output filename and "
412 "the output files will be suffixed from the input "
413 "ones.");
414
415 auto Index = loadCombinedIndex();
416 for (auto &Filename : InputFilenames) {
417 // Build a map of module to the GUIDs and summary objects that should
418 // be written to its index.
419 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
420 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
421 Filename, *Index, ModuleToSummariesForIndex);
422
423 std::string OutputName = OutputFilename;
424 if (OutputName.empty()) {
425 OutputName = Filename + ".thinlto.bc";
426 }
427 std::error_code EC;
428 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
429 error(EC, "error opening the file '" + OutputName + "'");
430 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
431 }
432 }
433
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 /// Load the combined index from disk, then load every file referenced by
435 /// the index and add them to the generator, finally perform the promotion
436 /// on the files mentioned on the command line (these must match the index
437 /// content).
438 void promote() {
439 if (InputFilenames.size() != 1 && !OutputFilename.empty())
440 report_fatal_error("Can't handle a single output filename and multiple "
441 "input files, do not provide an output filename and "
442 "the output files will be suffixed from the input "
443 "ones.");
444
445 auto Index = loadCombinedIndex();
446 for (auto &Filename : InputFilenames) {
447 LLVMContext Ctx;
448 auto TheModule = loadModule(Filename, Ctx);
449
450 ThinGenerator.promote(*TheModule, *Index);
451
452 std::string OutputName = OutputFilename;
453 if (OutputName.empty()) {
454 OutputName = Filename + ".thinlto.promoted.bc";
455 }
456 writeModuleToFile(*TheModule, OutputName);
457 }
458 }
459
460 /// Load the combined index from disk, then load every file referenced by
461 /// the index and add them to the generator, then performs the promotion and
462 /// cross module importing on the files mentioned on the command line
463 /// (these must match the index content).
464 void import() {
465 if (InputFilenames.size() != 1 && !OutputFilename.empty())
466 report_fatal_error("Can't handle a single output filename and multiple "
467 "input files, do not provide an output filename and "
468 "the output files will be suffixed from the input "
469 "ones.");
470
471 auto Index = loadCombinedIndex();
472 auto InputBuffers = loadAllFilesForIndex(*Index);
473 for (auto &MemBuffer : InputBuffers)
474 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
475 MemBuffer->getBuffer());
476
477 for (auto &Filename : InputFilenames) {
478 LLVMContext Ctx;
479 auto TheModule = loadModule(Filename, Ctx);
480
481 ThinGenerator.crossModuleImport(*TheModule, *Index);
482
483 std::string OutputName = OutputFilename;
484 if (OutputName.empty()) {
485 OutputName = Filename + ".thinlto.imported.bc";
486 }
487 writeModuleToFile(*TheModule, OutputName);
488 }
489 }
490
Mehdi Amini059464f2016-04-24 03:18:01 +0000491 void internalize() {
492 if (InputFilenames.size() != 1 && !OutputFilename.empty())
493 report_fatal_error("Can't handle a single output filename and multiple "
494 "input files, do not provide an output filename and "
495 "the output files will be suffixed from the input "
496 "ones.");
497
498 if (ExportedSymbols.empty())
499 errs() << "Warning: -internalize will not perform without "
500 "-exported-symbol\n";
501
502 auto Index = loadCombinedIndex();
503 auto InputBuffers = loadAllFilesForIndex(*Index);
504 for (auto &MemBuffer : InputBuffers)
505 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
506 MemBuffer->getBuffer());
507
508 for (auto &Filename : InputFilenames) {
509 LLVMContext Ctx;
510 auto TheModule = loadModule(Filename, Ctx);
511
512 ThinGenerator.internalize(*TheModule, *Index);
513
514 std::string OutputName = OutputFilename;
515 if (OutputName.empty()) {
516 OutputName = Filename + ".thinlto.internalized.bc";
517 }
518 writeModuleToFile(*TheModule, OutputName);
519 }
520 }
521
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000522 void optimize() {
523 if (InputFilenames.size() != 1 && !OutputFilename.empty())
524 report_fatal_error("Can't handle a single output filename and multiple "
525 "input files, do not provide an output filename and "
526 "the output files will be suffixed from the input "
527 "ones.");
528 if (!ThinLTOIndex.empty())
529 errs() << "Warning: -thinlto-index ignored for optimize stage";
530
531 for (auto &Filename : InputFilenames) {
532 LLVMContext Ctx;
533 auto TheModule = loadModule(Filename, Ctx);
534
535 ThinGenerator.optimize(*TheModule);
536
537 std::string OutputName = OutputFilename;
538 if (OutputName.empty()) {
539 OutputName = Filename + ".thinlto.imported.bc";
540 }
541 writeModuleToFile(*TheModule, OutputName);
542 }
543 }
544
545 void codegen() {
546 if (InputFilenames.size() != 1 && !OutputFilename.empty())
547 report_fatal_error("Can't handle a single output filename and multiple "
548 "input files, do not provide an output filename and "
549 "the output files will be suffixed from the input "
550 "ones.");
551 if (!ThinLTOIndex.empty())
552 errs() << "Warning: -thinlto-index ignored for codegen stage";
553
554 for (auto &Filename : InputFilenames) {
555 LLVMContext Ctx;
556 auto TheModule = loadModule(Filename, Ctx);
557
558 auto Buffer = ThinGenerator.codegen(*TheModule);
559 std::string OutputName = OutputFilename;
560 if (OutputName.empty()) {
561 OutputName = Filename + ".thinlto.o";
562 }
563 if (OutputName == "-") {
564 outs() << Buffer->getBuffer();
565 return;
566 }
567
568 std::error_code EC;
569 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
570 error(EC, "error opening the file '" + OutputName + "'");
571 OS << Buffer->getBuffer();
572 }
573 }
574
575 /// Full ThinLTO process
576 void runAll() {
577 if (!OutputFilename.empty())
578 report_fatal_error("Do not provide an output filename for ThinLTO "
579 " processing, the output files will be suffixed from "
580 "the input ones.");
581
582 if (!ThinLTOIndex.empty())
583 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
584
585 LLVMContext Ctx;
586 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
587 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
588 auto &Filename = InputFilenames[i];
589 StringRef CurrentActivity = "loading file '" + Filename + "'";
590 auto InputOrErr = MemoryBuffer::getFile(Filename);
591 error(InputOrErr, "error " + CurrentActivity);
592 InputBuffers.push_back(std::move(*InputOrErr));
593 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
594 }
595
596 ThinGenerator.run();
597
598 auto &Binaries = ThinGenerator.getProducedBinaries();
599 if (Binaries.size() != InputFilenames.size())
600 report_fatal_error("Number of output objects does not match the number "
601 "of inputs");
602
603 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
604 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
605 std::error_code EC;
606 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
607 error(EC, "error opening the file '" + OutputName + "'");
608 OS << Binaries[BufID]->getBuffer();
609 }
610 }
611
612 /// Load the combined index from disk, then load every file referenced by
613};
614
615} // namespace thinlto
616
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000617int main(int argc, char **argv) {
618 // Print a stack trace if we signal out.
619 sys::PrintStackTraceOnErrorSignal();
620 PrettyStackTraceProgram X(argc, argv);
621
622 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
623 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
624
Rafael Espindola5e128db2015-12-04 00:45:57 +0000625 if (OptLevel < '0' || OptLevel > '3')
626 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000627
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000628 // Initialize the configured targets.
629 InitializeAllTargets();
630 InitializeAllTargetMCs();
631 InitializeAllAsmPrinters();
632 InitializeAllAsmParsers();
633
Rafael Espindola0b385c72013-09-30 16:39:19 +0000634 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000635 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000636
Rafael Espindola5e128db2015-12-04 00:45:57 +0000637 if (ListSymbolsOnly) {
638 listSymbols(Options);
639 return 0;
640 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000641
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000642 if (ThinLTOMode.getNumOccurrences()) {
643 if (ThinLTOMode.getNumOccurrences() > 1)
644 report_fatal_error("You can't specify more than one -thinlto-action");
645 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
646 ThinLTOProcessor.run();
647 return 0;
648 }
649
Rafael Espindola5e128db2015-12-04 00:45:57 +0000650 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000651 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000652 return 0;
653 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000654
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000655 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000656
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000657 LLVMContext Context;
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000658 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000659
660 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000661
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000662 if (UseDiagnosticHandler)
663 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
664
Peter Collingbourne44ee84e2015-08-21 22:57:17 +0000665 CodeGen.setCodePICModel(RelocModel);
James Molloy951e5292014-04-14 13:54:16 +0000666
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000667 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000668 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000669 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000670
Rafael Espindola282a4702013-10-31 20:51:58 +0000671 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
672 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
673 DSOSymbolsSet.insert(DSOSymbols[i]);
674
675 std::vector<std::string> KeptDSOSyms;
676
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000677 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000678 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
679 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
680 LTOModule::createFromFile(Context, InputFilenames[i].c_str(), Options);
681 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
682 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000683
Peter Collingbourne552174392015-08-21 19:09:42 +0000684 unsigned NumSyms = Module->getSymbolCount();
685 for (unsigned I = 0; I < NumSyms; ++I) {
686 StringRef Name = Module->getSymbolName(I);
687 if (!DSOSymbolsSet.count(Name))
688 continue;
689 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
690 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
691 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
692 KeptDSOSyms.push_back(Name);
693 }
Manman Ren6487ce92015-02-24 00:45:56 +0000694
695 // We use the first input module as the destination module when
696 // SetMergedModule is true.
697 if (SetMergedModule && i == BaseArg) {
698 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000699 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000700 } else if (!CodeGen.addModule(Module.get())) {
701 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000702 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000703 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000704 }
705
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000706 // Add all the exported symbols to the table of symbols to preserve.
707 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
708 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
709
Rafael Espindolacda29112013-10-03 18:29:09 +0000710 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000711 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
712 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000713
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000714 // Set cpu and attrs strings for the default target/subtarget.
715 CodeGen.setCpu(MCPU.c_str());
716
Peter Collingbourne070843d2015-03-19 22:01:00 +0000717 CodeGen.setOptLevel(OptLevel - '0');
718
Tom Roederfd1bc602014-04-25 21:46:51 +0000719 std::string attrs;
720 for (unsigned i = 0; i < MAttrs.size(); ++i) {
721 if (i > 0)
722 attrs.append(",");
723 attrs.append(MAttrs[i]);
724 }
725
726 if (!attrs.empty())
727 CodeGen.setAttr(attrs.c_str());
728
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000729 if (FileType.getNumOccurrences())
730 CodeGen.setFileType(FileType);
731
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000732 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000733 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000734 DisableLTOVectorization)) {
735 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000736 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000737 }
738
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000739 if (SaveModuleFile) {
740 std::string ModuleFilename = OutputFilename;
741 ModuleFilename += ".merged.bc";
742 std::string ErrMsg;
743
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000744 if (!CodeGen.writeMergedModules(ModuleFilename.c_str()))
745 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000746 }
747
Peter Collingbournec269ed52015-08-27 23:37:36 +0000748 std::list<tool_output_file> OSs;
749 std::vector<raw_pwrite_stream *> OSPtrs;
750 for (unsigned I = 0; I != Parallelism; ++I) {
751 std::string PartFilename = OutputFilename;
752 if (Parallelism != 1)
753 PartFilename += "." + utostr(I);
754 std::error_code EC;
755 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000756 if (EC)
757 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000758 OSPtrs.push_back(&OSs.back().os());
759 }
760
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000761 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000762 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000763 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000764
Peter Collingbournec269ed52015-08-27 23:37:36 +0000765 for (tool_output_file &OS : OSs)
766 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000767 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000768 if (Parallelism != 1)
769 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000770
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000771 if (SaveModuleFile)
772 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000773
Craig Toppere6cb63e2014-04-25 04:24:47 +0000774 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000775 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000776 DisableGVNLoadPRE, DisableLTOVectorization))
777 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000778 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000779
780 outs() << "Wrote native object file '" << OutputName << "'\n";
781 }
782
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000783 return 0;
784}