blob: 2f005412a3b928e12664494ec0b2b947de6324b0 [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 Johnsonad176792016-11-11 05:34:58 +000016#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000018#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000019#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000020#include "llvm/IR/LLVMContext.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000021#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000022#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000023#include "llvm/LTO/legacy/LTOCodeGenerator.h"
24#include "llvm/LTO/legacy/LTOModule.h"
25#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000026#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000027#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000028#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000029#include "llvm/Support/ManagedStatic.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000030#include "llvm/Support/Path.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000031#include "llvm/Support/PrettyStackTrace.h"
32#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000034#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000035#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000036#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000037#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038
39using namespace llvm;
40
Peter Collingbourne070843d2015-03-19 22:01:00 +000041static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000042 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
43 "(default = '-O2')"),
44 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000045
Mehdi Amini06a47802016-09-14 21:04:59 +000046static cl::opt<bool>
47 IndexStats("thinlto-index-stats",
48 cl::desc("Print statistic for the index in every input files"),
49 cl::init(false));
50
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000051static cl::opt<bool> DisableVerify(
52 "disable-verify", cl::init(false),
53 cl::desc("Do not run the verifier during the optimization pipeline"));
54
Davide Italianob10e8932016-04-13 21:41:35 +000055static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
56 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000057
58static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000059 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000061
Davide Italianob10e8932016-04-13 21:41:35 +000062static cl::opt<bool> DisableLTOVectorization(
63 "disable-lto-vectorization", cl::init(false),
64 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000065
Mehdi Aminib5a46c12017-03-28 18:55:44 +000066static cl::opt<bool> EnableFreestanding(
67 "lto-freestanding", cl::init(false),
68 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
69
Davide Italianob10e8932016-04-13 21:41:35 +000070static cl::opt<bool> UseDiagnosticHandler(
71 "use-diagnostic-handler", cl::init(false),
72 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000073
Teresa Johnsonf72278f2015-11-02 18:02:11 +000074static cl::opt<bool>
75 ThinLTO("thinlto", cl::init(false),
76 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000077
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000078enum ThinLTOModes {
79 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000080 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +000081 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000082 THINPROMOTE,
83 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000084 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 THINOPT,
86 THINCODEGEN,
87 THINALL
88};
89
90cl::opt<ThinLTOModes> ThinLTOMode(
91 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
92 cl::values(
93 clEnumValN(
94 THINLINK, "thinlink",
95 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000096 clEnumValN(THINDISTRIBUTE, "distributedindexes",
97 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000098 clEnumValN(THINEMITIMPORTS, "emitimports",
99 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000100 clEnumValN(THINPROMOTE, "promote",
101 "Perform pre-import promotion (requires -thinlto-index)."),
102 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
103 "cross-module importing (requires "
104 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000105 clEnumValN(THININTERNALIZE, "internalize",
106 "Perform internalization driven by -exported-symbol "
107 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000108 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
109 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000110 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000111
112static cl::opt<std::string>
113 ThinLTOIndex("thinlto-index",
114 cl::desc("Provide the index produced by a ThinLink, required "
115 "to perform the promotion and/or importing."));
116
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000117static cl::opt<std::string> ThinLTOPrefixReplace(
118 "thinlto-prefix-replace",
119 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000120 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000121 "prefix of output file is oldprefix it will be "
122 "replaced with newprefix."));
123
Mehdi Amini03abce92016-05-05 16:33:51 +0000124static cl::opt<std::string> ThinLTOModuleId(
125 "thinlto-module-id",
126 cl::desc("For the module ID for the file to process, useful to "
127 "match what is in the index."));
128
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000129static cl::opt<std::string>
130 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
131
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000132static cl::opt<std::string> ThinLTOSaveTempsPrefix(
133 "thinlto-save-temps",
134 cl::desc("Save ThinLTO temp files using filenames created by adding "
135 "suffixes to the given file path prefix."));
136
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000137static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
138 "thinlto-save-objects",
139 cl::desc("Save ThinLTO generated object files using filenames created in "
140 "the given directory."));
141
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000142static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000143 SaveModuleFile("save-merged-module", cl::init(false),
144 cl::desc("Write merged LTO module to file before CodeGen"));
145
146static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
147 cl::desc("<input bitcode files>"));
148
149static cl::opt<std::string> OutputFilename("o", cl::init(""),
150 cl::desc("Override output filename"),
151 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000152
Mehdi Amini059464f2016-04-24 03:18:01 +0000153static cl::list<std::string> ExportedSymbols(
154 "exported-symbol",
155 cl::desc("List of symbols to export from the resulting object file"),
156 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000157
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000158static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000159 DSOSymbols("dso-symbol",
160 cl::desc("Symbol to put in the symtab in the resulting dso"),
161 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000162
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000163static cl::opt<bool> ListSymbolsOnly(
164 "list-symbols-only", cl::init(false),
165 cl::desc("Instead of running LTO, list the symbols in each IR file"));
166
Manman Ren6487ce92015-02-24 00:45:56 +0000167static cl::opt<bool> SetMergedModule(
168 "set-merged-module", cl::init(false),
169 cl::desc("Use the first input module as the merged module"));
170
Peter Collingbournec269ed52015-08-27 23:37:36 +0000171static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
172 cl::desc("Number of backend threads"));
173
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000174static cl::opt<bool> RestoreGlobalsLinkage(
175 "restore-linkage", cl::init(false),
176 cl::desc("Restore original linkage of globals prior to CodeGen"));
177
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000178static cl::opt<bool> CheckHasObjC(
179 "check-for-objc", cl::init(false),
180 cl::desc("Only check if the module has objective-C defined in it"));
181
Rafael Espindola282a4702013-10-31 20:51:58 +0000182namespace {
183struct ModuleInfo {
184 std::vector<bool> CanBeHidden;
185};
186}
187
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000188static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
189 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000190 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000191 switch (Severity) {
192 case LTO_DS_NOTE:
193 errs() << "note: ";
194 break;
195 case LTO_DS_REMARK:
196 errs() << "remark: ";
197 break;
198 case LTO_DS_ERROR:
199 errs() << "error: ";
200 break;
201 case LTO_DS_WARNING:
202 errs() << "warning: ";
203 break;
204 }
205 errs() << Msg << "\n";
206}
207
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000208static std::string CurrentActivity;
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000209static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
Mehdi Amini354f5202015-11-19 05:52:29 +0000210 raw_ostream &OS = errs();
211 OS << "llvm-lto: ";
212 switch (DI.getSeverity()) {
213 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000214 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000215 break;
216 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000217 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000218 break;
219 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000220 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000221 break;
222 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000223 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000224 break;
225 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000226 if (!CurrentActivity.empty())
227 OS << ' ' << CurrentActivity;
228 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000229
230 DiagnosticPrinterRawOStream DP(OS);
231 DI.print(DP);
232 OS << '\n';
233
234 if (DI.getSeverity() == DS_Error)
235 exit(1);
236}
237
Rafael Espindola5e128db2015-12-04 00:45:57 +0000238static void error(const Twine &Msg) {
239 errs() << "llvm-lto: " << Msg << '\n';
240 exit(1);
241}
242
243static void error(std::error_code EC, const Twine &Prefix) {
244 if (EC)
245 error(Prefix + ": " + EC.message());
246}
247
248template <typename T>
249static void error(const ErrorOr<T> &V, const Twine &Prefix) {
250 error(V.getError(), Prefix);
251}
252
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000253static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000254 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000255 error("Broken Module");
256}
257
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000258static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000259getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000260 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000261 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
262 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000263 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000264 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000265 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000266 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000267 Context->setDiagnosticHandler(diagnosticHandler, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000268 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000269 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
270 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000271 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000272 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000273 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000274}
275
Mehdi Amini06a47802016-09-14 21:04:59 +0000276/// Print some statistics on the index for each input files.
277void printIndexStats() {
278 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000279 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
280 std::unique_ptr<ModuleSummaryIndex> Index =
281 ExitOnErr(llvm::getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000282 // Skip files without a module summary.
283 if (!Index)
284 report_fatal_error(Filename + " does not contain an index");
285
286 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
287 for (auto &Summaries : *Index) {
288 for (auto &Summary : Summaries.second) {
289 Refs += Summary->refs().size();
290 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
291 Functions++;
292 Calls += FuncSummary->calls().size();
293 } else if (isa<AliasSummary>(Summary.get()))
294 Alias++;
295 else
296 Globals++;
297 }
298 }
299 outs() << "Index " << Filename << " contains "
300 << (Alias + Globals + Functions) << " nodes (" << Functions
301 << " functions, " << Alias << " alias, " << Globals
302 << " globals) and " << (Calls + Refs) << " edges (" << Refs
303 << " refs and " << Calls << " calls)\n";
304 }
305}
306
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000307/// \brief List symbols in each IR file.
308///
309/// The main point here is to provide lit-testable coverage for the LTOModule
310/// functionality that's exposed by the C API to list symbols. Moreover, this
311/// provides testing coverage for modules that have been created in their own
312/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000313static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000314 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000315 std::unique_ptr<MemoryBuffer> Buffer;
316 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000317 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000318
319 // List the symbols.
320 outs() << Filename << ":\n";
321 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
322 outs() << Module->getSymbolName(I) << "\n";
323 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000324}
325
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000326/// Create a combined index file from the input IR files and write it.
327///
328/// This is meant to enable testing of ThinLTO combined index generation,
329/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000330static void createCombinedModuleSummaryIndex() {
331 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000332 uint64_t NextModuleId = 0;
333 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000334 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
335 std::unique_ptr<ModuleSummaryIndex> Index =
336 ExitOnErr(llvm::getModuleSummaryIndexForFile(Filename));
Teresa Johnson26ab5772016-03-15 00:04:37 +0000337 // Skip files without a module summary.
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000338 if (!Index)
339 continue;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000340 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
341 }
342 std::error_code EC;
343 assert(!OutputFilename.empty());
344 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
345 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000346 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000347 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000348 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000349}
350
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000351/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
352/// \p NewPrefix strings, if it was specified.
353static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
354 std::string &NewPrefix) {
355 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000356 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000357 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000358 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000359 OldPrefix = Split.first.str();
360 NewPrefix = Split.second.str();
361}
362
363/// Given the original \p Path to an output file, replace any path
364/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
365/// resulting directory if it does not yet exist.
366static std::string getThinLTOOutputFile(const std::string &Path,
367 const std::string &OldPrefix,
368 const std::string &NewPrefix) {
369 if (OldPrefix.empty() && NewPrefix.empty())
370 return Path;
371 SmallString<128> NewPath(Path);
372 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
373 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
374 if (!ParentPath.empty()) {
375 // Make sure the new directory exists, creating it if necessary.
376 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
377 error(EC, "error creating the directory '" + ParentPath + "'");
378 }
379 return NewPath.str();
380}
381
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000382namespace thinlto {
383
384std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000385loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000386 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
387
Mehdi Amini385cf282016-03-26 03:35:38 +0000388 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000389 const auto &Filename = ModPath.first();
390 auto CurrentActivity = "loading file '" + Filename + "'";
391 auto InputOrErr = MemoryBuffer::getFile(Filename);
392 error(InputOrErr, "error " + CurrentActivity);
393 InputBuffers.push_back(std::move(*InputOrErr));
394 }
395 return InputBuffers;
396}
397
Teresa Johnson26ab5772016-03-15 00:04:37 +0000398std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000399 if (ThinLTOIndex.empty())
400 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000401 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
402 "': ");
403 return ExitOnErr(llvm::getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000404}
405
406static std::unique_ptr<Module> loadModule(StringRef Filename,
407 LLVMContext &Ctx) {
408 SMDiagnostic Err;
409 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
410 if (!M) {
411 Err.print("llvm-lto", errs());
412 report_fatal_error("Can't load module for file " + Filename);
413 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000414 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000415
416 if (ThinLTOModuleId.getNumOccurrences()) {
417 if (InputFilenames.size() != 1)
418 report_fatal_error("Can't override the module id for multiple files");
419 M->setModuleIdentifier(ThinLTOModuleId);
420 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421 return M;
422}
423
424static void writeModuleToFile(Module &TheModule, StringRef Filename) {
425 std::error_code EC;
426 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
427 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000428 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000429 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000430}
431
432class ThinLTOProcessing {
433public:
434 ThinLTOCodeGenerator ThinGenerator;
435
436 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000437 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000438 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000439 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000440 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000441
442 // Add all the exported symbols to the table of symbols to preserve.
443 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
444 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000445 }
446
447 void run() {
448 switch (ThinLTOMode) {
449 case THINLINK:
450 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000451 case THINDISTRIBUTE:
452 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000453 case THINEMITIMPORTS:
454 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000455 case THINPROMOTE:
456 return promote();
457 case THINIMPORT:
458 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000459 case THININTERNALIZE:
460 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000461 case THINOPT:
462 return optimize();
463 case THINCODEGEN:
464 return codegen();
465 case THINALL:
466 return runAll();
467 }
468 }
469
470private:
471 /// Load the input files, create the combined index, and write it out.
472 void thinLink() {
473 // Perform "ThinLink": just produce the index
474 if (OutputFilename.empty())
475 report_fatal_error(
476 "OutputFilename is necessary to store the combined index.\n");
477
478 LLVMContext Ctx;
479 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
480 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
481 auto &Filename = InputFilenames[i];
482 StringRef CurrentActivity = "loading file '" + Filename + "'";
483 auto InputOrErr = MemoryBuffer::getFile(Filename);
484 error(InputOrErr, "error " + CurrentActivity);
485 InputBuffers.push_back(std::move(*InputOrErr));
486 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
487 }
488
489 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000490 if (!CombinedIndex)
491 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000492 std::error_code EC;
493 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
494 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000495 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000496 return;
497 }
498
Teresa Johnson84174c32016-05-10 13:48:23 +0000499 /// Load the combined index from disk, then compute and generate
500 /// individual index files suitable for ThinLTO distributed backend builds
501 /// on the files mentioned on the command line (these must match the index
502 /// content).
503 void distributedIndexes() {
504 if (InputFilenames.size() != 1 && !OutputFilename.empty())
505 report_fatal_error("Can't handle a single output filename and multiple "
506 "input files, do not provide an output filename and "
507 "the output files will be suffixed from the input "
508 "ones.");
509
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000510 std::string OldPrefix, NewPrefix;
511 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
512
Teresa Johnson84174c32016-05-10 13:48:23 +0000513 auto Index = loadCombinedIndex();
514 for (auto &Filename : InputFilenames) {
515 // Build a map of module to the GUIDs and summary objects that should
516 // be written to its index.
517 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
518 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
519 Filename, *Index, ModuleToSummariesForIndex);
520
521 std::string OutputName = OutputFilename;
522 if (OutputName.empty()) {
523 OutputName = Filename + ".thinlto.bc";
524 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000525 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000526 std::error_code EC;
527 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
528 error(EC, "error opening the file '" + OutputName + "'");
529 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
530 }
531 }
532
Teresa Johnson8570fe42016-05-10 15:54:09 +0000533 /// Load the combined index from disk, compute the imports, and emit
534 /// the import file lists for each module to disk.
535 void emitImports() {
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 Johnson8570fe42016-05-10 15:54:09 +0000545 auto Index = loadCombinedIndex();
546 for (auto &Filename : InputFilenames) {
547 std::string OutputName = OutputFilename;
548 if (OutputName.empty()) {
549 OutputName = Filename + ".imports";
550 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000551 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000552 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
553 }
554 }
555
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000556 /// Load the combined index from disk, then load every file referenced by
557 /// the index and add them to the generator, finally perform the promotion
558 /// on the files mentioned on the command line (these must match the index
559 /// content).
560 void promote() {
561 if (InputFilenames.size() != 1 && !OutputFilename.empty())
562 report_fatal_error("Can't handle a single output filename and multiple "
563 "input files, do not provide an output filename and "
564 "the output files will be suffixed from the input "
565 "ones.");
566
567 auto Index = loadCombinedIndex();
568 for (auto &Filename : InputFilenames) {
569 LLVMContext Ctx;
570 auto TheModule = loadModule(Filename, Ctx);
571
572 ThinGenerator.promote(*TheModule, *Index);
573
574 std::string OutputName = OutputFilename;
575 if (OutputName.empty()) {
576 OutputName = Filename + ".thinlto.promoted.bc";
577 }
578 writeModuleToFile(*TheModule, OutputName);
579 }
580 }
581
582 /// Load the combined index from disk, then load every file referenced by
583 /// the index and add them to the generator, then performs the promotion and
584 /// cross module importing on the files mentioned on the command line
585 /// (these must match the index content).
586 void import() {
587 if (InputFilenames.size() != 1 && !OutputFilename.empty())
588 report_fatal_error("Can't handle a single output filename and multiple "
589 "input files, do not provide an output filename and "
590 "the output files will be suffixed from the input "
591 "ones.");
592
593 auto Index = loadCombinedIndex();
594 auto InputBuffers = loadAllFilesForIndex(*Index);
595 for (auto &MemBuffer : InputBuffers)
596 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
597 MemBuffer->getBuffer());
598
599 for (auto &Filename : InputFilenames) {
600 LLVMContext Ctx;
601 auto TheModule = loadModule(Filename, Ctx);
602
603 ThinGenerator.crossModuleImport(*TheModule, *Index);
604
605 std::string OutputName = OutputFilename;
606 if (OutputName.empty()) {
607 OutputName = Filename + ".thinlto.imported.bc";
608 }
609 writeModuleToFile(*TheModule, OutputName);
610 }
611 }
612
Mehdi Amini059464f2016-04-24 03:18:01 +0000613 void internalize() {
614 if (InputFilenames.size() != 1 && !OutputFilename.empty())
615 report_fatal_error("Can't handle a single output filename and multiple "
616 "input files, do not provide an output filename and "
617 "the output files will be suffixed from the input "
618 "ones.");
619
620 if (ExportedSymbols.empty())
621 errs() << "Warning: -internalize will not perform without "
622 "-exported-symbol\n";
623
624 auto Index = loadCombinedIndex();
625 auto InputBuffers = loadAllFilesForIndex(*Index);
626 for (auto &MemBuffer : InputBuffers)
627 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
628 MemBuffer->getBuffer());
629
630 for (auto &Filename : InputFilenames) {
631 LLVMContext Ctx;
632 auto TheModule = loadModule(Filename, Ctx);
633
634 ThinGenerator.internalize(*TheModule, *Index);
635
636 std::string OutputName = OutputFilename;
637 if (OutputName.empty()) {
638 OutputName = Filename + ".thinlto.internalized.bc";
639 }
640 writeModuleToFile(*TheModule, OutputName);
641 }
642 }
643
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000644 void optimize() {
645 if (InputFilenames.size() != 1 && !OutputFilename.empty())
646 report_fatal_error("Can't handle a single output filename and multiple "
647 "input files, do not provide an output filename and "
648 "the output files will be suffixed from the input "
649 "ones.");
650 if (!ThinLTOIndex.empty())
651 errs() << "Warning: -thinlto-index ignored for optimize stage";
652
653 for (auto &Filename : InputFilenames) {
654 LLVMContext Ctx;
655 auto TheModule = loadModule(Filename, Ctx);
656
657 ThinGenerator.optimize(*TheModule);
658
659 std::string OutputName = OutputFilename;
660 if (OutputName.empty()) {
661 OutputName = Filename + ".thinlto.imported.bc";
662 }
663 writeModuleToFile(*TheModule, OutputName);
664 }
665 }
666
667 void codegen() {
668 if (InputFilenames.size() != 1 && !OutputFilename.empty())
669 report_fatal_error("Can't handle a single output filename and multiple "
670 "input files, do not provide an output filename and "
671 "the output files will be suffixed from the input "
672 "ones.");
673 if (!ThinLTOIndex.empty())
674 errs() << "Warning: -thinlto-index ignored for codegen stage";
675
676 for (auto &Filename : InputFilenames) {
677 LLVMContext Ctx;
678 auto TheModule = loadModule(Filename, Ctx);
679
680 auto Buffer = ThinGenerator.codegen(*TheModule);
681 std::string OutputName = OutputFilename;
682 if (OutputName.empty()) {
683 OutputName = Filename + ".thinlto.o";
684 }
685 if (OutputName == "-") {
686 outs() << Buffer->getBuffer();
687 return;
688 }
689
690 std::error_code EC;
691 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
692 error(EC, "error opening the file '" + OutputName + "'");
693 OS << Buffer->getBuffer();
694 }
695 }
696
697 /// Full ThinLTO process
698 void runAll() {
699 if (!OutputFilename.empty())
700 report_fatal_error("Do not provide an output filename for ThinLTO "
701 " processing, the output files will be suffixed from "
702 "the input ones.");
703
704 if (!ThinLTOIndex.empty())
705 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
706
707 LLVMContext Ctx;
708 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
709 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
710 auto &Filename = InputFilenames[i];
711 StringRef CurrentActivity = "loading file '" + Filename + "'";
712 auto InputOrErr = MemoryBuffer::getFile(Filename);
713 error(InputOrErr, "error " + CurrentActivity);
714 InputBuffers.push_back(std::move(*InputOrErr));
715 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
716 }
717
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000718 if (!ThinLTOSaveTempsPrefix.empty())
719 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000720
721 if (!ThinLTOGeneratedObjectsDir.empty()) {
722 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
723 ThinGenerator.run();
724 return;
725 }
726
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000727 ThinGenerator.run();
728
729 auto &Binaries = ThinGenerator.getProducedBinaries();
730 if (Binaries.size() != InputFilenames.size())
731 report_fatal_error("Number of output objects does not match the number "
732 "of inputs");
733
734 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
735 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
736 std::error_code EC;
737 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
738 error(EC, "error opening the file '" + OutputName + "'");
739 OS << Binaries[BufID]->getBuffer();
740 }
741 }
742
743 /// Load the combined index from disk, then load every file referenced by
744};
745
746} // namespace thinlto
747
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000748int main(int argc, char **argv) {
749 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000750 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000751 PrettyStackTraceProgram X(argc, argv);
752
753 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
754 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
755
Rafael Espindola5e128db2015-12-04 00:45:57 +0000756 if (OptLevel < '0' || OptLevel > '3')
757 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000758
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000759 // Initialize the configured targets.
760 InitializeAllTargets();
761 InitializeAllTargetMCs();
762 InitializeAllAsmPrinters();
763 InitializeAllAsmParsers();
764
Rafael Espindola0b385c72013-09-30 16:39:19 +0000765 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000766 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000767
Rafael Espindola5e128db2015-12-04 00:45:57 +0000768 if (ListSymbolsOnly) {
769 listSymbols(Options);
770 return 0;
771 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000772
Mehdi Amini06a47802016-09-14 21:04:59 +0000773 if (IndexStats) {
774 printIndexStats();
775 return 0;
776 }
777
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000778 if (CheckHasObjC) {
779 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000780 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
781 Filename + "': ");
782 std::unique_ptr<MemoryBuffer> BufferOrErr =
783 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000784 auto Buffer = std::move(BufferOrErr.get());
Peter Collingbournecd513a42016-11-11 19:50:24 +0000785 if (ExitOnErr(llvm::isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000786 outs() << "Bitcode " << Filename << " contains ObjC\n";
787 else
788 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
789 }
790 return 0;
791 }
792
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000793 if (ThinLTOMode.getNumOccurrences()) {
794 if (ThinLTOMode.getNumOccurrences() > 1)
795 report_fatal_error("You can't specify more than one -thinlto-action");
796 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
797 ThinLTOProcessor.run();
798 return 0;
799 }
800
Rafael Espindola5e128db2015-12-04 00:45:57 +0000801 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000802 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000803 return 0;
804 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000805
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000806 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000807
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000808 LLVMContext Context;
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000809 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000810
811 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000812
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000813 if (UseDiagnosticHandler)
814 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
815
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000816 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000817 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000818
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000819 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000820 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000821 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000822
Rafael Espindola282a4702013-10-31 20:51:58 +0000823 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
824 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
825 DSOSymbolsSet.insert(DSOSymbols[i]);
826
827 std::vector<std::string> KeptDSOSyms;
828
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000829 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000830 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
831 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000832 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000833 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
834 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000835
Peter Collingbourne552174392015-08-21 19:09:42 +0000836 unsigned NumSyms = Module->getSymbolCount();
837 for (unsigned I = 0; I < NumSyms; ++I) {
838 StringRef Name = Module->getSymbolName(I);
839 if (!DSOSymbolsSet.count(Name))
840 continue;
841 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
842 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
843 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
844 KeptDSOSyms.push_back(Name);
845 }
Manman Ren6487ce92015-02-24 00:45:56 +0000846
847 // We use the first input module as the destination module when
848 // SetMergedModule is true.
849 if (SetMergedModule && i == BaseArg) {
850 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000851 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000852 } else if (!CodeGen.addModule(Module.get())) {
853 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000854 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000855 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000856 }
857
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000858 // Add all the exported symbols to the table of symbols to preserve.
859 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000860 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000861
Rafael Espindolacda29112013-10-03 18:29:09 +0000862 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000863 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000864 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000865
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000866 // Set cpu and attrs strings for the default target/subtarget.
867 CodeGen.setCpu(MCPU.c_str());
868
Peter Collingbourne070843d2015-03-19 22:01:00 +0000869 CodeGen.setOptLevel(OptLevel - '0');
870
Tom Roederfd1bc602014-04-25 21:46:51 +0000871 std::string attrs;
872 for (unsigned i = 0; i < MAttrs.size(); ++i) {
873 if (i > 0)
874 attrs.append(",");
875 attrs.append(MAttrs[i]);
876 }
877
878 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000879 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000880
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000881 if (FileType.getNumOccurrences())
882 CodeGen.setFileType(FileType);
883
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000884 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000885 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000886 DisableLTOVectorization)) {
887 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000888 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000889 }
890
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000891 if (SaveModuleFile) {
892 std::string ModuleFilename = OutputFilename;
893 ModuleFilename += ".merged.bc";
894 std::string ErrMsg;
895
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000896 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000897 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000898 }
899
Peter Collingbournec269ed52015-08-27 23:37:36 +0000900 std::list<tool_output_file> OSs;
901 std::vector<raw_pwrite_stream *> OSPtrs;
902 for (unsigned I = 0; I != Parallelism; ++I) {
903 std::string PartFilename = OutputFilename;
904 if (Parallelism != 1)
905 PartFilename += "." + utostr(I);
906 std::error_code EC;
907 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000908 if (EC)
909 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000910 OSPtrs.push_back(&OSs.back().os());
911 }
912
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000913 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000914 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000915 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000916
Peter Collingbournec269ed52015-08-27 23:37:36 +0000917 for (tool_output_file &OS : OSs)
918 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000919 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000920 if (Parallelism != 1)
921 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000922
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000923 if (SaveModuleFile)
924 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000925
Craig Toppere6cb63e2014-04-25 04:24:47 +0000926 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000927 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000928 DisableGVNLoadPRE, DisableLTOVectorization))
929 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000930 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000931
932 outs() << "Wrote native object file '" << OutputName << "'\n";
933 }
934
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000935 return 0;
936}