Teach the 'opt' tool about '-Os' and '-Oz', corresponding to the Clang
[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/DebugInfo.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/RegionPass.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLibraryInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/StringSet.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Support/PassNameParser.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/IRReader.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PluginLoader.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/LinkAllVMCore.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
43 #include <memory>
44 #include <algorithm>
45 using namespace llvm;
46
47 // The OptimizationList is automatically populated with registered Passes by the
48 // PassNameParser.
49 //
50 static cl::list<const PassInfo*, bool, PassNameParser>
51 PassList(cl::desc("Optimizations available:"));
52
53 // Other command line options...
54 //
55 static cl::opt<std::string>
56 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
57     cl::init("-"), cl::value_desc("filename"));
58
59 static cl::opt<std::string>
60 OutputFilename("o", cl::desc("Override output filename"),
61                cl::value_desc("filename"));
62
63 static cl::opt<bool>
64 Force("f", cl::desc("Enable binary output on terminals"));
65
66 static cl::opt<bool>
67 PrintEachXForm("p", cl::desc("Print module after each transformation"));
68
69 static cl::opt<bool>
70 NoOutput("disable-output",
71          cl::desc("Do not write result bitcode file"), cl::Hidden);
72
73 static cl::opt<bool>
74 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
75
76 static cl::opt<bool>
77 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
78
79 static cl::opt<bool>
80 VerifyEach("verify-each", cl::desc("Verify after each transform"));
81
82 static cl::opt<bool>
83 StripDebug("strip-debug",
84            cl::desc("Strip debugger symbol info from translation unit"));
85
86 static cl::opt<bool>
87 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
88
89 static cl::opt<bool>
90 DisableOptimizations("disable-opt",
91                      cl::desc("Do not run any optimization passes"));
92
93 static cl::opt<bool>
94 DisableInternalize("disable-internalize",
95                    cl::desc("Do not mark all symbols as internal"));
96
97 static cl::opt<bool>
98 StandardCompileOpts("std-compile-opts",
99                    cl::desc("Include the standard compile time optimizations"));
100
101 static cl::opt<bool>
102 StandardLinkOpts("std-link-opts",
103                  cl::desc("Include the standard link time optimizations"));
104
105 static cl::opt<bool>
106 OptLevelO1("O1",
107            cl::desc("Optimization level 1. Similar to clang -O1"));
108
109 static cl::opt<bool>
110 OptLevelO2("O2",
111            cl::desc("Optimization level 2. Similar to clang -O2"));
112
113 static cl::opt<bool>
114 OptLevelOs("Os",
115            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
116
117 static cl::opt<bool>
118 OptLevelOz("Oz",
119            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
120
121 static cl::opt<bool>
122 OptLevelO3("O3",
123            cl::desc("Optimization level 3. Similar to clang -O3"));
124
125 static cl::opt<std::string>
126 TargetTriple("mtriple", cl::desc("Override target triple for module"));
127
128 static cl::opt<bool>
129 UnitAtATime("funit-at-a-time",
130             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
131             cl::init(true));
132
133 static cl::opt<bool>
134 DisableSimplifyLibCalls("disable-simplify-libcalls",
135                         cl::desc("Disable simplify-libcalls"));
136
137 static cl::opt<bool>
138 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
139
140 static cl::alias
141 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
142
143 static cl::opt<bool>
144 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
145
146 static cl::opt<bool>
147 PrintBreakpoints("print-breakpoints-for-testing",
148                  cl::desc("Print select breakpoints location for testing"));
149
150 static cl::opt<std::string>
151 DefaultDataLayout("default-data-layout",
152           cl::desc("data layout string to use if not specified by module"),
153           cl::value_desc("layout-string"), cl::init(""));
154
155 // ---------- Define Printers for module and function passes ------------
156 namespace {
157
158 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
159   static char ID;
160   const PassInfo *PassToPrint;
161   raw_ostream &Out;
162   std::string PassName;
163
164   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
165     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
166       std::string PassToPrintName =  PassToPrint->getPassName();
167       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
168     }
169
170   virtual bool runOnSCC(CallGraphSCC &SCC) {
171     if (!Quiet)
172       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
173
174     // Get and print pass...
175     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
176       Function *F = (*I)->getFunction();
177       if (F)
178         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
179                                                               F->getParent());
180     }
181     return false;
182   }
183
184   virtual const char *getPassName() const { return PassName.c_str(); }
185
186   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
187     AU.addRequiredID(PassToPrint->getTypeInfo());
188     AU.setPreservesAll();
189   }
190 };
191
192 char CallGraphSCCPassPrinter::ID = 0;
193
194 struct ModulePassPrinter : public ModulePass {
195   static char ID;
196   const PassInfo *PassToPrint;
197   raw_ostream &Out;
198   std::string PassName;
199
200   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
201     : ModulePass(ID), PassToPrint(PI), Out(out) {
202       std::string PassToPrintName =  PassToPrint->getPassName();
203       PassName = "ModulePass Printer: " + PassToPrintName;
204     }
205
206   virtual bool runOnModule(Module &M) {
207     if (!Quiet)
208       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
209
210     // Get and print pass...
211     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
212     return false;
213   }
214
215   virtual const char *getPassName() const { return PassName.c_str(); }
216
217   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218     AU.addRequiredID(PassToPrint->getTypeInfo());
219     AU.setPreservesAll();
220   }
221 };
222
223 char ModulePassPrinter::ID = 0;
224 struct FunctionPassPrinter : public FunctionPass {
225   const PassInfo *PassToPrint;
226   raw_ostream &Out;
227   static char ID;
228   std::string PassName;
229
230   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
231     : FunctionPass(ID), PassToPrint(PI), Out(out) {
232       std::string PassToPrintName =  PassToPrint->getPassName();
233       PassName = "FunctionPass Printer: " + PassToPrintName;
234     }
235
236   virtual bool runOnFunction(Function &F) {
237     if (!Quiet)
238       Out << "Printing analysis '" << PassToPrint->getPassName()
239           << "' for function '" << F.getName() << "':\n";
240
241     // Get and print pass...
242     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
243             F.getParent());
244     return false;
245   }
246
247   virtual const char *getPassName() const { return PassName.c_str(); }
248
249   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
250     AU.addRequiredID(PassToPrint->getTypeInfo());
251     AU.setPreservesAll();
252   }
253 };
254
255 char FunctionPassPrinter::ID = 0;
256
257 struct LoopPassPrinter : public LoopPass {
258   static char ID;
259   const PassInfo *PassToPrint;
260   raw_ostream &Out;
261   std::string PassName;
262
263   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
264     LoopPass(ID), PassToPrint(PI), Out(out) {
265       std::string PassToPrintName =  PassToPrint->getPassName();
266       PassName = "LoopPass Printer: " + PassToPrintName;
267     }
268
269
270   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
271     if (!Quiet)
272       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
273
274     // Get and print pass...
275     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
276                         L->getHeader()->getParent()->getParent());
277     return false;
278   }
279
280   virtual const char *getPassName() const { return PassName.c_str(); }
281
282   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
283     AU.addRequiredID(PassToPrint->getTypeInfo());
284     AU.setPreservesAll();
285   }
286 };
287
288 char LoopPassPrinter::ID = 0;
289
290 struct RegionPassPrinter : public RegionPass {
291   static char ID;
292   const PassInfo *PassToPrint;
293   raw_ostream &Out;
294   std::string PassName;
295
296   RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
297     PassToPrint(PI), Out(out) {
298     std::string PassToPrintName =  PassToPrint->getPassName();
299     PassName = "RegionPass Printer: " + PassToPrintName;
300   }
301
302   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
303     if (!Quiet) {
304       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
305           << "region: '" << R->getNameStr() << "' in function '"
306           << R->getEntry()->getParent()->getName() << "':\n";
307     }
308     // Get and print pass...
309    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
310                        R->getEntry()->getParent()->getParent());
311     return false;
312   }
313
314   virtual const char *getPassName() const { return PassName.c_str(); }
315
316   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
317     AU.addRequiredID(PassToPrint->getTypeInfo());
318     AU.setPreservesAll();
319   }
320 };
321
322 char RegionPassPrinter::ID = 0;
323
324 struct BasicBlockPassPrinter : public BasicBlockPass {
325   const PassInfo *PassToPrint;
326   raw_ostream &Out;
327   static char ID;
328   std::string PassName;
329
330   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
331     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
332       std::string PassToPrintName =  PassToPrint->getPassName();
333       PassName = "BasicBlockPass Printer: " + PassToPrintName;
334     }
335
336   virtual bool runOnBasicBlock(BasicBlock &BB) {
337     if (!Quiet)
338       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
339           << "': Pass " << PassToPrint->getPassName() << ":\n";
340
341     // Get and print pass...
342     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
343             BB.getParent()->getParent());
344     return false;
345   }
346
347   virtual const char *getPassName() const { return PassName.c_str(); }
348
349   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
350     AU.addRequiredID(PassToPrint->getTypeInfo());
351     AU.setPreservesAll();
352   }
353 };
354
355 char BasicBlockPassPrinter::ID = 0;
356
357 struct BreakpointPrinter : public ModulePass {
358   raw_ostream &Out;
359   static char ID;
360
361   BreakpointPrinter(raw_ostream &out)
362     : ModulePass(ID), Out(out) {
363     }
364
365   void getContextName(DIDescriptor Context, std::string &N) {
366     if (Context.isNameSpace()) {
367       DINameSpace NS(Context);
368       if (!NS.getName().empty()) {
369         getContextName(NS.getContext(), N);
370         N = N + NS.getName().str() + "::";
371       }
372     } else if (Context.isType()) {
373       DIType TY(Context);
374       if (!TY.getName().empty()) {
375         getContextName(TY.getContext(), N);
376         N = N + TY.getName().str() + "::";
377       }
378     }
379   }
380
381   virtual bool runOnModule(Module &M) {
382     StringSet<> Processed;
383     if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
384       for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
385         std::string Name;
386         DISubprogram SP(NMD->getOperand(i));
387         if (SP.Verify())
388           getContextName(SP.getContext(), Name);
389         Name = Name + SP.getDisplayName().str();
390         if (!Name.empty() && Processed.insert(Name)) {
391           Out << Name << "\n";
392         }
393       }
394     return false;
395   }
396
397   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
398     AU.setPreservesAll();
399   }
400 };
401  
402 } // anonymous namespace
403
404 char BreakpointPrinter::ID = 0;
405
406 static inline void addPass(PassManagerBase &PM, Pass *P) {
407   // Add the pass to the pass manager...
408   PM.add(P);
409
410   // If we are verifying all of the intermediate steps, add the verifier...
411   if (VerifyEach) PM.add(createVerifierPass());
412 }
413
414 /// AddOptimizationPasses - This routine adds optimization passes
415 /// based on selected optimization level, OptLevel. This routine
416 /// duplicates llvm-gcc behaviour.
417 ///
418 /// OptLevel - Optimization Level
419 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
420                                   unsigned OptLevel, unsigned SizeLevel) {
421   FPM.add(createVerifierPass());                  // Verify that input is correct
422
423   PassManagerBuilder Builder;
424   Builder.OptLevel = OptLevel;
425   Builder.SizeLevel = SizeLevel;
426
427   if (DisableInline) {
428     // No inlining pass
429   } else if (OptLevel > 1) {
430     unsigned Threshold = 225;
431     if (SizeLevel == 1)      // -Os
432       Threshold = 75;
433     else if (SizeLevel == 2) // -Oz
434       Threshold = 25;
435     if (OptLevel > 2)
436       Threshold = 275;
437     Builder.Inliner = createFunctionInliningPass(Threshold);
438   } else {
439     Builder.Inliner = createAlwaysInlinerPass();
440   }
441   Builder.DisableUnitAtATime = !UnitAtATime;
442   Builder.DisableUnrollLoops = OptLevel == 0;
443   Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
444   
445   Builder.populateFunctionPassManager(FPM);
446   Builder.populateModulePassManager(MPM);
447 }
448
449 static void AddStandardCompilePasses(PassManagerBase &PM) {
450   PM.add(createVerifierPass());                  // Verify that input is correct
451
452   // If the -strip-debug command line option was specified, do it.
453   if (StripDebug)
454     addPass(PM, createStripSymbolsPass(true));
455
456   if (DisableOptimizations) return;
457
458   // -std-compile-opts adds the same module passes as -O3.
459   PassManagerBuilder Builder;
460   if (!DisableInline)
461     Builder.Inliner = createFunctionInliningPass();
462   Builder.OptLevel = 3;
463   Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
464   Builder.populateModulePassManager(PM);
465 }
466
467 static void AddStandardLinkPasses(PassManagerBase &PM) {
468   PM.add(createVerifierPass());                  // Verify that input is correct
469
470   // If the -strip-debug command line option was specified, do it.
471   if (StripDebug)
472     addPass(PM, createStripSymbolsPass(true));
473
474   if (DisableOptimizations) return;
475
476   PassManagerBuilder Builder;
477   Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
478                                  /*RunInliner=*/ !DisableInline);
479 }
480
481
482 //===----------------------------------------------------------------------===//
483 // main for opt
484 //
485 int main(int argc, char **argv) {
486   sys::PrintStackTraceOnErrorSignal();
487   llvm::PrettyStackTraceProgram X(argc, argv);
488
489   // Enable debug stream buffering.
490   EnableDebugBuffering = true;
491
492   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
493   LLVMContext &Context = getGlobalContext();
494
495   // Initialize passes
496   PassRegistry &Registry = *PassRegistry::getPassRegistry();
497   initializeCore(Registry);
498   initializeScalarOpts(Registry);
499   initializeVectorization(Registry);
500   initializeIPO(Registry);
501   initializeAnalysis(Registry);
502   initializeIPA(Registry);
503   initializeTransformUtils(Registry);
504   initializeInstCombine(Registry);
505   initializeInstrumentation(Registry);
506   initializeTarget(Registry);
507
508   cl::ParseCommandLineOptions(argc, argv,
509     "llvm .bc -> .bc modular optimizer and analysis printer\n");
510
511   if (AnalyzeOnly && NoOutput) {
512     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
513     return 1;
514   }
515
516   // Allocate a full target machine description only if necessary.
517   // FIXME: The choice of target should be controllable on the command line.
518   std::auto_ptr<TargetMachine> target;
519
520   SMDiagnostic Err;
521
522   // Load the input module...
523   std::auto_ptr<Module> M;
524   M.reset(ParseIRFile(InputFilename, Err, Context));
525
526   if (M.get() == 0) {
527     Err.print(argv[0], errs());
528     return 1;
529   }
530
531   // If we are supposed to override the target triple, do so now.
532   if (!TargetTriple.empty())
533     M->setTargetTriple(Triple::normalize(TargetTriple));
534
535   // Figure out what stream we are supposed to write to...
536   OwningPtr<tool_output_file> Out;
537   if (NoOutput) {
538     if (!OutputFilename.empty())
539       errs() << "WARNING: The -o (output filename) option is ignored when\n"
540                 "the --disable-output option is used.\n";
541   } else {
542     // Default to standard output.
543     if (OutputFilename.empty())
544       OutputFilename = "-";
545
546     std::string ErrorInfo;
547     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
548                                    raw_fd_ostream::F_Binary));
549     if (!ErrorInfo.empty()) {
550       errs() << ErrorInfo << '\n';
551       return 1;
552     }
553   }
554
555   // If the output is set to be emitted to standard out, and standard out is a
556   // console, print out a warning message and refuse to do it.  We don't
557   // impress anyone by spewing tons of binary goo to a terminal.
558   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
559     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
560       NoOutput = true;
561
562   // Create a PassManager to hold and optimize the collection of passes we are
563   // about to build.
564   //
565   PassManager Passes;
566
567   // Add an appropriate TargetLibraryInfo pass for the module's triple.
568   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
569
570   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
571   if (DisableSimplifyLibCalls)
572     TLI->disableAllFunctions();
573   Passes.add(TLI);
574
575   // Add an appropriate TargetData instance for this module.
576   TargetData *TD = 0;
577   const std::string &ModuleDataLayout = M.get()->getDataLayout();
578   if (!ModuleDataLayout.empty())
579     TD = new TargetData(ModuleDataLayout);
580   else if (!DefaultDataLayout.empty())
581     TD = new TargetData(DefaultDataLayout);
582
583   if (TD)
584     Passes.add(TD);
585
586   OwningPtr<FunctionPassManager> FPasses;
587   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
588     FPasses.reset(new FunctionPassManager(M.get()));
589     if (TD)
590       FPasses->add(new TargetData(*TD));
591   }
592
593   if (PrintBreakpoints) {
594     // Default to standard output.
595     if (!Out) {
596       if (OutputFilename.empty())
597         OutputFilename = "-";
598
599       std::string ErrorInfo;
600       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
601                                      raw_fd_ostream::F_Binary));
602       if (!ErrorInfo.empty()) {
603         errs() << ErrorInfo << '\n';
604         return 1;
605       }
606     }
607     Passes.add(new BreakpointPrinter(Out->os()));
608     NoOutput = true;
609   }
610
611   // If the -strip-debug command line option was specified, add it.  If
612   // -std-compile-opts was also specified, it will handle StripDebug.
613   if (StripDebug && !StandardCompileOpts)
614     addPass(Passes, createStripSymbolsPass(true));
615
616   // Create a new optimization pass for each one specified on the command line
617   for (unsigned i = 0; i < PassList.size(); ++i) {
618     // Check to see if -std-compile-opts was specified before this option.  If
619     // so, handle it.
620     if (StandardCompileOpts &&
621         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
622       AddStandardCompilePasses(Passes);
623       StandardCompileOpts = false;
624     }
625
626     if (StandardLinkOpts &&
627         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
628       AddStandardLinkPasses(Passes);
629       StandardLinkOpts = false;
630     }
631
632     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
633       AddOptimizationPasses(Passes, *FPasses, 1, 0);
634       OptLevelO1 = false;
635     }
636
637     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
638       AddOptimizationPasses(Passes, *FPasses, 2, 0);
639       OptLevelO2 = false;
640     }
641
642     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
643       AddOptimizationPasses(Passes, *FPasses, 2, 1);
644       OptLevelOs = false;
645     }
646
647     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
648       AddOptimizationPasses(Passes, *FPasses, 2, 2);
649       OptLevelOz = false;
650     }
651
652     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
653       AddOptimizationPasses(Passes, *FPasses, 3, 0);
654       OptLevelO3 = false;
655     }
656
657     const PassInfo *PassInf = PassList[i];
658     Pass *P = 0;
659     if (PassInf->getNormalCtor())
660       P = PassInf->getNormalCtor()();
661     else
662       errs() << argv[0] << ": cannot create pass: "
663              << PassInf->getPassName() << "\n";
664     if (P) {
665       PassKind Kind = P->getPassKind();
666       addPass(Passes, P);
667
668       if (AnalyzeOnly) {
669         switch (Kind) {
670         case PT_BasicBlock:
671           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
672           break;
673         case PT_Region:
674           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
675           break;
676         case PT_Loop:
677           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
678           break;
679         case PT_Function:
680           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
681           break;
682         case PT_CallGraphSCC:
683           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
684           break;
685         default:
686           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
687           break;
688         }
689       }
690     }
691
692     if (PrintEachXForm)
693       Passes.add(createPrintModulePass(&errs()));
694   }
695
696   // If -std-compile-opts was specified at the end of the pass list, add them.
697   if (StandardCompileOpts) {
698     AddStandardCompilePasses(Passes);
699     StandardCompileOpts = false;
700   }
701
702   if (StandardLinkOpts) {
703     AddStandardLinkPasses(Passes);
704     StandardLinkOpts = false;
705   }
706
707   if (OptLevelO1)
708     AddOptimizationPasses(Passes, *FPasses, 1, 0);
709
710   if (OptLevelO2)
711     AddOptimizationPasses(Passes, *FPasses, 2, 0);
712
713   if (OptLevelOs)
714     AddOptimizationPasses(Passes, *FPasses, 2, 1);
715
716   if (OptLevelOz)
717     AddOptimizationPasses(Passes, *FPasses, 2, 2);
718
719   if (OptLevelO3)
720     AddOptimizationPasses(Passes, *FPasses, 3, 0);
721
722   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
723     FPasses->doInitialization();
724     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
725       FPasses->run(*F);
726     FPasses->doFinalization();
727   }
728
729   // Check that the module is well formed on completion of optimization
730   if (!NoVerify && !VerifyEach)
731     Passes.add(createVerifierPass());
732
733   // Write bitcode or assembly to the output as the last step...
734   if (!NoOutput && !AnalyzeOnly) {
735     if (OutputAssembly)
736       Passes.add(createPrintModulePass(&Out->os()));
737     else
738       Passes.add(createBitcodeWriterPass(Out->os()));
739   }
740
741   // Before executing passes, print the final values of the LLVM options.
742   cl::PrintOptionValues();
743
744   // Now that we have all of the passes ready, run them.
745   Passes.run(*M.get());
746
747   // Declare success.
748   if (!NoOutput || PrintBreakpoints)
749     Out->keep();
750
751   return 0;
752 }