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/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/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.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 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
135 // ---------- Define Printers for module and function passes ------------
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
140 const PassInfo *PassToPrint;
141 CallGraphSCCPassPrinter(const PassInfo *PI) :
142 CallGraphSCCPass(&ID), PassToPrint(PI) {}
144 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
146 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
148 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
149 Function *F = SCC[i]->getFunction();
151 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
155 // Get and print pass...
159 virtual const char *getPassName() const { return "'Pass' Printer"; }
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.addRequiredID(PassToPrint);
163 AU.setPreservesAll();
167 char CallGraphSCCPassPrinter::ID = 0;
169 struct ModulePassPrinter : public ModulePass {
171 const PassInfo *PassToPrint;
172 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
175 virtual bool runOnModule(Module &M) {
177 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
178 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
181 // Get and print pass...
185 virtual const char *getPassName() const { return "'Pass' Printer"; }
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addRequiredID(PassToPrint);
189 AU.setPreservesAll();
193 char ModulePassPrinter::ID = 0;
194 struct FunctionPassPrinter : public FunctionPass {
195 const PassInfo *PassToPrint;
197 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
200 virtual bool runOnFunction(Function &F) {
202 outs() << "Printing analysis '" << PassToPrint->getPassName()
203 << "' for function '" << F.getName() << "':\n";
205 // Get and print pass...
206 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
210 virtual const char *getPassName() const { return "FunctionPass Printer"; }
212 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
213 AU.addRequiredID(PassToPrint);
214 AU.setPreservesAll();
218 char FunctionPassPrinter::ID = 0;
220 struct LoopPassPrinter : public LoopPass {
222 const PassInfo *PassToPrint;
223 LoopPassPrinter(const PassInfo *PI) :
224 LoopPass(&ID), PassToPrint(PI) {}
226 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
228 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
229 getAnalysisID<Pass>(PassToPrint).print(outs(),
230 L->getHeader()->getParent()->getParent());
232 // Get and print pass...
236 virtual const char *getPassName() const { return "'Pass' Printer"; }
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
239 AU.addRequiredID(PassToPrint);
240 AU.setPreservesAll();
244 char LoopPassPrinter::ID = 0;
246 struct BasicBlockPassPrinter : public BasicBlockPass {
247 const PassInfo *PassToPrint;
249 BasicBlockPassPrinter(const PassInfo *PI)
250 : BasicBlockPass(&ID), PassToPrint(PI) {}
252 virtual bool runOnBasicBlock(BasicBlock &BB) {
254 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
255 << "': Pass " << PassToPrint->getPassName() << ":\n";
258 // Get and print pass...
259 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
263 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
265 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
266 AU.addRequiredID(PassToPrint);
267 AU.setPreservesAll();
271 char BasicBlockPassPrinter::ID = 0;
272 inline void addPass(PassManager &PM, Pass *P) {
273 // Add the pass to the pass manager...
276 // If we are verifying all of the intermediate steps, add the verifier...
277 if (VerifyEach) PM.add(createVerifierPass());
280 /// AddOptimizationPasses - This routine adds optimization passes
281 /// based on selected optimization level, OptLevel. This routine
282 /// duplicates llvm-gcc behaviour.
284 /// OptLevel - Optimization Level
285 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
287 createStandardFunctionPasses(&FPM, OptLevel);
289 llvm::Pass *InliningPass = 0;
292 } else if (OptLevel) {
293 unsigned Threshold = 200;
296 InliningPass = createFunctionInliningPass(Threshold);
298 InliningPass = createAlwaysInlinerPass();
300 createStandardModulePasses(&MPM, OptLevel,
301 /*OptimizeSize=*/ false,
303 /*UnrollLoops=*/ OptLevel > 1,
304 !DisableSimplifyLibCalls,
305 /*HaveExceptions=*/ true,
309 void AddStandardCompilePasses(PassManager &PM) {
310 PM.add(createVerifierPass()); // Verify that input is correct
312 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
314 // If the -strip-debug command line option was specified, do it.
316 addPass(PM, createStripSymbolsPass(true));
318 if (DisableOptimizations) return;
320 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
322 // -std-compile-opts adds the same module passes as -O3.
323 createStandardModulePasses(&PM, 3,
324 /*OptimizeSize=*/ false,
325 /*UnitAtATime=*/ true,
326 /*UnrollLoops=*/ true,
327 /*SimplifyLibCalls=*/ true,
328 /*HaveExceptions=*/ true,
332 void AddStandardLinkPasses(PassManager &PM) {
333 PM.add(createVerifierPass()); // Verify that input is correct
335 // If the -strip-debug command line option was specified, do it.
337 addPass(PM, createStripSymbolsPass(true));
339 if (DisableOptimizations) return;
341 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
342 /*RunInliner=*/ !DisableInline,
343 /*VerifyEach=*/ VerifyEach);
346 } // anonymous namespace
349 //===----------------------------------------------------------------------===//
352 int main(int argc, char **argv) {
353 sys::PrintStackTraceOnErrorSignal();
354 llvm::PrettyStackTraceProgram X(argc, argv);
356 // Enable debug stream buffering.
357 EnableDebugBuffering = true;
359 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
360 LLVMContext &Context = getGlobalContext();
362 cl::ParseCommandLineOptions(argc, argv,
363 "llvm .bc -> .bc modular optimizer and analysis printer\n");
365 // Allocate a full target machine description only if necessary.
366 // FIXME: The choice of target should be controllable on the command line.
367 std::auto_ptr<TargetMachine> target;
371 // Load the input module...
372 std::auto_ptr<Module> M;
373 M.reset(ParseIRFile(InputFilename, Err, Context));
376 Err.Print(argv[0], errs());
380 // Figure out what stream we are supposed to write to...
381 // FIXME: outs() is not binary!
382 raw_ostream *Out = &outs(); // Default to printing to stdout...
383 if (OutputFilename != "-") {
384 if (NoOutput || AnalyzeOnly) {
385 errs() << "WARNING: The -o (output filename) option is ignored when\n"
386 "the --disable-output or --analyze options are used.\n";
388 // Make sure that the Output file gets unlinked from the disk if we get a
390 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
392 std::string ErrorInfo;
393 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
394 raw_fd_ostream::F_Binary);
395 if (!ErrorInfo.empty()) {
396 errs() << ErrorInfo << '\n';
403 // If the output is set to be emitted to standard out, and standard out is a
404 // console, print out a warning message and refuse to do it. We don't
405 // impress anyone by spewing tons of binary goo to a terminal.
406 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
407 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
410 // Create a PassManager to hold and optimize the collection of passes we are
415 // Add an appropriate TargetData instance for this module...
417 const std::string &ModuleDataLayout = M.get()->getDataLayout();
418 if (!ModuleDataLayout.empty())
419 TD = new TargetData(ModuleDataLayout);
420 else if (!DefaultDataLayout.empty())
421 TD = new TargetData(DefaultDataLayout);
426 OwningPtr<FunctionPassManager> FPasses;
427 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
428 FPasses.reset(new FunctionPassManager(M.get()));
430 FPasses->add(new TargetData(*TD));
433 // If the -strip-debug command line option was specified, add it. If
434 // -std-compile-opts was also specified, it will handle StripDebug.
435 if (StripDebug && !StandardCompileOpts)
436 addPass(Passes, createStripSymbolsPass(true));
438 // Create a new optimization pass for each one specified on the command line
439 for (unsigned i = 0; i < PassList.size(); ++i) {
440 // Check to see if -std-compile-opts was specified before this option. If
442 if (StandardCompileOpts &&
443 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
444 AddStandardCompilePasses(Passes);
445 StandardCompileOpts = false;
448 if (StandardLinkOpts &&
449 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
450 AddStandardLinkPasses(Passes);
451 StandardLinkOpts = false;
454 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
455 AddOptimizationPasses(Passes, *FPasses, 1);
459 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
460 AddOptimizationPasses(Passes, *FPasses, 2);
464 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
465 AddOptimizationPasses(Passes, *FPasses, 3);
469 const PassInfo *PassInf = PassList[i];
471 if (PassInf->getNormalCtor())
472 P = PassInf->getNormalCtor()();
474 errs() << argv[0] << ": cannot create pass: "
475 << PassInf->getPassName() << "\n";
477 PassKind Kind = P->getPassKind();
483 Passes.add(new BasicBlockPassPrinter(PassInf));
486 Passes.add(new LoopPassPrinter(PassInf));
489 Passes.add(new FunctionPassPrinter(PassInf));
491 case PT_CallGraphSCC:
492 Passes.add(new CallGraphSCCPassPrinter(PassInf));
495 Passes.add(new ModulePassPrinter(PassInf));
502 Passes.add(createPrintModulePass(&errs()));
505 // If -std-compile-opts was specified at the end of the pass list, add them.
506 if (StandardCompileOpts) {
507 AddStandardCompilePasses(Passes);
508 StandardCompileOpts = false;
511 if (StandardLinkOpts) {
512 AddStandardLinkPasses(Passes);
513 StandardLinkOpts = false;
517 AddOptimizationPasses(Passes, *FPasses, 1);
520 AddOptimizationPasses(Passes, *FPasses, 2);
523 AddOptimizationPasses(Passes, *FPasses, 3);
525 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
526 FPasses->doInitialization();
527 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
532 // Check that the module is well formed on completion of optimization
533 if (!NoVerify && !VerifyEach)
534 Passes.add(createVerifierPass());
536 // Write bitcode or assembly out to disk or outs() as the last step...
537 if (!NoOutput && !AnalyzeOnly) {
539 Passes.add(createPrintModulePass(Out));
541 Passes.add(createBitcodeWriterPass(*Out));
544 // Now that we have all of the passes ready, run them.
545 Passes.run(*M.get());
547 // Delete the raw_fd_ostream.