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 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
72 VerifyEach("verify-each", cl::desc("Verify after each transform"));
75 StripDebug("strip-debug",
76 cl::desc("Strip debugger symbol info from translation unit"));
79 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
82 DisableOptimizations("disable-opt",
83 cl::desc("Do not run any optimization passes"));
86 DisableInternalize("disable-internalize",
87 cl::desc("Do not mark all symbols as internal"));
90 StandardCompileOpts("std-compile-opts",
91 cl::desc("Include the standard compile time optimizations"));
94 StandardLinkOpts("std-link-opts",
95 cl::desc("Include the standard link time optimizations"));
99 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
103 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
107 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
110 UnitAtATime("funit-at-a-time",
111 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115 DisableSimplifyLibCalls("disable-simplify-libcalls",
116 cl::desc("Disable simplify-libcalls"));
119 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
122 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
125 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
127 // ---------- Define Printers for module and function passes ------------
130 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
132 const PassInfo *PassToPrint;
133 CallGraphSCCPassPrinter(const PassInfo *PI) :
134 CallGraphSCCPass(&ID), PassToPrint(PI) {}
136 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
138 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
140 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
141 Function *F = SCC[i]->getFunction();
143 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
147 // Get and print pass...
151 virtual const char *getPassName() const { return "'Pass' Printer"; }
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequiredID(PassToPrint);
155 AU.setPreservesAll();
159 char CallGraphSCCPassPrinter::ID = 0;
161 struct ModulePassPrinter : public ModulePass {
163 const PassInfo *PassToPrint;
164 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
167 virtual bool runOnModule(Module &M) {
169 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
170 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
173 // Get and print pass...
177 virtual const char *getPassName() const { return "'Pass' Printer"; }
179 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
180 AU.addRequiredID(PassToPrint);
181 AU.setPreservesAll();
185 char ModulePassPrinter::ID = 0;
186 struct FunctionPassPrinter : public FunctionPass {
187 const PassInfo *PassToPrint;
189 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
192 virtual bool runOnFunction(Function &F) {
194 outs() << "Printing analysis '" << PassToPrint->getPassName()
195 << "' for function '" << F.getName() << "':\n";
197 // Get and print pass...
198 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
202 virtual const char *getPassName() const { return "FunctionPass Printer"; }
204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205 AU.addRequiredID(PassToPrint);
206 AU.setPreservesAll();
210 char FunctionPassPrinter::ID = 0;
212 struct LoopPassPrinter : public LoopPass {
214 const PassInfo *PassToPrint;
215 LoopPassPrinter(const PassInfo *PI) :
216 LoopPass(&ID), PassToPrint(PI) {}
218 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
220 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
221 getAnalysisID<Pass>(PassToPrint).print(outs(),
222 L->getHeader()->getParent()->getParent());
224 // Get and print pass...
228 virtual const char *getPassName() const { return "'Pass' Printer"; }
230 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
231 AU.addRequiredID(PassToPrint);
232 AU.setPreservesAll();
236 char LoopPassPrinter::ID = 0;
238 struct BasicBlockPassPrinter : public BasicBlockPass {
239 const PassInfo *PassToPrint;
241 BasicBlockPassPrinter(const PassInfo *PI)
242 : BasicBlockPass(&ID), PassToPrint(PI) {}
244 virtual bool runOnBasicBlock(BasicBlock &BB) {
246 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
247 << "': Pass " << PassToPrint->getPassName() << ":\n";
250 // Get and print pass...
251 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
255 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
257 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
258 AU.addRequiredID(PassToPrint);
259 AU.setPreservesAll();
263 char BasicBlockPassPrinter::ID = 0;
264 inline void addPass(PassManager &PM, Pass *P) {
265 // Add the pass to the pass manager...
268 // If we are verifying all of the intermediate steps, add the verifier...
269 if (VerifyEach) PM.add(createVerifierPass());
272 /// AddOptimizationPasses - This routine adds optimization passes
273 /// based on selected optimization level, OptLevel. This routine
274 /// duplicates llvm-gcc behaviour.
276 /// OptLevel - Optimization Level
277 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
279 createStandardFunctionPasses(&FPM, OptLevel);
281 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
282 createStandardModulePasses(&MPM, OptLevel,
283 /*OptimizeSize=*/ false,
285 /*UnrollLoops=*/ OptLevel > 1,
286 !DisableSimplifyLibCalls,
287 /*HaveExceptions=*/ true,
291 void AddStandardCompilePasses(PassManager &PM) {
292 PM.add(createVerifierPass()); // Verify that input is correct
294 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
296 // If the -strip-debug command line option was specified, do it.
298 addPass(PM, createStripSymbolsPass(true));
300 if (DisableOptimizations) return;
302 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
304 // -std-compile-opts adds the same module passes as -O3.
305 createStandardModulePasses(&PM, 3,
306 /*OptimizeSize=*/ false,
307 /*UnitAtATime=*/ true,
308 /*UnrollLoops=*/ true,
309 /*SimplifyLibCalls=*/ true,
310 /*HaveExceptions=*/ true,
314 void AddStandardLinkPasses(PassManager &PM) {
315 PM.add(createVerifierPass()); // Verify that input is correct
317 // If the -strip-debug command line option was specified, do it.
319 addPass(PM, createStripSymbolsPass(true));
321 if (DisableOptimizations) return;
323 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
324 /*RunInliner=*/ !DisableInline,
325 /*VerifyEach=*/ VerifyEach);
328 } // anonymous namespace
331 //===----------------------------------------------------------------------===//
334 int main(int argc, char **argv) {
335 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
336 LLVMContext &Context = getGlobalContext();
338 cl::ParseCommandLineOptions(argc, argv,
339 "llvm .bc -> .bc modular optimizer and analysis printer\n");
340 sys::PrintStackTraceOnErrorSignal();
342 // Allocate a full target machine description only if necessary.
343 // FIXME: The choice of target should be controllable on the command line.
344 std::auto_ptr<TargetMachine> target;
348 // Load the input module...
349 std::auto_ptr<Module> M;
350 M.reset(ParseIRFile(InputFilename, Err, Context));
353 Err.Print(argv[0], errs());
357 // Figure out what stream we are supposed to write to...
358 // FIXME: outs() is not binary!
359 raw_ostream *Out = &outs(); // Default to printing to stdout...
360 if (OutputFilename != "-") {
361 std::string ErrorInfo;
362 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
363 raw_fd_ostream::F_Binary);
364 if (!ErrorInfo.empty()) {
365 errs() << ErrorInfo << '\n';
370 // Make sure that the Output file gets unlinked from the disk if we get a
372 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
375 // If the output is set to be emitted to standard out, and standard out is a
376 // console, print out a warning message and refuse to do it. We don't
377 // impress anyone by spewing tons of binary goo to a terminal.
378 if (!Force && !NoOutput && CheckBitcodeOutputToConsole(*Out, !Quiet))
381 // Create a PassManager to hold and optimize the collection of passes we are
386 // Add an appropriate TargetData instance for this module...
387 Passes.add(new TargetData(M.get()));
389 FunctionPassManager *FPasses = NULL;
390 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
391 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
392 FPasses->add(new TargetData(M.get()));
395 // If the -strip-debug command line option was specified, add it. If
396 // -std-compile-opts was also specified, it will handle StripDebug.
397 if (StripDebug && !StandardCompileOpts)
398 addPass(Passes, createStripSymbolsPass(true));
400 // Create a new optimization pass for each one specified on the command line
401 for (unsigned i = 0; i < PassList.size(); ++i) {
402 // Check to see if -std-compile-opts was specified before this option. If
404 if (StandardCompileOpts &&
405 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
406 AddStandardCompilePasses(Passes);
407 StandardCompileOpts = false;
410 if (StandardLinkOpts &&
411 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
412 AddStandardLinkPasses(Passes);
413 StandardLinkOpts = false;
416 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
417 AddOptimizationPasses(Passes, *FPasses, 1);
421 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
422 AddOptimizationPasses(Passes, *FPasses, 2);
426 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
427 AddOptimizationPasses(Passes, *FPasses, 3);
431 const PassInfo *PassInf = PassList[i];
433 if (PassInf->getNormalCtor())
434 P = PassInf->getNormalCtor()();
436 errs() << argv[0] << ": cannot create pass: "
437 << PassInf->getPassName() << "\n";
439 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
440 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
441 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
442 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
448 Passes.add(new BasicBlockPassPrinter(PassInf));
450 Passes.add(new LoopPassPrinter(PassInf));
452 Passes.add(new FunctionPassPrinter(PassInf));
453 else if (isCGSCCPass)
454 Passes.add(new CallGraphSCCPassPrinter(PassInf));
456 Passes.add(new ModulePassPrinter(PassInf));
461 Passes.add(createPrintModulePass(&errs()));
464 // If -std-compile-opts was specified at the end of the pass list, add them.
465 if (StandardCompileOpts) {
466 AddStandardCompilePasses(Passes);
467 StandardCompileOpts = false;
470 if (StandardLinkOpts) {
471 AddStandardLinkPasses(Passes);
472 StandardLinkOpts = false;
476 AddOptimizationPasses(Passes, *FPasses, 1);
480 AddOptimizationPasses(Passes, *FPasses, 2);
484 AddOptimizationPasses(Passes, *FPasses, 3);
487 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
488 FPasses->doInitialization();
489 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
494 // Check that the module is well formed on completion of optimization
495 if (!NoVerify && !VerifyEach)
496 Passes.add(createVerifierPass());
498 // Write bitcode out to disk or outs() as the last step...
499 if (!NoOutput && !AnalyzeOnly)
500 Passes.add(createBitcodeWriterPass(*Out));
502 // Now that we have all of the passes ready, run them.
503 Passes.run(*M.get());
505 // Delete the raw_fd_ostream.
510 } catch (const std::string& msg) {
511 errs() << argv[0] << ": " << msg << "\n";
513 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";