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/StringSet.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Support/PassNameParser.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/IRReader.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PluginLoader.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/LinkAllVMCore.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 // The OptimizationList is automatically populated with registered Passes by the
50 static cl::list<const PassInfo*, bool, PassNameParser>
51 PassList(cl::desc("Optimizations available:"));
53 // Other command line options...
55 static cl::opt<std::string>
56 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
57 cl::init("-"), cl::value_desc("filename"));
59 static cl::opt<std::string>
60 OutputFilename("o", cl::desc("Override output filename"),
61 cl::value_desc("filename"));
64 Force("f", cl::desc("Enable binary output on terminals"));
67 PrintEachXForm("p", cl::desc("Print module after each transformation"));
70 NoOutput("disable-output",
71 cl::desc("Do not write result bitcode file"), cl::Hidden);
74 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
77 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
80 VerifyEach("verify-each", cl::desc("Verify after each transform"));
83 StripDebug("strip-debug",
84 cl::desc("Strip debugger symbol info from translation unit"));
87 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
90 DisableOptimizations("disable-opt",
91 cl::desc("Do not run any optimization passes"));
94 DisableInternalize("disable-internalize",
95 cl::desc("Do not mark all symbols as internal"));
98 StandardCompileOpts("std-compile-opts",
99 cl::desc("Include the standard compile time optimizations"));
102 StandardLinkOpts("std-link-opts",
103 cl::desc("Include the standard link time optimizations"));
107 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
111 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
115 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
118 UnitAtATime("funit-at-a-time",
119 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
123 DisableSimplifyLibCalls("disable-simplify-libcalls",
124 cl::desc("Disable simplify-libcalls"));
127 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
130 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
133 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
136 PrintBreakpoints("print-breakpoints-for-testing",
137 cl::desc("Print select breakpoints location for testing"));
139 static cl::opt<std::string>
140 DefaultDataLayout("default-data-layout",
141 cl::desc("data layout string to use if not specified by module"),
142 cl::value_desc("layout-string"), cl::init(""));
144 // ---------- Define Printers for module and function passes ------------
147 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
149 const PassInfo *PassToPrint;
151 std::string PassName;
153 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
154 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
155 std::string PassToPrintName = PassToPrint->getPassName();
156 PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
159 virtual bool runOnSCC(CallGraphSCC &SCC) {
161 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
163 // Get and print pass...
164 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
165 Function *F = (*I)->getFunction();
167 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
173 virtual const char *getPassName() const { return PassName.c_str(); }
175 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
176 AU.addRequiredID(PassToPrint->getTypeInfo());
177 AU.setPreservesAll();
181 char CallGraphSCCPassPrinter::ID = 0;
183 struct ModulePassPrinter : public ModulePass {
185 const PassInfo *PassToPrint;
187 std::string PassName;
189 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
190 : ModulePass(ID), PassToPrint(PI), Out(out) {
191 std::string PassToPrintName = PassToPrint->getPassName();
192 PassName = "ModulePass Printer: " + PassToPrintName;
195 virtual bool runOnModule(Module &M) {
197 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
199 // Get and print pass...
200 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
204 virtual const char *getPassName() const { return PassName.c_str(); }
206 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207 AU.addRequiredID(PassToPrint->getTypeInfo());
208 AU.setPreservesAll();
212 char ModulePassPrinter::ID = 0;
213 struct FunctionPassPrinter : public FunctionPass {
214 const PassInfo *PassToPrint;
217 std::string PassName;
219 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
220 : FunctionPass(ID), PassToPrint(PI), Out(out) {
221 std::string PassToPrintName = PassToPrint->getPassName();
222 PassName = "FunctionPass Printer: " + PassToPrintName;
225 virtual bool runOnFunction(Function &F) {
227 Out << "Printing analysis '" << PassToPrint->getPassName()
228 << "' for function '" << F.getName() << "':\n";
230 // Get and print pass...
231 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
236 virtual const char *getPassName() const { return PassName.c_str(); }
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
239 AU.addRequiredID(PassToPrint->getTypeInfo());
240 AU.setPreservesAll();
244 char FunctionPassPrinter::ID = 0;
246 struct LoopPassPrinter : public LoopPass {
248 const PassInfo *PassToPrint;
250 std::string PassName;
252 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
253 LoopPass(ID), PassToPrint(PI), Out(out) {
254 std::string PassToPrintName = PassToPrint->getPassName();
255 PassName = "LoopPass Printer: " + PassToPrintName;
259 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
261 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
263 // Get and print pass...
264 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
265 L->getHeader()->getParent()->getParent());
269 virtual const char *getPassName() const { return PassName.c_str(); }
271 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
272 AU.addRequiredID(PassToPrint->getTypeInfo());
273 AU.setPreservesAll();
277 char LoopPassPrinter::ID = 0;
279 struct RegionPassPrinter : public RegionPass {
281 const PassInfo *PassToPrint;
283 std::string PassName;
285 RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
286 PassToPrint(PI), Out(out) {
287 std::string PassToPrintName = PassToPrint->getPassName();
288 PassName = "RegionPass Printer: " + PassToPrintName;
291 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
293 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
294 << "region: '" << R->getNameStr() << "' in function '"
295 << R->getEntry()->getParent()->getName() << "':\n";
297 // Get and print pass...
298 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
299 R->getEntry()->getParent()->getParent());
303 virtual const char *getPassName() const { return PassName.c_str(); }
305 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
306 AU.addRequiredID(PassToPrint->getTypeInfo());
307 AU.setPreservesAll();
311 char RegionPassPrinter::ID = 0;
313 struct BasicBlockPassPrinter : public BasicBlockPass {
314 const PassInfo *PassToPrint;
317 std::string PassName;
319 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
320 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
321 std::string PassToPrintName = PassToPrint->getPassName();
322 PassName = "BasicBlockPass Printer: " + PassToPrintName;
325 virtual bool runOnBasicBlock(BasicBlock &BB) {
327 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
328 << "': Pass " << PassToPrint->getPassName() << ":\n";
330 // Get and print pass...
331 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
332 BB.getParent()->getParent());
336 virtual const char *getPassName() const { return PassName.c_str(); }
338 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
339 AU.addRequiredID(PassToPrint->getTypeInfo());
340 AU.setPreservesAll();
344 char BasicBlockPassPrinter::ID = 0;
346 struct BreakpointPrinter : public ModulePass {
350 BreakpointPrinter(raw_ostream &out)
351 : ModulePass(ID), Out(out) {
354 void getContextName(DIDescriptor Context, std::string &N) {
355 if (Context.isNameSpace()) {
356 DINameSpace NS(Context);
357 if (!NS.getName().empty()) {
358 getContextName(NS.getContext(), N);
359 N = N + NS.getName().str() + "::";
361 } else if (Context.isType()) {
363 if (!TY.getName().empty()) {
364 getContextName(TY.getContext(), N);
365 N = N + TY.getName().str() + "::";
370 virtual bool runOnModule(Module &M) {
371 StringSet<> Processed;
372 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
373 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
375 DISubprogram SP(NMD->getOperand(i));
377 getContextName(SP.getContext(), Name);
378 Name = Name + SP.getDisplayName().str();
379 if (!Name.empty() && Processed.insert(Name)) {
386 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
387 AU.setPreservesAll();
391 } // anonymous namespace
393 char BreakpointPrinter::ID = 0;
395 static inline void addPass(PassManagerBase &PM, Pass *P) {
396 // Add the pass to the pass manager...
399 // If we are verifying all of the intermediate steps, add the verifier...
400 if (VerifyEach) PM.add(createVerifierPass());
403 /// AddOptimizationPasses - This routine adds optimization passes
404 /// based on selected optimization level, OptLevel. This routine
405 /// duplicates llvm-gcc behaviour.
407 /// OptLevel - Optimization Level
408 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
410 FPM.add(createVerifierPass()); // Verify that input is correct
412 PassManagerBuilder Builder;
413 Builder.OptLevel = OptLevel;
417 } else if (OptLevel > 1) {
418 unsigned Threshold = 225;
421 Builder.Inliner = createFunctionInliningPass(Threshold);
423 Builder.Inliner = createAlwaysInlinerPass();
425 Builder.DisableUnitAtATime = !UnitAtATime;
426 Builder.DisableUnrollLoops = OptLevel == 0;
427 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
429 Builder.populateFunctionPassManager(FPM);
430 Builder.populateModulePassManager(MPM);
433 static void AddStandardCompilePasses(PassManagerBase &PM) {
434 PM.add(createVerifierPass()); // Verify that input is correct
436 // If the -strip-debug command line option was specified, do it.
438 addPass(PM, createStripSymbolsPass(true));
440 if (DisableOptimizations) return;
442 // -std-compile-opts adds the same module passes as -O3.
443 PassManagerBuilder Builder;
445 Builder.Inliner = createFunctionInliningPass();
446 Builder.OptLevel = 3;
447 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls;
448 Builder.populateModulePassManager(PM);
451 static void AddStandardLinkPasses(PassManagerBase &PM) {
452 PM.add(createVerifierPass()); // Verify that input is correct
454 // If the -strip-debug command line option was specified, do it.
456 addPass(PM, createStripSymbolsPass(true));
458 if (DisableOptimizations) return;
460 PassManagerBuilder Builder;
461 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
462 /*RunInliner=*/ !DisableInline);
466 //===----------------------------------------------------------------------===//
469 int main(int argc, char **argv) {
470 sys::PrintStackTraceOnErrorSignal();
471 llvm::PrettyStackTraceProgram X(argc, argv);
473 // Enable debug stream buffering.
474 EnableDebugBuffering = true;
476 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
477 LLVMContext &Context = getGlobalContext();
480 PassRegistry &Registry = *PassRegistry::getPassRegistry();
481 initializeCore(Registry);
482 initializeScalarOpts(Registry);
483 initializeVectorization(Registry);
484 initializeIPO(Registry);
485 initializeAnalysis(Registry);
486 initializeIPA(Registry);
487 initializeTransformUtils(Registry);
488 initializeInstCombine(Registry);
489 initializeInstrumentation(Registry);
490 initializeTarget(Registry);
492 cl::ParseCommandLineOptions(argc, argv,
493 "llvm .bc -> .bc modular optimizer and analysis printer\n");
495 if (AnalyzeOnly && NoOutput) {
496 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
500 // Allocate a full target machine description only if necessary.
501 // FIXME: The choice of target should be controllable on the command line.
502 std::auto_ptr<TargetMachine> target;
506 // Load the input module...
507 std::auto_ptr<Module> M;
508 M.reset(ParseIRFile(InputFilename, Err, Context));
511 Err.print(argv[0], errs());
515 // Figure out what stream we are supposed to write to...
516 OwningPtr<tool_output_file> Out;
518 if (!OutputFilename.empty())
519 errs() << "WARNING: The -o (output filename) option is ignored when\n"
520 "the --disable-output option is used.\n";
522 // Default to standard output.
523 if (OutputFilename.empty())
524 OutputFilename = "-";
526 std::string ErrorInfo;
527 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
528 raw_fd_ostream::F_Binary));
529 if (!ErrorInfo.empty()) {
530 errs() << ErrorInfo << '\n';
535 // If the output is set to be emitted to standard out, and standard out is a
536 // console, print out a warning message and refuse to do it. We don't
537 // impress anyone by spewing tons of binary goo to a terminal.
538 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
539 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
542 // Create a PassManager to hold and optimize the collection of passes we are
547 // Add an appropriate TargetLibraryInfo pass for the module's triple.
548 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
550 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
551 if (DisableSimplifyLibCalls)
552 TLI->disableAllFunctions();
555 // Add an appropriate TargetData instance for this module.
557 const std::string &ModuleDataLayout = M.get()->getDataLayout();
558 if (!ModuleDataLayout.empty())
559 TD = new TargetData(ModuleDataLayout);
560 else if (!DefaultDataLayout.empty())
561 TD = new TargetData(DefaultDataLayout);
566 OwningPtr<FunctionPassManager> FPasses;
567 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
568 FPasses.reset(new FunctionPassManager(M.get()));
570 FPasses->add(new TargetData(*TD));
573 if (PrintBreakpoints) {
574 // Default to standard output.
576 if (OutputFilename.empty())
577 OutputFilename = "-";
579 std::string ErrorInfo;
580 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
581 raw_fd_ostream::F_Binary));
582 if (!ErrorInfo.empty()) {
583 errs() << ErrorInfo << '\n';
587 Passes.add(new BreakpointPrinter(Out->os()));
591 // If the -strip-debug command line option was specified, add it. If
592 // -std-compile-opts was also specified, it will handle StripDebug.
593 if (StripDebug && !StandardCompileOpts)
594 addPass(Passes, createStripSymbolsPass(true));
596 // Create a new optimization pass for each one specified on the command line
597 for (unsigned i = 0; i < PassList.size(); ++i) {
598 // Check to see if -std-compile-opts was specified before this option. If
600 if (StandardCompileOpts &&
601 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
602 AddStandardCompilePasses(Passes);
603 StandardCompileOpts = false;
606 if (StandardLinkOpts &&
607 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
608 AddStandardLinkPasses(Passes);
609 StandardLinkOpts = false;
612 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
613 AddOptimizationPasses(Passes, *FPasses, 1);
617 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
618 AddOptimizationPasses(Passes, *FPasses, 2);
622 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
623 AddOptimizationPasses(Passes, *FPasses, 3);
627 const PassInfo *PassInf = PassList[i];
629 if (PassInf->getNormalCtor())
630 P = PassInf->getNormalCtor()();
632 errs() << argv[0] << ": cannot create pass: "
633 << PassInf->getPassName() << "\n";
635 PassKind Kind = P->getPassKind();
641 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
644 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
647 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
650 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
652 case PT_CallGraphSCC:
653 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
656 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
663 Passes.add(createPrintModulePass(&errs()));
666 // If -std-compile-opts was specified at the end of the pass list, add them.
667 if (StandardCompileOpts) {
668 AddStandardCompilePasses(Passes);
669 StandardCompileOpts = false;
672 if (StandardLinkOpts) {
673 AddStandardLinkPasses(Passes);
674 StandardLinkOpts = false;
678 AddOptimizationPasses(Passes, *FPasses, 1);
681 AddOptimizationPasses(Passes, *FPasses, 2);
684 AddOptimizationPasses(Passes, *FPasses, 3);
686 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
687 FPasses->doInitialization();
688 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
690 FPasses->doFinalization();
693 // Check that the module is well formed on completion of optimization
694 if (!NoVerify && !VerifyEach)
695 Passes.add(createVerifierPass());
697 // Write bitcode or assembly to the output as the last step...
698 if (!NoOutput && !AnalyzeOnly) {
700 Passes.add(createPrintModulePass(&Out->os()));
702 Passes.add(createBitcodeWriterPass(Out->os()));
705 // Before executing passes, print the final values of the LLVM options.
706 cl::PrintOptionValues();
708 // Now that we have all of the passes ready, run them.
709 Passes.run(*M.get());
712 if (!NoOutput || PrintBreakpoints)