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