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