LTO: Disable extra verify runs in release builds
[oota-llvm.git] / tools / llvm-lto / llvm-lto.cpp
1 //===-- 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
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/CodeGen/CommandFlags.h"
17 #include "llvm/LTO/LTOCodeGenerator.h"
18 #include "llvm/LTO/LTOModule.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/Support/ToolOutputFile.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <list>
28
29 using namespace llvm;
30
31 static cl::opt<char>
32 OptLevel("O",
33          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
34                   "(default = '-O2')"),
35          cl::Prefix,
36          cl::ZeroOrMore,
37          cl::init('2'));
38
39 static cl::opt<bool> DisableVerify(
40     "disable-verify", cl::init(false),
41     cl::desc("Do not run the verifier during the optimization pipeline"));
42
43 static cl::opt<bool>
44 DisableInline("disable-inlining", cl::init(false),
45   cl::desc("Do not run the inliner pass"));
46
47 static cl::opt<bool>
48 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
49   cl::desc("Do not run the GVN load PRE pass"));
50
51 static cl::opt<bool>
52 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
53   cl::desc("Do not run loop or slp vectorization during LTO"));
54
55 static cl::opt<bool>
56 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
57   cl::desc("Use a diagnostic handler to test the handler interface"));
58
59 static cl::list<std::string>
60 InputFilenames(cl::Positional, cl::OneOrMore,
61   cl::desc("<input bitcode files>"));
62
63 static cl::opt<std::string>
64 OutputFilename("o", cl::init(""),
65   cl::desc("Override output filename"),
66   cl::value_desc("filename"));
67
68 static cl::list<std::string>
69 ExportedSymbols("exported-symbol",
70   cl::desc("Symbol to export from the resulting object file"),
71   cl::ZeroOrMore);
72
73 static cl::list<std::string>
74 DSOSymbols("dso-symbol",
75   cl::desc("Symbol to put in the symtab in the resulting dso"),
76   cl::ZeroOrMore);
77
78 static 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
82 static cl::opt<bool> SetMergedModule(
83     "set-merged-module", cl::init(false),
84     cl::desc("Use the first input module as the merged module"));
85
86 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
87                                      cl::desc("Number of backend threads"));
88
89 namespace {
90 struct ModuleInfo {
91   std::vector<bool> CanBeHidden;
92 };
93 }
94
95 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
96                               const char *Msg, void *) {
97   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
114 static std::unique_ptr<LTOModule>
115 getLocalLTOModule(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.
134 static int listSymbols(StringRef Command, const TargetOptions &Options) {
135   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
154 int 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
162   if (OptLevel < '0' || OptLevel > '3') {
163     errs() << argv[0] << ": optimization level must be between 0 and 3\n";
164     return 1;
165   }
166
167   // Initialize the configured targets.
168   InitializeAllTargets();
169   InitializeAllTargetMCs();
170   InitializeAllAsmPrinters();
171   InitializeAllAsmParsers();
172
173   // set up the TargetOptions for the machine
174   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
175
176   if (ListSymbolsOnly)
177     return listSymbols(argv[0], Options);
178
179   unsigned BaseArg = 0;
180
181   LTOCodeGenerator CodeGen;
182
183   if (UseDiagnosticHandler)
184     CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
185
186   CodeGen.setCodePICModel(RelocModel);
187
188   CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
189   CodeGen.setTargetOptions(Options);
190
191   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
197   for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
198     std::string error;
199     std::unique_ptr<LTOModule> Module(
200         LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
201     if (!error.empty()) {
202       errs() << argv[0] << ": error loading file '" << InputFilenames[i]
203              << "': " << error << "\n";
204       return 1;
205     }
206
207     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     }
217
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.
222       CodeGen.setModule(std::move(Module));
223     } 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";
226       return 1;
227     }
228   }
229
230   // 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
234   // Add all the dso symbols to the table of symbols to expose.
235   for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
236     CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
237
238   // Set cpu and attrs strings for the default target/subtarget.
239   CodeGen.setCpu(MCPU.c_str());
240
241   CodeGen.setOptLevel(OptLevel - '0');
242
243   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
253   if (!OutputFilename.empty()) {
254     std::string ErrorInfo;
255     if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
256                           DisableLTOVectorization, ErrorInfo)) {
257       errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
258       return 1;
259     }
260
261     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";
279       return 1;
280     }
281
282     for (tool_output_file &OS : OSs)
283       OS.keep();
284   } else {
285     if (Parallelism != 1) {
286       errs() << argv[0] << ": -j must be specified together with -o\n";
287       return 1;
288     }
289
290     std::string ErrorInfo;
291     const char *OutputName = nullptr;
292     if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
293                                  DisableGVNLoadPRE, DisableLTOVectorization,
294                                  ErrorInfo)) {
295       errs() << argv[0]
296              << ": error compiling the code: " << ErrorInfo
297              << "\n";
298       return 1;
299     }
300
301     outs() << "Wrote native object file '" << OutputName << "'\n";
302   }
303
304   return 0;
305 }