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/ModuleProvider.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/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/IRReader.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/StandardPasses.h"
36 #include "llvm/Support/SystemUtils.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/LinkAllVMCore.h"
44 // The OptimizationList is automatically populated with registered Passes by the
47 static cl::list
<const PassInfo
*, bool, PassNameParser
>
48 PassList(cl::desc("Optimizations available:"));
50 // Other command line options...
52 static cl::opt
<std::string
>
53 InputFilename(cl::Positional
, cl::desc("<input bitcode file>"),
54 cl::init("-"), cl::value_desc("filename"));
56 static cl::opt
<std::string
>
57 OutputFilename("o", cl::desc("Override output filename"),
58 cl::value_desc("filename"), cl::init("-"));
61 Force("f", cl::desc("Enable binary output on terminals"));
64 PrintEachXForm("p", cl::desc("Print module after each transformation"));
67 NoOutput("disable-output",
68 cl::desc("Do not write result bitcode file"), cl::Hidden
);
71 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
74 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden
);
77 VerifyEach("verify-each", cl::desc("Verify after each transform"));
80 StripDebug("strip-debug",
81 cl::desc("Strip debugger symbol info from translation unit"));
84 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
87 DisableOptimizations("disable-opt",
88 cl::desc("Do not run any optimization passes"));
91 DisableInternalize("disable-internalize",
92 cl::desc("Do not mark all symbols as internal"));
95 StandardCompileOpts("std-compile-opts",
96 cl::desc("Include the standard compile time optimizations"));
99 StandardLinkOpts("std-link-opts",
100 cl::desc("Include the standard link time optimizations"));
104 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
108 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
112 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
115 UnitAtATime("funit-at-a-time",
116 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
120 DisableSimplifyLibCalls("disable-simplify-libcalls",
121 cl::desc("Disable simplify-libcalls"));
124 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
127 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
130 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
132 static cl::opt
<std::string
>
133 DefaultDataLayout("default-data-layout",
134 cl::desc("data layout string to use if not specified by module"),
135 cl::value_desc("layout-string"), cl::init(""));
137 // ---------- Define Printers for module and function passes ------------
140 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
142 const PassInfo
*PassToPrint
;
143 CallGraphSCCPassPrinter(const PassInfo
*PI
) :
144 CallGraphSCCPass(&ID
), PassToPrint(PI
) {}
146 virtual bool runOnSCC(std::vector
<CallGraphNode
*>&SCC
) {
148 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
150 for (unsigned i
= 0, e
= SCC
.size(); i
!= e
; ++i
) {
151 Function
*F
= SCC
[i
]->getFunction();
153 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
->getParent());
157 // Get and print pass...
161 virtual const char *getPassName() const { return "'Pass' Printer"; }
163 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
164 AU
.addRequiredID(PassToPrint
);
165 AU
.setPreservesAll();
169 char CallGraphSCCPassPrinter::ID
= 0;
171 struct ModulePassPrinter
: public ModulePass
{
173 const PassInfo
*PassToPrint
;
174 ModulePassPrinter(const PassInfo
*PI
) : ModulePass(&ID
),
177 virtual bool runOnModule(Module
&M
) {
179 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
180 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), &M
);
183 // Get and print pass...
187 virtual const char *getPassName() const { return "'Pass' Printer"; }
189 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
190 AU
.addRequiredID(PassToPrint
);
191 AU
.setPreservesAll();
195 char ModulePassPrinter::ID
= 0;
196 struct FunctionPassPrinter
: public FunctionPass
{
197 const PassInfo
*PassToPrint
;
199 FunctionPassPrinter(const PassInfo
*PI
) : FunctionPass(&ID
),
202 virtual bool runOnFunction(Function
&F
) {
204 outs() << "Printing analysis '" << PassToPrint
->getPassName()
205 << "' for function '" << F
.getName() << "':\n";
207 // Get and print pass...
208 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
.getParent());
212 virtual const char *getPassName() const { return "FunctionPass Printer"; }
214 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
215 AU
.addRequiredID(PassToPrint
);
216 AU
.setPreservesAll();
220 char FunctionPassPrinter::ID
= 0;
222 struct LoopPassPrinter
: public LoopPass
{
224 const PassInfo
*PassToPrint
;
225 LoopPassPrinter(const PassInfo
*PI
) :
226 LoopPass(&ID
), PassToPrint(PI
) {}
228 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
230 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
231 getAnalysisID
<Pass
>(PassToPrint
).print(outs(),
232 L
->getHeader()->getParent()->getParent());
234 // Get and print pass...
238 virtual const char *getPassName() const { return "'Pass' Printer"; }
240 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
241 AU
.addRequiredID(PassToPrint
);
242 AU
.setPreservesAll();
246 char LoopPassPrinter::ID
= 0;
248 struct BasicBlockPassPrinter
: public BasicBlockPass
{
249 const PassInfo
*PassToPrint
;
251 BasicBlockPassPrinter(const PassInfo
*PI
)
252 : BasicBlockPass(&ID
), PassToPrint(PI
) {}
254 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
256 outs() << "Printing Analysis info for BasicBlock '" << BB
.getName()
257 << "': Pass " << PassToPrint
->getPassName() << ":\n";
260 // Get and print pass...
261 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), BB
.getParent()->getParent());
265 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
267 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
268 AU
.addRequiredID(PassToPrint
);
269 AU
.setPreservesAll();
273 char BasicBlockPassPrinter::ID
= 0;
274 inline void addPass(PassManager
&PM
, Pass
*P
) {
275 // Add the pass to the pass manager...
278 // If we are verifying all of the intermediate steps, add the verifier...
279 if (VerifyEach
) PM
.add(createVerifierPass());
282 /// AddOptimizationPasses - This routine adds optimization passes
283 /// based on selected optimization level, OptLevel. This routine
284 /// duplicates llvm-gcc behaviour.
286 /// OptLevel - Optimization Level
287 void AddOptimizationPasses(PassManager
&MPM
, FunctionPassManager
&FPM
,
289 createStandardFunctionPasses(&FPM
, OptLevel
);
291 llvm::Pass
*InliningPass
= OptLevel
> 1 ? createFunctionInliningPass() : 0;
292 createStandardModulePasses(&MPM
, OptLevel
,
293 /*OptimizeSize=*/ false,
295 /*UnrollLoops=*/ OptLevel
> 1,
296 !DisableSimplifyLibCalls
,
297 /*HaveExceptions=*/ true,
301 void AddStandardCompilePasses(PassManager
&PM
) {
302 PM
.add(createVerifierPass()); // Verify that input is correct
304 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
306 // If the -strip-debug command line option was specified, do it.
308 addPass(PM
, createStripSymbolsPass(true));
310 if (DisableOptimizations
) return;
312 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
314 // -std-compile-opts adds the same module passes as -O3.
315 createStandardModulePasses(&PM
, 3,
316 /*OptimizeSize=*/ false,
317 /*UnitAtATime=*/ true,
318 /*UnrollLoops=*/ true,
319 /*SimplifyLibCalls=*/ true,
320 /*HaveExceptions=*/ true,
324 void AddStandardLinkPasses(PassManager
&PM
) {
325 PM
.add(createVerifierPass()); // Verify that input is correct
327 // If the -strip-debug command line option was specified, do it.
329 addPass(PM
, createStripSymbolsPass(true));
331 if (DisableOptimizations
) return;
333 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
334 /*RunInliner=*/ !DisableInline
,
335 /*VerifyEach=*/ VerifyEach
);
338 } // anonymous namespace
341 //===----------------------------------------------------------------------===//
344 int main(int argc
, char **argv
) {
345 sys::PrintStackTraceOnErrorSignal();
346 llvm::PrettyStackTraceProgram
X(argc
, argv
);
348 // Enable debug stream buffering.
349 EnableDebugBuffering
= true;
351 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
352 LLVMContext
&Context
= getGlobalContext();
354 cl::ParseCommandLineOptions(argc
, argv
,
355 "llvm .bc -> .bc modular optimizer and analysis printer\n");
357 // Allocate a full target machine description only if necessary.
358 // FIXME: The choice of target should be controllable on the command line.
359 std::auto_ptr
<TargetMachine
> target
;
363 // Load the input module...
364 std::auto_ptr
<Module
> M
;
365 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
368 Err
.Print(argv
[0], errs());
372 // Figure out what stream we are supposed to write to...
373 // FIXME: outs() is not binary!
374 raw_ostream
*Out
= &outs(); // Default to printing to stdout...
375 if (OutputFilename
!= "-") {
376 // Make sure that the Output file gets unlinked from the disk if we get a
378 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
380 std::string ErrorInfo
;
381 Out
= new raw_fd_ostream(OutputFilename
.c_str(), ErrorInfo
,
382 raw_fd_ostream::F_Binary
);
383 if (!ErrorInfo
.empty()) {
384 errs() << ErrorInfo
<< '\n';
390 // If the output is set to be emitted to standard out, and standard out is a
391 // console, print out a warning message and refuse to do it. We don't
392 // impress anyone by spewing tons of binary goo to a terminal.
393 if (!Force
&& !NoOutput
&& !OutputAssembly
)
394 if (CheckBitcodeOutputToConsole(*Out
, !Quiet
))
397 // Create a PassManager to hold and optimize the collection of passes we are
402 // Add an appropriate TargetData instance for this module...
404 const std::string
&ModuleDataLayout
= M
.get()->getDataLayout();
405 if (!ModuleDataLayout
.empty())
406 TD
= new TargetData(ModuleDataLayout
);
407 else if (!DefaultDataLayout
.empty())
408 TD
= new TargetData(DefaultDataLayout
);
413 FunctionPassManager
*FPasses
= NULL
;
414 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
415 FPasses
= new FunctionPassManager(new ExistingModuleProvider(M
.get()));
417 FPasses
->add(new TargetData(*TD
));
420 // If the -strip-debug command line option was specified, add it. If
421 // -std-compile-opts was also specified, it will handle StripDebug.
422 if (StripDebug
&& !StandardCompileOpts
)
423 addPass(Passes
, createStripSymbolsPass(true));
425 // Create a new optimization pass for each one specified on the command line
426 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
427 // Check to see if -std-compile-opts was specified before this option. If
429 if (StandardCompileOpts
&&
430 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
431 AddStandardCompilePasses(Passes
);
432 StandardCompileOpts
= false;
435 if (StandardLinkOpts
&&
436 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
437 AddStandardLinkPasses(Passes
);
438 StandardLinkOpts
= false;
441 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
442 AddOptimizationPasses(Passes
, *FPasses
, 1);
446 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
447 AddOptimizationPasses(Passes
, *FPasses
, 2);
451 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
452 AddOptimizationPasses(Passes
, *FPasses
, 3);
456 const PassInfo
*PassInf
= PassList
[i
];
458 if (PassInf
->getNormalCtor())
459 P
= PassInf
->getNormalCtor()();
461 errs() << argv
[0] << ": cannot create pass: "
462 << PassInf
->getPassName() << "\n";
464 bool isBBPass
= dynamic_cast<BasicBlockPass
*>(P
) != 0;
465 bool isLPass
= !isBBPass
&& dynamic_cast<LoopPass
*>(P
) != 0;
466 bool isFPass
= !isLPass
&& dynamic_cast<FunctionPass
*>(P
) != 0;
467 bool isCGSCCPass
= !isFPass
&& dynamic_cast<CallGraphSCCPass
*>(P
) != 0;
473 Passes
.add(new BasicBlockPassPrinter(PassInf
));
475 Passes
.add(new LoopPassPrinter(PassInf
));
477 Passes
.add(new FunctionPassPrinter(PassInf
));
478 else if (isCGSCCPass
)
479 Passes
.add(new CallGraphSCCPassPrinter(PassInf
));
481 Passes
.add(new ModulePassPrinter(PassInf
));
486 Passes
.add(createPrintModulePass(&errs()));
489 // If -std-compile-opts was specified at the end of the pass list, add them.
490 if (StandardCompileOpts
) {
491 AddStandardCompilePasses(Passes
);
492 StandardCompileOpts
= false;
495 if (StandardLinkOpts
) {
496 AddStandardLinkPasses(Passes
);
497 StandardLinkOpts
= false;
501 AddOptimizationPasses(Passes
, *FPasses
, 1);
504 AddOptimizationPasses(Passes
, *FPasses
, 2);
507 AddOptimizationPasses(Passes
, *FPasses
, 3);
509 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
510 FPasses
->doInitialization();
511 for (Module::iterator I
= M
.get()->begin(), E
= M
.get()->end();
516 // Check that the module is well formed on completion of optimization
517 if (!NoVerify
&& !VerifyEach
)
518 Passes
.add(createVerifierPass());
520 // Write bitcode or assembly out to disk or outs() as the last step...
521 if (!NoOutput
&& !AnalyzeOnly
) {
523 Passes
.add(createPrintModulePass(Out
));
525 Passes
.add(createBitcodeWriterPass(*Out
));
528 // Now that we have all of the passes ready, run them.
529 Passes
.run(*M
.get());
531 // Delete the raw_fd_ostream.