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);
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 // ---------- Define Printers for module and function passes ------------
133 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
135 const PassInfo *PassToPrint;
136 CallGraphSCCPassPrinter(const PassInfo *PI) :
137 CallGraphSCCPass(&ID), PassToPrint(PI) {}
139 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
141 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
143 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
144 Function *F = SCC[i]->getFunction();
146 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
150 // Get and print pass...
154 virtual const char *getPassName() const { return "'Pass' Printer"; }
156 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
157 AU.addRequiredID(PassToPrint);
158 AU.setPreservesAll();
162 char CallGraphSCCPassPrinter::ID = 0;
164 struct ModulePassPrinter : public ModulePass {
166 const PassInfo *PassToPrint;
167 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
170 virtual bool runOnModule(Module &M) {
172 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
173 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
176 // Get and print pass...
180 virtual const char *getPassName() const { return "'Pass' Printer"; }
182 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.addRequiredID(PassToPrint);
184 AU.setPreservesAll();
188 char ModulePassPrinter::ID = 0;
189 struct FunctionPassPrinter : public FunctionPass {
190 const PassInfo *PassToPrint;
192 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
195 virtual bool runOnFunction(Function &F) {
197 outs() << "Printing analysis '" << PassToPrint->getPassName()
198 << "' for function '" << F.getName() << "':\n";
200 // Get and print pass...
201 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
205 virtual const char *getPassName() const { return "FunctionPass Printer"; }
207 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
208 AU.addRequiredID(PassToPrint);
209 AU.setPreservesAll();
213 char FunctionPassPrinter::ID = 0;
215 struct LoopPassPrinter : public LoopPass {
217 const PassInfo *PassToPrint;
218 LoopPassPrinter(const PassInfo *PI) :
219 LoopPass(&ID), PassToPrint(PI) {}
221 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
223 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
224 getAnalysisID<Pass>(PassToPrint).print(outs(),
225 L->getHeader()->getParent()->getParent());
227 // Get and print pass...
231 virtual const char *getPassName() const { return "'Pass' Printer"; }
233 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
234 AU.addRequiredID(PassToPrint);
235 AU.setPreservesAll();
239 char LoopPassPrinter::ID = 0;
241 struct BasicBlockPassPrinter : public BasicBlockPass {
242 const PassInfo *PassToPrint;
244 BasicBlockPassPrinter(const PassInfo *PI)
245 : BasicBlockPass(&ID), PassToPrint(PI) {}
247 virtual bool runOnBasicBlock(BasicBlock &BB) {
249 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
250 << "': Pass " << PassToPrint->getPassName() << ":\n";
253 // Get and print pass...
254 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
258 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
260 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
261 AU.addRequiredID(PassToPrint);
262 AU.setPreservesAll();
266 char BasicBlockPassPrinter::ID = 0;
267 inline void addPass(PassManager &PM, Pass *P) {
268 // Add the pass to the pass manager...
271 // If we are verifying all of the intermediate steps, add the verifier...
272 if (VerifyEach) PM.add(createVerifierPass());
275 /// AddOptimizationPasses - This routine adds optimization passes
276 /// based on selected optimization level, OptLevel. This routine
277 /// duplicates llvm-gcc behaviour.
279 /// OptLevel - Optimization Level
280 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
282 createStandardFunctionPasses(&FPM, OptLevel);
284 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
285 createStandardModulePasses(&MPM, OptLevel,
286 /*OptimizeSize=*/ false,
288 /*UnrollLoops=*/ OptLevel > 1,
289 !DisableSimplifyLibCalls,
290 /*HaveExceptions=*/ true,
294 void AddStandardCompilePasses(PassManager &PM) {
295 PM.add(createVerifierPass()); // Verify that input is correct
297 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
299 // If the -strip-debug command line option was specified, do it.
301 addPass(PM, createStripSymbolsPass(true));
303 if (DisableOptimizations) return;
305 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
307 // -std-compile-opts adds the same module passes as -O3.
308 createStandardModulePasses(&PM, 3,
309 /*OptimizeSize=*/ false,
310 /*UnitAtATime=*/ true,
311 /*UnrollLoops=*/ true,
312 /*SimplifyLibCalls=*/ true,
313 /*HaveExceptions=*/ true,
317 void AddStandardLinkPasses(PassManager &PM) {
318 PM.add(createVerifierPass()); // Verify that input is correct
320 // If the -strip-debug command line option was specified, do it.
322 addPass(PM, createStripSymbolsPass(true));
324 if (DisableOptimizations) return;
326 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
327 /*RunInliner=*/ !DisableInline,
328 /*VerifyEach=*/ VerifyEach);
331 } // anonymous namespace
334 //===----------------------------------------------------------------------===//
337 int main(int argc, char **argv) {
338 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
339 LLVMContext &Context = getGlobalContext();
341 cl::ParseCommandLineOptions(argc, argv,
342 "llvm .bc -> .bc modular optimizer and analysis printer\n");
343 sys::PrintStackTraceOnErrorSignal();
345 // Allocate a full target machine description only if necessary.
346 // FIXME: The choice of target should be controllable on the command line.
347 std::auto_ptr<TargetMachine> target;
351 // Load the input module...
352 std::auto_ptr<Module> M;
353 M.reset(ParseIRFile(InputFilename, Err, Context));
356 Err.Print(argv[0], errs());
360 // Figure out what stream we are supposed to write to...
361 // FIXME: outs() is not binary!
362 raw_ostream *Out = &outs(); // Default to printing to stdout...
363 if (OutputFilename != "-") {
364 // Make sure that the Output file gets unlinked from the disk if we get a
366 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
368 std::string ErrorInfo;
369 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
370 raw_fd_ostream::F_Binary);
371 if (!ErrorInfo.empty()) {
372 errs() << ErrorInfo << '\n';
378 // If the output is set to be emitted to standard out, and standard out is a
379 // console, print out a warning message and refuse to do it. We don't
380 // impress anyone by spewing tons of binary goo to a terminal.
381 if (!Force && !NoOutput && !OutputAssembly)
382 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
385 // Create a PassManager to hold and optimize the collection of passes we are
390 // Add an appropriate TargetData instance for this module...
391 Passes.add(new TargetData(M.get()));
393 FunctionPassManager *FPasses = NULL;
394 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
395 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
396 FPasses->add(new TargetData(M.get()));
399 // If the -strip-debug command line option was specified, add it. If
400 // -std-compile-opts was also specified, it will handle StripDebug.
401 if (StripDebug && !StandardCompileOpts)
402 addPass(Passes, createStripSymbolsPass(true));
404 // Create a new optimization pass for each one specified on the command line
405 for (unsigned i = 0; i < PassList.size(); ++i) {
406 // Check to see if -std-compile-opts was specified before this option. If
408 if (StandardCompileOpts &&
409 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
410 AddStandardCompilePasses(Passes);
411 StandardCompileOpts = false;
414 if (StandardLinkOpts &&
415 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
416 AddStandardLinkPasses(Passes);
417 StandardLinkOpts = false;
420 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
421 AddOptimizationPasses(Passes, *FPasses, 1);
425 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
426 AddOptimizationPasses(Passes, *FPasses, 2);
430 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
431 AddOptimizationPasses(Passes, *FPasses, 3);
435 const PassInfo *PassInf = PassList[i];
437 if (PassInf->getNormalCtor())
438 P = PassInf->getNormalCtor()();
440 errs() << argv[0] << ": cannot create pass: "
441 << PassInf->getPassName() << "\n";
443 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
444 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
445 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
446 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
452 Passes.add(new BasicBlockPassPrinter(PassInf));
454 Passes.add(new LoopPassPrinter(PassInf));
456 Passes.add(new FunctionPassPrinter(PassInf));
457 else if (isCGSCCPass)
458 Passes.add(new CallGraphSCCPassPrinter(PassInf));
460 Passes.add(new ModulePassPrinter(PassInf));
465 Passes.add(createPrintModulePass(&errs()));
468 // If -std-compile-opts was specified at the end of the pass list, add them.
469 if (StandardCompileOpts) {
470 AddStandardCompilePasses(Passes);
471 StandardCompileOpts = false;
474 if (StandardLinkOpts) {
475 AddStandardLinkPasses(Passes);
476 StandardLinkOpts = false;
480 AddOptimizationPasses(Passes, *FPasses, 1);
484 AddOptimizationPasses(Passes, *FPasses, 2);
488 AddOptimizationPasses(Passes, *FPasses, 3);
491 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
492 FPasses->doInitialization();
493 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
498 // Check that the module is well formed on completion of optimization
499 if (!NoVerify && !VerifyEach)
500 Passes.add(createVerifierPass());
502 // Write bitcode or assembly out to disk or outs() as the last step...
503 if (!NoOutput && !AnalyzeOnly) {
505 Passes.add(createPrintModulePass(Out));
507 Passes.add(createBitcodeWriterPass(*Out));
510 // Now that we have all of the passes ready, run them.
511 Passes.run(*M.get());
513 // Delete the raw_fd_ostream.
518 } catch (const std::string& msg) {
519 errs() << argv[0] << ": " << msg << "\n";
521 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";