blob: bbd0edac108f00e831f3a351aeae549ce57b34b3 [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- llvm-lto: a simple command-line program to link modules with LTO ---===//
Peter Collingbourne4e380b02013-09-19 22:15:52 +00002//
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
Eugene Zelenko975293f2017-09-07 23:28:24 +000015#include "llvm-c/lto.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
Rafael Espindola282a4702013-10-31 20:51:58 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000022#include "llvm/ADT/Twine.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000025#include "llvm/CodeGen/CommandFlags.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000026#include "llvm/IR/DiagnosticInfo.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000028#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000029#include "llvm/IR/Module.h"
30#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000031#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000033#include "llvm/LTO/legacy/LTOCodeGenerator.h"
34#include "llvm/LTO/legacy/LTOModule.h"
35#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000036#include "llvm/Support/Allocator.h"
37#include "llvm/Support/Casting.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038#include "llvm/Support/CommandLine.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/Support/Error.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/ErrorOr.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000042#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000043#include "llvm/Support/ManagedStatic.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000044#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000045#include "llvm/Support/Path.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000046#include "llvm/Support/PrettyStackTrace.h"
47#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000048#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000049#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000050#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000051#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000052#include "llvm/Target/TargetOptions.h"
53#include <algorithm>
54#include <cassert>
55#include <cstdint>
56#include <cstdlib>
Peter Collingbournec269ed52015-08-27 23:37:36 +000057#include <list>
Eugene Zelenko975293f2017-09-07 23:28:24 +000058#include <map>
59#include <memory>
60#include <string>
61#include <system_error>
62#include <tuple>
63#include <utility>
64#include <vector>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000065
66using namespace llvm;
67
Peter Collingbourne070843d2015-03-19 22:01:00 +000068static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000069 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70 "(default = '-O2')"),
71 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000072
Mehdi Amini06a47802016-09-14 21:04:59 +000073static cl::opt<bool>
74 IndexStats("thinlto-index-stats",
75 cl::desc("Print statistic for the index in every input files"),
76 cl::init(false));
77
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000078static cl::opt<bool> DisableVerify(
79 "disable-verify", cl::init(false),
80 cl::desc("Do not run the verifier during the optimization pipeline"));
81
Davide Italianob10e8932016-04-13 21:41:35 +000082static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
83 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000084
85static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000086 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
87 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000088
Davide Italianob10e8932016-04-13 21:41:35 +000089static cl::opt<bool> DisableLTOVectorization(
90 "disable-lto-vectorization", cl::init(false),
91 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000092
Mehdi Aminib5a46c12017-03-28 18:55:44 +000093static cl::opt<bool> EnableFreestanding(
94 "lto-freestanding", cl::init(false),
95 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
96
Davide Italianob10e8932016-04-13 21:41:35 +000097static cl::opt<bool> UseDiagnosticHandler(
98 "use-diagnostic-handler", cl::init(false),
99 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000100
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000101static cl::opt<bool>
102 ThinLTO("thinlto", cl::init(false),
103 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000104
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000105enum ThinLTOModes {
106 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +0000107 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +0000108 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000109 THINPROMOTE,
110 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +0000111 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000112 THINOPT,
113 THINCODEGEN,
114 THINALL
115};
116
117cl::opt<ThinLTOModes> ThinLTOMode(
118 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
119 cl::values(
120 clEnumValN(
121 THINLINK, "thinlink",
122 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +0000123 clEnumValN(THINDISTRIBUTE, "distributedindexes",
124 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +0000125 clEnumValN(THINEMITIMPORTS, "emitimports",
126 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000127 clEnumValN(THINPROMOTE, "promote",
128 "Perform pre-import promotion (requires -thinlto-index)."),
129 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
130 "cross-module importing (requires "
131 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000132 clEnumValN(THININTERNALIZE, "internalize",
133 "Perform internalization driven by -exported-symbol "
134 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000135 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
136 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000137 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000138
139static cl::opt<std::string>
140 ThinLTOIndex("thinlto-index",
141 cl::desc("Provide the index produced by a ThinLink, required "
142 "to perform the promotion and/or importing."));
143
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000144static cl::opt<std::string> ThinLTOPrefixReplace(
145 "thinlto-prefix-replace",
146 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000147 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000148 "prefix of output file is oldprefix it will be "
149 "replaced with newprefix."));
150
Mehdi Amini03abce92016-05-05 16:33:51 +0000151static cl::opt<std::string> ThinLTOModuleId(
152 "thinlto-module-id",
153 cl::desc("For the module ID for the file to process, useful to "
154 "match what is in the index."));
155
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000156static cl::opt<std::string>
157 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
158
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000159static cl::opt<std::string> ThinLTOSaveTempsPrefix(
160 "thinlto-save-temps",
161 cl::desc("Save ThinLTO temp files using filenames created by adding "
162 "suffixes to the given file path prefix."));
163
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000164static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
165 "thinlto-save-objects",
166 cl::desc("Save ThinLTO generated object files using filenames created in "
167 "the given directory."));
168
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000169static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000170 SaveModuleFile("save-merged-module", cl::init(false),
171 cl::desc("Write merged LTO module to file before CodeGen"));
172
173static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
174 cl::desc("<input bitcode files>"));
175
176static cl::opt<std::string> OutputFilename("o", cl::init(""),
177 cl::desc("Override output filename"),
178 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000179
Mehdi Amini059464f2016-04-24 03:18:01 +0000180static cl::list<std::string> ExportedSymbols(
181 "exported-symbol",
182 cl::desc("List of symbols to export from the resulting object file"),
183 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000184
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000185static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000186 DSOSymbols("dso-symbol",
187 cl::desc("Symbol to put in the symtab in the resulting dso"),
188 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000189
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000190static cl::opt<bool> ListSymbolsOnly(
191 "list-symbols-only", cl::init(false),
192 cl::desc("Instead of running LTO, list the symbols in each IR file"));
193
Manman Ren6487ce92015-02-24 00:45:56 +0000194static cl::opt<bool> SetMergedModule(
195 "set-merged-module", cl::init(false),
196 cl::desc("Use the first input module as the merged module"));
197
Peter Collingbournec269ed52015-08-27 23:37:36 +0000198static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
199 cl::desc("Number of backend threads"));
200
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000201static cl::opt<bool> RestoreGlobalsLinkage(
202 "restore-linkage", cl::init(false),
203 cl::desc("Restore original linkage of globals prior to CodeGen"));
204
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000205static cl::opt<bool> CheckHasObjC(
206 "check-for-objc", cl::init(false),
207 cl::desc("Only check if the module has objective-C defined in it"));
208
Rafael Espindola282a4702013-10-31 20:51:58 +0000209namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000210
Rafael Espindola282a4702013-10-31 20:51:58 +0000211struct ModuleInfo {
212 std::vector<bool> CanBeHidden;
213};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000214
215} // end anonymous namespace
Rafael Espindola282a4702013-10-31 20:51:58 +0000216
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000217static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
218 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000219 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000220 switch (Severity) {
221 case LTO_DS_NOTE:
222 errs() << "note: ";
223 break;
224 case LTO_DS_REMARK:
225 errs() << "remark: ";
226 break;
227 case LTO_DS_ERROR:
228 errs() << "error: ";
229 break;
230 case LTO_DS_WARNING:
231 errs() << "warning: ";
232 break;
233 }
234 errs() << Msg << "\n";
235}
236
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000237static std::string CurrentActivity;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000238
239namespace {
240 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
241 bool handleDiagnostics(const DiagnosticInfo &DI) override {
242 raw_ostream &OS = errs();
243 OS << "llvm-lto: ";
244 switch (DI.getSeverity()) {
245 case DS_Error:
246 OS << "error";
247 break;
248 case DS_Warning:
249 OS << "warning";
250 break;
251 case DS_Remark:
252 OS << "remark";
253 break;
254 case DS_Note:
255 OS << "note";
256 break;
257 }
258 if (!CurrentActivity.empty())
259 OS << ' ' << CurrentActivity;
260 OS << ": ";
261
262 DiagnosticPrinterRawOStream DP(OS);
263 DI.print(DP);
264 OS << '\n';
265
266 if (DI.getSeverity() == DS_Error)
267 exit(1);
268 return true;
269 }
270 };
Mehdi Amini354f5202015-11-19 05:52:29 +0000271 }
Mehdi Amini354f5202015-11-19 05:52:29 +0000272
Rafael Espindola5e128db2015-12-04 00:45:57 +0000273static void error(const Twine &Msg) {
274 errs() << "llvm-lto: " << Msg << '\n';
275 exit(1);
276}
277
278static void error(std::error_code EC, const Twine &Prefix) {
279 if (EC)
280 error(Prefix + ": " + EC.message());
281}
282
283template <typename T>
284static void error(const ErrorOr<T> &V, const Twine &Prefix) {
285 error(V.getError(), Prefix);
286}
287
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000288static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000289 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000290 error("Broken Module");
291}
292
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000293static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000294getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000295 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000296 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
297 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000298 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000299 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000300 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000301 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000302 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
303 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000304 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000305 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
306 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000307 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000308 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000309 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000310}
311
Mehdi Amini06a47802016-09-14 21:04:59 +0000312/// Print some statistics on the index for each input files.
313void printIndexStats() {
314 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000315 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
316 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenko975293f2017-09-07 23:28:24 +0000317 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000318 // Skip files without a module summary.
319 if (!Index)
320 report_fatal_error(Filename + " does not contain an index");
321
322 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
323 for (auto &Summaries : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000324 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Amini06a47802016-09-14 21:04:59 +0000325 Refs += Summary->refs().size();
326 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
327 Functions++;
328 Calls += FuncSummary->calls().size();
329 } else if (isa<AliasSummary>(Summary.get()))
330 Alias++;
331 else
332 Globals++;
333 }
334 }
335 outs() << "Index " << Filename << " contains "
336 << (Alias + Globals + Functions) << " nodes (" << Functions
337 << " functions, " << Alias << " alias, " << Globals
338 << " globals) and " << (Calls + Refs) << " edges (" << Refs
339 << " refs and " << Calls << " calls)\n";
340 }
341}
342
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000343/// \brief List symbols in each IR file.
344///
345/// The main point here is to provide lit-testable coverage for the LTOModule
346/// functionality that's exposed by the C API to list symbols. Moreover, this
347/// provides testing coverage for modules that have been created in their own
348/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000349static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000350 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000351 std::unique_ptr<MemoryBuffer> Buffer;
352 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000353 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000354
355 // List the symbols.
356 outs() << Filename << ":\n";
357 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
358 outs() << Module->getSymbolName(I) << "\n";
359 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000360}
361
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000362/// Create a combined index file from the input IR files and write it.
363///
364/// This is meant to enable testing of ThinLTO combined index generation,
365/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000366static void createCombinedModuleSummaryIndex() {
367 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000368 uint64_t NextModuleId = 0;
369 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000370 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000371 std::unique_ptr<MemoryBuffer> MB =
372 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
373 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, ++NextModuleId));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000374 }
375 std::error_code EC;
376 assert(!OutputFilename.empty());
377 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
378 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000379 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000380 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000381 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000382}
383
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000384/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
385/// \p NewPrefix strings, if it was specified.
386static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
387 std::string &NewPrefix) {
388 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000389 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000390 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000391 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000392 OldPrefix = Split.first.str();
393 NewPrefix = Split.second.str();
394}
395
396/// Given the original \p Path to an output file, replace any path
397/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
398/// resulting directory if it does not yet exist.
399static std::string getThinLTOOutputFile(const std::string &Path,
400 const std::string &OldPrefix,
401 const std::string &NewPrefix) {
402 if (OldPrefix.empty() && NewPrefix.empty())
403 return Path;
404 SmallString<128> NewPath(Path);
405 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
406 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
407 if (!ParentPath.empty()) {
408 // Make sure the new directory exists, creating it if necessary.
409 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
410 error(EC, "error creating the directory '" + ParentPath + "'");
411 }
412 return NewPath.str();
413}
414
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000415namespace thinlto {
416
417std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000418loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000419 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
420
Mehdi Amini385cf282016-03-26 03:35:38 +0000421 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000422 const auto &Filename = ModPath.first();
Alexander Kornienko656466e2017-07-04 15:13:02 +0000423 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000424 auto InputOrErr = MemoryBuffer::getFile(Filename);
425 error(InputOrErr, "error " + CurrentActivity);
426 InputBuffers.push_back(std::move(*InputOrErr));
427 }
428 return InputBuffers;
429}
430
Teresa Johnson26ab5772016-03-15 00:04:37 +0000431std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000432 if (ThinLTOIndex.empty())
433 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000434 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
435 "': ");
Eugene Zelenko975293f2017-09-07 23:28:24 +0000436 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000437}
438
439static std::unique_ptr<Module> loadModule(StringRef Filename,
440 LLVMContext &Ctx) {
441 SMDiagnostic Err;
442 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
443 if (!M) {
444 Err.print("llvm-lto", errs());
445 report_fatal_error("Can't load module for file " + Filename);
446 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000447 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000448
449 if (ThinLTOModuleId.getNumOccurrences()) {
450 if (InputFilenames.size() != 1)
451 report_fatal_error("Can't override the module id for multiple files");
452 M->setModuleIdentifier(ThinLTOModuleId);
453 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000454 return M;
455}
456
457static void writeModuleToFile(Module &TheModule, StringRef Filename) {
458 std::error_code EC;
459 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
460 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000461 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000462 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000463}
464
465class ThinLTOProcessing {
466public:
467 ThinLTOCodeGenerator ThinGenerator;
468
469 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000470 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000472 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000473 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000474
475 // Add all the exported symbols to the table of symbols to preserve.
476 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
477 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000478 }
479
480 void run() {
481 switch (ThinLTOMode) {
482 case THINLINK:
483 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000484 case THINDISTRIBUTE:
485 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000486 case THINEMITIMPORTS:
487 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488 case THINPROMOTE:
489 return promote();
490 case THINIMPORT:
491 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000492 case THININTERNALIZE:
493 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000494 case THINOPT:
495 return optimize();
496 case THINCODEGEN:
497 return codegen();
498 case THINALL:
499 return runAll();
500 }
501 }
502
503private:
504 /// Load the input files, create the combined index, and write it out.
505 void thinLink() {
506 // Perform "ThinLink": just produce the index
507 if (OutputFilename.empty())
508 report_fatal_error(
509 "OutputFilename is necessary to store the combined index.\n");
510
511 LLVMContext Ctx;
512 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
513 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
514 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000515 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000516 auto InputOrErr = MemoryBuffer::getFile(Filename);
517 error(InputOrErr, "error " + CurrentActivity);
518 InputBuffers.push_back(std::move(*InputOrErr));
519 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
520 }
521
522 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000523 if (!CombinedIndex)
524 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 std::error_code EC;
526 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
527 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000528 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000529 }
530
Teresa Johnson84174c32016-05-10 13:48:23 +0000531 /// Load the combined index from disk, then compute and generate
532 /// individual index files suitable for ThinLTO distributed backend builds
533 /// on the files mentioned on the command line (these must match the index
534 /// content).
535 void distributedIndexes() {
536 if (InputFilenames.size() != 1 && !OutputFilename.empty())
537 report_fatal_error("Can't handle a single output filename and multiple "
538 "input files, do not provide an output filename and "
539 "the output files will be suffixed from the input "
540 "ones.");
541
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000542 std::string OldPrefix, NewPrefix;
543 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
544
Teresa Johnson84174c32016-05-10 13:48:23 +0000545 auto Index = loadCombinedIndex();
546 for (auto &Filename : InputFilenames) {
547 // Build a map of module to the GUIDs and summary objects that should
548 // be written to its index.
549 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
550 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
551 Filename, *Index, ModuleToSummariesForIndex);
552
553 std::string OutputName = OutputFilename;
554 if (OutputName.empty()) {
555 OutputName = Filename + ".thinlto.bc";
556 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000557 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000558 std::error_code EC;
559 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
560 error(EC, "error opening the file '" + OutputName + "'");
561 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
562 }
563 }
564
Teresa Johnson8570fe42016-05-10 15:54:09 +0000565 /// Load the combined index from disk, compute the imports, and emit
566 /// the import file lists for each module to disk.
567 void emitImports() {
568 if (InputFilenames.size() != 1 && !OutputFilename.empty())
569 report_fatal_error("Can't handle a single output filename and multiple "
570 "input files, do not provide an output filename and "
571 "the output files will be suffixed from the input "
572 "ones.");
573
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000574 std::string OldPrefix, NewPrefix;
575 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
576
Teresa Johnson8570fe42016-05-10 15:54:09 +0000577 auto Index = loadCombinedIndex();
578 for (auto &Filename : InputFilenames) {
579 std::string OutputName = OutputFilename;
580 if (OutputName.empty()) {
581 OutputName = Filename + ".imports";
582 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000583 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000584 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
585 }
586 }
587
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000588 /// Load the combined index from disk, then load every file referenced by
589 /// the index and add them to the generator, finally perform the promotion
590 /// on the files mentioned on the command line (these must match the index
591 /// content).
592 void promote() {
593 if (InputFilenames.size() != 1 && !OutputFilename.empty())
594 report_fatal_error("Can't handle a single output filename and multiple "
595 "input files, do not provide an output filename and "
596 "the output files will be suffixed from the input "
597 "ones.");
598
599 auto Index = loadCombinedIndex();
600 for (auto &Filename : InputFilenames) {
601 LLVMContext Ctx;
602 auto TheModule = loadModule(Filename, Ctx);
603
604 ThinGenerator.promote(*TheModule, *Index);
605
606 std::string OutputName = OutputFilename;
607 if (OutputName.empty()) {
608 OutputName = Filename + ".thinlto.promoted.bc";
609 }
610 writeModuleToFile(*TheModule, OutputName);
611 }
612 }
613
614 /// Load the combined index from disk, then load every file referenced by
615 /// the index and add them to the generator, then performs the promotion and
616 /// cross module importing on the files mentioned on the command line
617 /// (these must match the index content).
618 void import() {
619 if (InputFilenames.size() != 1 && !OutputFilename.empty())
620 report_fatal_error("Can't handle a single output filename and multiple "
621 "input files, do not provide an output filename and "
622 "the output files will be suffixed from the input "
623 "ones.");
624
625 auto Index = loadCombinedIndex();
626 auto InputBuffers = loadAllFilesForIndex(*Index);
627 for (auto &MemBuffer : InputBuffers)
628 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
629 MemBuffer->getBuffer());
630
631 for (auto &Filename : InputFilenames) {
632 LLVMContext Ctx;
633 auto TheModule = loadModule(Filename, Ctx);
634
635 ThinGenerator.crossModuleImport(*TheModule, *Index);
636
637 std::string OutputName = OutputFilename;
638 if (OutputName.empty()) {
639 OutputName = Filename + ".thinlto.imported.bc";
640 }
641 writeModuleToFile(*TheModule, OutputName);
642 }
643 }
644
Mehdi Amini059464f2016-04-24 03:18:01 +0000645 void internalize() {
646 if (InputFilenames.size() != 1 && !OutputFilename.empty())
647 report_fatal_error("Can't handle a single output filename and multiple "
648 "input files, do not provide an output filename and "
649 "the output files will be suffixed from the input "
650 "ones.");
651
652 if (ExportedSymbols.empty())
653 errs() << "Warning: -internalize will not perform without "
654 "-exported-symbol\n";
655
656 auto Index = loadCombinedIndex();
657 auto InputBuffers = loadAllFilesForIndex(*Index);
658 for (auto &MemBuffer : InputBuffers)
659 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
660 MemBuffer->getBuffer());
661
662 for (auto &Filename : InputFilenames) {
663 LLVMContext Ctx;
664 auto TheModule = loadModule(Filename, Ctx);
665
666 ThinGenerator.internalize(*TheModule, *Index);
667
668 std::string OutputName = OutputFilename;
669 if (OutputName.empty()) {
670 OutputName = Filename + ".thinlto.internalized.bc";
671 }
672 writeModuleToFile(*TheModule, OutputName);
673 }
674 }
675
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000676 void optimize() {
677 if (InputFilenames.size() != 1 && !OutputFilename.empty())
678 report_fatal_error("Can't handle a single output filename and multiple "
679 "input files, do not provide an output filename and "
680 "the output files will be suffixed from the input "
681 "ones.");
682 if (!ThinLTOIndex.empty())
683 errs() << "Warning: -thinlto-index ignored for optimize stage";
684
685 for (auto &Filename : InputFilenames) {
686 LLVMContext Ctx;
687 auto TheModule = loadModule(Filename, Ctx);
688
689 ThinGenerator.optimize(*TheModule);
690
691 std::string OutputName = OutputFilename;
692 if (OutputName.empty()) {
693 OutputName = Filename + ".thinlto.imported.bc";
694 }
695 writeModuleToFile(*TheModule, OutputName);
696 }
697 }
698
699 void codegen() {
700 if (InputFilenames.size() != 1 && !OutputFilename.empty())
701 report_fatal_error("Can't handle a single output filename and multiple "
702 "input files, do not provide an output filename and "
703 "the output files will be suffixed from the input "
704 "ones.");
705 if (!ThinLTOIndex.empty())
706 errs() << "Warning: -thinlto-index ignored for codegen stage";
707
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000708 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000709 for (auto &Filename : InputFilenames) {
710 LLVMContext Ctx;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000711 auto InputOrErr = MemoryBuffer::getFile(Filename);
712 error(InputOrErr, "error " + CurrentActivity);
713 InputBuffers.push_back(std::move(*InputOrErr));
714 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
715 }
716 ThinGenerator.setCodeGenOnly(true);
717 ThinGenerator.run();
718 for (auto BinName :
719 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000720 std::string OutputName = OutputFilename;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000721 if (OutputName.empty())
722 OutputName = std::get<1>(BinName) + ".thinlto.o";
723 else if (OutputName == "-") {
724 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000725 return;
726 }
727
728 std::error_code EC;
729 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
730 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000731 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000732 }
733 }
734
735 /// Full ThinLTO process
736 void runAll() {
737 if (!OutputFilename.empty())
738 report_fatal_error("Do not provide an output filename for ThinLTO "
739 " processing, the output files will be suffixed from "
740 "the input ones.");
741
742 if (!ThinLTOIndex.empty())
743 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
744
745 LLVMContext Ctx;
746 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
747 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
748 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000749 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000750 auto InputOrErr = MemoryBuffer::getFile(Filename);
751 error(InputOrErr, "error " + CurrentActivity);
752 InputBuffers.push_back(std::move(*InputOrErr));
753 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
754 }
755
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000756 if (!ThinLTOSaveTempsPrefix.empty())
757 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000758
759 if (!ThinLTOGeneratedObjectsDir.empty()) {
760 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
761 ThinGenerator.run();
762 return;
763 }
764
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000765 ThinGenerator.run();
766
767 auto &Binaries = ThinGenerator.getProducedBinaries();
768 if (Binaries.size() != InputFilenames.size())
769 report_fatal_error("Number of output objects does not match the number "
770 "of inputs");
771
772 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
773 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
774 std::error_code EC;
775 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
776 error(EC, "error opening the file '" + OutputName + "'");
777 OS << Binaries[BufID]->getBuffer();
778 }
779 }
780
781 /// Load the combined index from disk, then load every file referenced by
782};
783
Eugene Zelenko975293f2017-09-07 23:28:24 +0000784} // end namespace thinlto
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000785
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000786int main(int argc, char **argv) {
787 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000788 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000789 PrettyStackTraceProgram X(argc, argv);
790
791 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
792 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
793
Rafael Espindola5e128db2015-12-04 00:45:57 +0000794 if (OptLevel < '0' || OptLevel > '3')
795 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000796
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000797 // Initialize the configured targets.
798 InitializeAllTargets();
799 InitializeAllTargetMCs();
800 InitializeAllAsmPrinters();
801 InitializeAllAsmParsers();
802
Rafael Espindola0b385c72013-09-30 16:39:19 +0000803 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000804 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000805
Rafael Espindola5e128db2015-12-04 00:45:57 +0000806 if (ListSymbolsOnly) {
807 listSymbols(Options);
808 return 0;
809 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000810
Mehdi Amini06a47802016-09-14 21:04:59 +0000811 if (IndexStats) {
812 printIndexStats();
813 return 0;
814 }
815
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000816 if (CheckHasObjC) {
817 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000818 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
819 Filename + "': ");
820 std::unique_ptr<MemoryBuffer> BufferOrErr =
821 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000822 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenko975293f2017-09-07 23:28:24 +0000823 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000824 outs() << "Bitcode " << Filename << " contains ObjC\n";
825 else
826 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
827 }
828 return 0;
829 }
830
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000831 if (ThinLTOMode.getNumOccurrences()) {
832 if (ThinLTOMode.getNumOccurrences() > 1)
833 report_fatal_error("You can't specify more than one -thinlto-action");
834 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
835 ThinLTOProcessor.run();
836 return 0;
837 }
838
Rafael Espindola5e128db2015-12-04 00:45:57 +0000839 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000840 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000841 return 0;
842 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000843
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000844 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000845
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000846 LLVMContext Context;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000847 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
848 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000849
850 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000851
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000852 if (UseDiagnosticHandler)
853 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
854
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000855 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000856 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000857
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000858 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000859 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000860 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000861
Eugene Zelenko975293f2017-09-07 23:28:24 +0000862 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola282a4702013-10-31 20:51:58 +0000863 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
864 DSOSymbolsSet.insert(DSOSymbols[i]);
865
866 std::vector<std::string> KeptDSOSyms;
867
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000868 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000869 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
870 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000871 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000872 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
873 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000874
Peter Collingbourne552174392015-08-21 19:09:42 +0000875 unsigned NumSyms = Module->getSymbolCount();
876 for (unsigned I = 0; I < NumSyms; ++I) {
877 StringRef Name = Module->getSymbolName(I);
878 if (!DSOSymbolsSet.count(Name))
879 continue;
880 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
881 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
882 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
883 KeptDSOSyms.push_back(Name);
884 }
Manman Ren6487ce92015-02-24 00:45:56 +0000885
886 // We use the first input module as the destination module when
887 // SetMergedModule is true.
888 if (SetMergedModule && i == BaseArg) {
889 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000890 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000891 } else if (!CodeGen.addModule(Module.get())) {
892 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000893 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000894 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000895 }
896
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000897 // Add all the exported symbols to the table of symbols to preserve.
898 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000899 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000900
Rafael Espindolacda29112013-10-03 18:29:09 +0000901 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000902 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000903 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000904
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000905 // Set cpu and attrs strings for the default target/subtarget.
906 CodeGen.setCpu(MCPU.c_str());
907
Peter Collingbourne070843d2015-03-19 22:01:00 +0000908 CodeGen.setOptLevel(OptLevel - '0');
909
Tom Roederfd1bc602014-04-25 21:46:51 +0000910 std::string attrs;
911 for (unsigned i = 0; i < MAttrs.size(); ++i) {
912 if (i > 0)
913 attrs.append(",");
914 attrs.append(MAttrs[i]);
915 }
916
917 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000918 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000919
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000920 if (FileType.getNumOccurrences())
921 CodeGen.setFileType(FileType);
922
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000923 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000924 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000925 DisableLTOVectorization)) {
926 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000927 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000928 }
929
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000930 if (SaveModuleFile) {
931 std::string ModuleFilename = OutputFilename;
932 ModuleFilename += ".merged.bc";
933 std::string ErrMsg;
934
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000935 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000936 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000937 }
938
Peter Collingbournec269ed52015-08-27 23:37:36 +0000939 std::list<tool_output_file> OSs;
940 std::vector<raw_pwrite_stream *> OSPtrs;
941 for (unsigned I = 0; I != Parallelism; ++I) {
942 std::string PartFilename = OutputFilename;
943 if (Parallelism != 1)
944 PartFilename += "." + utostr(I);
945 std::error_code EC;
946 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000947 if (EC)
948 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000949 OSPtrs.push_back(&OSs.back().os());
950 }
951
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000952 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000953 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000954 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000955
Peter Collingbournec269ed52015-08-27 23:37:36 +0000956 for (tool_output_file &OS : OSs)
957 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000958 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000959 if (Parallelism != 1)
960 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000961
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000962 if (SaveModuleFile)
963 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000964
Craig Toppere6cb63e2014-04-25 04:24:47 +0000965 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000966 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000967 DisableGVNLoadPRE, DisableLTOVectorization))
968 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000969 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000970
971 outs() << "Wrote native object file '" << OutputName << "'\n";
972 }
973
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000974 return 0;
975}