Use the new tool_output_file in several tools. This fixes a variety
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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/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"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
41
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
44 //
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
47
48 // Other command line options...
49 //
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52     cl::init("-"), cl::value_desc("filename"));
53
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56                cl::value_desc("filename"));
57
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
60
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
63
64 static cl::opt<bool>
65 NoOutput("disable-output",
66          cl::desc("Do not write result bitcode file"), cl::Hidden);
67
68 static cl::opt<bool>
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
70
71 static cl::opt<bool>
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
73
74 static cl::opt<bool>
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
76
77 static cl::opt<bool>
78 StripDebug("strip-debug",
79            cl::desc("Strip debugger symbol info from translation unit"));
80
81 static cl::opt<bool>
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
83
84 static cl::opt<bool>
85 DisableOptimizations("disable-opt",
86                      cl::desc("Do not run any optimization passes"));
87
88 static cl::opt<bool>
89 DisableInternalize("disable-internalize",
90                    cl::desc("Do not mark all symbols as internal"));
91
92 static cl::opt<bool>
93 StandardCompileOpts("std-compile-opts",
94                    cl::desc("Include the standard compile time optimizations"));
95
96 static cl::opt<bool>
97 StandardLinkOpts("std-link-opts",
98                  cl::desc("Include the standard link time optimizations"));
99
100 static cl::opt<bool>
101 OptLevelO1("O1",
102            cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
103
104 static cl::opt<bool>
105 OptLevelO2("O2",
106            cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
107
108 static cl::opt<bool>
109 OptLevelO3("O3",
110            cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
111
112 static cl::opt<bool>
113 UnitAtATime("funit-at-a-time",
114             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115             cl::init(true));
116
117 static cl::opt<bool>
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119                         cl::desc("Disable simplify-libcalls"));
120
121 static cl::opt<bool>
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
123
124 static cl::alias
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
126
127 static cl::opt<bool>
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
129
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(""));
134
135 // ---------- Define Printers for module and function passes ------------
136 namespace {
137
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
139   static char ID;
140   const PassInfo *PassToPrint;
141   raw_ostream &Out;
142   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
143     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {}
144
145   virtual bool runOnSCC(CallGraphSCC &SCC) {
146     if (!Quiet) {
147       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
148
149       for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
150         Function *F = (*I)->getFunction();
151         if (F)
152           getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
153                 F->getParent());
154       }
155     }
156     // Get and print pass...
157     return false;
158   }
159
160   virtual const char *getPassName() const { return "'Pass' Printer"; }
161
162   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
163     AU.addRequiredID(PassToPrint->getTypeInfo());
164     AU.setPreservesAll();
165   }
166 };
167
168 char CallGraphSCCPassPrinter::ID = 0;
169
170 struct ModulePassPrinter : public ModulePass {
171   static char ID;
172   const PassInfo *PassToPrint;
173   raw_ostream &Out;
174   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
175     : ModulePass(ID), PassToPrint(PI), Out(out) {}
176
177   virtual bool runOnModule(Module &M) {
178     if (!Quiet) {
179       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
180       getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
181     }
182
183     // Get and print pass...
184     return false;
185   }
186
187   virtual const char *getPassName() const { return "'Pass' Printer"; }
188
189   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
190     AU.addRequiredID(PassToPrint->getTypeInfo());
191     AU.setPreservesAll();
192   }
193 };
194
195 char ModulePassPrinter::ID = 0;
196 struct FunctionPassPrinter : public FunctionPass {
197   const PassInfo *PassToPrint;
198   raw_ostream &Out;
199   static char ID;
200   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
201     : FunctionPass(ID), PassToPrint(PI), Out(out) {}
202
203   virtual bool runOnFunction(Function &F) {
204     if (!Quiet) {
205       Out << "Printing analysis '" << PassToPrint->getPassName()
206           << "' for function '" << F.getName() << "':\n";
207     }
208     // Get and print pass...
209     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
210             F.getParent());
211     return false;
212   }
213
214   virtual const char *getPassName() const { return "FunctionPass Printer"; }
215
216   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
217     AU.addRequiredID(PassToPrint->getTypeInfo());
218     AU.setPreservesAll();
219   }
220 };
221
222 char FunctionPassPrinter::ID = 0;
223
224 struct LoopPassPrinter : public LoopPass {
225   static char ID;
226   const PassInfo *PassToPrint;
227   raw_ostream &Out;
228   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
229     LoopPass(ID), PassToPrint(PI), Out(out) {}
230
231   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
232     if (!Quiet) {
233       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
234       getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
235                                   L->getHeader()->getParent()->getParent());
236     }
237     // Get and print pass...
238     return false;
239   }
240
241   virtual const char *getPassName() const { return "'Pass' Printer"; }
242
243   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
244     AU.addRequiredID(PassToPrint->getTypeInfo());
245     AU.setPreservesAll();
246   }
247 };
248
249 char LoopPassPrinter::ID = 0;
250
251 struct BasicBlockPassPrinter : public BasicBlockPass {
252   const PassInfo *PassToPrint;
253   raw_ostream &Out;
254   static char ID;
255   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
256     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {}
257
258   virtual bool runOnBasicBlock(BasicBlock &BB) {
259     if (!Quiet) {
260       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
261           << "': Pass " << PassToPrint->getPassName() << ":\n";
262     }
263
264     // Get and print pass...
265     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
266             BB.getParent()->getParent());
267     return false;
268   }
269
270   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
271
272   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
273     AU.addRequiredID(PassToPrint->getTypeInfo());
274     AU.setPreservesAll();
275   }
276 };
277
278 char BasicBlockPassPrinter::ID = 0;
279 inline void addPass(PassManagerBase &PM, Pass *P) {
280   // Add the pass to the pass manager...
281   PM.add(P);
282
283   // If we are verifying all of the intermediate steps, add the verifier...
284   if (VerifyEach) PM.add(createVerifierPass());
285 }
286
287 /// AddOptimizationPasses - This routine adds optimization passes
288 /// based on selected optimization level, OptLevel. This routine
289 /// duplicates llvm-gcc behaviour.
290 ///
291 /// OptLevel - Optimization Level
292 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
293                            unsigned OptLevel) {
294   createStandardFunctionPasses(&FPM, OptLevel);
295
296   llvm::Pass *InliningPass = 0;
297   if (DisableInline) {
298     // No inlining pass
299   } else if (OptLevel) {
300     unsigned Threshold = 200;
301     if (OptLevel > 2)
302       Threshold = 250;
303     InliningPass = createFunctionInliningPass(Threshold);
304   } else {
305     InliningPass = createAlwaysInlinerPass();
306   }
307   createStandardModulePasses(&MPM, OptLevel,
308                              /*OptimizeSize=*/ false,
309                              UnitAtATime,
310                              /*UnrollLoops=*/ OptLevel > 1,
311                              !DisableSimplifyLibCalls,
312                              /*HaveExceptions=*/ true,
313                              InliningPass);
314 }
315
316 void AddStandardCompilePasses(PassManagerBase &PM) {
317   PM.add(createVerifierPass());                  // Verify that input is correct
318
319   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
320
321   // If the -strip-debug command line option was specified, do it.
322   if (StripDebug)
323     addPass(PM, createStripSymbolsPass(true));
324
325   if (DisableOptimizations) return;
326
327   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
328
329   // -std-compile-opts adds the same module passes as -O3.
330   createStandardModulePasses(&PM, 3,
331                              /*OptimizeSize=*/ false,
332                              /*UnitAtATime=*/ true,
333                              /*UnrollLoops=*/ true,
334                              /*SimplifyLibCalls=*/ true,
335                              /*HaveExceptions=*/ true,
336                              InliningPass);
337 }
338
339 void AddStandardLinkPasses(PassManagerBase &PM) {
340   PM.add(createVerifierPass());                  // Verify that input is correct
341
342   // If the -strip-debug command line option was specified, do it.
343   if (StripDebug)
344     addPass(PM, createStripSymbolsPass(true));
345
346   if (DisableOptimizations) return;
347
348   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
349                           /*RunInliner=*/ !DisableInline,
350                           /*VerifyEach=*/ VerifyEach);
351 }
352
353 } // anonymous namespace
354
355
356 //===----------------------------------------------------------------------===//
357 // main for opt
358 //
359 int main(int argc, char **argv) {
360   sys::PrintStackTraceOnErrorSignal();
361   llvm::PrettyStackTraceProgram X(argc, argv);
362   
363   // Enable debug stream buffering.
364   EnableDebugBuffering = true;
365
366   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
367   LLVMContext &Context = getGlobalContext();
368   
369   cl::ParseCommandLineOptions(argc, argv,
370     "llvm .bc -> .bc modular optimizer and analysis printer\n");
371
372   // Allocate a full target machine description only if necessary.
373   // FIXME: The choice of target should be controllable on the command line.
374   std::auto_ptr<TargetMachine> target;
375
376   SMDiagnostic Err;
377
378   // Load the input module...
379   std::auto_ptr<Module> M;
380   M.reset(ParseIRFile(InputFilename, Err, Context));
381
382   if (M.get() == 0) {
383     Err.Print(argv[0], errs());
384     return 1;
385   }
386
387   // Figure out what stream we are supposed to write to...
388   OwningPtr<tool_output_file> Out;
389   if (NoOutput) {
390     if (!OutputFilename.empty())
391       errs() << "WARNING: The -o (output filename) option is ignored when\n"
392                 "the --disable-output option is used.\n";
393   } else {
394     // Default to standard output.
395     if (OutputFilename.empty())
396       OutputFilename = "-";
397
398     std::string ErrorInfo;
399     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
400                                    raw_fd_ostream::F_Binary));
401     if (!ErrorInfo.empty()) {
402       errs() << ErrorInfo << '\n';
403       return 1;
404     }
405   }
406
407   // If the output is set to be emitted to standard out, and standard out is a
408   // console, print out a warning message and refuse to do it.  We don't
409   // impress anyone by spewing tons of binary goo to a terminal.
410   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
411     if (CheckBitcodeOutputToConsole(*Out, !Quiet))
412       NoOutput = true;
413
414   // Create a PassManager to hold and optimize the collection of passes we are
415   // about to build...
416   //
417   PassManager Passes;
418
419   // Add an appropriate TargetData instance for this module...
420   TargetData *TD = 0;
421   const std::string &ModuleDataLayout = M.get()->getDataLayout();
422   if (!ModuleDataLayout.empty())
423     TD = new TargetData(ModuleDataLayout);
424   else if (!DefaultDataLayout.empty())
425     TD = new TargetData(DefaultDataLayout);
426
427   if (TD)
428     Passes.add(TD);
429
430   OwningPtr<PassManager> FPasses;
431   if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
432     FPasses.reset(new PassManager());
433     if (TD)
434       FPasses->add(new TargetData(*TD));
435   }
436
437   // If the -strip-debug command line option was specified, add it.  If
438   // -std-compile-opts was also specified, it will handle StripDebug.
439   if (StripDebug && !StandardCompileOpts)
440     addPass(Passes, createStripSymbolsPass(true));
441
442   // Create a new optimization pass for each one specified on the command line
443   for (unsigned i = 0; i < PassList.size(); ++i) {
444     // Check to see if -std-compile-opts was specified before this option.  If
445     // so, handle it.
446     if (StandardCompileOpts &&
447         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
448       AddStandardCompilePasses(Passes);
449       StandardCompileOpts = false;
450     }
451
452     if (StandardLinkOpts &&
453         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
454       AddStandardLinkPasses(Passes);
455       StandardLinkOpts = false;
456     }
457
458     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
459       AddOptimizationPasses(Passes, *FPasses, 1);
460       OptLevelO1 = false;
461     }
462
463     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
464       AddOptimizationPasses(Passes, *FPasses, 2);
465       OptLevelO2 = false;
466     }
467
468     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
469       AddOptimizationPasses(Passes, *FPasses, 3);
470       OptLevelO3 = false;
471     }
472
473     const PassInfo *PassInf = PassList[i];
474     Pass *P = 0;
475     if (PassInf->getNormalCtor())
476       P = PassInf->getNormalCtor()();
477     else
478       errs() << argv[0] << ": cannot create pass: "
479              << PassInf->getPassName() << "\n";
480     if (P) {
481       PassKind Kind = P->getPassKind();
482       addPass(Passes, P);
483
484       if (AnalyzeOnly) {
485         switch (Kind) {
486         case PT_BasicBlock:
487           Passes.add(new BasicBlockPassPrinter(PassInf, *Out));
488           break;
489         case PT_Loop:
490           Passes.add(new LoopPassPrinter(PassInf, *Out));
491           break;
492         case PT_Function:
493           Passes.add(new FunctionPassPrinter(PassInf, *Out));
494           break;
495         case PT_CallGraphSCC:
496           Passes.add(new CallGraphSCCPassPrinter(PassInf, *Out));
497           break;
498         default:
499           Passes.add(new ModulePassPrinter(PassInf, *Out));
500           break;
501         }
502       }
503     }
504
505     if (PrintEachXForm)
506       Passes.add(createPrintModulePass(&errs()));
507   }
508
509   // If -std-compile-opts was specified at the end of the pass list, add them.
510   if (StandardCompileOpts) {
511     AddStandardCompilePasses(Passes);
512     StandardCompileOpts = false;
513   }
514
515   if (StandardLinkOpts) {
516     AddStandardLinkPasses(Passes);
517     StandardLinkOpts = false;
518   }
519
520   if (OptLevelO1)
521     AddOptimizationPasses(Passes, *FPasses, 1);
522
523   if (OptLevelO2)
524     AddOptimizationPasses(Passes, *FPasses, 2);
525
526   if (OptLevelO3)
527     AddOptimizationPasses(Passes, *FPasses, 3);
528
529   if (OptLevelO1 || OptLevelO2 || OptLevelO3)
530     FPasses->run(*M.get());
531
532   // Check that the module is well formed on completion of optimization
533   if (!NoVerify && !VerifyEach)
534     Passes.add(createVerifierPass());
535
536   // Write bitcode or assembly to the output as the last step...
537   if (!NoOutput && !AnalyzeOnly) {
538     if (OutputAssembly)
539       Passes.add(createPrintModulePass(Out.get()));
540     else
541       Passes.add(createBitcodeWriterPass(*Out));
542   }
543
544   // Now that we have all of the passes ready, run them.
545   Passes.run(*M.get());
546
547   // Declare success.
548   if (!NoOutput)
549     Out->keep();
550
551   return 0;
552 }