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