There seems to be no reason for opt's -S option to be hidden.
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
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 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
41
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
44 //
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
47
48 // Other command line options...
49 //
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52     cl::init("-"), cl::value_desc("filename"));
53
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56                cl::value_desc("filename"), cl::init("-"));
57
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
60
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
63
64 static cl::opt<bool>
65 NoOutput("disable-output",
66          cl::desc("Do not write result bitcode file"), cl::Hidden);
67
68 static cl::opt<bool>
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
70
71 static cl::opt<bool>
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
73
74 static cl::opt<bool>
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
76
77 static cl::opt<bool>
78 StripDebug("strip-debug",
79            cl::desc("Strip debugger symbol info from translation unit"));
80
81 static cl::opt<bool>
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
83
84 static cl::opt<bool>
85 DisableOptimizations("disable-opt",
86                      cl::desc("Do not run any optimization passes"));
87
88 static cl::opt<bool>
89 DisableInternalize("disable-internalize",
90                    cl::desc("Do not mark all symbols as internal"));
91
92 static cl::opt<bool>
93 StandardCompileOpts("std-compile-opts",
94                    cl::desc("Include the standard compile time optimizations"));
95
96 static cl::opt<bool>
97 StandardLinkOpts("std-link-opts",
98                  cl::desc("Include the standard link time optimizations"));
99
100 static cl::opt<bool>
101 OptLevelO1("O1",
102            cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
103
104 static cl::opt<bool>
105 OptLevelO2("O2",
106            cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
107
108 static cl::opt<bool>
109 OptLevelO3("O3",
110            cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
111
112 static cl::opt<bool>
113 UnitAtATime("funit-at-a-time",
114             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115             cl::init(true));
116
117 static cl::opt<bool>
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119                         cl::desc("Disable simplify-libcalls"));
120
121 static cl::opt<bool>
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
123
124 static cl::alias
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
126
127 static cl::opt<bool>
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
129
130 // ---------- Define Printers for module and function passes ------------
131 namespace {
132
133 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
134   static char ID;
135   const PassInfo *PassToPrint;
136   CallGraphSCCPassPrinter(const PassInfo *PI) :
137     CallGraphSCCPass(&ID), PassToPrint(PI) {}
138
139   virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
140     if (!Quiet) {
141       outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
142
143       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
144         Function *F = SCC[i]->getFunction();
145         if (F) {
146           getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
147         }
148       }
149     }
150     // Get and print pass...
151     return false;
152   }
153
154   virtual const char *getPassName() const { return "'Pass' Printer"; }
155
156   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
157     AU.addRequiredID(PassToPrint);
158     AU.setPreservesAll();
159   }
160 };
161
162 char CallGraphSCCPassPrinter::ID = 0;
163
164 struct ModulePassPrinter : public ModulePass {
165   static char ID;
166   const PassInfo *PassToPrint;
167   ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
168                                           PassToPrint(PI) {}
169
170   virtual bool runOnModule(Module &M) {
171     if (!Quiet) {
172       outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
173       getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
174     }
175
176     // Get and print pass...
177     return false;
178   }
179
180   virtual const char *getPassName() const { return "'Pass' Printer"; }
181
182   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
183     AU.addRequiredID(PassToPrint);
184     AU.setPreservesAll();
185   }
186 };
187
188 char ModulePassPrinter::ID = 0;
189 struct FunctionPassPrinter : public FunctionPass {
190   const PassInfo *PassToPrint;
191   static char ID;
192   FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
193                                             PassToPrint(PI) {}
194
195   virtual bool runOnFunction(Function &F) {
196     if (!Quiet) {
197       outs() << "Printing analysis '" << PassToPrint->getPassName()
198               << "' for function '" << F.getName() << "':\n";
199     }
200     // Get and print pass...
201     getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
202     return false;
203   }
204
205   virtual const char *getPassName() const { return "FunctionPass Printer"; }
206
207   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
208     AU.addRequiredID(PassToPrint);
209     AU.setPreservesAll();
210   }
211 };
212
213 char FunctionPassPrinter::ID = 0;
214
215 struct LoopPassPrinter : public LoopPass {
216   static char ID;
217   const PassInfo *PassToPrint;
218   LoopPassPrinter(const PassInfo *PI) :
219     LoopPass(&ID), PassToPrint(PI) {}
220
221   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
222     if (!Quiet) {
223       outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
224       getAnalysisID<Pass>(PassToPrint).print(outs(),
225                                   L->getHeader()->getParent()->getParent());
226     }
227     // Get and print pass...
228     return false;
229   }
230
231   virtual const char *getPassName() const { return "'Pass' Printer"; }
232
233   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
234     AU.addRequiredID(PassToPrint);
235     AU.setPreservesAll();
236   }
237 };
238
239 char LoopPassPrinter::ID = 0;
240
241 struct BasicBlockPassPrinter : public BasicBlockPass {
242   const PassInfo *PassToPrint;
243   static char ID;
244   BasicBlockPassPrinter(const PassInfo *PI)
245     : BasicBlockPass(&ID), PassToPrint(PI) {}
246
247   virtual bool runOnBasicBlock(BasicBlock &BB) {
248     if (!Quiet) {
249       outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
250              << "': Pass " << PassToPrint->getPassName() << ":\n";
251     }
252
253     // Get and print pass...
254     getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
255     return false;
256   }
257
258   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
259
260   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
261     AU.addRequiredID(PassToPrint);
262     AU.setPreservesAll();
263   }
264 };
265
266 char BasicBlockPassPrinter::ID = 0;
267 inline void addPass(PassManager &PM, Pass *P) {
268   // Add the pass to the pass manager...
269   PM.add(P);
270
271   // If we are verifying all of the intermediate steps, add the verifier...
272   if (VerifyEach) PM.add(createVerifierPass());
273 }
274
275 /// AddOptimizationPasses - This routine adds optimization passes
276 /// based on selected optimization level, OptLevel. This routine
277 /// duplicates llvm-gcc behaviour.
278 ///
279 /// OptLevel - Optimization Level
280 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
281                            unsigned OptLevel) {
282   createStandardFunctionPasses(&FPM, OptLevel);
283
284   llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
285   createStandardModulePasses(&MPM, OptLevel,
286                              /*OptimizeSize=*/ false,
287                              UnitAtATime,
288                              /*UnrollLoops=*/ OptLevel > 1,
289                              !DisableSimplifyLibCalls,
290                              /*HaveExceptions=*/ true,
291                              InliningPass);
292 }
293
294 void AddStandardCompilePasses(PassManager &PM) {
295   PM.add(createVerifierPass());                  // Verify that input is correct
296
297   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
298
299   // If the -strip-debug command line option was specified, do it.
300   if (StripDebug)
301     addPass(PM, createStripSymbolsPass(true));
302
303   if (DisableOptimizations) return;
304
305   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
306
307   // -std-compile-opts adds the same module passes as -O3.
308   createStandardModulePasses(&PM, 3,
309                              /*OptimizeSize=*/ false,
310                              /*UnitAtATime=*/ true,
311                              /*UnrollLoops=*/ true,
312                              /*SimplifyLibCalls=*/ true,
313                              /*HaveExceptions=*/ true,
314                              InliningPass);
315 }
316
317 void AddStandardLinkPasses(PassManager &PM) {
318   PM.add(createVerifierPass());                  // Verify that input is correct
319
320   // If the -strip-debug command line option was specified, do it.
321   if (StripDebug)
322     addPass(PM, createStripSymbolsPass(true));
323
324   if (DisableOptimizations) return;
325
326   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
327                           /*RunInliner=*/ !DisableInline,
328                           /*VerifyEach=*/ VerifyEach);
329 }
330
331 } // anonymous namespace
332
333
334 //===----------------------------------------------------------------------===//
335 // main for opt
336 //
337 int main(int argc, char **argv) {
338   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
339   LLVMContext &Context = getGlobalContext();
340   try {
341     cl::ParseCommandLineOptions(argc, argv,
342       "llvm .bc -> .bc modular optimizer and analysis printer\n");
343     sys::PrintStackTraceOnErrorSignal();
344
345     // Allocate a full target machine description only if necessary.
346     // FIXME: The choice of target should be controllable on the command line.
347     std::auto_ptr<TargetMachine> target;
348
349     SMDiagnostic Err;
350
351     // Load the input module...
352     std::auto_ptr<Module> M;
353     M.reset(ParseIRFile(InputFilename, Err, Context));
354
355     if (M.get() == 0) {
356       Err.Print(argv[0], errs());
357       return 1;
358     }
359
360     // Figure out what stream we are supposed to write to...
361     // FIXME: outs() is not binary!
362     raw_ostream *Out = &outs();  // Default to printing to stdout...
363     if (OutputFilename != "-") {
364       // Make sure that the Output file gets unlinked from the disk if we get a
365       // SIGINT
366       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
367
368       std::string ErrorInfo;
369       Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
370                                raw_fd_ostream::F_Binary);
371       if (!ErrorInfo.empty()) {
372         errs() << ErrorInfo << '\n';
373         delete Out;
374         return 1;
375       }
376     }
377
378     // If the output is set to be emitted to standard out, and standard out is a
379     // console, print out a warning message and refuse to do it.  We don't
380     // impress anyone by spewing tons of binary goo to a terminal.
381     if (!Force && !NoOutput && !OutputAssembly)
382       if (CheckBitcodeOutputToConsole(*Out, !Quiet))
383         NoOutput = true;
384
385     // Create a PassManager to hold and optimize the collection of passes we are
386     // about to build...
387     //
388     PassManager Passes;
389
390     // Add an appropriate TargetData instance for this module...
391     Passes.add(new TargetData(M.get()));
392
393     FunctionPassManager *FPasses = NULL;
394     if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
395       FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
396       FPasses->add(new TargetData(M.get()));
397     }
398
399     // If the -strip-debug command line option was specified, add it.  If
400     // -std-compile-opts was also specified, it will handle StripDebug.
401     if (StripDebug && !StandardCompileOpts)
402       addPass(Passes, createStripSymbolsPass(true));
403
404     // Create a new optimization pass for each one specified on the command line
405     for (unsigned i = 0; i < PassList.size(); ++i) {
406       // Check to see if -std-compile-opts was specified before this option.  If
407       // so, handle it.
408       if (StandardCompileOpts &&
409           StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
410         AddStandardCompilePasses(Passes);
411         StandardCompileOpts = false;
412       }
413
414       if (StandardLinkOpts &&
415           StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
416         AddStandardLinkPasses(Passes);
417         StandardLinkOpts = false;
418       }
419
420       if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
421         AddOptimizationPasses(Passes, *FPasses, 1);
422         OptLevelO1 = false;
423       }
424
425       if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
426         AddOptimizationPasses(Passes, *FPasses, 2);
427         OptLevelO2 = false;
428       }
429
430       if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
431         AddOptimizationPasses(Passes, *FPasses, 3);
432         OptLevelO3 = false;
433       }
434
435       const PassInfo *PassInf = PassList[i];
436       Pass *P = 0;
437       if (PassInf->getNormalCtor())
438         P = PassInf->getNormalCtor()();
439       else
440         errs() << argv[0] << ": cannot create pass: "
441                << PassInf->getPassName() << "\n";
442       if (P) {
443         bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
444         bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
445         bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
446         bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
447
448         addPass(Passes, P);
449
450         if (AnalyzeOnly) {
451           if (isBBPass)
452             Passes.add(new BasicBlockPassPrinter(PassInf));
453           else if (isLPass)
454             Passes.add(new LoopPassPrinter(PassInf));
455           else if (isFPass)
456             Passes.add(new FunctionPassPrinter(PassInf));
457           else if (isCGSCCPass)
458             Passes.add(new CallGraphSCCPassPrinter(PassInf));
459           else
460             Passes.add(new ModulePassPrinter(PassInf));
461         }
462       }
463
464       if (PrintEachXForm)
465         Passes.add(createPrintModulePass(&errs()));
466     }
467
468     // If -std-compile-opts was specified at the end of the pass list, add them.
469     if (StandardCompileOpts) {
470       AddStandardCompilePasses(Passes);
471       StandardCompileOpts = false;
472     }
473
474     if (StandardLinkOpts) {
475       AddStandardLinkPasses(Passes);
476       StandardLinkOpts = false;
477     }
478
479     if (OptLevelO1) {
480       AddOptimizationPasses(Passes, *FPasses, 1);
481     }
482
483     if (OptLevelO2) {
484       AddOptimizationPasses(Passes, *FPasses, 2);
485     }
486
487     if (OptLevelO3) {
488       AddOptimizationPasses(Passes, *FPasses, 3);
489     }
490
491     if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
492       FPasses->doInitialization();
493       for (Module::iterator I = M.get()->begin(), E = M.get()->end();
494            I != E; ++I)
495         FPasses->run(*I);
496     }
497
498     // Check that the module is well formed on completion of optimization
499     if (!NoVerify && !VerifyEach)
500       Passes.add(createVerifierPass());
501
502     // Write bitcode or assembly  out to disk or outs() as the last step...
503     if (!NoOutput && !AnalyzeOnly) {
504       if (OutputAssembly)
505         Passes.add(createPrintModulePass(Out));
506       else
507         Passes.add(createBitcodeWriterPass(*Out));
508     }
509
510     // Now that we have all of the passes ready, run them.
511     Passes.run(*M.get());
512
513     // Delete the raw_fd_ostream.
514     if (Out != &outs())
515       delete Out;
516     return 0;
517
518   } catch (const std::string& msg) {
519     errs() << argv[0] << ": " << msg << "\n";
520   } catch (...) {
521     errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
522   }
523   llvm_shutdown();
524   return 1;
525 }