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/Module.h"
16 #include "llvm/ModuleProvider.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/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/StandardPasses.h"
32 #include "llvm/Support/Streams.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/LinkAllPasses.h"
36 #include "llvm/LinkAllVMCore.h"
43 // The OptimizationList is automatically populated with registered Passes by the
46 static cl::list<const PassInfo*, bool, PassNameParser>
47 PassList(cl::desc("Optimizations available:"));
49 // Other command line options...
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
53 cl::init("-"), cl::value_desc("filename"));
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Override output filename"),
57 cl::value_desc("filename"), cl::init("-"));
60 Force("f", cl::desc("Overwrite output files"));
63 PrintEachXForm("p", cl::desc("Print module after each transformation"));
66 NoOutput("disable-output",
67 cl::desc("Do not write result bitcode file"), cl::Hidden);
70 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
73 VerifyEach("verify-each", cl::desc("Verify after each transform"));
76 StripDebug("strip-debug",
77 cl::desc("Strip debugger symbol info from translation unit"));
80 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
83 DisableOptimizations("disable-opt",
84 cl::desc("Do not run any optimization passes"));
87 StandardCompileOpts("std-compile-opts",
88 cl::desc("Include the standard compile time optimizations"));
92 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
96 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
100 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
103 UnitAtATime("funit-at-a-time",
104 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"));
107 DisableSimplifyLibCalls("disable-simplify-libcalls",
108 cl::desc("Disable simplify-libcalls"));
111 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
114 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
117 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
119 // ---------- Define Printers for module and function passes ------------
122 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
124 const PassInfo *PassToPrint;
125 CallGraphSCCPassPrinter(const PassInfo *PI) :
126 CallGraphSCCPass(&ID), PassToPrint(PI) {}
128 virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
130 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
132 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
133 Function *F = SCC[i]->getFunction();
135 getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
138 // Get and print pass...
142 virtual const char *getPassName() const { return "'Pass' Printer"; }
144 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
145 AU.addRequiredID(PassToPrint);
146 AU.setPreservesAll();
150 char CallGraphSCCPassPrinter::ID = 0;
152 struct ModulePassPrinter : public ModulePass {
154 const PassInfo *PassToPrint;
155 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
158 virtual bool runOnModule(Module &M) {
160 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
161 getAnalysisID<Pass>(PassToPrint).print(cout, &M);
164 // Get and print pass...
168 virtual const char *getPassName() const { return "'Pass' Printer"; }
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequiredID(PassToPrint);
172 AU.setPreservesAll();
176 char ModulePassPrinter::ID = 0;
177 struct FunctionPassPrinter : public FunctionPass {
178 const PassInfo *PassToPrint;
180 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
183 virtual bool runOnFunction(Function &F) {
185 cout << "Printing analysis '" << PassToPrint->getPassName()
186 << "' for function '" << F.getName() << "':\n";
188 // Get and print pass...
189 getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
193 virtual const char *getPassName() const { return "FunctionPass Printer"; }
195 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
196 AU.addRequiredID(PassToPrint);
197 AU.setPreservesAll();
201 char FunctionPassPrinter::ID = 0;
203 struct LoopPassPrinter : public LoopPass {
205 const PassInfo *PassToPrint;
206 LoopPassPrinter(const PassInfo *PI) :
207 LoopPass(&ID), PassToPrint(PI) {}
209 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
211 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
212 getAnalysisID<Pass>(PassToPrint).print(cout,
213 L->getHeader()->getParent()->getParent());
215 // Get and print pass...
219 virtual const char *getPassName() const { return "'Pass' Printer"; }
221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.addRequiredID(PassToPrint);
223 AU.setPreservesAll();
227 char LoopPassPrinter::ID = 0;
229 struct BasicBlockPassPrinter : public BasicBlockPass {
230 const PassInfo *PassToPrint;
232 BasicBlockPassPrinter(const PassInfo *PI)
233 : BasicBlockPass(&ID), PassToPrint(PI) {}
235 virtual bool runOnBasicBlock(BasicBlock &BB) {
237 cout << "Printing Analysis info for BasicBlock '" << BB.getName()
238 << "': Pass " << PassToPrint->getPassName() << ":\n";
241 // Get and print pass...
242 getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
246 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
248 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
249 AU.addRequiredID(PassToPrint);
250 AU.setPreservesAll();
254 char BasicBlockPassPrinter::ID = 0;
255 inline void addPass(PassManager &PM, Pass *P) {
256 // Add the pass to the pass manager...
259 // If we are verifying all of the intermediate steps, add the verifier...
260 if (VerifyEach) PM.add(createVerifierPass());
263 /// AddOptimizationPasses - This routine adds optimization passes
264 /// based on selected optimization level, OptLevel. This routine
265 /// duplicates llvm-gcc behaviour.
267 /// OptLevel - Optimization Level
268 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
270 createStandardFunctionPasses(&FPM, OptLevel);
272 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
273 createStandardModulePasses(&MPM, OptLevel,
274 /*OptimizeSize=*/ false,
276 /*UnrollLoops=*/ OptLevel > 1,
277 !DisableSimplifyLibCalls,
278 /*HaveExceptions=*/ true,
282 void AddStandardCompilePasses(PassManager &PM) {
283 PM.add(createVerifierPass()); // Verify that input is correct
285 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
287 // If the -strip-debug command line option was specified, do it.
289 addPass(PM, createStripSymbolsPass(true));
291 if (DisableOptimizations) return;
293 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
295 // -std-compile-opts adds the same module passes as -O3.
296 createStandardModulePasses(&PM, 3,
297 /*OptimizeSize=*/ false,
298 /*UnitAtATime=*/ true,
299 /*UnrollLoops=*/ true,
300 /*SimplifyLibCalls=*/ true,
301 /*HaveExceptions=*/ true,
305 } // anonymous namespace
308 //===----------------------------------------------------------------------===//
311 int main(int argc, char **argv) {
312 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
314 cl::ParseCommandLineOptions(argc, argv,
315 "llvm .bc -> .bc modular optimizer and analysis printer\n");
316 sys::PrintStackTraceOnErrorSignal();
318 // Allocate a full target machine description only if necessary.
319 // FIXME: The choice of target should be controllable on the command line.
320 std::auto_ptr<TargetMachine> target;
322 std::string ErrorMessage;
324 // Load the input module...
325 std::auto_ptr<Module> M;
326 if (MemoryBuffer *Buffer
327 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
328 M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
333 cerr << argv[0] << ": ";
334 if (ErrorMessage.size())
335 cerr << ErrorMessage << "\n";
337 cerr << "bitcode didn't read correctly.\n";
341 // Figure out what stream we are supposed to write to...
342 // FIXME: cout is not binary!
343 std::ostream *Out = &std::cout; // Default to printing to stdout...
344 if (OutputFilename != "-") {
345 if (!Force && std::ifstream(OutputFilename.c_str())) {
346 // If force is not specified, make sure not to overwrite a file!
347 cerr << argv[0] << ": error opening '" << OutputFilename
348 << "': file exists!\n"
349 << "Use -f command line argument to force output\n";
352 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
354 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
357 cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
361 // Make sure that the Output file gets unlinked from the disk if we get a
363 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
366 // If the output is set to be emitted to standard out, and standard out is a
367 // console, print out a warning message and refuse to do it. We don't
368 // impress anyone by spewing tons of binary goo to a terminal.
369 if (!Force && !NoOutput && CheckBitcodeOutputToConsole(Out,!Quiet)) {
373 // Create a PassManager to hold and optimize the collection of passes we are
378 // Add an appropriate TargetData instance for this module...
379 Passes.add(new TargetData(M.get()));
381 FunctionPassManager *FPasses = NULL;
382 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
383 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
384 FPasses->add(new TargetData(M.get()));
387 // If the -strip-debug command line option was specified, add it. If
388 // -std-compile-opts was also specified, it will handle StripDebug.
389 if (StripDebug && !StandardCompileOpts)
390 addPass(Passes, createStripSymbolsPass(true));
392 // Create a new optimization pass for each one specified on the command line
393 for (unsigned i = 0; i < PassList.size(); ++i) {
394 // Check to see if -std-compile-opts was specified before this option. If
396 if (StandardCompileOpts &&
397 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
398 AddStandardCompilePasses(Passes);
399 StandardCompileOpts = false;
402 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
403 AddOptimizationPasses(Passes, *FPasses, 1);
407 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
408 AddOptimizationPasses(Passes, *FPasses, 2);
412 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
413 AddOptimizationPasses(Passes, *FPasses, 3);
417 const PassInfo *PassInf = PassList[i];
419 if (PassInf->getNormalCtor())
420 P = PassInf->getNormalCtor()();
422 cerr << argv[0] << ": cannot create pass: "
423 << PassInf->getPassName() << "\n";
425 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
426 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
427 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
428 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
434 Passes.add(new BasicBlockPassPrinter(PassInf));
436 Passes.add(new LoopPassPrinter(PassInf));
438 Passes.add(new FunctionPassPrinter(PassInf));
439 else if (isCGSCCPass)
440 Passes.add(new CallGraphSCCPassPrinter(PassInf));
442 Passes.add(new ModulePassPrinter(PassInf));
447 Passes.add(createPrintModulePass(&errs()));
450 // If -std-compile-opts was specified at the end of the pass list, add them.
451 if (StandardCompileOpts) {
452 AddStandardCompilePasses(Passes);
453 StandardCompileOpts = false;
457 AddOptimizationPasses(Passes, *FPasses, 1);
461 AddOptimizationPasses(Passes, *FPasses, 2);
465 AddOptimizationPasses(Passes, *FPasses, 3);
468 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
469 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
474 // Check that the module is well formed on completion of optimization
475 if (!NoVerify && !VerifyEach)
476 Passes.add(createVerifierPass());
478 // Write bitcode out to disk or cout as the last step...
479 if (!NoOutput && !AnalyzeOnly)
480 Passes.add(CreateBitcodeWriterPass(*Out));
482 // Now that we have all of the passes ready, run them.
483 Passes.run(*M.get());
485 // Delete the ofstream.
486 if (Out != &std::cout)
490 } catch (const std::string& msg) {
491 cerr << argv[0] << ": " << msg << "\n";
493 cerr << argv[0] << ": Unexpected unknown exception occurred.\n";