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