1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
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/Analysis/Verifier.h"
23 #include "llvm/Bitcode/BitcodeWriterPass.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.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"
52 using namespace opt_tool;
54 // The OptimizationList is automatically populated with registered Passes by the
57 static cl::list<const PassInfo*, bool, PassNameParser>
58 PassList(cl::desc("Optimizations available:"));
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
64 static cl::opt<std::string> PassPipeline(
66 cl::desc("A textual description of the pass pipeline for optimizing"),
69 // Other command line options...
71 static cl::opt<std::string>
72 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
73 cl::init("-"), cl::value_desc("filename"));
75 static cl::opt<std::string>
76 OutputFilename("o", cl::desc("Override output filename"),
77 cl::value_desc("filename"));
80 Force("f", cl::desc("Enable binary output on terminals"));
83 PrintEachXForm("p", cl::desc("Print module after each transformation"));
86 NoOutput("disable-output",
87 cl::desc("Do not write result bitcode file"), cl::Hidden);
90 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
93 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
96 VerifyEach("verify-each", cl::desc("Verify after each transform"));
99 StripDebug("strip-debug",
100 cl::desc("Strip debugger symbol info from translation unit"));
103 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
106 DisableOptimizations("disable-opt",
107 cl::desc("Do not run any optimization passes"));
110 DisableInternalize("disable-internalize",
111 cl::desc("Do not mark all symbols as internal"));
114 StandardCompileOpts("std-compile-opts",
115 cl::desc("Include the standard compile time optimizations"));
118 StandardLinkOpts("std-link-opts",
119 cl::desc("Include the standard link time optimizations"));
123 cl::desc("Optimization level 1. Similar to clang -O1"));
127 cl::desc("Optimization level 2. Similar to clang -O2"));
131 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
135 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
139 cl::desc("Optimization level 3. Similar to clang -O3"));
141 static cl::opt<std::string>
142 TargetTriple("mtriple", cl::desc("Override target triple for module"));
145 UnitAtATime("funit-at-a-time",
146 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
150 DisableLoopUnrolling("disable-loop-unrolling",
151 cl::desc("Disable loop unrolling in all relevant passes"),
154 DisableLoopVectorization("disable-loop-vectorization",
155 cl::desc("Disable the loop vectorization pass"),
159 DisableSLPVectorization("disable-slp-vectorization",
160 cl::desc("Disable the slp vectorization pass"),
165 DisableSimplifyLibCalls("disable-simplify-libcalls",
166 cl::desc("Disable simplify-libcalls"));
169 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
172 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
175 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
178 PrintBreakpoints("print-breakpoints-for-testing",
179 cl::desc("Print select breakpoints location for testing"));
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(""));
186 // ---------- Define Printers for module and function passes ------------
189 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
191 const PassInfo *PassToPrint;
193 std::string PassName;
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;
201 virtual bool runOnSCC(CallGraphSCC &SCC) {
203 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
205 // Get and print pass...
206 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
207 Function *F = (*I)->getFunction();
209 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
215 virtual const char *getPassName() const { return PassName.c_str(); }
217 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218 AU.addRequiredID(PassToPrint->getTypeInfo());
219 AU.setPreservesAll();
223 char CallGraphSCCPassPrinter::ID = 0;
225 struct ModulePassPrinter : public ModulePass {
227 const PassInfo *PassToPrint;
229 std::string PassName;
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;
237 virtual bool runOnModule(Module &M) {
239 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
241 // Get and print pass...
242 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
246 virtual const char *getPassName() const { return PassName.c_str(); }
248 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
249 AU.addRequiredID(PassToPrint->getTypeInfo());
250 AU.setPreservesAll();
254 char ModulePassPrinter::ID = 0;
255 struct FunctionPassPrinter : public FunctionPass {
256 const PassInfo *PassToPrint;
259 std::string PassName;
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;
267 virtual bool runOnFunction(Function &F) {
269 Out << "Printing analysis '" << PassToPrint->getPassName()
270 << "' for function '" << F.getName() << "':\n";
272 // Get and print pass...
273 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
278 virtual const char *getPassName() const { return PassName.c_str(); }
280 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
281 AU.addRequiredID(PassToPrint->getTypeInfo());
282 AU.setPreservesAll();
286 char FunctionPassPrinter::ID = 0;
288 struct LoopPassPrinter : public LoopPass {
290 const PassInfo *PassToPrint;
292 std::string PassName;
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;
301 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
303 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
305 // Get and print pass...
306 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
307 L->getHeader()->getParent()->getParent());
311 virtual const char *getPassName() const { return PassName.c_str(); }
313 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
314 AU.addRequiredID(PassToPrint->getTypeInfo());
315 AU.setPreservesAll();
319 char LoopPassPrinter::ID = 0;
321 struct RegionPassPrinter : public RegionPass {
323 const PassInfo *PassToPrint;
325 std::string PassName;
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;
333 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
335 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
336 << "region: '" << R->getNameStr() << "' in function '"
337 << R->getEntry()->getParent()->getName() << "':\n";
339 // Get and print pass...
340 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
341 R->getEntry()->getParent()->getParent());
345 virtual const char *getPassName() const { return PassName.c_str(); }
347 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
348 AU.addRequiredID(PassToPrint->getTypeInfo());
349 AU.setPreservesAll();
353 char RegionPassPrinter::ID = 0;
355 struct BasicBlockPassPrinter : public BasicBlockPass {
356 const PassInfo *PassToPrint;
359 std::string PassName;
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;
367 virtual bool runOnBasicBlock(BasicBlock &BB) {
369 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
370 << "': Pass " << PassToPrint->getPassName() << ":\n";
372 // Get and print pass...
373 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
374 BB.getParent()->getParent());
378 virtual const char *getPassName() const { return PassName.c_str(); }
380 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
381 AU.addRequiredID(PassToPrint->getTypeInfo());
382 AU.setPreservesAll();
386 char BasicBlockPassPrinter::ID = 0;
388 struct BreakpointPrinter : public ModulePass {
391 DITypeIdentifierMap TypeIdentifierMap;
393 BreakpointPrinter(raw_ostream &out)
394 : ModulePass(ID), Out(out) {
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() + "::";
404 } else if (Context.isType()) {
406 if (!TY.getName().empty()) {
407 getContextName(TY.getContext().resolve(TypeIdentifierMap), N);
408 N = N + TY.getName().str() + "::";
413 virtual bool runOnModule(Module &M) {
414 TypeIdentifierMap.clear();
415 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
417 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
419 StringSet<> Processed;
420 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
421 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
423 DISubprogram SP(NMD->getOperand(i));
424 assert((!SP || SP.isSubprogram()) &&
425 "A MDNode in llvm.dbg.sp should be null or a DISubprogram.");
428 getContextName(SP.getContext().resolve(TypeIdentifierMap), Name);
429 Name = Name + SP.getDisplayName().str();
430 if (!Name.empty() && Processed.insert(Name)) {
437 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
438 AU.setPreservesAll();
442 } // anonymous namespace
444 char BreakpointPrinter::ID = 0;
446 static inline void addPass(PassManagerBase &PM, Pass *P) {
447 // Add the pass to the pass manager...
450 // If we are verifying all of the intermediate steps, add the verifier...
451 if (VerifyEach) PM.add(createVerifierPass());
454 /// AddOptimizationPasses - This routine adds optimization passes
455 /// based on selected optimization level, OptLevel. This routine
456 /// duplicates llvm-gcc behaviour.
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
463 PassManagerBuilder Builder;
464 Builder.OptLevel = OptLevel;
465 Builder.SizeLevel = SizeLevel;
469 } else if (OptLevel > 1) {
470 unsigned Threshold = 225;
471 if (SizeLevel == 1) // -Os
473 else if (SizeLevel == 2) // -Oz
477 Builder.Inliner = createFunctionInliningPass(Threshold);
479 Builder.Inliner = createAlwaysInlinerPass();
481 Builder.DisableUnitAtATime = !UnitAtATime;
482 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
483 DisableLoopUnrolling : OptLevel == 0;
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;
492 // When #pragma vectorize is on for SLP, do the same as above
493 Builder.SLPVectorize =
494 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
496 Builder.populateFunctionPassManager(FPM);
497 Builder.populateModulePassManager(MPM);
500 static void AddStandardCompilePasses(PassManagerBase &PM) {
501 PM.add(createVerifierPass()); // Verify that input is correct
503 // If the -strip-debug command line option was specified, do it.
505 addPass(PM, createStripSymbolsPass(true));
507 if (DisableOptimizations) return;
509 // -std-compile-opts adds the same module passes as -O3.
510 PassManagerBuilder Builder;
512 Builder.Inliner = createFunctionInliningPass();
513 Builder.OptLevel = 3;
514 Builder.populateModulePassManager(PM);
517 static void AddStandardLinkPasses(PassManagerBase &PM) {
518 PM.add(createVerifierPass()); // Verify that input is correct
520 // If the -strip-debug command line option was specified, do it.
522 addPass(PM, createStripSymbolsPass(true));
524 if (DisableOptimizations) return;
526 PassManagerBuilder Builder;
527 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
528 /*RunInliner=*/ !DisableInline);
531 //===----------------------------------------------------------------------===//
532 // CodeGen-related helper functions.
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;
558 CodeGenOpt::Level GetCodeGenOptLevel() {
560 return CodeGenOpt::Less;
562 return CodeGenOpt::Default;
564 return CodeGenOpt::Aggressive;
565 return CodeGenOpt::None;
568 // Returns the TargetMachine instance or zero if no triple is provided.
569 static TargetMachine* GetTargetMachine(Triple TheTriple) {
571 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
573 // Some modules don't specify a triple, and this is okay.
578 // Package up features to be passed to target/subtarget
579 std::string FeaturesStr;
581 SubtargetFeatures Features;
582 for (unsigned i = 0; i != MAttrs.size(); ++i)
583 Features.AddFeature(MAttrs[i]);
584 FeaturesStr = Features.getString();
587 return TheTarget->createTargetMachine(TheTriple.getTriple(),
588 MCPU, FeaturesStr, GetTargetOptions(),
590 GetCodeGenOptLevel());
593 //===----------------------------------------------------------------------===//
596 int main(int argc, char **argv) {
597 sys::PrintStackTraceOnErrorSignal();
598 llvm::PrettyStackTraceProgram X(argc, argv);
600 // Enable debug stream buffering.
601 EnableDebugBuffering = true;
603 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
604 LLVMContext &Context = getGlobalContext();
606 InitializeAllTargets();
607 InitializeAllTargetMCs();
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);
624 cl::ParseCommandLineOptions(argc, argv,
625 "llvm .bc -> .bc modular optimizer and analysis printer\n");
627 if (AnalyzeOnly && NoOutput) {
628 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
634 // Load the input module...
636 M.reset(ParseIRFile(InputFilename, Err, Context));
639 Err.print(argv[0], errs());
643 // If we are supposed to override the target triple, do so now.
644 if (!TargetTriple.empty())
645 M->setTargetTriple(Triple::normalize(TargetTriple));
647 // Figure out what stream we are supposed to write to...
648 OwningPtr<tool_output_file> Out;
650 if (!OutputFilename.empty())
651 errs() << "WARNING: The -o (output filename) option is ignored when\n"
652 "the --disable-output option is used.\n";
654 // Default to standard output.
655 if (OutputFilename.empty())
656 OutputFilename = "-";
658 std::string ErrorInfo;
659 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
661 if (!ErrorInfo.empty()) {
662 errs() << ErrorInfo << '\n';
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))
674 if (PassPipeline.getNumOccurrences() > 0) {
675 OutputKind OK = OK_NoOutput;
677 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
679 // The user has asked to use the new pass manager and provided a pipeline
680 // string. Hand off the rest of the functionality to the new code for that
682 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
688 // Create a PassManager to hold and optimize the collection of passes we are
693 // Add an appropriate TargetLibraryInfo pass for the module's triple.
694 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
696 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
697 if (DisableSimplifyLibCalls)
698 TLI->disableAllFunctions();
701 // Add an appropriate DataLayout instance for this module.
703 const std::string &ModuleDataLayout = M.get()->getDataLayout();
704 if (!ModuleDataLayout.empty())
705 TD = new DataLayout(ModuleDataLayout);
706 else if (!DefaultDataLayout.empty())
707 TD = new DataLayout(DefaultDataLayout);
712 Triple ModuleTriple(M->getTargetTriple());
713 TargetMachine *Machine = 0;
714 if (ModuleTriple.getArch())
715 Machine = GetTargetMachine(Triple(ModuleTriple));
716 OwningPtr<TargetMachine> TM(Machine);
718 // Add internal analysis passes from the target machine.
720 TM->addAnalysisPasses(Passes);
722 OwningPtr<FunctionPassManager> FPasses;
723 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
724 FPasses.reset(new FunctionPassManager(M.get()));
726 FPasses->add(new DataLayout(*TD));
728 TM->addAnalysisPasses(*FPasses);
732 if (PrintBreakpoints) {
733 // Default to standard output.
735 if (OutputFilename.empty())
736 OutputFilename = "-";
738 std::string ErrorInfo;
739 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
741 if (!ErrorInfo.empty()) {
742 errs() << ErrorInfo << '\n';
746 Passes.add(new BreakpointPrinter(Out->os()));
750 // If the -strip-debug command line option was specified, add it. If
751 // -std-compile-opts was also specified, it will handle StripDebug.
752 if (StripDebug && !StandardCompileOpts)
753 addPass(Passes, createStripSymbolsPass(true));
755 // Create a new optimization pass for each one specified on the command line
756 for (unsigned i = 0; i < PassList.size(); ++i) {
757 // Check to see if -std-compile-opts was specified before this option. If
759 if (StandardCompileOpts &&
760 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
761 AddStandardCompilePasses(Passes);
762 StandardCompileOpts = false;
765 if (StandardLinkOpts &&
766 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
767 AddStandardLinkPasses(Passes);
768 StandardLinkOpts = false;
771 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
772 AddOptimizationPasses(Passes, *FPasses, 1, 0);
776 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
777 AddOptimizationPasses(Passes, *FPasses, 2, 0);
781 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
782 AddOptimizationPasses(Passes, *FPasses, 2, 1);
786 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
787 AddOptimizationPasses(Passes, *FPasses, 2, 2);
791 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
792 AddOptimizationPasses(Passes, *FPasses, 3, 0);
796 const PassInfo *PassInf = PassList[i];
798 if (PassInf->getNormalCtor())
799 P = PassInf->getNormalCtor()();
801 errs() << argv[0] << ": cannot create pass: "
802 << PassInf->getPassName() << "\n";
804 PassKind Kind = P->getPassKind();
810 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
813 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
816 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
819 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
821 case PT_CallGraphSCC:
822 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
825 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
832 Passes.add(createPrintModulePass(errs()));
835 // If -std-compile-opts was specified at the end of the pass list, add them.
836 if (StandardCompileOpts) {
837 AddStandardCompilePasses(Passes);
838 StandardCompileOpts = false;
841 if (StandardLinkOpts) {
842 AddStandardLinkPasses(Passes);
843 StandardLinkOpts = false;
847 AddOptimizationPasses(Passes, *FPasses, 1, 0);
850 AddOptimizationPasses(Passes, *FPasses, 2, 0);
853 AddOptimizationPasses(Passes, *FPasses, 2, 1);
856 AddOptimizationPasses(Passes, *FPasses, 2, 2);
859 AddOptimizationPasses(Passes, *FPasses, 3, 0);
861 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
862 FPasses->doInitialization();
863 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
865 FPasses->doFinalization();
868 // Check that the module is well formed on completion of optimization
869 if (!NoVerify && !VerifyEach)
870 Passes.add(createVerifierPass());
872 // Write bitcode or assembly to the output as the last step...
873 if (!NoOutput && !AnalyzeOnly) {
875 Passes.add(createPrintModulePass(Out->os()));
877 Passes.add(createBitcodeWriterPass(Out->os()));
880 // Before executing passes, print the final values of the LLVM options.
881 cl::PrintOptionValues();
883 // Now that we have all of the passes ready, run them.
884 Passes.run(*M.get());
887 if (!NoOutput || PrintBreakpoints)