blob: b6facc919b5148bd0a5d9a0a6d345590f617baa8 [file] [log] [blame]
Eugene Zelenkof95cab82017-09-07 23:28:24 +00001//===- llvm-lto: a simple command-line program to link modules with LTO ---===//
Peter Collingbourne88fae0e2013-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 Zelenkof95cab82017-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 Espindola7e667c52013-10-31 20:51:58 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000022#include "llvm/ADT/Twine.h"
Teresa Johnsona5479192016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikie461bf522018-04-11 18:49:37 +000025#include "llvm/CodeGen/CommandFlags.inc"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000026#include "llvm/IR/DiagnosticInfo.h"
Mehdi Amini0ab4d522015-11-19 05:52:29 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsond6e77b72015-10-19 14:30:44 +000028#include "llvm/IR/LLVMContext.h"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000029#include "llvm/IR/Module.h"
30#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini63d7d492016-04-20 01:04:26 +000031#include "llvm/IR/Verifier.h"
Mehdi Amini73cf01b2016-03-09 01:37:22 +000032#include "llvm/IRReader/IRReader.h"
Peter Collingbourneef2acb52016-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 Zelenkof95cab82017-09-07 23:28:24 +000036#include "llvm/Support/Allocator.h"
37#include "llvm/Support/Casting.h"
Peter Collingbourne88fae0e2013-09-19 22:15:52 +000038#include "llvm/Support/CommandLine.h"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000039#include "llvm/Support/Error.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/ErrorOr.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000042#include "llvm/Support/FileSystem.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000043#include "llvm/Support/InitLLVM.h"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000044#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsona4863812016-05-17 14:45:30 +000045#include "llvm/Support/Path.h"
Mehdi Amini73cf01b2016-03-09 01:37:22 +000046#include "llvm/Support/SourceMgr.h"
Peter Collingbournecc488542013-09-24 23:52:22 +000047#include "llvm/Support/TargetSelect.h"
Peter Collingbournedaf68852015-08-27 23:37:36 +000048#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth9f20a4c2014-01-13 08:04:33 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof95cab82017-09-07 23:28:24 +000050#include "llvm/Target/TargetOptions.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstdlib>
Peter Collingbournedaf68852015-08-27 23:37:36 +000055#include <list>
Eugene Zelenkof95cab82017-09-07 23:28:24 +000056#include <map>
57#include <memory>
58#include <string>
59#include <system_error>
60#include <tuple>
61#include <utility>
62#include <vector>
Peter Collingbourne88fae0e2013-09-19 22:15:52 +000063
64using namespace llvm;
65
Peter Collingbourne416d8ec2015-03-19 22:01:00 +000066static cl::opt<char>
Davide Italianof8df4a02016-04-13 21:41:35 +000067 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
68 "(default = '-O2')"),
69 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne88fae0e2013-09-19 22:15:52 +000070
Mehdi Aminie0384662016-09-14 21:04:59 +000071static cl::opt<bool>
72 IndexStats("thinlto-index-stats",
73 cl::desc("Print statistic for the index in every input files"),
74 cl::init(false));
75
Duncan P. N. Exon Smith5e60a682015-09-15 23:05:59 +000076static cl::opt<bool> DisableVerify(
77 "disable-verify", cl::init(false),
78 cl::desc("Do not run the verifier during the optimization pipeline"));
79
Davide Italianof8df4a02016-04-13 21:41:35 +000080static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
81 cl::desc("Do not run the inliner pass"));
Rafael Espindolac13c9e52013-09-30 16:39:19 +000082
83static cl::opt<bool>
Davide Italianof8df4a02016-04-13 21:41:35 +000084 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
85 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindolac13c9e52013-09-30 16:39:19 +000086
Davide Italianof8df4a02016-04-13 21:41:35 +000087static cl::opt<bool> DisableLTOVectorization(
88 "disable-lto-vectorization", cl::init(false),
89 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighoferb26fb772014-10-26 21:50:58 +000090
Mehdi Aminie4c5b692017-03-28 18:55:44 +000091static cl::opt<bool> EnableFreestanding(
92 "lto-freestanding", cl::init(false),
93 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
94
Davide Italianof8df4a02016-04-13 21:41:35 +000095static cl::opt<bool> UseDiagnosticHandler(
96 "use-diagnostic-handler", cl::init(false),
97 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith04d21862014-10-01 18:36:03 +000098
Teresa Johnson9dd98c02015-11-02 18:02:11 +000099static cl::opt<bool>
100 ThinLTO("thinlto", cl::init(false),
101 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000102
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000103enum ThinLTOModes {
104 THINLINK,
Teresa Johnson27af2052016-05-10 13:48:23 +0000105 THINDISTRIBUTE,
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000106 THINEMITIMPORTS,
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000107 THINPROMOTE,
108 THINIMPORT,
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000109 THININTERNALIZE,
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000110 THINOPT,
111 THINCODEGEN,
112 THINALL
113};
114
115cl::opt<ThinLTOModes> ThinLTOMode(
116 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
117 cl::values(
118 clEnumValN(
119 THINLINK, "thinlink",
120 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson27af2052016-05-10 13:48:23 +0000121 clEnumValN(THINDISTRIBUTE, "distributedindexes",
122 "Produces individual indexes for distributed backends."),
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000123 clEnumValN(THINEMITIMPORTS, "emitimports",
124 "Emit imports files for distributed backends."),
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000125 clEnumValN(THINPROMOTE, "promote",
126 "Perform pre-import promotion (requires -thinlto-index)."),
127 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
128 "cross-module importing (requires "
129 "-thinlto-index)."),
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000130 clEnumValN(THININTERNALIZE, "internalize",
131 "Perform internalization driven by -exported-symbol "
132 "(requires -thinlto-index)."),
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000133 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
134 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini3ffe1132016-10-08 19:41:06 +0000135 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000136
137static cl::opt<std::string>
138 ThinLTOIndex("thinlto-index",
139 cl::desc("Provide the index produced by a ThinLink, required "
140 "to perform the promotion and/or importing."));
141
Teresa Johnsona4863812016-05-17 14:45:30 +0000142static cl::opt<std::string> ThinLTOPrefixReplace(
143 "thinlto-prefix-replace",
144 cl::desc("Control where files for distributed backends are "
Reid Kleckner4e35fa52016-05-17 18:43:22 +0000145 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsona4863812016-05-17 14:45:30 +0000146 "prefix of output file is oldprefix it will be "
147 "replaced with newprefix."));
148
Mehdi Amini3d130682016-05-05 16:33:51 +0000149static cl::opt<std::string> ThinLTOModuleId(
150 "thinlto-module-id",
151 cl::desc("For the module ID for the file to process, useful to "
152 "match what is in the index."));
153
Mehdi Aminib01d46b2016-05-14 05:16:41 +0000154static cl::opt<std::string>
155 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
156
Ben Dunbobbin5b5d2622017-12-19 14:42:38 +0000157static cl::opt<int>
Ekaterina Romanova51f80332018-02-15 23:29:21 +0000158 ThinLTOCachePruningInterval("thinlto-cache-pruning-interval",
159 cl::init(1200), cl::desc("Set ThinLTO cache pruning interval."));
Ben Dunbobbin5b5d2622017-12-19 14:42:38 +0000160
James Hendersonb981f4f2018-09-17 10:21:26 +0000161static cl::opt<unsigned long long>
Ekaterina Romanova76899c62018-03-02 03:51:27 +0000162 ThinLTOCacheMaxSizeBytes("thinlto-cache-max-size-bytes",
163 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
164
165static cl::opt<int>
166 ThinLTOCacheMaxSizeFiles("thinlto-cache-max-size-files", cl::init(1000000),
167 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
168
James Hendersonb8187872018-10-03 13:00:20 +0000169static cl::opt<unsigned>
170 ThinLTOCacheEntryExpiration("thinlto-cache-entry-expiration", cl::init(604800) /* 1w */,
171 cl::desc("Set ThinLTO cache entry expiration time."));
172
Teresa Johnson3d6b7182016-08-15 23:24:57 +0000173static cl::opt<std::string> ThinLTOSaveTempsPrefix(
174 "thinlto-save-temps",
175 cl::desc("Save ThinLTO temp files using filenames created by adding "
176 "suffixes to the given file path prefix."));
177
Mehdi Aminidbca62e2016-12-14 04:56:42 +0000178static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
179 "thinlto-save-objects",
180 cl::desc("Save ThinLTO generated object files using filenames created in "
181 "the given directory."));
182
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000183static cl::opt<bool>
Davide Italianof8df4a02016-04-13 21:41:35 +0000184 SaveModuleFile("save-merged-module", cl::init(false),
185 cl::desc("Write merged LTO module to file before CodeGen"));
186
187static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
188 cl::desc("<input bitcode files>"));
189
190static cl::opt<std::string> OutputFilename("o", cl::init(""),
191 cl::desc("Override output filename"),
192 cl::value_desc("filename"));
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000193
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000194static cl::list<std::string> ExportedSymbols(
195 "exported-symbol",
196 cl::desc("List of symbols to export from the resulting object file"),
197 cl::ZeroOrMore);
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000198
Rafael Espindolab9643662013-10-02 14:12:56 +0000199static cl::list<std::string>
Davide Italianof8df4a02016-04-13 21:41:35 +0000200 DSOSymbols("dso-symbol",
201 cl::desc("Symbol to put in the symtab in the resulting dso"),
202 cl::ZeroOrMore);
Rafael Espindolab9643662013-10-02 14:12:56 +0000203
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000204static cl::opt<bool> ListSymbolsOnly(
205 "list-symbols-only", cl::init(false),
206 cl::desc("Instead of running LTO, list the symbols in each IR file"));
207
Manman Renbd26e6a2015-02-24 00:45:56 +0000208static cl::opt<bool> SetMergedModule(
209 "set-merged-module", cl::init(false),
210 cl::desc("Use the first input module as the merged module"));
211
Peter Collingbournedaf68852015-08-27 23:37:36 +0000212static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
213 cl::desc("Number of backend threads"));
214
Tobias Edler von Koch910dc782016-01-18 23:35:24 +0000215static cl::opt<bool> RestoreGlobalsLinkage(
216 "restore-linkage", cl::init(false),
217 cl::desc("Restore original linkage of globals prior to CodeGen"));
218
Mehdi Amini45e997d2016-07-11 23:10:18 +0000219static cl::opt<bool> CheckHasObjC(
220 "check-for-objc", cl::init(false),
221 cl::desc("Only check if the module has objective-C defined in it"));
222
Rafael Espindola7e667c52013-10-31 20:51:58 +0000223namespace {
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000224
Rafael Espindola7e667c52013-10-31 20:51:58 +0000225struct ModuleInfo {
226 std::vector<bool> CanBeHidden;
227};
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000228
229} // end anonymous namespace
Rafael Espindola7e667c52013-10-31 20:51:58 +0000230
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000231static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
232 const char *Msg, void *) {
Yunzhong Gaoa987cc62015-11-10 18:52:48 +0000233 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith04d21862014-10-01 18:36:03 +0000234 switch (Severity) {
235 case LTO_DS_NOTE:
236 errs() << "note: ";
237 break;
238 case LTO_DS_REMARK:
239 errs() << "remark: ";
240 break;
241 case LTO_DS_ERROR:
242 errs() << "error: ";
243 break;
244 case LTO_DS_WARNING:
245 errs() << "warning: ";
246 break;
247 }
248 errs() << Msg << "\n";
249}
250
Rafael Espindola608d7b42015-12-04 16:14:31 +0000251static std::string CurrentActivity;
Vivek Pandya18b4c372017-09-15 20:10:09 +0000252
253namespace {
254 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
255 bool handleDiagnostics(const DiagnosticInfo &DI) override {
256 raw_ostream &OS = errs();
257 OS << "llvm-lto: ";
258 switch (DI.getSeverity()) {
259 case DS_Error:
260 OS << "error";
261 break;
262 case DS_Warning:
263 OS << "warning";
264 break;
265 case DS_Remark:
266 OS << "remark";
267 break;
268 case DS_Note:
269 OS << "note";
270 break;
271 }
272 if (!CurrentActivity.empty())
273 OS << ' ' << CurrentActivity;
274 OS << ": ";
275
276 DiagnosticPrinterRawOStream DP(OS);
277 DI.print(DP);
278 OS << '\n';
279
280 if (DI.getSeverity() == DS_Error)
281 exit(1);
282 return true;
283 }
284 };
Mehdi Amini0ab4d522015-11-19 05:52:29 +0000285 }
Mehdi Amini0ab4d522015-11-19 05:52:29 +0000286
Rafael Espindolaf0159282015-12-04 00:45:57 +0000287static void error(const Twine &Msg) {
288 errs() << "llvm-lto: " << Msg << '\n';
289 exit(1);
290}
291
292static void error(std::error_code EC, const Twine &Prefix) {
293 if (EC)
294 error(Prefix + ": " + EC.message());
295}
296
297template <typename T>
298static void error(const ErrorOr<T> &V, const Twine &Prefix) {
299 error(V.getError(), Prefix);
300}
301
Mehdi Amini63d7d492016-04-20 01:04:26 +0000302static void maybeVerifyModule(const Module &Mod) {
Mehdi Aminicda4dc62016-12-23 23:53:57 +0000303 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini63d7d492016-04-20 01:04:26 +0000304 error("Broken Module");
305}
306
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000307static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000308getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindolaf0159282015-12-04 00:45:57 +0000309 const TargetOptions &Options) {
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000310 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
311 MemoryBuffer::getFile(Path);
Rafael Espindolaf0159282015-12-04 00:45:57 +0000312 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000313 Buffer = std::move(BufferOrErr.get());
Rafael Espindola608d7b42015-12-04 16:14:31 +0000314 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu3a3e8dd2016-03-01 13:13:49 +0000315 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandya18b4c372017-09-15 20:10:09 +0000316 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
317 true);
Rafael Espindola608d7b42015-12-04 16:14:31 +0000318 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu3a3e8dd2016-03-01 13:13:49 +0000319 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
320 Options, Path);
Rafael Espindola608d7b42015-12-04 16:14:31 +0000321 CurrentActivity = "";
Mehdi Amini63d7d492016-04-20 01:04:26 +0000322 maybeVerifyModule((*Ret)->getModule());
Rafael Espindola608d7b42015-12-04 16:14:31 +0000323 return std::move(*Ret);
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000324}
325
Mehdi Aminie0384662016-09-14 21:04:59 +0000326/// Print some statistics on the index for each input files.
327void printIndexStats() {
328 for (auto &Filename : InputFilenames) {
Peter Collingbourneaeb2eff2016-11-11 19:50:39 +0000329 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
330 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000331 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Aminie0384662016-09-14 21:04:59 +0000332 // Skip files without a module summary.
333 if (!Index)
334 report_fatal_error(Filename + " does not contain an index");
335
336 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
337 for (auto &Summaries : *Index) {
Peter Collingbournee6110182017-05-04 18:03:25 +0000338 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Aminie0384662016-09-14 21:04:59 +0000339 Refs += Summary->refs().size();
340 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
341 Functions++;
342 Calls += FuncSummary->calls().size();
343 } else if (isa<AliasSummary>(Summary.get()))
344 Alias++;
345 else
346 Globals++;
347 }
348 }
349 outs() << "Index " << Filename << " contains "
350 << (Alias + Globals + Functions) << " nodes (" << Functions
351 << " functions, " << Alias << " alias, " << Globals
352 << " globals) and " << (Calls + Refs) << " edges (" << Refs
353 << " refs and " << Calls << " calls)\n";
354 }
355}
356
Adrian Prantl26b584c2018-05-01 15:54:18 +0000357/// List symbols in each IR file.
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000358///
359/// The main point here is to provide lit-testable coverage for the LTOModule
360/// functionality that's exposed by the C API to list symbols. Moreover, this
361/// provides testing coverage for modules that have been created in their own
362/// contexts.
Rafael Espindolaf0159282015-12-04 00:45:57 +0000363static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000364 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000365 std::unique_ptr<MemoryBuffer> Buffer;
366 std::unique_ptr<LTOModule> Module =
Rafael Espindolaf0159282015-12-04 00:45:57 +0000367 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000368
369 // List the symbols.
370 outs() << Filename << ":\n";
371 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
372 outs() << Module->getSymbolName(I) << "\n";
373 }
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000374}
375
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000376/// Create a combined index file from the input IR files and write it.
377///
378/// This is meant to enable testing of ThinLTO combined index generation,
379/// currently available via the gold plugin via -thinlto.
Teresa Johnsonf2403fe2016-03-15 00:04:37 +0000380static void createCombinedModuleSummaryIndex() {
Teresa Johnsone07c2602018-06-06 22:22:01 +0000381 ModuleSummaryIndex CombinedIndex(/*HaveGVs=*/false);
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000382 uint64_t NextModuleId = 0;
383 for (auto &Filename : InputFilenames) {
Peter Collingbourneaeb2eff2016-11-11 19:50:39 +0000384 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne10dbf122017-05-01 22:04:36 +0000385 std::unique_ptr<MemoryBuffer> MB =
386 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
Teresa Johnsonf90a5e02018-05-16 14:58:14 +0000387 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, NextModuleId++));
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000388 }
389 std::error_code EC;
390 assert(!OutputFilename.empty());
391 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
392 sys::fs::OpenFlags::F_None);
Rafael Espindolaf0159282015-12-04 00:45:57 +0000393 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnsondc6615a2016-03-11 18:52:24 +0000394 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000395 OS.close();
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000396}
397
Teresa Johnsona4863812016-05-17 14:45:30 +0000398/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
399/// \p NewPrefix strings, if it was specified.
400static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
401 std::string &NewPrefix) {
402 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner4e35fa52016-05-17 18:43:22 +0000403 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsona4863812016-05-17 14:45:30 +0000404 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner4e35fa52016-05-17 18:43:22 +0000405 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsona4863812016-05-17 14:45:30 +0000406 OldPrefix = Split.first.str();
407 NewPrefix = Split.second.str();
408}
409
410/// Given the original \p Path to an output file, replace any path
411/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
412/// resulting directory if it does not yet exist.
413static std::string getThinLTOOutputFile(const std::string &Path,
414 const std::string &OldPrefix,
415 const std::string &NewPrefix) {
416 if (OldPrefix.empty() && NewPrefix.empty())
417 return Path;
418 SmallString<128> NewPath(Path);
419 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
420 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
421 if (!ParentPath.empty()) {
422 // Make sure the new directory exists, creating it if necessary.
423 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
424 error(EC, "error creating the directory '" + ParentPath + "'");
425 }
426 return NewPath.str();
427}
428
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000429namespace thinlto {
430
431std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnsonf2403fe2016-03-15 00:04:37 +0000432loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000433 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
434
Mehdi Aminia3249482016-03-26 03:35:38 +0000435 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000436 const auto &Filename = ModPath.first();
Alexander Kornienkob8246842017-07-04 15:13:02 +0000437 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000438 auto InputOrErr = MemoryBuffer::getFile(Filename);
439 error(InputOrErr, "error " + CurrentActivity);
440 InputBuffers.push_back(std::move(*InputOrErr));
441 }
442 return InputBuffers;
443}
444
Teresa Johnsonf2403fe2016-03-15 00:04:37 +0000445std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000446 if (ThinLTOIndex.empty())
447 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourneaeb2eff2016-11-11 19:50:39 +0000448 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
449 "': ");
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000450 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000451}
452
453static std::unique_ptr<Module> loadModule(StringRef Filename,
454 LLVMContext &Ctx) {
455 SMDiagnostic Err;
456 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
457 if (!M) {
458 Err.print("llvm-lto", errs());
459 report_fatal_error("Can't load module for file " + Filename);
460 }
Mehdi Amini63d7d492016-04-20 01:04:26 +0000461 maybeVerifyModule(*M);
Mehdi Amini3d130682016-05-05 16:33:51 +0000462
463 if (ThinLTOModuleId.getNumOccurrences()) {
464 if (InputFilenames.size() != 1)
465 report_fatal_error("Can't override the module id for multiple files");
466 M->setModuleIdentifier(ThinLTOModuleId);
467 }
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000468 return M;
469}
470
471static void writeModuleToFile(Module &TheModule, StringRef Filename) {
472 std::error_code EC;
473 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
474 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini63d7d492016-04-20 01:04:26 +0000475 maybeVerifyModule(TheModule);
Rafael Espindola06d62072018-02-14 19:11:32 +0000476 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000477}
478
479class ThinLTOProcessing {
480public:
481 ThinLTOCodeGenerator ThinGenerator;
482
483 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindolaac8db592016-05-18 22:04:49 +0000484 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000485 ThinGenerator.setTargetOptions(Options);
Mehdi Aminib01d46b2016-05-14 05:16:41 +0000486 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Ben Dunbobbin5b5d2622017-12-19 14:42:38 +0000487 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
James Hendersonb8187872018-10-03 13:00:20 +0000488 ThinGenerator.setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
Ekaterina Romanova76899c62018-03-02 03:51:27 +0000489 ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
490 ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
Mehdi Aminie4c5b692017-03-28 18:55:44 +0000491 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000492
493 // Add all the exported symbols to the table of symbols to preserve.
494 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
495 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000496 }
497
498 void run() {
499 switch (ThinLTOMode) {
500 case THINLINK:
501 return thinLink();
Teresa Johnson27af2052016-05-10 13:48:23 +0000502 case THINDISTRIBUTE:
503 return distributedIndexes();
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000504 case THINEMITIMPORTS:
505 return emitImports();
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000506 case THINPROMOTE:
507 return promote();
508 case THINIMPORT:
509 return import();
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000510 case THININTERNALIZE:
511 return internalize();
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000512 case THINOPT:
513 return optimize();
514 case THINCODEGEN:
515 return codegen();
516 case THINALL:
517 return runAll();
518 }
519 }
520
521private:
522 /// Load the input files, create the combined index, and write it out.
523 void thinLink() {
524 // Perform "ThinLink": just produce the index
525 if (OutputFilename.empty())
526 report_fatal_error(
527 "OutputFilename is necessary to store the combined index.\n");
528
529 LLVMContext Ctx;
530 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
531 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
532 auto &Filename = InputFilenames[i];
Alexander Kornienkob8246842017-07-04 15:13:02 +0000533 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000534 auto InputOrErr = MemoryBuffer::getFile(Filename);
535 error(InputOrErr, "error " + CurrentActivity);
536 InputBuffers.push_back(std::move(*InputOrErr));
537 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
538 }
539
540 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini7fe28f82016-10-08 04:44:18 +0000541 if (!CombinedIndex)
542 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000543 std::error_code EC;
544 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
545 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnsondc6615a2016-03-11 18:52:24 +0000546 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000547 }
548
Teresa Johnson27af2052016-05-10 13:48:23 +0000549 /// Load the combined index from disk, then compute and generate
550 /// individual index files suitable for ThinLTO distributed backend builds
551 /// on the files mentioned on the command line (these must match the index
552 /// content).
553 void distributedIndexes() {
554 if (InputFilenames.size() != 1 && !OutputFilename.empty())
555 report_fatal_error("Can't handle a single output filename and multiple "
556 "input files, do not provide an output filename and "
557 "the output files will be suffixed from the input "
558 "ones.");
559
Teresa Johnsona4863812016-05-17 14:45:30 +0000560 std::string OldPrefix, NewPrefix;
561 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
562
Teresa Johnson27af2052016-05-10 13:48:23 +0000563 auto Index = loadCombinedIndex();
564 for (auto &Filename : InputFilenames) {
Teresa Johnson9a1f9912018-11-29 17:02:42 +0000565 LLVMContext Ctx;
566 auto TheModule = loadModule(Filename, Ctx);
567
Teresa Johnson27af2052016-05-10 13:48:23 +0000568 // Build a map of module to the GUIDs and summary objects that should
569 // be written to its index.
570 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
Teresa Johnson9a1f9912018-11-29 17:02:42 +0000571 ThinGenerator.gatherImportedSummariesForModule(*TheModule, *Index,
572 ModuleToSummariesForIndex);
Teresa Johnson27af2052016-05-10 13:48:23 +0000573
574 std::string OutputName = OutputFilename;
575 if (OutputName.empty()) {
576 OutputName = Filename + ".thinlto.bc";
577 }
Teresa Johnsona4863812016-05-17 14:45:30 +0000578 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson27af2052016-05-10 13:48:23 +0000579 std::error_code EC;
580 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
581 error(EC, "error opening the file '" + OutputName + "'");
582 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
583 }
584 }
585
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000586 /// Load the combined index from disk, compute the imports, and emit
587 /// the import file lists for each module to disk.
588 void emitImports() {
589 if (InputFilenames.size() != 1 && !OutputFilename.empty())
590 report_fatal_error("Can't handle a single output filename and multiple "
591 "input files, do not provide an output filename and "
592 "the output files will be suffixed from the input "
593 "ones.");
594
Teresa Johnsona4863812016-05-17 14:45:30 +0000595 std::string OldPrefix, NewPrefix;
596 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
597
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000598 auto Index = loadCombinedIndex();
599 for (auto &Filename : InputFilenames) {
Teresa Johnson9a1f9912018-11-29 17:02:42 +0000600 LLVMContext Ctx;
601 auto TheModule = loadModule(Filename, Ctx);
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000602 std::string OutputName = OutputFilename;
603 if (OutputName.empty()) {
604 OutputName = Filename + ".imports";
605 }
Teresa Johnsona4863812016-05-17 14:45:30 +0000606 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson9a1f9912018-11-29 17:02:42 +0000607 ThinGenerator.emitImports(*TheModule, OutputName, *Index);
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000608 }
609 }
610
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000611 /// Load the combined index from disk, then load every file referenced by
612 /// the index and add them to the generator, finally perform the promotion
613 /// on the files mentioned on the command line (these must match the index
614 /// content).
615 void promote() {
616 if (InputFilenames.size() != 1 && !OutputFilename.empty())
617 report_fatal_error("Can't handle a single output filename and multiple "
618 "input files, do not provide an output filename and "
619 "the output files will be suffixed from the input "
620 "ones.");
621
622 auto Index = loadCombinedIndex();
623 for (auto &Filename : InputFilenames) {
624 LLVMContext Ctx;
625 auto TheModule = loadModule(Filename, Ctx);
626
627 ThinGenerator.promote(*TheModule, *Index);
628
629 std::string OutputName = OutputFilename;
630 if (OutputName.empty()) {
631 OutputName = Filename + ".thinlto.promoted.bc";
632 }
633 writeModuleToFile(*TheModule, OutputName);
634 }
635 }
636
637 /// Load the combined index from disk, then load every file referenced by
638 /// the index and add them to the generator, then performs the promotion and
639 /// cross module importing on the files mentioned on the command line
640 /// (these must match the index content).
641 void import() {
642 if (InputFilenames.size() != 1 && !OutputFilename.empty())
643 report_fatal_error("Can't handle a single output filename and multiple "
644 "input files, do not provide an output filename and "
645 "the output files will be suffixed from the input "
646 "ones.");
647
648 auto Index = loadCombinedIndex();
649 auto InputBuffers = loadAllFilesForIndex(*Index);
650 for (auto &MemBuffer : InputBuffers)
651 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
652 MemBuffer->getBuffer());
653
654 for (auto &Filename : InputFilenames) {
655 LLVMContext Ctx;
656 auto TheModule = loadModule(Filename, Ctx);
657
658 ThinGenerator.crossModuleImport(*TheModule, *Index);
659
660 std::string OutputName = OutputFilename;
661 if (OutputName.empty()) {
662 OutputName = Filename + ".thinlto.imported.bc";
663 }
664 writeModuleToFile(*TheModule, OutputName);
665 }
666 }
667
Mehdi Aminibbf2e442016-04-24 03:18:01 +0000668 void internalize() {
669 if (InputFilenames.size() != 1 && !OutputFilename.empty())
670 report_fatal_error("Can't handle a single output filename and multiple "
671 "input files, do not provide an output filename and "
672 "the output files will be suffixed from the input "
673 "ones.");
674
675 if (ExportedSymbols.empty())
676 errs() << "Warning: -internalize will not perform without "
677 "-exported-symbol\n";
678
679 auto Index = loadCombinedIndex();
680 auto InputBuffers = loadAllFilesForIndex(*Index);
681 for (auto &MemBuffer : InputBuffers)
682 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
683 MemBuffer->getBuffer());
684
685 for (auto &Filename : InputFilenames) {
686 LLVMContext Ctx;
687 auto TheModule = loadModule(Filename, Ctx);
688
689 ThinGenerator.internalize(*TheModule, *Index);
690
691 std::string OutputName = OutputFilename;
692 if (OutputName.empty()) {
693 OutputName = Filename + ".thinlto.internalized.bc";
694 }
695 writeModuleToFile(*TheModule, OutputName);
696 }
697 }
698
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000699 void optimize() {
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 optimize stage";
707
708 for (auto &Filename : InputFilenames) {
709 LLVMContext Ctx;
710 auto TheModule = loadModule(Filename, Ctx);
711
712 ThinGenerator.optimize(*TheModule);
713
714 std::string OutputName = OutputFilename;
715 if (OutputName.empty()) {
716 OutputName = Filename + ".thinlto.imported.bc";
717 }
718 writeModuleToFile(*TheModule, OutputName);
719 }
720 }
721
722 void codegen() {
723 if (InputFilenames.size() != 1 && !OutputFilename.empty())
724 report_fatal_error("Can't handle a single output filename and multiple "
725 "input files, do not provide an output filename and "
726 "the output files will be suffixed from the input "
727 "ones.");
728 if (!ThinLTOIndex.empty())
729 errs() << "Warning: -thinlto-index ignored for codegen stage";
730
Adrian Prantl3770b2b2017-05-19 17:54:58 +0000731 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000732 for (auto &Filename : InputFilenames) {
733 LLVMContext Ctx;
Adrian Prantl3770b2b2017-05-19 17:54:58 +0000734 auto InputOrErr = MemoryBuffer::getFile(Filename);
735 error(InputOrErr, "error " + CurrentActivity);
736 InputBuffers.push_back(std::move(*InputOrErr));
737 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
738 }
739 ThinGenerator.setCodeGenOnly(true);
740 ThinGenerator.run();
741 for (auto BinName :
742 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000743 std::string OutputName = OutputFilename;
Adrian Prantl3770b2b2017-05-19 17:54:58 +0000744 if (OutputName.empty())
745 OutputName = std::get<1>(BinName) + ".thinlto.o";
746 else if (OutputName == "-") {
747 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000748 return;
749 }
750
751 std::error_code EC;
752 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
753 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantl3770b2b2017-05-19 17:54:58 +0000754 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000755 }
756 }
757
758 /// Full ThinLTO process
759 void runAll() {
760 if (!OutputFilename.empty())
761 report_fatal_error("Do not provide an output filename for ThinLTO "
762 " processing, the output files will be suffixed from "
763 "the input ones.");
764
765 if (!ThinLTOIndex.empty())
766 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
767
768 LLVMContext Ctx;
769 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
770 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
771 auto &Filename = InputFilenames[i];
Alexander Kornienkob8246842017-07-04 15:13:02 +0000772 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000773 auto InputOrErr = MemoryBuffer::getFile(Filename);
774 error(InputOrErr, "error " + CurrentActivity);
775 InputBuffers.push_back(std::move(*InputOrErr));
776 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
777 }
778
Teresa Johnson3d6b7182016-08-15 23:24:57 +0000779 if (!ThinLTOSaveTempsPrefix.empty())
780 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Aminidbca62e2016-12-14 04:56:42 +0000781
782 if (!ThinLTOGeneratedObjectsDir.empty()) {
783 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
784 ThinGenerator.run();
785 return;
786 }
787
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000788 ThinGenerator.run();
789
790 auto &Binaries = ThinGenerator.getProducedBinaries();
791 if (Binaries.size() != InputFilenames.size())
792 report_fatal_error("Number of output objects does not match the number "
793 "of inputs");
794
795 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
796 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
797 std::error_code EC;
798 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
799 error(EC, "error opening the file '" + OutputName + "'");
800 OS << Binaries[BufID]->getBuffer();
801 }
802 }
803
804 /// Load the combined index from disk, then load every file referenced by
805};
806
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000807} // end namespace thinlto
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000808
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000809int main(int argc, char **argv) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000810 InitLLVM X(argc, argv);
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000811 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
812
Rafael Espindolaf0159282015-12-04 00:45:57 +0000813 if (OptLevel < '0' || OptLevel > '3')
814 error("optimization level must be between 0 and 3");
Peter Collingbourne416d8ec2015-03-19 22:01:00 +0000815
Peter Collingbournecc488542013-09-24 23:52:22 +0000816 // Initialize the configured targets.
817 InitializeAllTargets();
818 InitializeAllTargetMCs();
819 InitializeAllAsmPrinters();
820 InitializeAllAsmParsers();
821
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000822 // set up the TargetOptions for the machine
Eli Benderskycf421742014-02-19 17:09:35 +0000823 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000824
Rafael Espindolaf0159282015-12-04 00:45:57 +0000825 if (ListSymbolsOnly) {
826 listSymbols(Options);
827 return 0;
828 }
Duncan P. N. Exon Smithc524b882014-12-17 02:00:38 +0000829
Mehdi Aminie0384662016-09-14 21:04:59 +0000830 if (IndexStats) {
831 printIndexStats();
832 return 0;
833 }
834
Mehdi Amini45e997d2016-07-11 23:10:18 +0000835 if (CheckHasObjC) {
836 for (auto &Filename : InputFilenames) {
Peter Collingbourne9b252f02016-11-11 19:50:24 +0000837 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
838 Filename + "': ");
839 std::unique_ptr<MemoryBuffer> BufferOrErr =
840 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Amini45e997d2016-07-11 23:10:18 +0000841 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000842 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Amini45e997d2016-07-11 23:10:18 +0000843 outs() << "Bitcode " << Filename << " contains ObjC\n";
844 else
845 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
846 }
847 return 0;
848 }
849
Mehdi Amini73cf01b2016-03-09 01:37:22 +0000850 if (ThinLTOMode.getNumOccurrences()) {
851 if (ThinLTOMode.getNumOccurrences() > 1)
852 report_fatal_error("You can't specify more than one -thinlto-action");
853 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
854 ThinLTOProcessor.run();
855 return 0;
856 }
857
Rafael Espindolaf0159282015-12-04 00:45:57 +0000858 if (ThinLTO) {
Teresa Johnsonf2403fe2016-03-15 00:04:37 +0000859 createCombinedModuleSummaryIndex();
Rafael Espindolaf0159282015-12-04 00:45:57 +0000860 return 0;
861 }
Teresa Johnsond6e77b72015-10-19 14:30:44 +0000862
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000863 unsigned BaseArg = 0;
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000864
Rafael Espindola608d7b42015-12-04 16:14:31 +0000865 LLVMContext Context;
Vivek Pandya18b4c372017-09-15 20:10:09 +0000866 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
867 true);
Rafael Espindola608d7b42015-12-04 16:14:31 +0000868
869 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000870
Duncan P. N. Exon Smith04d21862014-10-01 18:36:03 +0000871 if (UseDiagnosticHandler)
872 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
873
Rafael Espindolaac8db592016-05-18 22:04:49 +0000874 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminie4c5b692017-03-28 18:55:44 +0000875 CodeGen.setFreestanding(EnableFreestanding);
James Molloy555f97f2014-04-14 13:54:16 +0000876
Peter Collingbournecc488542013-09-24 23:52:22 +0000877 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000878 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch910dc782016-01-18 23:35:24 +0000879 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000880
Eugene Zelenkof95cab82017-09-07 23:28:24 +0000881 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola7e667c52013-10-31 20:51:58 +0000882 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
883 DSOSymbolsSet.insert(DSOSymbols[i]);
884
885 std::vector<std::string> KeptDSOSyms;
886
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000887 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindola608d7b42015-12-04 16:14:31 +0000888 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
889 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons4c127322016-11-02 16:43:50 +0000890 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindola608d7b42015-12-04 16:14:31 +0000891 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
892 CurrentActivity = "";
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000893
Peter Collingbourned01f3032015-08-21 19:09:42 +0000894 unsigned NumSyms = Module->getSymbolCount();
895 for (unsigned I = 0; I < NumSyms; ++I) {
896 StringRef Name = Module->getSymbolName(I);
897 if (!DSOSymbolsSet.count(Name))
898 continue;
899 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
900 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
901 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
902 KeptDSOSyms.push_back(Name);
903 }
Manman Renbd26e6a2015-02-24 00:45:56 +0000904
905 // We use the first input module as the destination module when
906 // SetMergedModule is true.
907 if (SetMergedModule && i == BaseArg) {
908 // Transfer ownership to the code generator.
Peter Collingbourne8c1602d2015-08-24 22:22:53 +0000909 CodeGen.setModule(std::move(Module));
Yunzhong Gao7ba33232015-09-11 20:01:53 +0000910 } else if (!CodeGen.addModule(Module.get())) {
911 // Print a message here so that we know addModule() did not abort.
Davide Italianoa6ab2612016-04-13 22:08:26 +0000912 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao7ba33232015-09-11 20:01:53 +0000913 }
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000914 }
915
Rafael Espindolab9643662013-10-02 14:12:56 +0000916 // Add all the exported symbols to the table of symbols to preserve.
917 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons4c127322016-11-02 16:43:50 +0000918 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindolab9643662013-10-02 14:12:56 +0000919
Rafael Espindola43890092013-10-03 18:29:09 +0000920 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola7e667c52013-10-31 20:51:58 +0000921 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons4c127322016-11-02 16:43:50 +0000922 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindola43890092013-10-03 18:29:09 +0000923
Akira Hatanaka31db3d62015-01-30 01:14:28 +0000924 // Set cpu and attrs strings for the default target/subtarget.
925 CodeGen.setCpu(MCPU.c_str());
926
Peter Collingbourne416d8ec2015-03-19 22:01:00 +0000927 CodeGen.setOptLevel(OptLevel - '0');
928
Tom Roeder817f5e22014-04-25 21:46:51 +0000929 std::string attrs;
930 for (unsigned i = 0; i < MAttrs.size(); ++i) {
931 if (i > 0)
932 attrs.append(",");
933 attrs.append(MAttrs[i]);
934 }
935
936 if (!attrs.empty())
Malcolm Parsons4c127322016-11-02 16:43:50 +0000937 CodeGen.setAttr(attrs);
Tom Roeder817f5e22014-04-25 21:46:51 +0000938
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000939 if (FileType.getNumOccurrences())
940 CodeGen.setFileType(FileType);
941
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000942 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smith5e60a682015-09-15 23:05:59 +0000943 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao576772b2015-11-17 19:48:12 +0000944 DisableLTOVectorization)) {
945 // Diagnostic messages should have been printed by the handler.
Davide Italianoa6ab2612016-04-13 22:08:26 +0000946 error("error optimizing the code");
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000947 }
948
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000949 if (SaveModuleFile) {
950 std::string ModuleFilename = OutputFilename;
951 ModuleFilename += ".merged.bc";
952 std::string ErrMsg;
953
Malcolm Parsons4c127322016-11-02 16:43:50 +0000954 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italianoa6ab2612016-04-13 22:08:26 +0000955 error("writing merged module failed.");
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000956 }
957
Reid Kleckner97ca9642017-09-23 01:03:17 +0000958 std::list<ToolOutputFile> OSs;
Peter Collingbournedaf68852015-08-27 23:37:36 +0000959 std::vector<raw_pwrite_stream *> OSPtrs;
960 for (unsigned I = 0; I != Parallelism; ++I) {
961 std::string PartFilename = OutputFilename;
962 if (Parallelism != 1)
963 PartFilename += "." + utostr(I);
964 std::error_code EC;
965 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italianoa6ab2612016-04-13 22:08:26 +0000966 if (EC)
967 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournedaf68852015-08-27 23:37:36 +0000968 OSPtrs.push_back(&OSs.back().os());
969 }
970
Davide Italianoa6ab2612016-04-13 22:08:26 +0000971 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao576772b2015-11-17 19:48:12 +0000972 // Diagnostic messages should have been printed by the handler.
Davide Italianoa6ab2612016-04-13 22:08:26 +0000973 error("error compiling the code");
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000974
Reid Kleckner97ca9642017-09-23 01:03:17 +0000975 for (ToolOutputFile &OS : OSs)
Peter Collingbournedaf68852015-08-27 23:37:36 +0000976 OS.keep();
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000977 } else {
Davide Italianoa6ab2612016-04-13 22:08:26 +0000978 if (Parallelism != 1)
979 error("-j must be specified together with -o");
Peter Collingbournedaf68852015-08-27 23:37:36 +0000980
Davide Italianoa6ab2612016-04-13 22:08:26 +0000981 if (SaveModuleFile)
982 error(": -save-merged-module must be specified with -o");
Tobias Edler von Kochcbf870d2015-11-20 00:13:05 +0000983
Craig Topper573faec2014-04-25 04:24:47 +0000984 const char *OutputName = nullptr;
Duncan P. N. Exon Smith5e60a682015-09-15 23:05:59 +0000985 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italianoa6ab2612016-04-13 22:08:26 +0000986 DisableGVNLoadPRE, DisableLTOVectorization))
987 error("error compiling the code");
Yunzhong Gao576772b2015-11-17 19:48:12 +0000988 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000989
990 outs() << "Wrote native object file '" << OutputName << "'\n";
991 }
992
Peter Collingbourne88fae0e2013-09-19 22:15:52 +0000993 return 0;
994}