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/DebugInfo.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.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 clang -O1"));
111 cl::desc("Optimization level 2. Similar to clang -O2"));
115 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
119 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
123 cl::desc("Optimization level 3. Similar to clang -O3"));
125 static cl::opt
<std::string
>
126 TargetTriple("mtriple", cl::desc("Override target triple for module"));
129 UnitAtATime("funit-at-a-time",
130 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
134 DisableSimplifyLibCalls("disable-simplify-libcalls",
135 cl::desc("Disable simplify-libcalls"));
138 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
141 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
144 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
147 PrintBreakpoints("print-breakpoints-for-testing",
148 cl::desc("Print select breakpoints location for testing"));
150 static cl::opt
<std::string
>
151 DefaultDataLayout("default-data-layout",
152 cl::desc("data layout string to use if not specified by module"),
153 cl::value_desc("layout-string"), cl::init(""));
155 // ---------- Define Printers for module and function passes ------------
158 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
160 const PassInfo
*PassToPrint
;
162 std::string PassName
;
164 CallGraphSCCPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) :
165 CallGraphSCCPass(ID
), PassToPrint(PI
), Out(out
) {
166 std::string PassToPrintName
= PassToPrint
->getPassName();
167 PassName
= "CallGraphSCCPass Printer: " + PassToPrintName
;
170 virtual bool runOnSCC(CallGraphSCC
&SCC
) {
172 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
174 // Get and print pass...
175 for (CallGraphSCC::iterator I
= SCC
.begin(), E
= SCC
.end(); I
!= E
; ++I
) {
176 Function
*F
= (*I
)->getFunction();
178 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
184 virtual const char *getPassName() const { return PassName
.c_str(); }
186 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
187 AU
.addRequiredID(PassToPrint
->getTypeInfo());
188 AU
.setPreservesAll();
192 char CallGraphSCCPassPrinter::ID
= 0;
194 struct ModulePassPrinter
: public ModulePass
{
196 const PassInfo
*PassToPrint
;
198 std::string PassName
;
200 ModulePassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
201 : ModulePass(ID
), PassToPrint(PI
), Out(out
) {
202 std::string PassToPrintName
= PassToPrint
->getPassName();
203 PassName
= "ModulePass Printer: " + PassToPrintName
;
206 virtual bool runOnModule(Module
&M
) {
208 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
210 // Get and print pass...
211 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
, &M
);
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 ModulePassPrinter::ID
= 0;
224 struct FunctionPassPrinter
: public FunctionPass
{
225 const PassInfo
*PassToPrint
;
228 std::string PassName
;
230 FunctionPassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
231 : FunctionPass(ID
), PassToPrint(PI
), Out(out
) {
232 std::string PassToPrintName
= PassToPrint
->getPassName();
233 PassName
= "FunctionPass Printer: " + PassToPrintName
;
236 virtual bool runOnFunction(Function
&F
) {
238 Out
<< "Printing analysis '" << PassToPrint
->getPassName()
239 << "' for function '" << F
.getName() << "':\n";
241 // Get and print pass...
242 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
247 virtual const char *getPassName() const { return PassName
.c_str(); }
249 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
250 AU
.addRequiredID(PassToPrint
->getTypeInfo());
251 AU
.setPreservesAll();
255 char FunctionPassPrinter::ID
= 0;
257 struct LoopPassPrinter
: public LoopPass
{
259 const PassInfo
*PassToPrint
;
261 std::string PassName
;
263 LoopPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) :
264 LoopPass(ID
), PassToPrint(PI
), Out(out
) {
265 std::string PassToPrintName
= PassToPrint
->getPassName();
266 PassName
= "LoopPass Printer: " + PassToPrintName
;
270 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
272 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
274 // Get and print pass...
275 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
276 L
->getHeader()->getParent()->getParent());
280 virtual const char *getPassName() const { return PassName
.c_str(); }
282 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
283 AU
.addRequiredID(PassToPrint
->getTypeInfo());
284 AU
.setPreservesAll();
288 char LoopPassPrinter::ID
= 0;
290 struct RegionPassPrinter
: public RegionPass
{
292 const PassInfo
*PassToPrint
;
294 std::string PassName
;
296 RegionPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) : RegionPass(ID
),
297 PassToPrint(PI
), Out(out
) {
298 std::string PassToPrintName
= PassToPrint
->getPassName();
299 PassName
= "RegionPass Printer: " + PassToPrintName
;
302 virtual bool runOnRegion(Region
*R
, RGPassManager
&RGM
) {
304 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "' for "
305 << "region: '" << R
->getNameStr() << "' in function '"
306 << R
->getEntry()->getParent()->getName() << "':\n";
308 // Get and print pass...
309 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
310 R
->getEntry()->getParent()->getParent());
314 virtual const char *getPassName() const { return PassName
.c_str(); }
316 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
317 AU
.addRequiredID(PassToPrint
->getTypeInfo());
318 AU
.setPreservesAll();
322 char RegionPassPrinter::ID
= 0;
324 struct BasicBlockPassPrinter
: public BasicBlockPass
{
325 const PassInfo
*PassToPrint
;
328 std::string PassName
;
330 BasicBlockPassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
331 : BasicBlockPass(ID
), PassToPrint(PI
), Out(out
) {
332 std::string PassToPrintName
= PassToPrint
->getPassName();
333 PassName
= "BasicBlockPass Printer: " + PassToPrintName
;
336 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
338 Out
<< "Printing Analysis info for BasicBlock '" << BB
.getName()
339 << "': Pass " << PassToPrint
->getPassName() << ":\n";
341 // Get and print pass...
342 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
343 BB
.getParent()->getParent());
347 virtual const char *getPassName() const { return PassName
.c_str(); }
349 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
350 AU
.addRequiredID(PassToPrint
->getTypeInfo());
351 AU
.setPreservesAll();
355 char BasicBlockPassPrinter::ID
= 0;
357 struct BreakpointPrinter
: public ModulePass
{
361 BreakpointPrinter(raw_ostream
&out
)
362 : ModulePass(ID
), Out(out
) {
365 void getContextName(DIDescriptor Context
, std::string
&N
) {
366 if (Context
.isNameSpace()) {
367 DINameSpace
NS(Context
);
368 if (!NS
.getName().empty()) {
369 getContextName(NS
.getContext(), N
);
370 N
= N
+ NS
.getName().str() + "::";
372 } else if (Context
.isType()) {
374 if (!TY
.getName().empty()) {
375 getContextName(TY
.getContext(), N
);
376 N
= N
+ TY
.getName().str() + "::";
381 virtual bool runOnModule(Module
&M
) {
382 StringSet
<> Processed
;
383 if (NamedMDNode
*NMD
= M
.getNamedMetadata("llvm.dbg.sp"))
384 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
386 DISubprogram
SP(NMD
->getOperand(i
));
388 getContextName(SP
.getContext(), Name
);
389 Name
= Name
+ SP
.getDisplayName().str();
390 if (!Name
.empty() && Processed
.insert(Name
)) {
397 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
398 AU
.setPreservesAll();
402 } // anonymous namespace
404 char BreakpointPrinter::ID
= 0;
406 static inline void addPass(PassManagerBase
&PM
, Pass
*P
) {
407 // Add the pass to the pass manager...
410 // If we are verifying all of the intermediate steps, add the verifier...
411 if (VerifyEach
) PM
.add(createVerifierPass());
414 /// AddOptimizationPasses - This routine adds optimization passes
415 /// based on selected optimization level, OptLevel. This routine
416 /// duplicates llvm-gcc behaviour.
418 /// OptLevel - Optimization Level
419 static void AddOptimizationPasses(PassManagerBase
&MPM
,FunctionPassManager
&FPM
,
420 unsigned OptLevel
, unsigned SizeLevel
) {
421 FPM
.add(createVerifierPass()); // Verify that input is correct
423 PassManagerBuilder Builder
;
424 Builder
.OptLevel
= OptLevel
;
425 Builder
.SizeLevel
= SizeLevel
;
429 } else if (OptLevel
> 1) {
430 unsigned Threshold
= 225;
431 if (SizeLevel
== 1) // -Os
433 else if (SizeLevel
== 2) // -Oz
437 Builder
.Inliner
= createFunctionInliningPass(Threshold
);
439 Builder
.Inliner
= createAlwaysInlinerPass();
441 Builder
.DisableUnitAtATime
= !UnitAtATime
;
442 Builder
.DisableUnrollLoops
= OptLevel
== 0;
443 Builder
.DisableSimplifyLibCalls
= DisableSimplifyLibCalls
;
445 Builder
.populateFunctionPassManager(FPM
);
446 Builder
.populateModulePassManager(MPM
);
449 static void AddStandardCompilePasses(PassManagerBase
&PM
) {
450 PM
.add(createVerifierPass()); // Verify that input is correct
452 // If the -strip-debug command line option was specified, do it.
454 addPass(PM
, createStripSymbolsPass(true));
456 if (DisableOptimizations
) return;
458 // -std-compile-opts adds the same module passes as -O3.
459 PassManagerBuilder Builder
;
461 Builder
.Inliner
= createFunctionInliningPass();
462 Builder
.OptLevel
= 3;
463 Builder
.DisableSimplifyLibCalls
= DisableSimplifyLibCalls
;
464 Builder
.populateModulePassManager(PM
);
467 static void AddStandardLinkPasses(PassManagerBase
&PM
) {
468 PM
.add(createVerifierPass()); // Verify that input is correct
470 // If the -strip-debug command line option was specified, do it.
472 addPass(PM
, createStripSymbolsPass(true));
474 if (DisableOptimizations
) return;
476 PassManagerBuilder Builder
;
477 Builder
.populateLTOPassManager(PM
, /*Internalize=*/ !DisableInternalize
,
478 /*RunInliner=*/ !DisableInline
);
482 //===----------------------------------------------------------------------===//
485 int main(int argc
, char **argv
) {
486 sys::PrintStackTraceOnErrorSignal();
487 llvm::PrettyStackTraceProgram
X(argc
, argv
);
489 // Enable debug stream buffering.
490 EnableDebugBuffering
= true;
492 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
493 LLVMContext
&Context
= getGlobalContext();
496 PassRegistry
&Registry
= *PassRegistry::getPassRegistry();
497 initializeCore(Registry
);
498 initializeScalarOpts(Registry
);
499 initializeVectorization(Registry
);
500 initializeIPO(Registry
);
501 initializeAnalysis(Registry
);
502 initializeIPA(Registry
);
503 initializeTransformUtils(Registry
);
504 initializeInstCombine(Registry
);
505 initializeInstrumentation(Registry
);
506 initializeTarget(Registry
);
508 cl::ParseCommandLineOptions(argc
, argv
,
509 "llvm .bc -> .bc modular optimizer and analysis printer\n");
511 if (AnalyzeOnly
&& NoOutput
) {
512 errs() << argv
[0] << ": analyze mode conflicts with no-output mode.\n";
518 // Load the input module...
519 std::auto_ptr
<Module
> M
;
520 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
523 Err
.print(argv
[0], errs());
527 // If we are supposed to override the target triple, do so now.
528 if (!TargetTriple
.empty())
529 M
->setTargetTriple(Triple::normalize(TargetTriple
));
531 // Figure out what stream we are supposed to write to...
532 OwningPtr
<tool_output_file
> Out
;
534 if (!OutputFilename
.empty())
535 errs() << "WARNING: The -o (output filename) option is ignored when\n"
536 "the --disable-output option is used.\n";
538 // Default to standard output.
539 if (OutputFilename
.empty())
540 OutputFilename
= "-";
542 std::string ErrorInfo
;
543 Out
.reset(new tool_output_file(OutputFilename
.c_str(), ErrorInfo
,
544 raw_fd_ostream::F_Binary
));
545 if (!ErrorInfo
.empty()) {
546 errs() << ErrorInfo
<< '\n';
551 // If the output is set to be emitted to standard out, and standard out is a
552 // console, print out a warning message and refuse to do it. We don't
553 // impress anyone by spewing tons of binary goo to a terminal.
554 if (!Force
&& !NoOutput
&& !AnalyzeOnly
&& !OutputAssembly
)
555 if (CheckBitcodeOutputToConsole(Out
->os(), !Quiet
))
558 // Create a PassManager to hold and optimize the collection of passes we are
563 // Add an appropriate TargetLibraryInfo pass for the module's triple.
564 TargetLibraryInfo
*TLI
= new TargetLibraryInfo(Triple(M
->getTargetTriple()));
566 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
567 if (DisableSimplifyLibCalls
)
568 TLI
->disableAllFunctions();
571 // Add an appropriate TargetData instance for this module.
573 const std::string
&ModuleDataLayout
= M
.get()->getDataLayout();
574 if (!ModuleDataLayout
.empty())
575 TD
= new TargetData(ModuleDataLayout
);
576 else if (!DefaultDataLayout
.empty())
577 TD
= new TargetData(DefaultDataLayout
);
582 OwningPtr
<FunctionPassManager
> FPasses
;
583 if (OptLevelO1
|| OptLevelO2
|| OptLevelOs
|| OptLevelOz
|| OptLevelO3
) {
584 FPasses
.reset(new FunctionPassManager(M
.get()));
586 FPasses
->add(new TargetData(*TD
));
589 if (PrintBreakpoints
) {
590 // Default to standard output.
592 if (OutputFilename
.empty())
593 OutputFilename
= "-";
595 std::string ErrorInfo
;
596 Out
.reset(new tool_output_file(OutputFilename
.c_str(), ErrorInfo
,
597 raw_fd_ostream::F_Binary
));
598 if (!ErrorInfo
.empty()) {
599 errs() << ErrorInfo
<< '\n';
603 Passes
.add(new BreakpointPrinter(Out
->os()));
607 // If the -strip-debug command line option was specified, add it. If
608 // -std-compile-opts was also specified, it will handle StripDebug.
609 if (StripDebug
&& !StandardCompileOpts
)
610 addPass(Passes
, createStripSymbolsPass(true));
612 // Create a new optimization pass for each one specified on the command line
613 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
614 // Check to see if -std-compile-opts was specified before this option. If
616 if (StandardCompileOpts
&&
617 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
618 AddStandardCompilePasses(Passes
);
619 StandardCompileOpts
= false;
622 if (StandardLinkOpts
&&
623 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
624 AddStandardLinkPasses(Passes
);
625 StandardLinkOpts
= false;
628 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
629 AddOptimizationPasses(Passes
, *FPasses
, 1, 0);
633 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
634 AddOptimizationPasses(Passes
, *FPasses
, 2, 0);
638 if (OptLevelOs
&& OptLevelOs
.getPosition() < PassList
.getPosition(i
)) {
639 AddOptimizationPasses(Passes
, *FPasses
, 2, 1);
643 if (OptLevelOz
&& OptLevelOz
.getPosition() < PassList
.getPosition(i
)) {
644 AddOptimizationPasses(Passes
, *FPasses
, 2, 2);
648 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
649 AddOptimizationPasses(Passes
, *FPasses
, 3, 0);
653 const PassInfo
*PassInf
= PassList
[i
];
655 if (PassInf
->getNormalCtor())
656 P
= PassInf
->getNormalCtor()();
658 errs() << argv
[0] << ": cannot create pass: "
659 << PassInf
->getPassName() << "\n";
661 PassKind Kind
= P
->getPassKind();
667 Passes
.add(new BasicBlockPassPrinter(PassInf
, Out
->os()));
670 Passes
.add(new RegionPassPrinter(PassInf
, Out
->os()));
673 Passes
.add(new LoopPassPrinter(PassInf
, Out
->os()));
676 Passes
.add(new FunctionPassPrinter(PassInf
, Out
->os()));
678 case PT_CallGraphSCC
:
679 Passes
.add(new CallGraphSCCPassPrinter(PassInf
, Out
->os()));
682 Passes
.add(new ModulePassPrinter(PassInf
, Out
->os()));
689 Passes
.add(createPrintModulePass(&errs()));
692 // If -std-compile-opts was specified at the end of the pass list, add them.
693 if (StandardCompileOpts
) {
694 AddStandardCompilePasses(Passes
);
695 StandardCompileOpts
= false;
698 if (StandardLinkOpts
) {
699 AddStandardLinkPasses(Passes
);
700 StandardLinkOpts
= false;
704 AddOptimizationPasses(Passes
, *FPasses
, 1, 0);
707 AddOptimizationPasses(Passes
, *FPasses
, 2, 0);
710 AddOptimizationPasses(Passes
, *FPasses
, 2, 1);
713 AddOptimizationPasses(Passes
, *FPasses
, 2, 2);
716 AddOptimizationPasses(Passes
, *FPasses
, 3, 0);
718 if (OptLevelO1
|| OptLevelO2
|| OptLevelOs
|| OptLevelOz
|| OptLevelO3
) {
719 FPasses
->doInitialization();
720 for (Module::iterator F
= M
->begin(), E
= M
->end(); F
!= E
; ++F
)
722 FPasses
->doFinalization();
725 // Check that the module is well formed on completion of optimization
726 if (!NoVerify
&& !VerifyEach
)
727 Passes
.add(createVerifierPass());
729 // Write bitcode or assembly to the output as the last step...
730 if (!NoOutput
&& !AnalyzeOnly
) {
732 Passes
.add(createPrintModulePass(&Out
->os()));
734 Passes
.add(createBitcodeWriterPass(Out
->os()));
737 // Before executing passes, print the final values of the LLVM options.
738 cl::PrintOptionValues();
740 // Now that we have all of the passes ready, run them.
741 Passes
.run(*M
.get());
744 if (!NoOutput
|| PrintBreakpoints
)