blob: ddde23175a3bc44b003e23fdcca5a1a309e214c7 [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"
Rafael Espindola0b385c72013-09-30 16:39:19 +000016#include "llvm/CodeGen/CommandFlags.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000017#include "llvm/LTO/LTOCodeGenerator.h"
18#include "llvm/LTO/LTOModule.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000019#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000020#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000021#include "llvm/Support/ManagedStatic.h"
22#include "llvm/Support/PrettyStackTrace.h"
23#include "llvm/Support/Signals.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000024#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000025#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000026#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000027#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000028
29using namespace llvm;
30
Peter Collingbourne070843d2015-03-19 22:01:00 +000031static cl::opt<char>
32OptLevel("O",
33 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
34 "(default = '-O2')"),
35 cl::Prefix,
36 cl::ZeroOrMore,
37 cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038
Rafael Espindola0b385c72013-09-30 16:39:19 +000039static cl::opt<bool>
40DisableInline("disable-inlining", cl::init(false),
41 cl::desc("Do not run the inliner pass"));
42
43static cl::opt<bool>
44DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
45 cl::desc("Do not run the GVN load PRE pass"));
46
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000047static cl::opt<bool>
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000048DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
49 cl::desc("Do not run loop or slp vectorization during LTO"));
50
51static cl::opt<bool>
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000052UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
53 cl::desc("Use a diagnostic handler to test the handler interface"));
54
Rafael Espindola0b385c72013-09-30 16:39:19 +000055static cl::list<std::string>
56InputFilenames(cl::Positional, cl::OneOrMore,
57 cl::desc("<input bitcode files>"));
58
59static cl::opt<std::string>
60OutputFilename("o", cl::init(""),
61 cl::desc("Override output filename"),
62 cl::value_desc("filename"));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000063
Rafael Espindoladafc53d2013-10-02 14:12:56 +000064static cl::list<std::string>
65ExportedSymbols("exported-symbol",
66 cl::desc("Symbol to export from the resulting object file"),
67 cl::ZeroOrMore);
68
Rafael Espindolacda29112013-10-03 18:29:09 +000069static cl::list<std::string>
70DSOSymbols("dso-symbol",
71 cl::desc("Symbol to put in the symtab in the resulting dso"),
72 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +000073
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +000074static cl::opt<bool> ListSymbolsOnly(
75 "list-symbols-only", cl::init(false),
76 cl::desc("Instead of running LTO, list the symbols in each IR file"));
77
Manman Ren6487ce92015-02-24 00:45:56 +000078static cl::opt<bool> SetMergedModule(
79 "set-merged-module", cl::init(false),
80 cl::desc("Use the first input module as the merged module"));
81
Peter Collingbournec269ed52015-08-27 23:37:36 +000082static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
83 cl::desc("Number of backend threads"));
84
Rafael Espindola282a4702013-10-31 20:51:58 +000085namespace {
86struct ModuleInfo {
87 std::vector<bool> CanBeHidden;
88};
89}
90
Benjamin Kramerf044d3f2015-03-09 16:23:46 +000091static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
92 const char *Msg, void *) {
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000093 switch (Severity) {
94 case LTO_DS_NOTE:
95 errs() << "note: ";
96 break;
97 case LTO_DS_REMARK:
98 errs() << "remark: ";
99 break;
100 case LTO_DS_ERROR:
101 errs() << "error: ";
102 break;
103 case LTO_DS_WARNING:
104 errs() << "warning: ";
105 break;
106 }
107 errs() << Msg << "\n";
108}
109
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000110static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000111getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
112 const TargetOptions &Options, std::string &Error) {
113 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
114 MemoryBuffer::getFile(Path);
115 if (std::error_code EC = BufferOrErr.getError()) {
116 Error = EC.message();
117 return nullptr;
118 }
119 Buffer = std::move(BufferOrErr.get());
120 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
121 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
122}
123
124/// \brief List symbols in each IR file.
125///
126/// The main point here is to provide lit-testable coverage for the LTOModule
127/// functionality that's exposed by the C API to list symbols. Moreover, this
128/// provides testing coverage for modules that have been created in their own
129/// contexts.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000130static int listSymbols(StringRef Command, const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000131 for (auto &Filename : InputFilenames) {
132 std::string Error;
133 std::unique_ptr<MemoryBuffer> Buffer;
134 std::unique_ptr<LTOModule> Module =
135 getLocalLTOModule(Filename, Buffer, Options, Error);
136 if (!Module) {
137 errs() << Command << ": error loading file '" << Filename
138 << "': " << Error << "\n";
139 return 1;
140 }
141
142 // List the symbols.
143 outs() << Filename << ":\n";
144 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
145 outs() << Module->getSymbolName(I) << "\n";
146 }
147 return 0;
148}
149
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000150int main(int argc, char **argv) {
151 // Print a stack trace if we signal out.
152 sys::PrintStackTraceOnErrorSignal();
153 PrettyStackTraceProgram X(argc, argv);
154
155 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
156 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
157
Peter Collingbourne070843d2015-03-19 22:01:00 +0000158 if (OptLevel < '0' || OptLevel > '3') {
159 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
160 return 1;
161 }
162
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000163 // Initialize the configured targets.
164 InitializeAllTargets();
165 InitializeAllTargetMCs();
166 InitializeAllAsmPrinters();
167 InitializeAllAsmParsers();
168
Rafael Espindola0b385c72013-09-30 16:39:19 +0000169 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000170 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000171
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000172 if (ListSymbolsOnly)
173 return listSymbols(argv[0], Options);
174
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000175 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000176
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000177 LTOCodeGenerator CodeGen;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000178
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000179 if (UseDiagnosticHandler)
180 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
181
Peter Collingbourne44ee84e2015-08-21 22:57:17 +0000182 CodeGen.setCodePICModel(RelocModel);
James Molloy951e5292014-04-14 13:54:16 +0000183
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000184 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000185 CodeGen.setTargetOptions(Options);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000186
Rafael Espindola282a4702013-10-31 20:51:58 +0000187 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
188 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
189 DSOSymbolsSet.insert(DSOSymbols[i]);
190
191 std::vector<std::string> KeptDSOSyms;
192
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000193 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000194 std::string error;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000195 std::unique_ptr<LTOModule> Module(
Peter Collingbourne63086fe2014-07-03 23:28:00 +0000196 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000197 if (!error.empty()) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000198 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000199 << "': " << error << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000200 return 1;
201 }
202
Peter Collingbourne552174392015-08-21 19:09:42 +0000203 unsigned NumSyms = Module->getSymbolCount();
204 for (unsigned I = 0; I < NumSyms; ++I) {
205 StringRef Name = Module->getSymbolName(I);
206 if (!DSOSymbolsSet.count(Name))
207 continue;
208 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
209 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
210 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
211 KeptDSOSyms.push_back(Name);
212 }
Manman Ren6487ce92015-02-24 00:45:56 +0000213
214 // We use the first input module as the destination module when
215 // SetMergedModule is true.
216 if (SetMergedModule && i == BaseArg) {
217 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000218 CodeGen.setModule(std::move(Module));
Manman Ren6487ce92015-02-24 00:45:56 +0000219 } else if (!CodeGen.addModule(Module.get()))
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000220 return 1;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000221 }
222
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000223 // Add all the exported symbols to the table of symbols to preserve.
224 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
225 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
226
Rafael Espindolacda29112013-10-03 18:29:09 +0000227 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000228 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
229 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000230
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000231 // Set cpu and attrs strings for the default target/subtarget.
232 CodeGen.setCpu(MCPU.c_str());
233
Peter Collingbourne070843d2015-03-19 22:01:00 +0000234 CodeGen.setOptLevel(OptLevel - '0');
235
Tom Roederfd1bc602014-04-25 21:46:51 +0000236 std::string attrs;
237 for (unsigned i = 0; i < MAttrs.size(); ++i) {
238 if (i > 0)
239 attrs.append(",");
240 attrs.append(MAttrs[i]);
241 }
242
243 if (!attrs.empty())
244 CodeGen.setAttr(attrs.c_str());
245
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000246 if (!OutputFilename.empty()) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000247 std::string ErrorInfo;
Peter Collingbournec269ed52015-08-27 23:37:36 +0000248 if (!CodeGen.optimize(DisableInline, DisableGVNLoadPRE,
249 DisableLTOVectorization, ErrorInfo)) {
250 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000251 return 1;
252 }
253
Peter Collingbournec269ed52015-08-27 23:37:36 +0000254 std::list<tool_output_file> OSs;
255 std::vector<raw_pwrite_stream *> OSPtrs;
256 for (unsigned I = 0; I != Parallelism; ++I) {
257 std::string PartFilename = OutputFilename;
258 if (Parallelism != 1)
259 PartFilename += "." + utostr(I);
260 std::error_code EC;
261 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
262 if (EC) {
263 errs() << argv[0] << ": error opening the file '" << PartFilename
264 << "': " << EC.message() << "\n";
265 return 1;
266 }
267 OSPtrs.push_back(&OSs.back().os());
268 }
269
270 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
271 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000272 return 1;
273 }
274
Peter Collingbournec269ed52015-08-27 23:37:36 +0000275 for (tool_output_file &OS : OSs)
276 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000277 } else {
Peter Collingbournec269ed52015-08-27 23:37:36 +0000278 if (Parallelism != 1) {
279 errs() << argv[0] << ": -j must be specified together with -o\n";
280 return 1;
281 }
282
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000283 std::string ErrorInfo;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000284 const char *OutputName = nullptr;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000285 if (!CodeGen.compile_to_file(&OutputName, DisableInline,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000286 DisableGVNLoadPRE, DisableLTOVectorization,
287 ErrorInfo)) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000288 errs() << argv[0]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000289 << ": error compiling the code: " << ErrorInfo
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000290 << "\n";
291 return 1;
292 }
293
294 outs() << "Wrote native object file '" << OutputName << "'\n";
295 }
296
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000297 return 0;
298}