Get rid of static constructors for pass registration. Instead, every pass exposes...
[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/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/ToolOutputFile.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"));
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 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout", 
132           cl::desc("data layout string to use if not specified by module"),
133           cl::value_desc("layout-string"), cl::init(""));
134
135 // ---------- Define Printers for module and function passes ------------
136 namespace {
137
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
139   static char ID;
140   const PassInfo *PassToPrint;
141   raw_ostream &Out;
142   std::string PassName;
143
144   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
145     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
146       std::string PassToPrintName =  PassToPrint->getPassName();
147       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
148     }
149
150   virtual bool runOnSCC(CallGraphSCC &SCC) {
151     if (!Quiet)
152       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
153
154     // Get and print pass...
155     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
156       Function *F = (*I)->getFunction();
157       if (F)
158         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
159                                                               F->getParent());
160     }
161     return false;
162   }
163
164   virtual const char *getPassName() const { return PassName.c_str(); }
165
166   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167     AU.addRequiredID(PassToPrint->getTypeInfo());
168     AU.setPreservesAll();
169   }
170 };
171
172 char CallGraphSCCPassPrinter::ID = 0;
173
174 struct ModulePassPrinter : public ModulePass {
175   static char ID;
176   const PassInfo *PassToPrint;
177   raw_ostream &Out;
178   std::string PassName;
179
180   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
181     : ModulePass(ID), PassToPrint(PI), Out(out) {
182       std::string PassToPrintName =  PassToPrint->getPassName();
183       PassName = "ModulePass Printer: " + PassToPrintName;
184     }
185
186   virtual bool runOnModule(Module &M) {
187     if (!Quiet)
188       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
189
190     // Get and print pass...
191     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
192     return false;
193   }
194
195   virtual const char *getPassName() const { return PassName.c_str(); }
196
197   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198     AU.addRequiredID(PassToPrint->getTypeInfo());
199     AU.setPreservesAll();
200   }
201 };
202
203 char ModulePassPrinter::ID = 0;
204 struct FunctionPassPrinter : public FunctionPass {
205   const PassInfo *PassToPrint;
206   raw_ostream &Out;
207   static char ID;
208   std::string PassName;
209
210   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
211     : FunctionPass(ID), PassToPrint(PI), Out(out) {
212       std::string PassToPrintName =  PassToPrint->getPassName();
213       PassName = "FunctionPass Printer: " + PassToPrintName;
214     }
215
216   virtual bool runOnFunction(Function &F) {
217     if (!Quiet)
218       Out << "Printing analysis '" << PassToPrint->getPassName()
219           << "' for function '" << F.getName() << "':\n";
220
221     // Get and print pass...
222     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
223             F.getParent());
224     return false;
225   }
226
227   virtual const char *getPassName() const { return PassName.c_str(); }
228
229   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230     AU.addRequiredID(PassToPrint->getTypeInfo());
231     AU.setPreservesAll();
232   }
233 };
234
235 char FunctionPassPrinter::ID = 0;
236
237 struct LoopPassPrinter : public LoopPass {
238   static char ID;
239   const PassInfo *PassToPrint;
240   raw_ostream &Out;
241   std::string PassName;
242
243   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
244     LoopPass(ID), PassToPrint(PI), Out(out) {
245       std::string PassToPrintName =  PassToPrint->getPassName();
246       PassName = "LoopPass Printer: " + PassToPrintName;
247     }
248
249
250   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
251     if (!Quiet)
252       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
253
254     // Get and print pass...
255     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
256                         L->getHeader()->getParent()->getParent());
257     return false;
258   }
259
260   virtual const char *getPassName() const { return PassName.c_str(); }
261
262   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
263     AU.addRequiredID(PassToPrint->getTypeInfo());
264     AU.setPreservesAll();
265   }
266 };
267
268 char LoopPassPrinter::ID = 0;
269
270 struct BasicBlockPassPrinter : public BasicBlockPass {
271   const PassInfo *PassToPrint;
272   raw_ostream &Out;
273   static char ID;
274   std::string PassName;
275
276   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
277     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
278       std::string PassToPrintName =  PassToPrint->getPassName();
279       PassName = "BasicBlockPass Printer: " + PassToPrintName;
280     }
281
282   virtual bool runOnBasicBlock(BasicBlock &BB) {
283     if (!Quiet)
284       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
285           << "': Pass " << PassToPrint->getPassName() << ":\n";
286
287     // Get and print pass...
288     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
289             BB.getParent()->getParent());
290     return false;
291   }
292
293   virtual const char *getPassName() const { return PassName.c_str(); }
294
295   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
296     AU.addRequiredID(PassToPrint->getTypeInfo());
297     AU.setPreservesAll();
298   }
299 };
300
301 char BasicBlockPassPrinter::ID = 0;
302 inline void addPass(PassManagerBase &PM, Pass *P) {
303   // Add the pass to the pass manager...
304   PM.add(P);
305
306   // If we are verifying all of the intermediate steps, add the verifier...
307   if (VerifyEach) PM.add(createVerifierPass());
308 }
309
310 /// AddOptimizationPasses - This routine adds optimization passes
311 /// based on selected optimization level, OptLevel. This routine
312 /// duplicates llvm-gcc behaviour.
313 ///
314 /// OptLevel - Optimization Level
315 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
316                            unsigned OptLevel) {
317   createStandardFunctionPasses(&FPM, OptLevel);
318
319   llvm::Pass *InliningPass = 0;
320   if (DisableInline) {
321     // No inlining pass
322   } else if (OptLevel) {
323     unsigned Threshold = 200;
324     if (OptLevel > 2)
325       Threshold = 250;
326     InliningPass = createFunctionInliningPass(Threshold);
327   } else {
328     InliningPass = createAlwaysInlinerPass();
329   }
330   createStandardModulePasses(&MPM, OptLevel,
331                              /*OptimizeSize=*/ false,
332                              UnitAtATime,
333                              /*UnrollLoops=*/ OptLevel > 1,
334                              !DisableSimplifyLibCalls,
335                              /*HaveExceptions=*/ true,
336                              InliningPass);
337 }
338
339 void AddStandardCompilePasses(PassManagerBase &PM) {
340   PM.add(createVerifierPass());                  // Verify that input is correct
341
342   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
343
344   // If the -strip-debug command line option was specified, do it.
345   if (StripDebug)
346     addPass(PM, createStripSymbolsPass(true));
347
348   if (DisableOptimizations) return;
349
350   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
351
352   // -std-compile-opts adds the same module passes as -O3.
353   createStandardModulePasses(&PM, 3,
354                              /*OptimizeSize=*/ false,
355                              /*UnitAtATime=*/ true,
356                              /*UnrollLoops=*/ true,
357                              /*SimplifyLibCalls=*/ true,
358                              /*HaveExceptions=*/ true,
359                              InliningPass);
360 }
361
362 void AddStandardLinkPasses(PassManagerBase &PM) {
363   PM.add(createVerifierPass());                  // Verify that input is correct
364
365   // If the -strip-debug command line option was specified, do it.
366   if (StripDebug)
367     addPass(PM, createStripSymbolsPass(true));
368
369   if (DisableOptimizations) return;
370
371   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
372                           /*RunInliner=*/ !DisableInline,
373                           /*VerifyEach=*/ VerifyEach);
374 }
375
376 } // anonymous namespace
377
378
379 //===----------------------------------------------------------------------===//
380 // main for opt
381 //
382 int main(int argc, char **argv) {
383   sys::PrintStackTraceOnErrorSignal();
384   llvm::PrettyStackTraceProgram X(argc, argv);
385
386   if (AnalyzeOnly && NoOutput) {
387     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
388     return 1;
389   }
390   
391   // Enable debug stream buffering.
392   EnableDebugBuffering = true;
393
394   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
395   LLVMContext &Context = getGlobalContext();
396   
397   // Initialize passes
398   PassRegistry &Registry = *PassRegistry::getPassRegistry();
399   initializeCore(Registry);
400   initializeScalarOpts(Registry);
401   initializeIPO(Registry);
402   initializeAnalysis(Registry);
403   initializeIPA(Registry);
404   initializeTransformUtils(Registry);
405   initializeInstCombine(Registry);
406   initializeInstrumentation(Registry);
407   initializeTarget(Registry);
408   
409   cl::ParseCommandLineOptions(argc, argv,
410     "llvm .bc -> .bc modular optimizer and analysis printer\n");
411
412   // Allocate a full target machine description only if necessary.
413   // FIXME: The choice of target should be controllable on the command line.
414   std::auto_ptr<TargetMachine> target;
415
416   SMDiagnostic Err;
417
418   // Load the input module...
419   std::auto_ptr<Module> M;
420   M.reset(ParseIRFile(InputFilename, Err, Context));
421
422   if (M.get() == 0) {
423     Err.Print(argv[0], errs());
424     return 1;
425   }
426
427   // Figure out what stream we are supposed to write to...
428   OwningPtr<tool_output_file> Out;
429   if (NoOutput) {
430     if (!OutputFilename.empty())
431       errs() << "WARNING: The -o (output filename) option is ignored when\n"
432                 "the --disable-output option is used.\n";
433   } else {
434     // Default to standard output.
435     if (OutputFilename.empty())
436       OutputFilename = "-";
437
438     std::string ErrorInfo;
439     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
440                                    raw_fd_ostream::F_Binary));
441     if (!ErrorInfo.empty()) {
442       errs() << ErrorInfo << '\n';
443       return 1;
444     }
445   }
446
447   // If the output is set to be emitted to standard out, and standard out is a
448   // console, print out a warning message and refuse to do it.  We don't
449   // impress anyone by spewing tons of binary goo to a terminal.
450   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
451     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
452       NoOutput = true;
453
454   // Create a PassManager to hold and optimize the collection of passes we are
455   // about to build...
456   //
457   PassManager Passes;
458
459   // Add an appropriate TargetData instance for this module...
460   TargetData *TD = 0;
461   const std::string &ModuleDataLayout = M.get()->getDataLayout();
462   if (!ModuleDataLayout.empty())
463     TD = new TargetData(ModuleDataLayout);
464   else if (!DefaultDataLayout.empty())
465     TD = new TargetData(DefaultDataLayout);
466
467   if (TD)
468     Passes.add(TD);
469
470   OwningPtr<PassManager> FPasses;
471   if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
472     FPasses.reset(new PassManager());
473     if (TD)
474       FPasses->add(new TargetData(*TD));
475   }
476
477   // If the -strip-debug command line option was specified, add it.  If
478   // -std-compile-opts was also specified, it will handle StripDebug.
479   if (StripDebug && !StandardCompileOpts)
480     addPass(Passes, createStripSymbolsPass(true));
481
482   // Create a new optimization pass for each one specified on the command line
483   for (unsigned i = 0; i < PassList.size(); ++i) {
484     // Check to see if -std-compile-opts was specified before this option.  If
485     // so, handle it.
486     if (StandardCompileOpts &&
487         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
488       AddStandardCompilePasses(Passes);
489       StandardCompileOpts = false;
490     }
491
492     if (StandardLinkOpts &&
493         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
494       AddStandardLinkPasses(Passes);
495       StandardLinkOpts = false;
496     }
497
498     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
499       AddOptimizationPasses(Passes, *FPasses, 1);
500       OptLevelO1 = false;
501     }
502
503     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
504       AddOptimizationPasses(Passes, *FPasses, 2);
505       OptLevelO2 = false;
506     }
507
508     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
509       AddOptimizationPasses(Passes, *FPasses, 3);
510       OptLevelO3 = false;
511     }
512
513     const PassInfo *PassInf = PassList[i];
514     Pass *P = 0;
515     if (PassInf->getNormalCtor())
516       P = PassInf->getNormalCtor()();
517     else
518       errs() << argv[0] << ": cannot create pass: "
519              << PassInf->getPassName() << "\n";
520     if (P) {
521       PassKind Kind = P->getPassKind();
522       addPass(Passes, P);
523
524       if (AnalyzeOnly) {
525         switch (Kind) {
526         case PT_BasicBlock:
527           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
528           break;
529         case PT_Loop:
530           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
531           break;
532         case PT_Function:
533           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
534           break;
535         case PT_CallGraphSCC:
536           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
537           break;
538         default:
539           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
540           break;
541         }
542       }
543     }
544
545     if (PrintEachXForm)
546       Passes.add(createPrintModulePass(&errs()));
547   }
548
549   // If -std-compile-opts was specified at the end of the pass list, add them.
550   if (StandardCompileOpts) {
551     AddStandardCompilePasses(Passes);
552     StandardCompileOpts = false;
553   }
554
555   if (StandardLinkOpts) {
556     AddStandardLinkPasses(Passes);
557     StandardLinkOpts = false;
558   }
559
560   if (OptLevelO1)
561     AddOptimizationPasses(Passes, *FPasses, 1);
562
563   if (OptLevelO2)
564     AddOptimizationPasses(Passes, *FPasses, 2);
565
566   if (OptLevelO3)
567     AddOptimizationPasses(Passes, *FPasses, 3);
568
569   if (OptLevelO1 || OptLevelO2 || OptLevelO3)
570     FPasses->run(*M.get());
571
572   // Check that the module is well formed on completion of optimization
573   if (!NoVerify && !VerifyEach)
574     Passes.add(createVerifierPass());
575
576   // Write bitcode or assembly to the output as the last step...
577   if (!NoOutput && !AnalyzeOnly) {
578     if (OutputAssembly)
579       Passes.add(createPrintModulePass(&Out->os()));
580     else
581       Passes.add(createBitcodeWriterPass(Out->os()));
582   }
583
584   // Now that we have all of the passes ready, run them.
585   Passes.run(*M.get());
586
587   // Declare success.
588   if (!NoOutput)
589     Out->keep();
590
591   return 0;
592 }