blob: 29d613f8cd2ce7b0068026197e04897ba3f5b480 [file] [log] [blame]
Peter Collingbourne4e380b02013-09-19 22:15:52 +00001//===-- llvm-lto: a simple command-line program to link modules with LTO --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program takes in a list of bitcode files, links them, performs link-time
11// optimization, and outputs an object file.
12//
13//===----------------------------------------------------------------------===//
14
Rafael Espindola282a4702013-10-31 20:51:58 +000015#include "llvm/ADT/StringSet.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000016#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000017#include "llvm/CodeGen/CommandFlags.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000018#include "llvm/IR/LLVMContext.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000019#include "llvm/LTO/LTOCodeGenerator.h"
20#include "llvm/LTO/LTOModule.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000021#include "llvm/Object/FunctionIndexObjectFile.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000022#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000023#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000024#include "llvm/Support/ManagedStatic.h"
25#include "llvm/Support/PrettyStackTrace.h"
26#include "llvm/Support/Signals.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000027#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000028#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000029#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000030#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000031
32using namespace llvm;
33
Peter Collingbourne070843d2015-03-19 22:01:00 +000034static cl::opt<char>
35OptLevel("O",
36 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
37 "(default = '-O2')"),
38 cl::Prefix,
39 cl::ZeroOrMore,
40 cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000041
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000042static cl::opt<bool> DisableVerify(
43 "disable-verify", cl::init(false),
44 cl::desc("Do not run the verifier during the optimization pipeline"));
45
Rafael Espindola0b385c72013-09-30 16:39:19 +000046static cl::opt<bool>
47DisableInline("disable-inlining", cl::init(false),
48 cl::desc("Do not run the inliner pass"));
49
50static cl::opt<bool>
51DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
52 cl::desc("Do not run the GVN load PRE pass"));
53
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000054static cl::opt<bool>
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000055DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
56 cl::desc("Do not run loop or slp vectorization during LTO"));
57
58static cl::opt<bool>
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000059UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
60 cl::desc("Use a diagnostic handler to test the handler interface"));
61
Teresa Johnson91a88bb2015-10-19 14:30:44 +000062static cl::opt<bool> ThinLTO(
63 "thinlto", cl::init(false),
64 cl::desc("Only write combined global index for ThinLTO backends"));
65
Rafael Espindola0b385c72013-09-30 16:39:19 +000066static cl::list<std::string>
67InputFilenames(cl::Positional, cl::OneOrMore,
68 cl::desc("<input bitcode files>"));
69
70static cl::opt<std::string>
71OutputFilename("o", cl::init(""),
72 cl::desc("Override output filename"),
73 cl::value_desc("filename"));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000074
Rafael Espindoladafc53d2013-10-02 14:12:56 +000075static cl::list<std::string>
76ExportedSymbols("exported-symbol",
77 cl::desc("Symbol to export from the resulting object file"),
78 cl::ZeroOrMore);
79
Rafael Espindolacda29112013-10-03 18:29:09 +000080static cl::list<std::string>
81DSOSymbols("dso-symbol",
82 cl::desc("Symbol to put in the symtab in the resulting dso"),
83 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +000084
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +000085static cl::opt<bool> ListSymbolsOnly(
86 "list-symbols-only", cl::init(false),
87 cl::desc("Instead of running LTO, list the symbols in each IR file"));
88
Manman Ren6487ce92015-02-24 00:45:56 +000089static cl::opt<bool> SetMergedModule(
90 "set-merged-module", cl::init(false),
91 cl::desc("Use the first input module as the merged module"));
92
Peter Collingbournec269ed52015-08-27 23:37:36 +000093static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
94 cl::desc("Number of backend threads"));
95
Rafael Espindola282a4702013-10-31 20:51:58 +000096namespace {
97struct ModuleInfo {
98 std::vector<bool> CanBeHidden;
99};
100}
101
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000102static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
103 const char *Msg, void *) {
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000104 switch (Severity) {
105 case LTO_DS_NOTE:
106 errs() << "note: ";
107 break;
108 case LTO_DS_REMARK:
109 errs() << "remark: ";
110 break;
111 case LTO_DS_ERROR:
112 errs() << "error: ";
113 break;
114 case LTO_DS_WARNING:
115 errs() << "warning: ";
116 break;
117 }
118 errs() << Msg << "\n";
119}
120
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000121static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000122getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
123 const TargetOptions &Options, std::string &Error) {
124 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
125 MemoryBuffer::getFile(Path);
126 if (std::error_code EC = BufferOrErr.getError()) {
127 Error = EC.message();
128 return nullptr;
129 }
130 Buffer = std::move(BufferOrErr.get());
131 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
132 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
133}
134
135/// \brief List symbols in each IR file.
136///
137/// The main point here is to provide lit-testable coverage for the LTOModule
138/// functionality that's exposed by the C API to list symbols. Moreover, this
139/// provides testing coverage for modules that have been created in their own
140/// contexts.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000141static int listSymbols(StringRef Command, const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000142 for (auto &Filename : InputFilenames) {
143 std::string Error;
144 std::unique_ptr<MemoryBuffer> Buffer;
145 std::unique_ptr<LTOModule> Module =
146 getLocalLTOModule(Filename, Buffer, Options, Error);
147 if (!Module) {
148 errs() << Command << ": error loading file '" << Filename
149 << "': " << Error << "\n";
150 return 1;
151 }
152
153 // List the symbols.
154 outs() << Filename << ":\n";
155 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
156 outs() << Module->getSymbolName(I) << "\n";
157 }
158 return 0;
159}
160
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000161/// Parse the function index out of an IR file and return the function
162/// index object if found, or nullptr if not.
163static std::unique_ptr<FunctionInfoIndex> getFunctionIndexForFile(
164 StringRef Path, std::string &Error, LLVMContext &Context) {
165 std::unique_ptr<MemoryBuffer> Buffer;
166 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
167 MemoryBuffer::getFile(Path);
168 if (std::error_code EC = BufferOrErr.getError()) {
169 Error = EC.message();
170 return nullptr;
171 }
172 Buffer = std::move(BufferOrErr.get());
173 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
174 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
175 Context);
176 if (std::error_code EC = ObjOrErr.getError()) {
177 Error = EC.message();
178 return nullptr;
179 }
180 return (*ObjOrErr)->takeIndex();
181}
182
183/// Create a combined index file from the input IR files and write it.
184///
185/// This is meant to enable testing of ThinLTO combined index generation,
186/// currently available via the gold plugin via -thinlto.
187static int createCombinedFunctionIndex(StringRef Command) {
188 LLVMContext Context;
189 FunctionInfoIndex CombinedIndex;
190 uint64_t NextModuleId = 0;
191 for (auto &Filename : InputFilenames) {
192 std::string Error;
193 std::unique_ptr<FunctionInfoIndex> Index =
194 getFunctionIndexForFile(Filename, Error, Context);
195 if (!Index) {
196 errs() << Command << ": error loading file '" << Filename
197 << "': " << Error << "\n";
198 return 1;
199 }
200 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
201 }
202 std::error_code EC;
203 assert(!OutputFilename.empty());
204 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
205 sys::fs::OpenFlags::F_None);
206 if (EC) {
207 errs() << Command << ": error opening the file '" << OutputFilename
208 << ".thinlto.bc': " << EC.message() << "\n";
209 return 1;
210 }
211 WriteFunctionSummaryToFile(&CombinedIndex, OS);
212 OS.close();
213 return 0;
214}
215
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000216int main(int argc, char **argv) {
217 // Print a stack trace if we signal out.
218 sys::PrintStackTraceOnErrorSignal();
219 PrettyStackTraceProgram X(argc, argv);
220
221 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
222 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
223
Peter Collingbourne070843d2015-03-19 22:01:00 +0000224 if (OptLevel < '0' || OptLevel > '3') {
225 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
226 return 1;
227 }
228
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000229 // Initialize the configured targets.
230 InitializeAllTargets();
231 InitializeAllTargetMCs();
232 InitializeAllAsmPrinters();
233 InitializeAllAsmParsers();
234
Rafael Espindola0b385c72013-09-30 16:39:19 +0000235 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000236 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000237
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000238 if (ListSymbolsOnly)
239 return listSymbols(argv[0], Options);
240
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000241 if (ThinLTO) return createCombinedFunctionIndex(argv[0]);
242
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000243 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000244
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000245 LTOCodeGenerator CodeGen;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000246
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000247 if (UseDiagnosticHandler)
248 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
249
Peter Collingbourne44ee84e2015-08-21 22:57:17 +0000250 CodeGen.setCodePICModel(RelocModel);
James Molloy951e5292014-04-14 13:54:16 +0000251
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000252 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000253 CodeGen.setTargetOptions(Options);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000254
Rafael Espindola282a4702013-10-31 20:51:58 +0000255 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
256 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
257 DSOSymbolsSet.insert(DSOSymbols[i]);
258
259 std::vector<std::string> KeptDSOSyms;
260
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000261 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000262 std::string error;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000263 std::unique_ptr<LTOModule> Module(
Peter Collingbourne63086fe2014-07-03 23:28:00 +0000264 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000265 if (!error.empty()) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000266 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000267 << "': " << error << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000268 return 1;
269 }
270
Peter Collingbourne552174392015-08-21 19:09:42 +0000271 unsigned NumSyms = Module->getSymbolCount();
272 for (unsigned I = 0; I < NumSyms; ++I) {
273 StringRef Name = Module->getSymbolName(I);
274 if (!DSOSymbolsSet.count(Name))
275 continue;
276 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
277 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
278 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
279 KeptDSOSyms.push_back(Name);
280 }
Manman Ren6487ce92015-02-24 00:45:56 +0000281
282 // We use the first input module as the destination module when
283 // SetMergedModule is true.
284 if (SetMergedModule && i == BaseArg) {
285 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000286 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000287 } else if (!CodeGen.addModule(Module.get())) {
288 // Print a message here so that we know addModule() did not abort.
289 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000290 return 1;
Yunzhong Gao46261a72015-09-11 20:01:53 +0000291 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000292 }
293
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000294 // Add all the exported symbols to the table of symbols to preserve.
295 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
296 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
297
Rafael Espindolacda29112013-10-03 18:29:09 +0000298 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000299 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
300 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000301
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000302 // Set cpu and attrs strings for the default target/subtarget.
303 CodeGen.setCpu(MCPU.c_str());
304
Peter Collingbourne070843d2015-03-19 22:01:00 +0000305 CodeGen.setOptLevel(OptLevel - '0');
306
Tom Roederfd1bc602014-04-25 21:46:51 +0000307 std::string attrs;
308 for (unsigned i = 0; i < MAttrs.size(); ++i) {
309 if (i > 0)
310 attrs.append(",");
311 attrs.append(MAttrs[i]);
312 }
313
314 if (!attrs.empty())
315 CodeGen.setAttr(attrs.c_str());
316
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000317 if (!OutputFilename.empty()) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000318 std::string ErrorInfo;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000319 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Peter Collingbournec269ed52015-08-27 23:37:36 +0000320 DisableLTOVectorization, ErrorInfo)) {
321 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000322 return 1;
323 }
324
Peter Collingbournec269ed52015-08-27 23:37:36 +0000325 std::list<tool_output_file> OSs;
326 std::vector<raw_pwrite_stream *> OSPtrs;
327 for (unsigned I = 0; I != Parallelism; ++I) {
328 std::string PartFilename = OutputFilename;
329 if (Parallelism != 1)
330 PartFilename += "." + utostr(I);
331 std::error_code EC;
332 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
333 if (EC) {
334 errs() << argv[0] << ": error opening the file '" << PartFilename
335 << "': " << EC.message() << "\n";
336 return 1;
337 }
338 OSPtrs.push_back(&OSs.back().os());
339 }
340
341 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
342 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000343 return 1;
344 }
345
Peter Collingbournec269ed52015-08-27 23:37:36 +0000346 for (tool_output_file &OS : OSs)
347 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000348 } else {
Peter Collingbournec269ed52015-08-27 23:37:36 +0000349 if (Parallelism != 1) {
350 errs() << argv[0] << ": -j must be specified together with -o\n";
351 return 1;
352 }
353
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000354 std::string ErrorInfo;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000355 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000356 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000357 DisableGVNLoadPRE, DisableLTOVectorization,
358 ErrorInfo)) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000359 errs() << argv[0]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000360 << ": error compiling the code: " << ErrorInfo
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000361 << "\n";
362 return 1;
363 }
364
365 outs() << "Wrote native object file '" << OutputName << "'\n";
366 }
367
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000368 return 0;
369}