blob: 50680ccb8ab3a21a15665ad12dac4020a08c19f3 [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
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000039static cl::opt<bool> DisableVerify(
40 "disable-verify", cl::init(false),
41 cl::desc("Do not run the verifier during the optimization pipeline"));
42
Rafael Espindola0b385c72013-09-30 16:39:19 +000043static cl::opt<bool>
44DisableInline("disable-inlining", cl::init(false),
45 cl::desc("Do not run the inliner pass"));
46
47static cl::opt<bool>
48DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
49 cl::desc("Do not run the GVN load PRE pass"));
50
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000051static cl::opt<bool>
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000052DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
53 cl::desc("Do not run loop or slp vectorization during LTO"));
54
55static cl::opt<bool>
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000056UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
57 cl::desc("Use a diagnostic handler to test the handler interface"));
58
Rafael Espindola0b385c72013-09-30 16:39:19 +000059static cl::list<std::string>
60InputFilenames(cl::Positional, cl::OneOrMore,
61 cl::desc("<input bitcode files>"));
62
63static cl::opt<std::string>
64OutputFilename("o", cl::init(""),
65 cl::desc("Override output filename"),
66 cl::value_desc("filename"));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000067
Rafael Espindoladafc53d2013-10-02 14:12:56 +000068static cl::list<std::string>
69ExportedSymbols("exported-symbol",
70 cl::desc("Symbol to export from the resulting object file"),
71 cl::ZeroOrMore);
72
Rafael Espindolacda29112013-10-03 18:29:09 +000073static cl::list<std::string>
74DSOSymbols("dso-symbol",
75 cl::desc("Symbol to put in the symtab in the resulting dso"),
76 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +000077
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +000078static cl::opt<bool> ListSymbolsOnly(
79 "list-symbols-only", cl::init(false),
80 cl::desc("Instead of running LTO, list the symbols in each IR file"));
81
Manman Ren6487ce92015-02-24 00:45:56 +000082static cl::opt<bool> SetMergedModule(
83 "set-merged-module", cl::init(false),
84 cl::desc("Use the first input module as the merged module"));
85
Peter Collingbournec269ed52015-08-27 23:37:36 +000086static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
87 cl::desc("Number of backend threads"));
88
Rafael Espindola282a4702013-10-31 20:51:58 +000089namespace {
90struct ModuleInfo {
91 std::vector<bool> CanBeHidden;
92};
93}
94
Benjamin Kramerf044d3f2015-03-09 16:23:46 +000095static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
96 const char *Msg, void *) {
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000097 switch (Severity) {
98 case LTO_DS_NOTE:
99 errs() << "note: ";
100 break;
101 case LTO_DS_REMARK:
102 errs() << "remark: ";
103 break;
104 case LTO_DS_ERROR:
105 errs() << "error: ";
106 break;
107 case LTO_DS_WARNING:
108 errs() << "warning: ";
109 break;
110 }
111 errs() << Msg << "\n";
112}
113
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000114static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000115getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
116 const TargetOptions &Options, std::string &Error) {
117 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
118 MemoryBuffer::getFile(Path);
119 if (std::error_code EC = BufferOrErr.getError()) {
120 Error = EC.message();
121 return nullptr;
122 }
123 Buffer = std::move(BufferOrErr.get());
124 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
125 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
126}
127
128/// \brief List symbols in each IR file.
129///
130/// The main point here is to provide lit-testable coverage for the LTOModule
131/// functionality that's exposed by the C API to list symbols. Moreover, this
132/// provides testing coverage for modules that have been created in their own
133/// contexts.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000134static int listSymbols(StringRef Command, const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000135 for (auto &Filename : InputFilenames) {
136 std::string Error;
137 std::unique_ptr<MemoryBuffer> Buffer;
138 std::unique_ptr<LTOModule> Module =
139 getLocalLTOModule(Filename, Buffer, Options, Error);
140 if (!Module) {
141 errs() << Command << ": error loading file '" << Filename
142 << "': " << Error << "\n";
143 return 1;
144 }
145
146 // List the symbols.
147 outs() << Filename << ":\n";
148 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
149 outs() << Module->getSymbolName(I) << "\n";
150 }
151 return 0;
152}
153
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000154int main(int argc, char **argv) {
155 // Print a stack trace if we signal out.
156 sys::PrintStackTraceOnErrorSignal();
157 PrettyStackTraceProgram X(argc, argv);
158
159 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
160 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
161
Peter Collingbourne070843d2015-03-19 22:01:00 +0000162 if (OptLevel < '0' || OptLevel > '3') {
163 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
164 return 1;
165 }
166
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000167 // Initialize the configured targets.
168 InitializeAllTargets();
169 InitializeAllTargetMCs();
170 InitializeAllAsmPrinters();
171 InitializeAllAsmParsers();
172
Rafael Espindola0b385c72013-09-30 16:39:19 +0000173 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000174 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000175
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000176 if (ListSymbolsOnly)
177 return listSymbols(argv[0], Options);
178
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000179 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000180
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000181 LTOCodeGenerator CodeGen;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000182
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000183 if (UseDiagnosticHandler)
184 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
185
Peter Collingbourne44ee84e2015-08-21 22:57:17 +0000186 CodeGen.setCodePICModel(RelocModel);
James Molloy951e5292014-04-14 13:54:16 +0000187
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000188 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000189 CodeGen.setTargetOptions(Options);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000190
Rafael Espindola282a4702013-10-31 20:51:58 +0000191 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
192 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
193 DSOSymbolsSet.insert(DSOSymbols[i]);
194
195 std::vector<std::string> KeptDSOSyms;
196
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000197 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000198 std::string error;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000199 std::unique_ptr<LTOModule> Module(
Peter Collingbourne63086fe2014-07-03 23:28:00 +0000200 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000201 if (!error.empty()) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000202 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000203 << "': " << error << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000204 return 1;
205 }
206
Peter Collingbourne552174392015-08-21 19:09:42 +0000207 unsigned NumSyms = Module->getSymbolCount();
208 for (unsigned I = 0; I < NumSyms; ++I) {
209 StringRef Name = Module->getSymbolName(I);
210 if (!DSOSymbolsSet.count(Name))
211 continue;
212 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
213 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
214 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
215 KeptDSOSyms.push_back(Name);
216 }
Manman Ren6487ce92015-02-24 00:45:56 +0000217
218 // We use the first input module as the destination module when
219 // SetMergedModule is true.
220 if (SetMergedModule && i == BaseArg) {
221 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000222 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000223 } else if (!CodeGen.addModule(Module.get())) {
224 // Print a message here so that we know addModule() did not abort.
225 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000226 return 1;
Yunzhong Gao46261a72015-09-11 20:01:53 +0000227 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000228 }
229
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000230 // Add all the exported symbols to the table of symbols to preserve.
231 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
232 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
233
Rafael Espindolacda29112013-10-03 18:29:09 +0000234 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000235 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
236 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000237
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000238 // Set cpu and attrs strings for the default target/subtarget.
239 CodeGen.setCpu(MCPU.c_str());
240
Peter Collingbourne070843d2015-03-19 22:01:00 +0000241 CodeGen.setOptLevel(OptLevel - '0');
242
Tom Roederfd1bc602014-04-25 21:46:51 +0000243 std::string attrs;
244 for (unsigned i = 0; i < MAttrs.size(); ++i) {
245 if (i > 0)
246 attrs.append(",");
247 attrs.append(MAttrs[i]);
248 }
249
250 if (!attrs.empty())
251 CodeGen.setAttr(attrs.c_str());
252
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000253 if (!OutputFilename.empty()) {
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000254 std::string ErrorInfo;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000255 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Peter Collingbournec269ed52015-08-27 23:37:36 +0000256 DisableLTOVectorization, ErrorInfo)) {
257 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000258 return 1;
259 }
260
Peter Collingbournec269ed52015-08-27 23:37:36 +0000261 std::list<tool_output_file> OSs;
262 std::vector<raw_pwrite_stream *> OSPtrs;
263 for (unsigned I = 0; I != Parallelism; ++I) {
264 std::string PartFilename = OutputFilename;
265 if (Parallelism != 1)
266 PartFilename += "." + utostr(I);
267 std::error_code EC;
268 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
269 if (EC) {
270 errs() << argv[0] << ": error opening the file '" << PartFilename
271 << "': " << EC.message() << "\n";
272 return 1;
273 }
274 OSPtrs.push_back(&OSs.back().os());
275 }
276
277 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
278 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000279 return 1;
280 }
281
Peter Collingbournec269ed52015-08-27 23:37:36 +0000282 for (tool_output_file &OS : OSs)
283 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000284 } else {
Peter Collingbournec269ed52015-08-27 23:37:36 +0000285 if (Parallelism != 1) {
286 errs() << argv[0] << ": -j must be specified together with -o\n";
287 return 1;
288 }
289
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000290 std::string ErrorInfo;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000291 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000292 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000293 DisableGVNLoadPRE, DisableLTOVectorization,
294 ErrorInfo)) {
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000295 errs() << argv[0]
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000296 << ": error compiling the code: " << ErrorInfo
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000297 << "\n";
298 return 1;
299 }
300
301 outs() << "Wrote native object file '" << OutputName << "'\n";
302 }
303
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000304 return 0;
305}