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