blob: 655e8c8379e6e0ce2c86641bc1689d1ff7f38229 [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,
Teresa Johnson8570fe42016-05-10 15:54:09 +000070 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071 THINPROMOTE,
72 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000073 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074 THINOPT,
75 THINCODEGEN,
76 THINALL
77};
78
79cl::opt<ThinLTOModes> ThinLTOMode(
80 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
81 cl::values(
82 clEnumValN(
83 THINLINK, "thinlink",
84 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000085 clEnumValN(THINDISTRIBUTE, "distributedindexes",
86 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000087 clEnumValN(THINEMITIMPORTS, "emitimports",
88 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089 clEnumValN(THINPROMOTE, "promote",
90 "Perform pre-import promotion (requires -thinlto-index)."),
91 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
92 "cross-module importing (requires "
93 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +000094 clEnumValN(THININTERNALIZE, "internalize",
95 "Perform internalization driven by -exported-symbol "
96 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000097 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
98 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
99 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end"),
100 clEnumValEnd));
101
102static cl::opt<std::string>
103 ThinLTOIndex("thinlto-index",
104 cl::desc("Provide the index produced by a ThinLink, required "
105 "to perform the promotion and/or importing."));
106
Mehdi Amini03abce92016-05-05 16:33:51 +0000107static cl::opt<std::string> ThinLTOModuleId(
108 "thinlto-module-id",
109 cl::desc("For the module ID for the file to process, useful to "
110 "match what is in the index."));
111
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000112static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000113 SaveModuleFile("save-merged-module", cl::init(false),
114 cl::desc("Write merged LTO module to file before CodeGen"));
115
116static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
117 cl::desc("<input bitcode files>"));
118
119static cl::opt<std::string> OutputFilename("o", cl::init(""),
120 cl::desc("Override output filename"),
121 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000122
Mehdi Amini059464f2016-04-24 03:18:01 +0000123static cl::list<std::string> ExportedSymbols(
124 "exported-symbol",
125 cl::desc("List of symbols to export from the resulting object file"),
126 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000127
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000128static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000129 DSOSymbols("dso-symbol",
130 cl::desc("Symbol to put in the symtab in the resulting dso"),
131 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000132
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000133static cl::opt<bool> ListSymbolsOnly(
134 "list-symbols-only", cl::init(false),
135 cl::desc("Instead of running LTO, list the symbols in each IR file"));
136
Manman Ren6487ce92015-02-24 00:45:56 +0000137static cl::opt<bool> SetMergedModule(
138 "set-merged-module", cl::init(false),
139 cl::desc("Use the first input module as the merged module"));
140
Peter Collingbournec269ed52015-08-27 23:37:36 +0000141static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
142 cl::desc("Number of backend threads"));
143
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000144static cl::opt<bool> RestoreGlobalsLinkage(
145 "restore-linkage", cl::init(false),
146 cl::desc("Restore original linkage of globals prior to CodeGen"));
147
Rafael Espindola282a4702013-10-31 20:51:58 +0000148namespace {
149struct ModuleInfo {
150 std::vector<bool> CanBeHidden;
151};
152}
153
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000154static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
155 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000156 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000157 switch (Severity) {
158 case LTO_DS_NOTE:
159 errs() << "note: ";
160 break;
161 case LTO_DS_REMARK:
162 errs() << "remark: ";
163 break;
164 case LTO_DS_ERROR:
165 errs() << "error: ";
166 break;
167 case LTO_DS_WARNING:
168 errs() << "warning: ";
169 break;
170 }
171 errs() << Msg << "\n";
172}
173
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000174static std::string CurrentActivity;
Mehdi Amini354f5202015-11-19 05:52:29 +0000175static void diagnosticHandler(const DiagnosticInfo &DI) {
176 raw_ostream &OS = errs();
177 OS << "llvm-lto: ";
178 switch (DI.getSeverity()) {
179 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000180 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000181 break;
182 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000183 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000184 break;
185 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000186 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000187 break;
188 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000189 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000190 break;
191 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000192 if (!CurrentActivity.empty())
193 OS << ' ' << CurrentActivity;
194 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000195
196 DiagnosticPrinterRawOStream DP(OS);
197 DI.print(DP);
198 OS << '\n';
199
200 if (DI.getSeverity() == DS_Error)
201 exit(1);
202}
203
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000204static void diagnosticHandlerWithContext(const DiagnosticInfo &DI,
205 void *Context) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000206 diagnosticHandler(DI);
207}
208
Rafael Espindola5e128db2015-12-04 00:45:57 +0000209static void error(const Twine &Msg) {
210 errs() << "llvm-lto: " << Msg << '\n';
211 exit(1);
212}
213
214static void error(std::error_code EC, const Twine &Prefix) {
215 if (EC)
216 error(Prefix + ": " + EC.message());
217}
218
219template <typename T>
220static void error(const ErrorOr<T> &V, const Twine &Prefix) {
221 error(V.getError(), Prefix);
222}
223
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000224static void maybeVerifyModule(const Module &Mod) {
225 if (!DisableVerify && verifyModule(Mod))
226 error("Broken Module");
227}
228
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000229static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000230getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000231 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000232 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
233 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000234 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000235 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000236 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000237 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
238 Context->setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000239 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000240 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
241 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000242 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000243 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000244 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000245}
246
247/// \brief List symbols in each IR file.
248///
249/// The main point here is to provide lit-testable coverage for the LTOModule
250/// functionality that's exposed by the C API to list symbols. Moreover, this
251/// provides testing coverage for modules that have been created in their own
252/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000253static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000254 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000255 std::unique_ptr<MemoryBuffer> Buffer;
256 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000257 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000258
259 // List the symbols.
260 outs() << Filename << ":\n";
261 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
262 outs() << Module->getSymbolName(I) << "\n";
263 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000264}
265
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000266/// Create a combined index file from the input IR files and write it.
267///
268/// This is meant to enable testing of ThinLTO combined index generation,
269/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000270static void createCombinedModuleSummaryIndex() {
271 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000272 uint64_t NextModuleId = 0;
273 for (auto &Filename : InputFilenames) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000274 CurrentActivity = "loading file '" + Filename + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000275 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
276 llvm::getModuleSummaryIndexForFile(Filename, diagnosticHandler);
Mehdi Amini155da5b2016-03-19 00:17:32 +0000277 error(IndexOrErr, "error " + CurrentActivity);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000278 std::unique_ptr<ModuleSummaryIndex> Index = std::move(IndexOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000279 CurrentActivity = "";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000280 // Skip files without a module summary.
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000281 if (!Index)
282 continue;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000283 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
284 }
285 std::error_code EC;
286 assert(!OutputFilename.empty());
287 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
288 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000289 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000290 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000291 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000292}
293
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000294namespace thinlto {
295
296std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000297loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000298 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
299
Mehdi Amini385cf282016-03-26 03:35:38 +0000300 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000301 const auto &Filename = ModPath.first();
302 auto CurrentActivity = "loading file '" + Filename + "'";
303 auto InputOrErr = MemoryBuffer::getFile(Filename);
304 error(InputOrErr, "error " + CurrentActivity);
305 InputBuffers.push_back(std::move(*InputOrErr));
306 }
307 return InputBuffers;
308}
309
Teresa Johnson26ab5772016-03-15 00:04:37 +0000310std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000311 if (ThinLTOIndex.empty())
312 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
313 auto CurrentActivity = "loading file '" + ThinLTOIndex + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000314 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
315 llvm::getModuleSummaryIndexForFile(ThinLTOIndex, diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000316 error(IndexOrErr, "error " + CurrentActivity);
317 return std::move(IndexOrErr.get());
318}
319
320static std::unique_ptr<Module> loadModule(StringRef Filename,
321 LLVMContext &Ctx) {
322 SMDiagnostic Err;
323 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
324 if (!M) {
325 Err.print("llvm-lto", errs());
326 report_fatal_error("Can't load module for file " + Filename);
327 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000328 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000329
330 if (ThinLTOModuleId.getNumOccurrences()) {
331 if (InputFilenames.size() != 1)
332 report_fatal_error("Can't override the module id for multiple files");
333 M->setModuleIdentifier(ThinLTOModuleId);
334 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000335 return M;
336}
337
338static void writeModuleToFile(Module &TheModule, StringRef Filename) {
339 std::error_code EC;
340 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
341 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000342 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000343 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000344}
345
346class ThinLTOProcessing {
347public:
348 ThinLTOCodeGenerator ThinGenerator;
349
350 ThinLTOProcessing(const TargetOptions &Options) {
351 ThinGenerator.setCodePICModel(RelocModel);
352 ThinGenerator.setTargetOptions(Options);
Mehdi Amini059464f2016-04-24 03:18:01 +0000353
354 // Add all the exported symbols to the table of symbols to preserve.
355 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
356 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000357 }
358
359 void run() {
360 switch (ThinLTOMode) {
361 case THINLINK:
362 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000363 case THINDISTRIBUTE:
364 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000365 case THINEMITIMPORTS:
366 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000367 case THINPROMOTE:
368 return promote();
369 case THINIMPORT:
370 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000371 case THININTERNALIZE:
372 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000373 case THINOPT:
374 return optimize();
375 case THINCODEGEN:
376 return codegen();
377 case THINALL:
378 return runAll();
379 }
380 }
381
382private:
383 /// Load the input files, create the combined index, and write it out.
384 void thinLink() {
385 // Perform "ThinLink": just produce the index
386 if (OutputFilename.empty())
387 report_fatal_error(
388 "OutputFilename is necessary to store the combined index.\n");
389
390 LLVMContext Ctx;
391 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
392 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
393 auto &Filename = InputFilenames[i];
394 StringRef CurrentActivity = "loading file '" + Filename + "'";
395 auto InputOrErr = MemoryBuffer::getFile(Filename);
396 error(InputOrErr, "error " + CurrentActivity);
397 InputBuffers.push_back(std::move(*InputOrErr));
398 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
399 }
400
401 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
402 std::error_code EC;
403 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
404 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000405 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000406 return;
407 }
408
Teresa Johnson84174c32016-05-10 13:48:23 +0000409 /// Load the combined index from disk, then compute and generate
410 /// individual index files suitable for ThinLTO distributed backend builds
411 /// on the files mentioned on the command line (these must match the index
412 /// content).
413 void distributedIndexes() {
414 if (InputFilenames.size() != 1 && !OutputFilename.empty())
415 report_fatal_error("Can't handle a single output filename and multiple "
416 "input files, do not provide an output filename and "
417 "the output files will be suffixed from the input "
418 "ones.");
419
420 auto Index = loadCombinedIndex();
421 for (auto &Filename : InputFilenames) {
422 // Build a map of module to the GUIDs and summary objects that should
423 // be written to its index.
424 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
425 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
426 Filename, *Index, ModuleToSummariesForIndex);
427
428 std::string OutputName = OutputFilename;
429 if (OutputName.empty()) {
430 OutputName = Filename + ".thinlto.bc";
431 }
432 std::error_code EC;
433 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
434 error(EC, "error opening the file '" + OutputName + "'");
435 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
436 }
437 }
438
Teresa Johnson8570fe42016-05-10 15:54:09 +0000439 /// Load the combined index from disk, compute the imports, and emit
440 /// the import file lists for each module to disk.
441 void emitImports() {
442 if (InputFilenames.size() != 1 && !OutputFilename.empty())
443 report_fatal_error("Can't handle a single output filename and multiple "
444 "input files, do not provide an output filename and "
445 "the output files will be suffixed from the input "
446 "ones.");
447
448 auto Index = loadCombinedIndex();
449 for (auto &Filename : InputFilenames) {
450 std::string OutputName = OutputFilename;
451 if (OutputName.empty()) {
452 OutputName = Filename + ".imports";
453 }
454 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
455 }
456 }
457
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000458 /// Load the combined index from disk, then load every file referenced by
459 /// the index and add them to the generator, finally perform the promotion
460 /// on the files mentioned on the command line (these must match the index
461 /// content).
462 void promote() {
463 if (InputFilenames.size() != 1 && !OutputFilename.empty())
464 report_fatal_error("Can't handle a single output filename and multiple "
465 "input files, do not provide an output filename and "
466 "the output files will be suffixed from the input "
467 "ones.");
468
469 auto Index = loadCombinedIndex();
470 for (auto &Filename : InputFilenames) {
471 LLVMContext Ctx;
472 auto TheModule = loadModule(Filename, Ctx);
473
474 ThinGenerator.promote(*TheModule, *Index);
475
476 std::string OutputName = OutputFilename;
477 if (OutputName.empty()) {
478 OutputName = Filename + ".thinlto.promoted.bc";
479 }
480 writeModuleToFile(*TheModule, OutputName);
481 }
482 }
483
484 /// Load the combined index from disk, then load every file referenced by
485 /// the index and add them to the generator, then performs the promotion and
486 /// cross module importing on the files mentioned on the command line
487 /// (these must match the index content).
488 void import() {
489 if (InputFilenames.size() != 1 && !OutputFilename.empty())
490 report_fatal_error("Can't handle a single output filename and multiple "
491 "input files, do not provide an output filename and "
492 "the output files will be suffixed from the input "
493 "ones.");
494
495 auto Index = loadCombinedIndex();
496 auto InputBuffers = loadAllFilesForIndex(*Index);
497 for (auto &MemBuffer : InputBuffers)
498 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
499 MemBuffer->getBuffer());
500
501 for (auto &Filename : InputFilenames) {
502 LLVMContext Ctx;
503 auto TheModule = loadModule(Filename, Ctx);
504
505 ThinGenerator.crossModuleImport(*TheModule, *Index);
506
507 std::string OutputName = OutputFilename;
508 if (OutputName.empty()) {
509 OutputName = Filename + ".thinlto.imported.bc";
510 }
511 writeModuleToFile(*TheModule, OutputName);
512 }
513 }
514
Mehdi Amini059464f2016-04-24 03:18:01 +0000515 void internalize() {
516 if (InputFilenames.size() != 1 && !OutputFilename.empty())
517 report_fatal_error("Can't handle a single output filename and multiple "
518 "input files, do not provide an output filename and "
519 "the output files will be suffixed from the input "
520 "ones.");
521
522 if (ExportedSymbols.empty())
523 errs() << "Warning: -internalize will not perform without "
524 "-exported-symbol\n";
525
526 auto Index = loadCombinedIndex();
527 auto InputBuffers = loadAllFilesForIndex(*Index);
528 for (auto &MemBuffer : InputBuffers)
529 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
530 MemBuffer->getBuffer());
531
532 for (auto &Filename : InputFilenames) {
533 LLVMContext Ctx;
534 auto TheModule = loadModule(Filename, Ctx);
535
536 ThinGenerator.internalize(*TheModule, *Index);
537
538 std::string OutputName = OutputFilename;
539 if (OutputName.empty()) {
540 OutputName = Filename + ".thinlto.internalized.bc";
541 }
542 writeModuleToFile(*TheModule, OutputName);
543 }
544 }
545
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546 void optimize() {
547 if (InputFilenames.size() != 1 && !OutputFilename.empty())
548 report_fatal_error("Can't handle a single output filename and multiple "
549 "input files, do not provide an output filename and "
550 "the output files will be suffixed from the input "
551 "ones.");
552 if (!ThinLTOIndex.empty())
553 errs() << "Warning: -thinlto-index ignored for optimize stage";
554
555 for (auto &Filename : InputFilenames) {
556 LLVMContext Ctx;
557 auto TheModule = loadModule(Filename, Ctx);
558
559 ThinGenerator.optimize(*TheModule);
560
561 std::string OutputName = OutputFilename;
562 if (OutputName.empty()) {
563 OutputName = Filename + ".thinlto.imported.bc";
564 }
565 writeModuleToFile(*TheModule, OutputName);
566 }
567 }
568
569 void codegen() {
570 if (InputFilenames.size() != 1 && !OutputFilename.empty())
571 report_fatal_error("Can't handle a single output filename and multiple "
572 "input files, do not provide an output filename and "
573 "the output files will be suffixed from the input "
574 "ones.");
575 if (!ThinLTOIndex.empty())
576 errs() << "Warning: -thinlto-index ignored for codegen stage";
577
578 for (auto &Filename : InputFilenames) {
579 LLVMContext Ctx;
580 auto TheModule = loadModule(Filename, Ctx);
581
582 auto Buffer = ThinGenerator.codegen(*TheModule);
583 std::string OutputName = OutputFilename;
584 if (OutputName.empty()) {
585 OutputName = Filename + ".thinlto.o";
586 }
587 if (OutputName == "-") {
588 outs() << Buffer->getBuffer();
589 return;
590 }
591
592 std::error_code EC;
593 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
594 error(EC, "error opening the file '" + OutputName + "'");
595 OS << Buffer->getBuffer();
596 }
597 }
598
599 /// Full ThinLTO process
600 void runAll() {
601 if (!OutputFilename.empty())
602 report_fatal_error("Do not provide an output filename for ThinLTO "
603 " processing, the output files will be suffixed from "
604 "the input ones.");
605
606 if (!ThinLTOIndex.empty())
607 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
608
609 LLVMContext Ctx;
610 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
611 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
612 auto &Filename = InputFilenames[i];
613 StringRef CurrentActivity = "loading file '" + Filename + "'";
614 auto InputOrErr = MemoryBuffer::getFile(Filename);
615 error(InputOrErr, "error " + CurrentActivity);
616 InputBuffers.push_back(std::move(*InputOrErr));
617 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
618 }
619
620 ThinGenerator.run();
621
622 auto &Binaries = ThinGenerator.getProducedBinaries();
623 if (Binaries.size() != InputFilenames.size())
624 report_fatal_error("Number of output objects does not match the number "
625 "of inputs");
626
627 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
628 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
629 std::error_code EC;
630 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
631 error(EC, "error opening the file '" + OutputName + "'");
632 OS << Binaries[BufID]->getBuffer();
633 }
634 }
635
636 /// Load the combined index from disk, then load every file referenced by
637};
638
639} // namespace thinlto
640
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000641int main(int argc, char **argv) {
642 // Print a stack trace if we signal out.
643 sys::PrintStackTraceOnErrorSignal();
644 PrettyStackTraceProgram X(argc, argv);
645
646 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
647 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
648
Rafael Espindola5e128db2015-12-04 00:45:57 +0000649 if (OptLevel < '0' || OptLevel > '3')
650 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000651
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000652 // Initialize the configured targets.
653 InitializeAllTargets();
654 InitializeAllTargetMCs();
655 InitializeAllAsmPrinters();
656 InitializeAllAsmParsers();
657
Rafael Espindola0b385c72013-09-30 16:39:19 +0000658 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000659 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000660
Rafael Espindola5e128db2015-12-04 00:45:57 +0000661 if (ListSymbolsOnly) {
662 listSymbols(Options);
663 return 0;
664 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000665
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000666 if (ThinLTOMode.getNumOccurrences()) {
667 if (ThinLTOMode.getNumOccurrences() > 1)
668 report_fatal_error("You can't specify more than one -thinlto-action");
669 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
670 ThinLTOProcessor.run();
671 return 0;
672 }
673
Rafael Espindola5e128db2015-12-04 00:45:57 +0000674 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000675 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000676 return 0;
677 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000678
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000679 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000680
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000681 LLVMContext Context;
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000682 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000683
684 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000685
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000686 if (UseDiagnosticHandler)
687 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
688
Peter Collingbourne44ee84e2015-08-21 22:57:17 +0000689 CodeGen.setCodePICModel(RelocModel);
James Molloy951e5292014-04-14 13:54:16 +0000690
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000691 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000692 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000693 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000694
Rafael Espindola282a4702013-10-31 20:51:58 +0000695 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
696 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
697 DSOSymbolsSet.insert(DSOSymbols[i]);
698
699 std::vector<std::string> KeptDSOSyms;
700
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000701 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000702 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
703 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
704 LTOModule::createFromFile(Context, InputFilenames[i].c_str(), Options);
705 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
706 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000707
Peter Collingbourne552174392015-08-21 19:09:42 +0000708 unsigned NumSyms = Module->getSymbolCount();
709 for (unsigned I = 0; I < NumSyms; ++I) {
710 StringRef Name = Module->getSymbolName(I);
711 if (!DSOSymbolsSet.count(Name))
712 continue;
713 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
714 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
715 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
716 KeptDSOSyms.push_back(Name);
717 }
Manman Ren6487ce92015-02-24 00:45:56 +0000718
719 // We use the first input module as the destination module when
720 // SetMergedModule is true.
721 if (SetMergedModule && i == BaseArg) {
722 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000723 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000724 } else if (!CodeGen.addModule(Module.get())) {
725 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000726 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000727 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000728 }
729
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000730 // Add all the exported symbols to the table of symbols to preserve.
731 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
732 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
733
Rafael Espindolacda29112013-10-03 18:29:09 +0000734 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000735 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
736 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000737
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000738 // Set cpu and attrs strings for the default target/subtarget.
739 CodeGen.setCpu(MCPU.c_str());
740
Peter Collingbourne070843d2015-03-19 22:01:00 +0000741 CodeGen.setOptLevel(OptLevel - '0');
742
Tom Roederfd1bc602014-04-25 21:46:51 +0000743 std::string attrs;
744 for (unsigned i = 0; i < MAttrs.size(); ++i) {
745 if (i > 0)
746 attrs.append(",");
747 attrs.append(MAttrs[i]);
748 }
749
750 if (!attrs.empty())
751 CodeGen.setAttr(attrs.c_str());
752
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000753 if (FileType.getNumOccurrences())
754 CodeGen.setFileType(FileType);
755
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000756 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000757 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000758 DisableLTOVectorization)) {
759 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000760 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000761 }
762
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000763 if (SaveModuleFile) {
764 std::string ModuleFilename = OutputFilename;
765 ModuleFilename += ".merged.bc";
766 std::string ErrMsg;
767
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000768 if (!CodeGen.writeMergedModules(ModuleFilename.c_str()))
769 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000770 }
771
Peter Collingbournec269ed52015-08-27 23:37:36 +0000772 std::list<tool_output_file> OSs;
773 std::vector<raw_pwrite_stream *> OSPtrs;
774 for (unsigned I = 0; I != Parallelism; ++I) {
775 std::string PartFilename = OutputFilename;
776 if (Parallelism != 1)
777 PartFilename += "." + utostr(I);
778 std::error_code EC;
779 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000780 if (EC)
781 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000782 OSPtrs.push_back(&OSs.back().os());
783 }
784
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000785 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000786 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000787 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000788
Peter Collingbournec269ed52015-08-27 23:37:36 +0000789 for (tool_output_file &OS : OSs)
790 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000791 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000792 if (Parallelism != 1)
793 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000794
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000795 if (SaveModuleFile)
796 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000797
Craig Toppere6cb63e2014-04-25 04:24:47 +0000798 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000799 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000800 DisableGVNLoadPRE, DisableLTOVectorization))
801 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000802 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000803
804 outs() << "Wrote native object file '" << OutputName << "'\n";
805 }
806
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000807 return 0;
808}