Revert "Debug Info: clean up usage of Verify." as it's breaking bots.
[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 DisableSimplifyLibCalls("disable-simplify-libcalls",
140                         cl::desc("Disable simplify-libcalls"));
141
142 static cl::opt<bool>
143 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
144
145 static cl::alias
146 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
147
148 static cl::opt<bool>
149 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
150
151 static cl::opt<bool>
152 PrintBreakpoints("print-breakpoints-for-testing",
153                  cl::desc("Print select breakpoints location for testing"));
154
155 static cl::opt<std::string>
156 DefaultDataLayout("default-data-layout",
157           cl::desc("data layout string to use if not specified by module"),
158           cl::value_desc("layout-string"), cl::init(""));
159
160 // ---------- Define Printers for module and function passes ------------
161 namespace {
162
163 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
164   static char ID;
165   const PassInfo *PassToPrint;
166   raw_ostream &Out;
167   std::string PassName;
168
169   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
170     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
171       std::string PassToPrintName =  PassToPrint->getPassName();
172       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
173     }
174
175   virtual bool runOnSCC(CallGraphSCC &SCC) {
176     if (!Quiet)
177       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
178
179     // Get and print pass...
180     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
181       Function *F = (*I)->getFunction();
182       if (F)
183         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
184                                                               F->getParent());
185     }
186     return false;
187   }
188
189   virtual const char *getPassName() const { return PassName.c_str(); }
190
191   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
192     AU.addRequiredID(PassToPrint->getTypeInfo());
193     AU.setPreservesAll();
194   }
195 };
196
197 char CallGraphSCCPassPrinter::ID = 0;
198
199 struct ModulePassPrinter : public ModulePass {
200   static char ID;
201   const PassInfo *PassToPrint;
202   raw_ostream &Out;
203   std::string PassName;
204
205   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
206     : ModulePass(ID), PassToPrint(PI), Out(out) {
207       std::string PassToPrintName =  PassToPrint->getPassName();
208       PassName = "ModulePass Printer: " + PassToPrintName;
209     }
210
211   virtual bool runOnModule(Module &M) {
212     if (!Quiet)
213       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
214
215     // Get and print pass...
216     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
217     return false;
218   }
219
220   virtual const char *getPassName() const { return PassName.c_str(); }
221
222   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
223     AU.addRequiredID(PassToPrint->getTypeInfo());
224     AU.setPreservesAll();
225   }
226 };
227
228 char ModulePassPrinter::ID = 0;
229 struct FunctionPassPrinter : public FunctionPass {
230   const PassInfo *PassToPrint;
231   raw_ostream &Out;
232   static char ID;
233   std::string PassName;
234
235   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
236     : FunctionPass(ID), PassToPrint(PI), Out(out) {
237       std::string PassToPrintName =  PassToPrint->getPassName();
238       PassName = "FunctionPass Printer: " + PassToPrintName;
239     }
240
241   virtual bool runOnFunction(Function &F) {
242     if (!Quiet)
243       Out << "Printing analysis '" << PassToPrint->getPassName()
244           << "' for function '" << F.getName() << "':\n";
245
246     // Get and print pass...
247     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
248             F.getParent());
249     return false;
250   }
251
252   virtual const char *getPassName() const { return PassName.c_str(); }
253
254   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
255     AU.addRequiredID(PassToPrint->getTypeInfo());
256     AU.setPreservesAll();
257   }
258 };
259
260 char FunctionPassPrinter::ID = 0;
261
262 struct LoopPassPrinter : public LoopPass {
263   static char ID;
264   const PassInfo *PassToPrint;
265   raw_ostream &Out;
266   std::string PassName;
267
268   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
269     LoopPass(ID), PassToPrint(PI), Out(out) {
270       std::string PassToPrintName =  PassToPrint->getPassName();
271       PassName = "LoopPass Printer: " + PassToPrintName;
272     }
273
274
275   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
276     if (!Quiet)
277       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
278
279     // Get and print pass...
280     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
281                         L->getHeader()->getParent()->getParent());
282     return false;
283   }
284
285   virtual const char *getPassName() const { return PassName.c_str(); }
286
287   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
288     AU.addRequiredID(PassToPrint->getTypeInfo());
289     AU.setPreservesAll();
290   }
291 };
292
293 char LoopPassPrinter::ID = 0;
294
295 struct RegionPassPrinter : public RegionPass {
296   static char ID;
297   const PassInfo *PassToPrint;
298   raw_ostream &Out;
299   std::string PassName;
300
301   RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
302     PassToPrint(PI), Out(out) {
303     std::string PassToPrintName =  PassToPrint->getPassName();
304     PassName = "RegionPass Printer: " + PassToPrintName;
305   }
306
307   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
308     if (!Quiet) {
309       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
310           << "region: '" << R->getNameStr() << "' in function '"
311           << R->getEntry()->getParent()->getName() << "':\n";
312     }
313     // Get and print pass...
314    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
315                        R->getEntry()->getParent()->getParent());
316     return false;
317   }
318
319   virtual const char *getPassName() const { return PassName.c_str(); }
320
321   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
322     AU.addRequiredID(PassToPrint->getTypeInfo());
323     AU.setPreservesAll();
324   }
325 };
326
327 char RegionPassPrinter::ID = 0;
328
329 struct BasicBlockPassPrinter : public BasicBlockPass {
330   const PassInfo *PassToPrint;
331   raw_ostream &Out;
332   static char ID;
333   std::string PassName;
334
335   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
336     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
337       std::string PassToPrintName =  PassToPrint->getPassName();
338       PassName = "BasicBlockPass Printer: " + PassToPrintName;
339     }
340
341   virtual bool runOnBasicBlock(BasicBlock &BB) {
342     if (!Quiet)
343       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
344           << "': Pass " << PassToPrint->getPassName() << ":\n";
345
346     // Get and print pass...
347     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
348             BB.getParent()->getParent());
349     return false;
350   }
351
352   virtual const char *getPassName() const { return PassName.c_str(); }
353
354   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
355     AU.addRequiredID(PassToPrint->getTypeInfo());
356     AU.setPreservesAll();
357   }
358 };
359
360 char BasicBlockPassPrinter::ID = 0;
361
362 struct BreakpointPrinter : public ModulePass {
363   raw_ostream &Out;
364   static char ID;
365
366   BreakpointPrinter(raw_ostream &out)
367     : ModulePass(ID), Out(out) {
368     }
369
370   void getContextName(DIDescriptor Context, std::string &N) {
371     if (Context.isNameSpace()) {
372       DINameSpace NS(Context);
373       if (!NS.getName().empty()) {
374         getContextName(NS.getContext(), N);
375         N = N + NS.getName().str() + "::";
376       }
377     } else if (Context.isType()) {
378       DIType TY(Context);
379       if (!TY.getName().empty()) {
380         getContextName(TY.getContext(), N);
381         N = N + TY.getName().str() + "::";
382       }
383     }
384   }
385
386   virtual bool runOnModule(Module &M) {
387     StringSet<> Processed;
388     if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
389       for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
390         std::string Name;
391         DISubprogram SP(NMD->getOperand(i));
392         if (SP.Verify())
393           getContextName(SP.getContext(), Name);
394         Name = Name + SP.getDisplayName().str();
395         if (!Name.empty() && Processed.insert(Name)) {
396           Out << Name << "\n";
397         }
398       }
399     return false;
400   }
401
402   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
403     AU.setPreservesAll();
404   }
405 };
406  
407 } // anonymous namespace
408
409 char BreakpointPrinter::ID = 0;
410
411 static inline void addPass(PassManagerBase &PM, Pass *P) {
412   // Add the pass to the pass manager...
413   PM.add(P);
414
415   // If we are verifying all of the intermediate steps, add the verifier...
416   if (VerifyEach) PM.add(createVerifierPass());
417 }
418
419 /// AddOptimizationPasses - This routine adds optimization passes
420 /// based on selected optimization level, OptLevel. This routine
421 /// duplicates llvm-gcc behaviour.
422 ///
423 /// OptLevel - Optimization Level
424 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
425                                   unsigned OptLevel, unsigned SizeLevel) {
426   FPM.add(createVerifierPass());                  // Verify that input is correct
427
428   PassManagerBuilder Builder;
429   Builder.OptLevel = OptLevel;
430   Builder.SizeLevel = SizeLevel;
431
432   if (DisableInline) {
433     // No inlining pass
434   } else if (OptLevel > 1) {
435     unsigned Threshold = 225;
436     if (SizeLevel == 1)      // -Os
437       Threshold = 75;
438     else if (SizeLevel == 2) // -Oz
439       Threshold = 25;
440     if (OptLevel > 2)
441       Threshold = 275;
442     Builder.Inliner = createFunctionInliningPass(Threshold);
443   } else {
444     Builder.Inliner = createAlwaysInlinerPass();
445   }
446   Builder.DisableUnitAtATime = !UnitAtATime;
447   Builder.DisableUnrollLoops = OptLevel == 0;
448   
449   Builder.populateFunctionPassManager(FPM);
450   Builder.populateModulePassManager(MPM);
451 }
452
453 static void AddStandardCompilePasses(PassManagerBase &PM) {
454   PM.add(createVerifierPass());                  // Verify that input is correct
455
456   // If the -strip-debug command line option was specified, do it.
457   if (StripDebug)
458     addPass(PM, createStripSymbolsPass(true));
459
460   if (DisableOptimizations) return;
461
462   // -std-compile-opts adds the same module passes as -O3.
463   PassManagerBuilder Builder;
464   if (!DisableInline)
465     Builder.Inliner = createFunctionInliningPass();
466   Builder.OptLevel = 3;
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(Triple TheTriple) {
526   std::string Error;
527   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
528                                                          Error);
529   // Some modules don't specify a triple, and this is okay.
530   if (!TheTarget) {
531     return 0;
532   }
533
534   // Package up features to be passed to target/subtarget
535   std::string FeaturesStr;
536   if (MAttrs.size()) {
537     SubtargetFeatures Features;
538     for (unsigned i = 0; i != MAttrs.size(); ++i)
539       Features.AddFeature(MAttrs[i]);
540     FeaturesStr = Features.getString();
541   }
542
543   return TheTarget->createTargetMachine(TheTriple.getTriple(),
544                                         MCPU, FeaturesStr, GetTargetOptions(),
545                                         RelocModel, CMModel,
546                                         GetCodeGenOptLevel());
547 }
548
549 //===----------------------------------------------------------------------===//
550 // main for opt
551 //
552 int main(int argc, char **argv) {
553   sys::PrintStackTraceOnErrorSignal();
554   llvm::PrettyStackTraceProgram X(argc, argv);
555
556   // Enable debug stream buffering.
557   EnableDebugBuffering = true;
558
559   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
560   LLVMContext &Context = getGlobalContext();
561
562   InitializeAllTargets();
563   InitializeAllTargetMCs();
564
565   // Initialize passes
566   PassRegistry &Registry = *PassRegistry::getPassRegistry();
567   initializeCore(Registry);
568   initializeDebugIRPass(Registry);
569   initializeScalarOpts(Registry);
570   initializeObjCARCOpts(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   OwningPtr<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   Triple ModuleTriple(M->getTargetTriple());
655   TargetMachine *Machine = 0;
656   if (ModuleTriple.getArch())
657     Machine = GetTargetMachine(Triple(ModuleTriple));
658   OwningPtr<TargetMachine> TM(Machine);
659
660   // Add internal analysis passes from the target machine.
661   if (TM.get())
662     TM->addAnalysisPasses(Passes);
663
664   OwningPtr<FunctionPassManager> FPasses;
665   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
666     FPasses.reset(new FunctionPassManager(M.get()));
667     if (TD)
668       FPasses->add(new DataLayout(*TD));
669   }
670
671   if (PrintBreakpoints) {
672     // Default to standard output.
673     if (!Out) {
674       if (OutputFilename.empty())
675         OutputFilename = "-";
676
677       std::string ErrorInfo;
678       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
679                                      raw_fd_ostream::F_Binary));
680       if (!ErrorInfo.empty()) {
681         errs() << ErrorInfo << '\n';
682         return 1;
683       }
684     }
685     Passes.add(new BreakpointPrinter(Out->os()));
686     NoOutput = true;
687   }
688
689   // If the -strip-debug command line option was specified, add it.  If
690   // -std-compile-opts was also specified, it will handle StripDebug.
691   if (StripDebug && !StandardCompileOpts)
692     addPass(Passes, createStripSymbolsPass(true));
693
694   // Create a new optimization pass for each one specified on the command line
695   for (unsigned i = 0; i < PassList.size(); ++i) {
696     // Check to see if -std-compile-opts was specified before this option.  If
697     // so, handle it.
698     if (StandardCompileOpts &&
699         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
700       AddStandardCompilePasses(Passes);
701       StandardCompileOpts = false;
702     }
703
704     if (StandardLinkOpts &&
705         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
706       AddStandardLinkPasses(Passes);
707       StandardLinkOpts = false;
708     }
709
710     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
711       AddOptimizationPasses(Passes, *FPasses, 1, 0);
712       OptLevelO1 = false;
713     }
714
715     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
716       AddOptimizationPasses(Passes, *FPasses, 2, 0);
717       OptLevelO2 = false;
718     }
719
720     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
721       AddOptimizationPasses(Passes, *FPasses, 2, 1);
722       OptLevelOs = false;
723     }
724
725     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
726       AddOptimizationPasses(Passes, *FPasses, 2, 2);
727       OptLevelOz = false;
728     }
729
730     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
731       AddOptimizationPasses(Passes, *FPasses, 3, 0);
732       OptLevelO3 = false;
733     }
734
735     const PassInfo *PassInf = PassList[i];
736     Pass *P = 0;
737     if (PassInf->getNormalCtor())
738       P = PassInf->getNormalCtor()();
739     else
740       errs() << argv[0] << ": cannot create pass: "
741              << PassInf->getPassName() << "\n";
742     if (P) {
743       PassKind Kind = P->getPassKind();
744       addPass(Passes, P);
745
746       if (AnalyzeOnly) {
747         switch (Kind) {
748         case PT_BasicBlock:
749           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
750           break;
751         case PT_Region:
752           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
753           break;
754         case PT_Loop:
755           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
756           break;
757         case PT_Function:
758           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
759           break;
760         case PT_CallGraphSCC:
761           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
762           break;
763         default:
764           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
765           break;
766         }
767       }
768     }
769
770     if (PrintEachXForm)
771       Passes.add(createPrintModulePass(&errs()));
772   }
773
774   // If -std-compile-opts was specified at the end of the pass list, add them.
775   if (StandardCompileOpts) {
776     AddStandardCompilePasses(Passes);
777     StandardCompileOpts = false;
778   }
779
780   if (StandardLinkOpts) {
781     AddStandardLinkPasses(Passes);
782     StandardLinkOpts = false;
783   }
784
785   if (OptLevelO1)
786     AddOptimizationPasses(Passes, *FPasses, 1, 0);
787
788   if (OptLevelO2)
789     AddOptimizationPasses(Passes, *FPasses, 2, 0);
790
791   if (OptLevelOs)
792     AddOptimizationPasses(Passes, *FPasses, 2, 1);
793
794   if (OptLevelOz)
795     AddOptimizationPasses(Passes, *FPasses, 2, 2);
796
797   if (OptLevelO3)
798     AddOptimizationPasses(Passes, *FPasses, 3, 0);
799
800   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
801     FPasses->doInitialization();
802     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
803       FPasses->run(*F);
804     FPasses->doFinalization();
805   }
806
807   // Check that the module is well formed on completion of optimization
808   if (!NoVerify && !VerifyEach)
809     Passes.add(createVerifierPass());
810
811   // Write bitcode or assembly to the output as the last step...
812   if (!NoOutput && !AnalyzeOnly) {
813     if (OutputAssembly)
814       Passes.add(createPrintModulePass(&Out->os()));
815     else
816       Passes.add(createBitcodeWriterPass(Out->os()));
817   }
818
819   // Before executing passes, print the final values of the LLVM options.
820   cl::PrintOptionValues();
821
822   // Now that we have all of the passes ready, run them.
823   Passes.run(*M.get());
824
825   // Declare success.
826   if (!NoOutput || PrintBreakpoints)
827     Out->keep();
828
829   return 0;
830 }