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