blob: 0c36e21fa58bd1726a45ca53a747b9f1e1ef8f39 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Optimizations may be specified an arbitrary number of times on the command
11// line, They are run in the order specified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Module.h"
Devang Patel14d07602008-09-16 22:25:14 +000016#include "llvm/ModuleProvider.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000017#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"
Daniel Dunbarcae51cb2009-06-03 18:22:15 +000031#include "llvm/Support/StandardPasses.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/Streams.h"
33#include "llvm/Support/SystemUtils.h"
Daniel Dunbar3b475e92008-10-22 03:25:22 +000034#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/LinkAllPasses.h"
36#include "llvm/LinkAllVMCore.h"
37#include <iostream>
38#include <fstream>
39#include <memory>
40#include <algorithm>
41using namespace llvm;
42
43// The OptimizationList is automatically populated with registered Passes by the
44// PassNameParser.
45//
46static cl::list<const PassInfo*, bool, PassNameParser>
47PassList(cl::desc("Optimizations available:"));
48
49// Other command line options...
50//
51static cl::opt<std::string>
52InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
53 cl::init("-"), cl::value_desc("filename"));
54
55static cl::opt<std::string>
56OutputFilename("o", cl::desc("Override output filename"),
57 cl::value_desc("filename"), cl::init("-"));
58
59static cl::opt<bool>
60Force("f", cl::desc("Overwrite output files"));
61
62static cl::opt<bool>
63PrintEachXForm("p", cl::desc("Print module after each transformation"));
64
65static cl::opt<bool>
66NoOutput("disable-output",
67 cl::desc("Do not write result bitcode file"), cl::Hidden);
68
69static cl::opt<bool>
70NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
71
72static cl::opt<bool>
73VerifyEach("verify-each", cl::desc("Verify after each transform"));
74
75static cl::opt<bool>
76StripDebug("strip-debug",
77 cl::desc("Strip debugger symbol info from translation unit"));
78
79static cl::opt<bool>
80DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
81
82static cl::opt<bool>
83DisableOptimizations("disable-opt",
84 cl::desc("Do not run any optimization passes"));
85
86static cl::opt<bool>
87StandardCompileOpts("std-compile-opts",
88 cl::desc("Include the standard compile time optimizations"));
89
90static cl::opt<bool>
Devang Patel14d07602008-09-16 22:25:14 +000091OptLevelO1("O1",
92 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
93
94static cl::opt<bool>
95OptLevelO2("O2",
Devang Pateld02ad902008-09-17 00:01:04 +000096 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
Devang Patel14d07602008-09-16 22:25:14 +000097
98static cl::opt<bool>
99OptLevelO3("O3",
Devang Pateld02ad902008-09-17 00:01:04 +0000100 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
Devang Patel14d07602008-09-16 22:25:14 +0000101
102static cl::opt<bool>
103UnitAtATime("funit-at-a-time",
Devang Patel8dba36c2008-09-17 16:01:39 +0000104 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"));
Devang Patel14d07602008-09-16 22:25:14 +0000105
106static cl::opt<bool>
107DisableSimplifyLibCalls("disable-simplify-libcalls",
Devang Patel8dba36c2008-09-17 16:01:39 +0000108 cl::desc("Disable simplify-libcalls"));
Devang Patel14d07602008-09-16 22:25:14 +0000109
110static cl::opt<bool>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
112
113static cl::alias
114QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
115
116static cl::opt<bool>
117AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
118
119// ---------- Define Printers for module and function passes ------------
120namespace {
121
122struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
123 static char ID;
124 const PassInfo *PassToPrint;
125 CallGraphSCCPassPrinter(const PassInfo *PI) :
Dan Gohmanc74a1972009-02-18 05:09:16 +0000126 CallGraphSCCPass(&ID), PassToPrint(PI) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
129 if (!Quiet) {
130 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
131
132 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
133 Function *F = SCC[i]->getFunction();
134 if (F)
135 getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
136 }
137 }
138 // Get and print pass...
139 return false;
140 }
141
142 virtual const char *getPassName() const { return "'Pass' Printer"; }
143
144 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
145 AU.addRequiredID(PassToPrint);
146 AU.setPreservesAll();
147 }
148};
149
150char CallGraphSCCPassPrinter::ID = 0;
151
152struct ModulePassPrinter : public ModulePass {
153 static char ID;
154 const PassInfo *PassToPrint;
Dan Gohmanc74a1972009-02-18 05:09:16 +0000155 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 PassToPrint(PI) {}
157
158 virtual bool runOnModule(Module &M) {
159 if (!Quiet) {
160 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
161 getAnalysisID<Pass>(PassToPrint).print(cout, &M);
162 }
163
164 // Get and print pass...
165 return false;
166 }
167
168 virtual const char *getPassName() const { return "'Pass' Printer"; }
169
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequiredID(PassToPrint);
172 AU.setPreservesAll();
173 }
174};
175
176char ModulePassPrinter::ID = 0;
177struct FunctionPassPrinter : public FunctionPass {
178 const PassInfo *PassToPrint;
179 static char ID;
Dan Gohmanc74a1972009-02-18 05:09:16 +0000180 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 PassToPrint(PI) {}
182
183 virtual bool runOnFunction(Function &F) {
184 if (!Quiet) {
185 cout << "Printing analysis '" << PassToPrint->getPassName()
186 << "' for function '" << F.getName() << "':\n";
187 }
188 // Get and print pass...
189 getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
190 return false;
191 }
192
193 virtual const char *getPassName() const { return "FunctionPass Printer"; }
194
195 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
196 AU.addRequiredID(PassToPrint);
197 AU.setPreservesAll();
198 }
199};
200
201char FunctionPassPrinter::ID = 0;
202
203struct LoopPassPrinter : public LoopPass {
204 static char ID;
205 const PassInfo *PassToPrint;
206 LoopPassPrinter(const PassInfo *PI) :
Dan Gohmanc74a1972009-02-18 05:09:16 +0000207 LoopPass(&ID), PassToPrint(PI) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208
209 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
210 if (!Quiet) {
211 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
212 getAnalysisID<Pass>(PassToPrint).print(cout,
213 L->getHeader()->getParent()->getParent());
214 }
215 // Get and print pass...
216 return false;
217 }
218
219 virtual const char *getPassName() const { return "'Pass' Printer"; }
220
221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.addRequiredID(PassToPrint);
223 AU.setPreservesAll();
224 }
225};
226
227char LoopPassPrinter::ID = 0;
228
229struct BasicBlockPassPrinter : public BasicBlockPass {
230 const PassInfo *PassToPrint;
231 static char ID;
232 BasicBlockPassPrinter(const PassInfo *PI)
Dan Gohmanc74a1972009-02-18 05:09:16 +0000233 : BasicBlockPass(&ID), PassToPrint(PI) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234
235 virtual bool runOnBasicBlock(BasicBlock &BB) {
236 if (!Quiet) {
237 cout << "Printing Analysis info for BasicBlock '" << BB.getName()
238 << "': Pass " << PassToPrint->getPassName() << ":\n";
239 }
240
241 // Get and print pass...
242 getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
243 return false;
244 }
245
246 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
247
248 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
249 AU.addRequiredID(PassToPrint);
250 AU.setPreservesAll();
251 }
252};
253
254char BasicBlockPassPrinter::ID = 0;
255inline void addPass(PassManager &PM, Pass *P) {
256 // Add the pass to the pass manager...
257 PM.add(P);
258
259 // If we are verifying all of the intermediate steps, add the verifier...
260 if (VerifyEach) PM.add(createVerifierPass());
261}
262
Devang Patel14d07602008-09-16 22:25:14 +0000263/// AddOptimizationPasses - This routine adds optimization passes
264/// based on selected optimization level, OptLevel. This routine
265/// duplicates llvm-gcc behaviour.
266///
267/// OptLevel - Optimization Level
Zhongxing Xu42854c82008-11-26 02:57:24 +0000268void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
269 unsigned OptLevel) {
Daniel Dunbarcae51cb2009-06-03 18:22:15 +0000270 createStandardFunctionPasses(&FPM, OptLevel);
Devang Patel14d07602008-09-16 22:25:14 +0000271
Daniel Dunbarcae51cb2009-06-03 18:22:15 +0000272 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
273 createStandardModulePasses(&MPM, OptLevel,
274 /*OptimizeSize=*/ false,
275 UnitAtATime,
276 /*UnrollLoops=*/ OptLevel > 1,
277 !DisableSimplifyLibCalls,
278 /*HaveExceptions=*/ true,
279 InliningPass);
Devang Patel14d07602008-09-16 22:25:14 +0000280}
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282void AddStandardCompilePasses(PassManager &PM) {
283 PM.add(createVerifierPass()); // Verify that input is correct
284
285 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
286
287 // If the -strip-debug command line option was specified, do it.
288 if (StripDebug)
289 addPass(PM, createStripSymbolsPass(true));
290
291 if (DisableOptimizations) return;
292
Daniel Dunbarcae51cb2009-06-03 18:22:15 +0000293 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
Daniel Dunbarcae51cb2009-06-03 18:22:15 +0000295 // -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,
302 InliningPass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303}
304
305} // anonymous namespace
306
307
308//===----------------------------------------------------------------------===//
309// main for opt
310//
311int main(int argc, char **argv) {
312 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
313 try {
314 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman6099df82007-10-08 15:45:12 +0000315 "llvm .bc -> .bc modular optimizer and analysis printer\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 sys::PrintStackTraceOnErrorSignal();
317
Devang Patelf6a112f2008-08-27 20:51:49 +0000318 // 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;
321
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 std::string ErrorMessage;
323
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));
329 delete Buffer;
330 }
331
332 if (M.get() == 0) {
333 cerr << argv[0] << ": ";
334 if (ErrorMessage.size())
335 cerr << ErrorMessage << "\n";
336 else
337 cerr << "bitcode didn't read correctly.\n";
338 return 1;
339 }
340
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";
350 return 1;
351 }
352 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
353 std::ios::binary;
354 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
355
356 if (!Out->good()) {
357 cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
358 return 1;
359 }
360
361 // Make sure that the Output file gets unlinked from the disk if we get a
362 // SIGINT
363 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
364 }
365
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)) {
370 NoOutput = true;
371 }
372
373 // Create a PassManager to hold and optimize the collection of passes we are
374 // about to build...
375 //
376 PassManager Passes;
377
378 // Add an appropriate TargetData instance for this module...
379 Passes.add(new TargetData(M.get()));
380
Devang Patel14d07602008-09-16 22:25:14 +0000381 FunctionPassManager *FPasses = NULL;
382 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
383 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
384 FPasses->add(new TargetData(M.get()));
385 }
386
Chris Lattnerfe3cc652008-07-13 19:35:21 +0000387 // 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)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 addPass(Passes, createStripSymbolsPass(true));
391
392 // Create a new optimization pass for each one specified on the command line
393 for (unsigned i = 0; i < PassList.size(); ++i) {
Duncan Sands54327b02008-07-13 20:14:38 +0000394 // Check to see if -std-compile-opts was specified before this option. If
Chris Lattnerfe3cc652008-07-13 19:35:21 +0000395 // so, handle it.
396 if (StandardCompileOpts &&
397 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
398 AddStandardCompilePasses(Passes);
399 StandardCompileOpts = false;
400 }
401
Devang Patel14d07602008-09-16 22:25:14 +0000402 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
403 AddOptimizationPasses(Passes, *FPasses, 1);
404 OptLevelO1 = false;
405 }
406
407 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
408 AddOptimizationPasses(Passes, *FPasses, 2);
409 OptLevelO2 = false;
410 }
411
412 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
413 AddOptimizationPasses(Passes, *FPasses, 3);
414 OptLevelO3 = false;
415 }
416
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 const PassInfo *PassInf = PassList[i];
418 Pass *P = 0;
419 if (PassInf->getNormalCtor())
420 P = PassInf->getNormalCtor()();
421 else
422 cerr << argv[0] << ": cannot create pass: "
423 << PassInf->getPassName() << "\n";
424 if (P) {
Nuno Lopese1801a62008-11-04 23:03:58 +0000425 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;
429
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 addPass(Passes, P);
Nuno Lopese1801a62008-11-04 23:03:58 +0000431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 if (AnalyzeOnly) {
Nuno Lopese1801a62008-11-04 23:03:58 +0000433 if (isBBPass)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 Passes.add(new BasicBlockPassPrinter(PassInf));
Nuno Lopese1801a62008-11-04 23:03:58 +0000435 else if (isLPass)
436 Passes.add(new LoopPassPrinter(PassInf));
437 else if (isFPass)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 Passes.add(new FunctionPassPrinter(PassInf));
Nuno Lopese1801a62008-11-04 23:03:58 +0000439 else if (isCGSCCPass)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 Passes.add(new CallGraphSCCPassPrinter(PassInf));
441 else
442 Passes.add(new ModulePassPrinter(PassInf));
443 }
444 }
445
446 if (PrintEachXForm)
Daniel Dunbar3b475e92008-10-22 03:25:22 +0000447 Passes.add(createPrintModulePass(&errs()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 }
Chris Lattnerfe3cc652008-07-13 19:35:21 +0000449
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;
454 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455
Devang Patel14d07602008-09-16 22:25:14 +0000456 if (OptLevelO1) {
457 AddOptimizationPasses(Passes, *FPasses, 1);
458 }
459
460 if (OptLevelO2) {
461 AddOptimizationPasses(Passes, *FPasses, 2);
462 }
463
464 if (OptLevelO3) {
465 AddOptimizationPasses(Passes, *FPasses, 3);
466 }
467
468 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
469 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
470 I != E; ++I)
471 FPasses->run(*I);
472 }
473
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 // Check that the module is well formed on completion of optimization
475 if (!NoVerify && !VerifyEach)
476 Passes.add(createVerifierPass());
477
478 // Write bitcode out to disk or cout as the last step...
479 if (!NoOutput && !AnalyzeOnly)
480 Passes.add(CreateBitcodeWriterPass(*Out));
481
482 // Now that we have all of the passes ready, run them.
483 Passes.run(*M.get());
484
485 // Delete the ofstream.
486 if (Out != &std::cout)
487 delete Out;
488 return 0;
489
490 } catch (const std::string& msg) {
491 cerr << argv[0] << ": " << msg << "\n";
492 } catch (...) {
493 cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
494 }
495 llvm_shutdown();
496 return 1;
497}