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/Verifier.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
42 // The OptimizationList is automatically populated with registered Passes by the
45 static cl::list
<const PassInfo
*, bool, PassNameParser
>
46 PassList(cl::desc("Optimizations available:"));
48 // Other command line options...
50 static cl::opt
<std::string
>
51 InputFilename(cl::Positional
, cl::desc("<input bitcode file>"),
52 cl::init("-"), cl::value_desc("filename"));
54 static cl::opt
<std::string
>
55 OutputFilename("o", cl::desc("Override output filename"),
56 cl::value_desc("filename"), cl::init("-"));
59 Force("f", cl::desc("Enable binary output on terminals"));
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden
);
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden
);
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130 static cl::opt
<std::string
>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
135 // ---------- Define Printers for module and function passes ------------
138 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
140 const PassInfo
*PassToPrint
;
141 CallGraphSCCPassPrinter(const PassInfo
*PI
) :
142 CallGraphSCCPass(&ID
), PassToPrint(PI
) {}
144 virtual bool runOnSCC(CallGraphSCC
&SCC
) {
146 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
148 for (CallGraphSCC::iterator I
= SCC
.begin(), E
= SCC
.end(); I
!= E
; ++I
) {
149 Function
*F
= (*I
)->getFunction();
151 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
->getParent());
154 // Get and print pass...
158 virtual const char *getPassName() const { return "'Pass' Printer"; }
160 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
161 AU
.addRequiredID(PassToPrint
);
162 AU
.setPreservesAll();
166 char CallGraphSCCPassPrinter::ID
= 0;
168 struct ModulePassPrinter
: public ModulePass
{
170 const PassInfo
*PassToPrint
;
171 ModulePassPrinter(const PassInfo
*PI
) : ModulePass(&ID
),
174 virtual bool runOnModule(Module
&M
) {
176 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
177 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), &M
);
180 // Get and print pass...
184 virtual const char *getPassName() const { return "'Pass' Printer"; }
186 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
187 AU
.addRequiredID(PassToPrint
);
188 AU
.setPreservesAll();
192 char ModulePassPrinter::ID
= 0;
193 struct FunctionPassPrinter
: public FunctionPass
{
194 const PassInfo
*PassToPrint
;
196 FunctionPassPrinter(const PassInfo
*PI
) : FunctionPass(&ID
),
199 virtual bool runOnFunction(Function
&F
) {
201 outs() << "Printing analysis '" << PassToPrint
->getPassName()
202 << "' for function '" << F
.getName() << "':\n";
204 // Get and print pass...
205 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
.getParent());
209 virtual const char *getPassName() const { return "FunctionPass Printer"; }
211 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
212 AU
.addRequiredID(PassToPrint
);
213 AU
.setPreservesAll();
217 char FunctionPassPrinter::ID
= 0;
219 struct LoopPassPrinter
: public LoopPass
{
221 const PassInfo
*PassToPrint
;
222 LoopPassPrinter(const PassInfo
*PI
) :
223 LoopPass(&ID
), PassToPrint(PI
) {}
225 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
227 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
228 getAnalysisID
<Pass
>(PassToPrint
).print(outs(),
229 L
->getHeader()->getParent()->getParent());
231 // Get and print pass...
235 virtual const char *getPassName() const { return "'Pass' Printer"; }
237 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
238 AU
.addRequiredID(PassToPrint
);
239 AU
.setPreservesAll();
243 char LoopPassPrinter::ID
= 0;
245 struct BasicBlockPassPrinter
: public BasicBlockPass
{
246 const PassInfo
*PassToPrint
;
248 BasicBlockPassPrinter(const PassInfo
*PI
)
249 : BasicBlockPass(&ID
), PassToPrint(PI
) {}
251 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
253 outs() << "Printing Analysis info for BasicBlock '" << BB
.getName()
254 << "': Pass " << PassToPrint
->getPassName() << ":\n";
257 // Get and print pass...
258 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), BB
.getParent()->getParent());
262 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
264 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
265 AU
.addRequiredID(PassToPrint
);
266 AU
.setPreservesAll();
270 char BasicBlockPassPrinter::ID
= 0;
271 inline void addPass(PassManagerBase
&PM
, Pass
*P
) {
272 // Add the pass to the pass manager...
275 // If we are verifying all of the intermediate steps, add the verifier...
276 if (VerifyEach
) PM
.add(createVerifierPass());
279 /// AddOptimizationPasses - This routine adds optimization passes
280 /// based on selected optimization level, OptLevel. This routine
281 /// duplicates llvm-gcc behaviour.
283 /// OptLevel - Optimization Level
284 void AddOptimizationPasses(PassManagerBase
&MPM
, PassManagerBase
&FPM
,
286 createStandardFunctionPasses(&FPM
, OptLevel
);
288 llvm::Pass
*InliningPass
= 0;
291 } else if (OptLevel
) {
292 unsigned Threshold
= 200;
295 InliningPass
= createFunctionInliningPass(Threshold
);
297 InliningPass
= createAlwaysInlinerPass();
299 createStandardModulePasses(&MPM
, OptLevel
,
300 /*OptimizeSize=*/ false,
302 /*UnrollLoops=*/ OptLevel
> 1,
303 !DisableSimplifyLibCalls
,
304 /*HaveExceptions=*/ true,
308 void AddStandardCompilePasses(PassManagerBase
&PM
) {
309 PM
.add(createVerifierPass()); // Verify that input is correct
311 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
313 // If the -strip-debug command line option was specified, do it.
315 addPass(PM
, createStripSymbolsPass(true));
317 if (DisableOptimizations
) return;
319 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
321 // -std-compile-opts adds the same module passes as -O3.
322 createStandardModulePasses(&PM
, 3,
323 /*OptimizeSize=*/ false,
324 /*UnitAtATime=*/ true,
325 /*UnrollLoops=*/ true,
326 /*SimplifyLibCalls=*/ true,
327 /*HaveExceptions=*/ true,
331 void AddStandardLinkPasses(PassManagerBase
&PM
) {
332 PM
.add(createVerifierPass()); // Verify that input is correct
334 // If the -strip-debug command line option was specified, do it.
336 addPass(PM
, createStripSymbolsPass(true));
338 if (DisableOptimizations
) return;
340 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
341 /*RunInliner=*/ !DisableInline
,
342 /*VerifyEach=*/ VerifyEach
);
345 } // anonymous namespace
348 //===----------------------------------------------------------------------===//
351 int main(int argc
, char **argv
) {
352 sys::PrintStackTraceOnErrorSignal();
353 llvm::PrettyStackTraceProgram
X(argc
, argv
);
355 // Enable debug stream buffering.
356 EnableDebugBuffering
= true;
358 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
359 LLVMContext
&Context
= getGlobalContext();
361 cl::ParseCommandLineOptions(argc
, argv
,
362 "llvm .bc -> .bc modular optimizer and analysis printer\n");
364 // Allocate a full target machine description only if necessary.
365 // FIXME: The choice of target should be controllable on the command line.
366 std::auto_ptr
<TargetMachine
> target
;
370 // Load the input module...
371 std::auto_ptr
<Module
> M
;
372 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
375 Err
.Print(argv
[0], errs());
379 // Figure out what stream we are supposed to write to...
380 raw_ostream
*Out
= 0;
381 bool DeleteStream
= false;
382 if (!NoOutput
&& !AnalyzeOnly
) {
383 if (OutputFilename
== "-") {
386 // If we're printing a bitcode file, switch stdout to binary mode.
387 // FIXME: This switches outs() globally, not just for the bitcode output.
389 sys::Program::ChangeStdoutToBinary();
391 if (NoOutput
|| AnalyzeOnly
) {
392 errs() << "WARNING: The -o (output filename) option is ignored when\n"
393 "the --disable-output or --analyze options are used.\n";
395 // Make sure that the Output file gets unlinked from the disk if we get
397 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
399 std::string ErrorInfo
;
400 Out
= new raw_fd_ostream(OutputFilename
.c_str(), ErrorInfo
,
401 raw_fd_ostream::F_Binary
);
402 if (!ErrorInfo
.empty()) {
403 errs() << ErrorInfo
<< '\n';
412 // If the output is set to be emitted to standard out, and standard out is a
413 // console, print out a warning message and refuse to do it. We don't
414 // impress anyone by spewing tons of binary goo to a terminal.
415 if (!Force
&& !NoOutput
&& !AnalyzeOnly
&& !OutputAssembly
)
416 if (CheckBitcodeOutputToConsole(*Out
, !Quiet
))
419 // Create a PassManager to hold and optimize the collection of passes we are
424 // Add an appropriate TargetData instance for this module...
426 const std::string
&ModuleDataLayout
= M
.get()->getDataLayout();
427 if (!ModuleDataLayout
.empty())
428 TD
= new TargetData(ModuleDataLayout
);
429 else if (!DefaultDataLayout
.empty())
430 TD
= new TargetData(DefaultDataLayout
);
435 OwningPtr
<PassManager
> FPasses
;
436 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
437 FPasses
.reset(new PassManager());
439 FPasses
->add(new TargetData(*TD
));
442 // If the -strip-debug command line option was specified, add it. If
443 // -std-compile-opts was also specified, it will handle StripDebug.
444 if (StripDebug
&& !StandardCompileOpts
)
445 addPass(Passes
, createStripSymbolsPass(true));
447 // Create a new optimization pass for each one specified on the command line
448 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
449 // Check to see if -std-compile-opts was specified before this option. If
451 if (StandardCompileOpts
&&
452 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
453 AddStandardCompilePasses(Passes
);
454 StandardCompileOpts
= false;
457 if (StandardLinkOpts
&&
458 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
459 AddStandardLinkPasses(Passes
);
460 StandardLinkOpts
= false;
463 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
464 AddOptimizationPasses(Passes
, *FPasses
, 1);
468 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
469 AddOptimizationPasses(Passes
, *FPasses
, 2);
473 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
474 AddOptimizationPasses(Passes
, *FPasses
, 3);
478 const PassInfo
*PassInf
= PassList
[i
];
480 if (PassInf
->getNormalCtor())
481 P
= PassInf
->getNormalCtor()();
483 errs() << argv
[0] << ": cannot create pass: "
484 << PassInf
->getPassName() << "\n";
486 PassKind Kind
= P
->getPassKind();
492 Passes
.add(new BasicBlockPassPrinter(PassInf
));
495 Passes
.add(new LoopPassPrinter(PassInf
));
498 Passes
.add(new FunctionPassPrinter(PassInf
));
500 case PT_CallGraphSCC
:
501 Passes
.add(new CallGraphSCCPassPrinter(PassInf
));
504 Passes
.add(new ModulePassPrinter(PassInf
));
511 Passes
.add(createPrintModulePass(&errs()));
514 // If -std-compile-opts was specified at the end of the pass list, add them.
515 if (StandardCompileOpts
) {
516 AddStandardCompilePasses(Passes
);
517 StandardCompileOpts
= false;
520 if (StandardLinkOpts
) {
521 AddStandardLinkPasses(Passes
);
522 StandardLinkOpts
= false;
526 AddOptimizationPasses(Passes
, *FPasses
, 1);
529 AddOptimizationPasses(Passes
, *FPasses
, 2);
532 AddOptimizationPasses(Passes
, *FPasses
, 3);
534 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
)
535 FPasses
->run(*M
.get());
537 // Check that the module is well formed on completion of optimization
538 if (!NoVerify
&& !VerifyEach
)
539 Passes
.add(createVerifierPass());
541 // Write bitcode or assembly out to disk or outs() as the last step...
542 if (!NoOutput
&& !AnalyzeOnly
) {
544 Passes
.add(createPrintModulePass(Out
));
546 Passes
.add(createBitcodeWriterPass(*Out
));
549 // Now that we have all of the passes ready, run them.
550 Passes
.run(*M
.get());
552 // Delete the raw_fd_ostream.