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