OSDN Git Service

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