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