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/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.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
);
70 cl::desc("Write output as LLVM assembly"), cl::Hidden
);
73 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden
);
76 VerifyEach("verify-each", cl::desc("Verify after each transform"));
79 StripDebug("strip-debug",
80 cl::desc("Strip debugger symbol info from translation unit"));
83 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
86 DisableOptimizations("disable-opt",
87 cl::desc("Do not run any optimization passes"));
90 DisableInternalize("disable-internalize",
91 cl::desc("Do not mark all symbols as internal"));
94 StandardCompileOpts("std-compile-opts",
95 cl::desc("Include the standard compile time optimizations"));
98 StandardLinkOpts("std-link-opts",
99 cl::desc("Include the standard link time optimizations"));
103 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
107 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
111 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
114 UnitAtATime("funit-at-a-time",
115 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
119 DisableSimplifyLibCalls("disable-simplify-libcalls",
120 cl::desc("Disable simplify-libcalls"));
123 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
126 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
129 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
131 // ---------- Define Printers for module and function passes ------------
134 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
136 const PassInfo
*PassToPrint
;
137 CallGraphSCCPassPrinter(const PassInfo
*PI
) :
138 CallGraphSCCPass(&ID
), PassToPrint(PI
) {}
140 virtual bool runOnSCC(std::vector
<CallGraphNode
*>&SCC
) {
142 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
144 for (unsigned i
= 0, e
= SCC
.size(); i
!= e
; ++i
) {
145 Function
*F
= SCC
[i
]->getFunction();
147 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
->getParent());
151 // Get and print pass...
155 virtual const char *getPassName() const { return "'Pass' Printer"; }
157 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
158 AU
.addRequiredID(PassToPrint
);
159 AU
.setPreservesAll();
163 char CallGraphSCCPassPrinter::ID
= 0;
165 struct ModulePassPrinter
: public ModulePass
{
167 const PassInfo
*PassToPrint
;
168 ModulePassPrinter(const PassInfo
*PI
) : ModulePass(&ID
),
171 virtual bool runOnModule(Module
&M
) {
173 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
174 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), &M
);
177 // Get and print pass...
181 virtual const char *getPassName() const { return "'Pass' Printer"; }
183 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
184 AU
.addRequiredID(PassToPrint
);
185 AU
.setPreservesAll();
189 char ModulePassPrinter::ID
= 0;
190 struct FunctionPassPrinter
: public FunctionPass
{
191 const PassInfo
*PassToPrint
;
193 FunctionPassPrinter(const PassInfo
*PI
) : FunctionPass(&ID
),
196 virtual bool runOnFunction(Function
&F
) {
198 outs() << "Printing analysis '" << PassToPrint
->getPassName()
199 << "' for function '" << F
.getName() << "':\n";
201 // Get and print pass...
202 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
.getParent());
206 virtual const char *getPassName() const { return "FunctionPass Printer"; }
208 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
209 AU
.addRequiredID(PassToPrint
);
210 AU
.setPreservesAll();
214 char FunctionPassPrinter::ID
= 0;
216 struct LoopPassPrinter
: public LoopPass
{
218 const PassInfo
*PassToPrint
;
219 LoopPassPrinter(const PassInfo
*PI
) :
220 LoopPass(&ID
), PassToPrint(PI
) {}
222 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
224 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
225 getAnalysisID
<Pass
>(PassToPrint
).print(outs(),
226 L
->getHeader()->getParent()->getParent());
228 // Get and print pass...
232 virtual const char *getPassName() const { return "'Pass' Printer"; }
234 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
235 AU
.addRequiredID(PassToPrint
);
236 AU
.setPreservesAll();
240 char LoopPassPrinter::ID
= 0;
242 struct BasicBlockPassPrinter
: public BasicBlockPass
{
243 const PassInfo
*PassToPrint
;
245 BasicBlockPassPrinter(const PassInfo
*PI
)
246 : BasicBlockPass(&ID
), PassToPrint(PI
) {}
248 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
250 outs() << "Printing Analysis info for BasicBlock '" << BB
.getName()
251 << "': Pass " << PassToPrint
->getPassName() << ":\n";
254 // Get and print pass...
255 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), BB
.getParent()->getParent());
259 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
261 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
262 AU
.addRequiredID(PassToPrint
);
263 AU
.setPreservesAll();
267 char BasicBlockPassPrinter::ID
= 0;
268 inline void addPass(PassManager
&PM
, Pass
*P
) {
269 // Add the pass to the pass manager...
272 // If we are verifying all of the intermediate steps, add the verifier...
273 if (VerifyEach
) PM
.add(createVerifierPass());
276 /// AddOptimizationPasses - This routine adds optimization passes
277 /// based on selected optimization level, OptLevel. This routine
278 /// duplicates llvm-gcc behaviour.
280 /// OptLevel - Optimization Level
281 void AddOptimizationPasses(PassManager
&MPM
, FunctionPassManager
&FPM
,
283 createStandardFunctionPasses(&FPM
, OptLevel
);
285 llvm::Pass
*InliningPass
= OptLevel
> 1 ? createFunctionInliningPass() : 0;
286 createStandardModulePasses(&MPM
, OptLevel
,
287 /*OptimizeSize=*/ false,
289 /*UnrollLoops=*/ OptLevel
> 1,
290 !DisableSimplifyLibCalls
,
291 /*HaveExceptions=*/ true,
295 void AddStandardCompilePasses(PassManager
&PM
) {
296 PM
.add(createVerifierPass()); // Verify that input is correct
298 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
300 // If the -strip-debug command line option was specified, do it.
302 addPass(PM
, createStripSymbolsPass(true));
304 if (DisableOptimizations
) return;
306 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
308 // -std-compile-opts adds the same module passes as -O3.
309 createStandardModulePasses(&PM
, 3,
310 /*OptimizeSize=*/ false,
311 /*UnitAtATime=*/ true,
312 /*UnrollLoops=*/ true,
313 /*SimplifyLibCalls=*/ true,
314 /*HaveExceptions=*/ true,
318 void AddStandardLinkPasses(PassManager
&PM
) {
319 PM
.add(createVerifierPass()); // Verify that input is correct
321 // If the -strip-debug command line option was specified, do it.
323 addPass(PM
, createStripSymbolsPass(true));
325 if (DisableOptimizations
) return;
327 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
328 /*RunInliner=*/ !DisableInline
,
329 /*VerifyEach=*/ VerifyEach
);
332 } // anonymous namespace
335 //===----------------------------------------------------------------------===//
338 int main(int argc
, char **argv
) {
339 llvm_shutdown_obj X
; // Call llvm_shutdown() on exit.
340 LLVMContext
&Context
= getGlobalContext();
342 cl::ParseCommandLineOptions(argc
, argv
,
343 "llvm .bc -> .bc modular optimizer and analysis printer\n");
344 sys::PrintStackTraceOnErrorSignal();
346 // Allocate a full target machine description only if necessary.
347 // FIXME: The choice of target should be controllable on the command line.
348 std::auto_ptr
<TargetMachine
> target
;
352 // Load the input module...
353 std::auto_ptr
<Module
> M
;
354 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
357 Err
.Print(argv
[0], errs());
361 // Figure out what stream we are supposed to write to...
362 // FIXME: outs() is not binary!
363 raw_ostream
*Out
= &outs(); // Default to printing to stdout...
364 if (OutputFilename
!= "-") {
365 // Make sure that the Output file gets unlinked from the disk if we get a
367 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
369 std::string ErrorInfo
;
370 Out
= new raw_fd_ostream(OutputFilename
.c_str(), ErrorInfo
,
371 raw_fd_ostream::F_Binary
);
372 if (!ErrorInfo
.empty()) {
373 errs() << ErrorInfo
<< '\n';
379 // If the output is set to be emitted to standard out, and standard out is a
380 // console, print out a warning message and refuse to do it. We don't
381 // impress anyone by spewing tons of binary goo to a terminal.
382 if (!Force
&& !NoOutput
&& !OutputAssembly
)
383 if (CheckBitcodeOutputToConsole(*Out
, !Quiet
))
386 // Create a PassManager to hold and optimize the collection of passes we are
391 // Add an appropriate TargetData instance for this module...
392 Passes
.add(new TargetData(M
.get()));
394 FunctionPassManager
*FPasses
= NULL
;
395 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
396 FPasses
= new FunctionPassManager(new ExistingModuleProvider(M
.get()));
397 FPasses
->add(new TargetData(M
.get()));
400 // If the -strip-debug command line option was specified, add it. If
401 // -std-compile-opts was also specified, it will handle StripDebug.
402 if (StripDebug
&& !StandardCompileOpts
)
403 addPass(Passes
, createStripSymbolsPass(true));
405 // Create a new optimization pass for each one specified on the command line
406 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
407 // Check to see if -std-compile-opts was specified before this option. If
409 if (StandardCompileOpts
&&
410 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
411 AddStandardCompilePasses(Passes
);
412 StandardCompileOpts
= false;
415 if (StandardLinkOpts
&&
416 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
417 AddStandardLinkPasses(Passes
);
418 StandardLinkOpts
= false;
421 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
422 AddOptimizationPasses(Passes
, *FPasses
, 1);
426 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
427 AddOptimizationPasses(Passes
, *FPasses
, 2);
431 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
432 AddOptimizationPasses(Passes
, *FPasses
, 3);
436 const PassInfo
*PassInf
= PassList
[i
];
438 if (PassInf
->getNormalCtor())
439 P
= PassInf
->getNormalCtor()();
441 errs() << argv
[0] << ": cannot create pass: "
442 << PassInf
->getPassName() << "\n";
444 bool isBBPass
= dynamic_cast<BasicBlockPass
*>(P
) != 0;
445 bool isLPass
= !isBBPass
&& dynamic_cast<LoopPass
*>(P
) != 0;
446 bool isFPass
= !isLPass
&& dynamic_cast<FunctionPass
*>(P
) != 0;
447 bool isCGSCCPass
= !isFPass
&& dynamic_cast<CallGraphSCCPass
*>(P
) != 0;
453 Passes
.add(new BasicBlockPassPrinter(PassInf
));
455 Passes
.add(new LoopPassPrinter(PassInf
));
457 Passes
.add(new FunctionPassPrinter(PassInf
));
458 else if (isCGSCCPass
)
459 Passes
.add(new CallGraphSCCPassPrinter(PassInf
));
461 Passes
.add(new ModulePassPrinter(PassInf
));
466 Passes
.add(createPrintModulePass(&errs()));
469 // If -std-compile-opts was specified at the end of the pass list, add them.
470 if (StandardCompileOpts
) {
471 AddStandardCompilePasses(Passes
);
472 StandardCompileOpts
= false;
475 if (StandardLinkOpts
) {
476 AddStandardLinkPasses(Passes
);
477 StandardLinkOpts
= false;
481 AddOptimizationPasses(Passes
, *FPasses
, 1);
485 AddOptimizationPasses(Passes
, *FPasses
, 2);
489 AddOptimizationPasses(Passes
, *FPasses
, 3);
492 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
493 FPasses
->doInitialization();
494 for (Module::iterator I
= M
.get()->begin(), E
= M
.get()->end();
499 // Check that the module is well formed on completion of optimization
500 if (!NoVerify
&& !VerifyEach
)
501 Passes
.add(createVerifierPass());
503 // Write bitcode or assembly out to disk or outs() as the last step...
504 if (!NoOutput
&& !AnalyzeOnly
) {
506 Passes
.add(createPrintModulePass(Out
));
508 Passes
.add(createBitcodeWriterPass(*Out
));
511 // Now that we have all of the passes ready, run them.
512 Passes
.run(*M
.get());
514 // Delete the raw_fd_ostream.
519 } catch (const std::string
& msg
) {
520 errs() << argv
[0] << ": " << msg
<< "\n";
522 errs() << argv
[0] << ": Unexpected unknown exception occurred.\n";