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 "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/RegionPass.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLibraryInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/Support/PassNameParser.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/IRReader.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/StandardPasses.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/LinkAllVMCore.h"
46 // The OptimizationList is automatically populated with registered Passes by the
49 static cl::list<const PassInfo*, bool, PassNameParser>
50 PassList(cl::desc("Optimizations available:"));
52 // Other command line options...
54 static cl::opt<std::string>
55 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
56 cl::init("-"), cl::value_desc("filename"));
58 static cl::opt<std::string>
59 OutputFilename("o", cl::desc("Override output filename"),
60 cl::value_desc("filename"));
63 Force("f", cl::desc("Enable binary output on terminals"));
66 PrintEachXForm("p", cl::desc("Print module after each transformation"));
69 NoOutput("disable-output",
70 cl::desc("Do not write result bitcode file"), cl::Hidden);
73 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
76 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
79 VerifyEach("verify-each", cl::desc("Verify after each transform"));
82 StripDebug("strip-debug",
83 cl::desc("Strip debugger symbol info from translation unit"));
86 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
89 DisableOptimizations("disable-opt",
90 cl::desc("Do not run any optimization passes"));
93 DisableInternalize("disable-internalize",
94 cl::desc("Do not mark all symbols as internal"));
97 StandardCompileOpts("std-compile-opts",
98 cl::desc("Include the standard compile time optimizations"));
101 StandardLinkOpts("std-link-opts",
102 cl::desc("Include the standard link time optimizations"));
106 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
110 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
114 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
117 UnitAtATime("funit-at-a-time",
118 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
122 DisableSimplifyLibCalls("disable-simplify-libcalls",
123 cl::desc("Disable simplify-libcalls"));
126 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
129 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
132 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
135 PrintBreakpoints("print-breakpoints-for-testing",
136 cl::desc("Print select breakpoints location for testing"));
138 static cl::opt<std::string>
139 DefaultDataLayout("default-data-layout",
140 cl::desc("data layout string to use if not specified by module"),
141 cl::value_desc("layout-string"), cl::init(""));
143 // ---------- Define Printers for module and function passes ------------
146 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
148 const PassInfo *PassToPrint;
150 std::string PassName;
152 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
153 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
154 std::string PassToPrintName = PassToPrint->getPassName();
155 PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
158 virtual bool runOnSCC(CallGraphSCC &SCC) {
160 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
162 // Get and print pass...
163 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
164 Function *F = (*I)->getFunction();
166 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
172 virtual const char *getPassName() const { return PassName.c_str(); }
174 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
175 AU.addRequiredID(PassToPrint->getTypeInfo());
176 AU.setPreservesAll();
180 char CallGraphSCCPassPrinter::ID = 0;
182 struct ModulePassPrinter : public ModulePass {
184 const PassInfo *PassToPrint;
186 std::string PassName;
188 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
189 : ModulePass(ID), PassToPrint(PI), Out(out) {
190 std::string PassToPrintName = PassToPrint->getPassName();
191 PassName = "ModulePass Printer: " + PassToPrintName;
194 virtual bool runOnModule(Module &M) {
196 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
198 // Get and print pass...
199 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
203 virtual const char *getPassName() const { return PassName.c_str(); }
205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
206 AU.addRequiredID(PassToPrint->getTypeInfo());
207 AU.setPreservesAll();
211 char ModulePassPrinter::ID = 0;
212 struct FunctionPassPrinter : public FunctionPass {
213 const PassInfo *PassToPrint;
216 std::string PassName;
218 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
219 : FunctionPass(ID), PassToPrint(PI), Out(out) {
220 std::string PassToPrintName = PassToPrint->getPassName();
221 PassName = "FunctionPass Printer: " + PassToPrintName;
224 virtual bool runOnFunction(Function &F) {
226 Out << "Printing analysis '" << PassToPrint->getPassName()
227 << "' for function '" << F.getName() << "':\n";
229 // Get and print pass...
230 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
235 virtual const char *getPassName() const { return PassName.c_str(); }
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
238 AU.addRequiredID(PassToPrint->getTypeInfo());
239 AU.setPreservesAll();
243 char FunctionPassPrinter::ID = 0;
245 struct LoopPassPrinter : public LoopPass {
247 const PassInfo *PassToPrint;
249 std::string PassName;
251 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
252 LoopPass(ID), PassToPrint(PI), Out(out) {
253 std::string PassToPrintName = PassToPrint->getPassName();
254 PassName = "LoopPass Printer: " + PassToPrintName;
258 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
260 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
262 // Get and print pass...
263 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
264 L->getHeader()->getParent()->getParent());
268 virtual const char *getPassName() const { return PassName.c_str(); }
270 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
271 AU.addRequiredID(PassToPrint->getTypeInfo());
272 AU.setPreservesAll();
276 char LoopPassPrinter::ID = 0;
278 struct RegionPassPrinter : public RegionPass {
280 const PassInfo *PassToPrint;
282 std::string PassName;
284 RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
285 PassToPrint(PI), Out(out) {
286 std::string PassToPrintName = PassToPrint->getPassName();
287 PassName = "RegionPass Printer: " + PassToPrintName;
290 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
292 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
293 << "region: '" << R->getNameStr() << "' in function '"
294 << R->getEntry()->getParent()->getNameStr() << "':\n";
296 // Get and print pass...
297 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
298 R->getEntry()->getParent()->getParent());
302 virtual const char *getPassName() const { return PassName.c_str(); }
304 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
305 AU.addRequiredID(PassToPrint->getTypeInfo());
306 AU.setPreservesAll();
310 char RegionPassPrinter::ID = 0;
312 struct BasicBlockPassPrinter : public BasicBlockPass {
313 const PassInfo *PassToPrint;
316 std::string PassName;
318 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
319 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
320 std::string PassToPrintName = PassToPrint->getPassName();
321 PassName = "BasicBlockPass Printer: " + PassToPrintName;
324 virtual bool runOnBasicBlock(BasicBlock &BB) {
326 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
327 << "': Pass " << PassToPrint->getPassName() << ":\n";
329 // Get and print pass...
330 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
331 BB.getParent()->getParent());
335 virtual const char *getPassName() const { return PassName.c_str(); }
337 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
338 AU.addRequiredID(PassToPrint->getTypeInfo());
339 AU.setPreservesAll();
343 char BasicBlockPassPrinter::ID = 0;
345 struct BreakpointPrinter : public FunctionPass {
349 BreakpointPrinter(raw_ostream &out)
350 : FunctionPass(ID), Out(out) {
353 virtual bool runOnFunction(Function &F) {
354 BasicBlock &EntryBB = F.getEntryBlock();
355 BasicBlock::const_iterator BI = EntryBB.end();
358 const Instruction *In = BI;
359 const DebugLoc DL = In->getDebugLoc();
360 if (!DL.isUnknown()) {
361 DIScope S(DL.getScope(getGlobalContext()));
362 Out << S.getFilename() << " " << DL.getLine() << "\n";
366 } while (BI != EntryBB.begin());
370 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
371 AU.setPreservesAll();
375 char BreakpointPrinter::ID = 0;
377 inline void addPass(PassManagerBase &PM, Pass *P) {
378 // Add the pass to the pass manager...
381 // If we are verifying all of the intermediate steps, add the verifier...
382 if (VerifyEach) PM.add(createVerifierPass());
385 /// AddOptimizationPasses - This routine adds optimization passes
386 /// based on selected optimization level, OptLevel. This routine
387 /// duplicates llvm-gcc behaviour.
389 /// OptLevel - Optimization Level
390 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
392 createStandardFunctionPasses(&FPM, OptLevel);
394 llvm::Pass *InliningPass = 0;
397 } else if (OptLevel) {
398 unsigned Threshold = 225;
401 InliningPass = createFunctionInliningPass(Threshold);
403 InliningPass = createAlwaysInlinerPass();
405 createStandardModulePasses(&MPM, OptLevel,
406 /*OptimizeSize=*/ false,
408 /*UnrollLoops=*/ OptLevel > 1,
409 !DisableSimplifyLibCalls,
410 /*HaveExceptions=*/ true,
414 void AddStandardCompilePasses(PassManagerBase &PM) {
415 PM.add(createVerifierPass()); // Verify that input is correct
417 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
419 // If the -strip-debug command line option was specified, do it.
421 addPass(PM, createStripSymbolsPass(true));
423 if (DisableOptimizations) return;
425 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
427 // -std-compile-opts adds the same module passes as -O3.
428 createStandardModulePasses(&PM, 3,
429 /*OptimizeSize=*/ false,
430 /*UnitAtATime=*/ true,
431 /*UnrollLoops=*/ true,
432 !DisableSimplifyLibCalls,
433 /*HaveExceptions=*/ true,
437 void AddStandardLinkPasses(PassManagerBase &PM) {
438 PM.add(createVerifierPass()); // Verify that input is correct
440 // If the -strip-debug command line option was specified, do it.
442 addPass(PM, createStripSymbolsPass(true));
444 if (DisableOptimizations) return;
446 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
447 /*RunInliner=*/ !DisableInline,
448 /*VerifyEach=*/ VerifyEach);
451 } // anonymous namespace
454 //===----------------------------------------------------------------------===//
457 int main(int argc, char **argv) {
458 sys::PrintStackTraceOnErrorSignal();
459 llvm::PrettyStackTraceProgram X(argc, argv);
461 // Enable debug stream buffering.
462 EnableDebugBuffering = true;
464 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
465 LLVMContext &Context = getGlobalContext();
468 PassRegistry &Registry = *PassRegistry::getPassRegistry();
469 initializeCore(Registry);
470 initializeScalarOpts(Registry);
471 initializeIPO(Registry);
472 initializeAnalysis(Registry);
473 initializeIPA(Registry);
474 initializeTransformUtils(Registry);
475 initializeInstCombine(Registry);
476 initializeInstrumentation(Registry);
477 initializeTarget(Registry);
479 cl::ParseCommandLineOptions(argc, argv,
480 "llvm .bc -> .bc modular optimizer and analysis printer\n");
482 if (AnalyzeOnly && NoOutput) {
483 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
487 // Allocate a full target machine description only if necessary.
488 // FIXME: The choice of target should be controllable on the command line.
489 std::auto_ptr<TargetMachine> target;
493 // Load the input module...
494 std::auto_ptr<Module> M;
495 M.reset(ParseIRFile(InputFilename, Err, Context));
498 Err.Print(argv[0], errs());
502 // Figure out what stream we are supposed to write to...
503 OwningPtr<tool_output_file> Out;
505 if (!OutputFilename.empty())
506 errs() << "WARNING: The -o (output filename) option is ignored when\n"
507 "the --disable-output option is used.\n";
509 // Default to standard output.
510 if (OutputFilename.empty())
511 OutputFilename = "-";
513 std::string ErrorInfo;
514 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
515 raw_fd_ostream::F_Binary));
516 if (!ErrorInfo.empty()) {
517 errs() << ErrorInfo << '\n';
522 // If the output is set to be emitted to standard out, and standard out is a
523 // console, print out a warning message and refuse to do it. We don't
524 // impress anyone by spewing tons of binary goo to a terminal.
525 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
526 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
529 // Create a PassManager to hold and optimize the collection of passes we are
534 // Add an appropriate TargetLibraryInfo pass for the module's triple.
535 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
537 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
538 if (DisableSimplifyLibCalls)
539 TLI->disableAllFunctions();
542 // Add an appropriate TargetData instance for this module.
544 const std::string &ModuleDataLayout = M.get()->getDataLayout();
545 if (!ModuleDataLayout.empty())
546 TD = new TargetData(ModuleDataLayout);
547 else if (!DefaultDataLayout.empty())
548 TD = new TargetData(DefaultDataLayout);
553 OwningPtr<PassManager> FPasses;
554 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
555 FPasses.reset(new PassManager());
557 FPasses->add(new TargetData(*TD));
560 if (PrintBreakpoints) {
561 // Default to standard output.
563 if (OutputFilename.empty())
564 OutputFilename = "-";
566 std::string ErrorInfo;
567 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
568 raw_fd_ostream::F_Binary));
569 if (!ErrorInfo.empty()) {
570 errs() << ErrorInfo << '\n';
574 Passes.add(new BreakpointPrinter(Out->os()));
578 // If the -strip-debug command line option was specified, add it. If
579 // -std-compile-opts was also specified, it will handle StripDebug.
580 if (StripDebug && !StandardCompileOpts)
581 addPass(Passes, createStripSymbolsPass(true));
583 // Create a new optimization pass for each one specified on the command line
584 for (unsigned i = 0; i < PassList.size(); ++i) {
585 // Check to see if -std-compile-opts was specified before this option. If
587 if (StandardCompileOpts &&
588 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
589 AddStandardCompilePasses(Passes);
590 StandardCompileOpts = false;
593 if (StandardLinkOpts &&
594 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
595 AddStandardLinkPasses(Passes);
596 StandardLinkOpts = false;
599 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
600 AddOptimizationPasses(Passes, *FPasses, 1);
604 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
605 AddOptimizationPasses(Passes, *FPasses, 2);
609 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
610 AddOptimizationPasses(Passes, *FPasses, 3);
614 const PassInfo *PassInf = PassList[i];
616 if (PassInf->getNormalCtor())
617 P = PassInf->getNormalCtor()();
619 errs() << argv[0] << ": cannot create pass: "
620 << PassInf->getPassName() << "\n";
622 PassKind Kind = P->getPassKind();
628 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
631 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
634 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
637 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
639 case PT_CallGraphSCC:
640 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
643 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
650 Passes.add(createPrintModulePass(&errs()));
653 // If -std-compile-opts was specified at the end of the pass list, add them.
654 if (StandardCompileOpts) {
655 AddStandardCompilePasses(Passes);
656 StandardCompileOpts = false;
659 if (StandardLinkOpts) {
660 AddStandardLinkPasses(Passes);
661 StandardLinkOpts = false;
665 AddOptimizationPasses(Passes, *FPasses, 1);
668 AddOptimizationPasses(Passes, *FPasses, 2);
671 AddOptimizationPasses(Passes, *FPasses, 3);
673 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
674 FPasses->run(*M.get());
676 // Check that the module is well formed on completion of optimization
677 if (!NoVerify && !VerifyEach)
678 Passes.add(createVerifierPass());
680 // Write bitcode or assembly to the output as the last step...
681 if (!NoOutput && !AnalyzeOnly) {
683 Passes.add(createPrintModulePass(&Out->os()));
685 Passes.add(createBitcodeWriterPass(Out->os()));
688 // Now that we have all of the passes ready, run them.
689 Passes.run(*M.get());
692 if (!NoOutput || PrintBreakpoints)