Convert to using llvm streams instead of iostreams.
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Bytecode/Reader.h"
18 #include "llvm/Bytecode/WriteBytecodePass.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/PassNameParser.h"
24 #include "llvm/System/Signals.h"
25 #include "llvm/Support/PluginLoader.h"
26 #include "llvm/Support/Streams.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/LinkAllPasses.h"
30 #include "llvm/LinkAllVMCore.h"
31 #include <fstream>
32 #include <memory>
33 #include <algorithm>
34 using namespace llvm;
35
36 // The OptimizationList is automatically populated with registered Passes by the
37 // PassNameParser.
38 //
39 static cl::list<const PassInfo*, bool, PassNameParser>
40 PassList(cl::desc("Optimizations available:"));
41
42 static cl::opt<bool> NoCompress("disable-compression", cl::init(false),
43        cl::desc("Don't compress the generated bytecode"));
44
45 // Other command line options...
46 //
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input bytecode file>"), 
49     cl::init("-"), cl::value_desc("filename"));
50
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Override output filename"),
53                cl::value_desc("filename"), cl::init("-"));
54
55 static cl::opt<bool>
56 Force("f", cl::desc("Overwrite output files"));
57
58 static cl::opt<bool>
59 PrintEachXForm("p", cl::desc("Print module after each transformation"));
60
61 static cl::opt<bool>
62 NoOutput("disable-output",
63          cl::desc("Do not write result bytecode file"), cl::Hidden);
64
65 static cl::opt<bool>
66 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
67
68 static cl::opt<bool>
69 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
70
71 static cl::alias
72 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
73
74 static cl::opt<bool>
75 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
76
77 static Timer BytecodeLoadTimer("Bytecode Loader");
78
79 // ---------- Define Printers for module and function passes ------------
80 namespace {
81
82 struct ModulePassPrinter : public ModulePass {
83   const PassInfo *PassToPrint;
84   ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
85
86   virtual bool runOnModule(Module &M) {
87     if (!Quiet) {
88       llvm_cout << "Printing analysis '" << PassToPrint->getPassName() 
89                 << "':\n";
90       getAnalysisID<Pass>(PassToPrint).print(llvm_cout, &M);
91     }
92
93     // Get and print pass...
94     return false;
95   }
96
97   virtual const char *getPassName() const { return "'Pass' Printer"; }
98
99   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100     AU.addRequiredID(PassToPrint);
101     AU.setPreservesAll();
102   }
103 };
104
105 struct FunctionPassPrinter : public FunctionPass {
106   const PassInfo *PassToPrint;
107   FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
108
109   virtual bool runOnFunction(Function &F) {
110     if (!Quiet) {
111       llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
112                 << "' for function '" << F.getName() << "':\n";
113     }
114     // Get and print pass...
115     getAnalysisID<Pass>(PassToPrint).print(llvm_cout, F.getParent());
116     return false;
117   }
118
119   virtual const char *getPassName() const { return "FunctionPass Printer"; }
120
121   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122     AU.addRequiredID(PassToPrint);
123     AU.setPreservesAll();
124   }
125 };
126
127 struct BasicBlockPassPrinter : public BasicBlockPass {
128   const PassInfo *PassToPrint;
129   BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
130
131   virtual bool runOnBasicBlock(BasicBlock &BB) {
132     if (!Quiet) {
133       llvm_cout << "Printing Analysis info for BasicBlock '" << BB.getName()
134                 << "': Pass " << PassToPrint->getPassName() << ":\n";
135     }
136
137     // Get and print pass...
138     getAnalysisID<Pass>(PassToPrint).print(
139       llvm_cout, BB.getParent()->getParent());
140     return false;
141   }
142
143   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
144
145   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146     AU.addRequiredID(PassToPrint);
147     AU.setPreservesAll();
148   }
149 };
150
151 } // anonymous namespace
152
153
154 //===----------------------------------------------------------------------===//
155 // main for opt
156 //
157 int main(int argc, char **argv) {
158   try {
159     cl::ParseCommandLineOptions(argc, argv,
160       " llvm .bc -> .bc modular optimizer and analysis printer \n");
161     sys::PrintStackTraceOnErrorSignal();
162
163     // Allocate a full target machine description only if necessary.
164     // FIXME: The choice of target should be controllable on the command line.
165     std::auto_ptr<TargetMachine> target;
166
167     std::string ErrorMessage;
168
169     // Load the input module...
170     std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
171     if (M.get() == 0) {
172       llvm_cerr << argv[0] << ": ";
173       if (ErrorMessage.size())
174         llvm_cerr << ErrorMessage << "\n";
175       else
176         llvm_cerr << "bytecode didn't read correctly.\n";
177       return 1;
178     }
179
180     // Figure out what stream we are supposed to write to...
181     // FIXME: cout is not binary!
182     std::ostream *Out = &std::cout;  // Default to printing to stdout...
183     if (OutputFilename != "-") {
184       if (!Force && std::ifstream(OutputFilename.c_str())) {
185         // If force is not specified, make sure not to overwrite a file!
186         llvm_cerr << argv[0] << ": error opening '" << OutputFilename
187                   << "': file exists!\n"
188                   << "Use -f command line argument to force output\n";
189         return 1;
190       }
191       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
192                                    std::ios::binary;
193       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
194
195       if (!Out->good()) {
196         llvm_cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
197         return 1;
198       }
199
200       // Make sure that the Output file gets unlinked from the disk if we get a
201       // SIGINT
202       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
203     }
204
205     // If the output is set to be emitted to standard out, and standard out is a
206     // console, print out a warning message and refuse to do it.  We don't
207     // impress anyone by spewing tons of binary goo to a terminal.
208     if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
209       NoOutput = true;
210     }
211
212     // Create a PassManager to hold and optimize the collection of passes we are
213     // about to build...
214     //
215     PassManager Passes;
216
217     // Add an appropriate TargetData instance for this module...
218     Passes.add(new TargetData(M.get()));
219
220     // Create a new optimization pass for each one specified on the command line
221     for (unsigned i = 0; i < PassList.size(); ++i) {
222       const PassInfo *PassInf = PassList[i];
223       Pass *P = 0;
224       if (PassInf->getNormalCtor())
225         P = PassInf->getNormalCtor()();
226       else if (PassInf->getTargetCtor()) {
227         assert(target.get() && "Could not allocate target machine!");
228         P = PassInf->getTargetCtor()(*target.get());
229       } else
230         llvm_cerr << argv[0] << ": cannot create pass: "
231                   << PassInf->getPassName() << "\n";
232       if (P) {
233         Passes.add(P);
234         
235         if (AnalyzeOnly) {
236           if (dynamic_cast<BasicBlockPass*>(P))
237             Passes.add(new BasicBlockPassPrinter(PassInf));
238           else if (dynamic_cast<FunctionPass*>(P))
239             Passes.add(new FunctionPassPrinter(PassInf));
240           else
241             Passes.add(new ModulePassPrinter(PassInf));
242         }
243       }
244       
245       if (PrintEachXForm)
246         Passes.add(new PrintModulePass(&llvm_cerr));
247     }
248
249     // Check that the module is well formed on completion of optimization
250     if (!NoVerify)
251       Passes.add(createVerifierPass());
252
253     // Write bytecode out to disk or cout as the last step...
254     if (!NoOutput && !AnalyzeOnly)
255       Passes.add(new WriteBytecodePass(Out, Out != &std::cout, !NoCompress));
256
257     // Now that we have all of the passes ready, run them.
258     Passes.run(*M.get());
259
260     return 0;
261
262   } catch (const std::string& msg) {
263     llvm_cerr << argv[0] << ": " << msg << "\n";
264   } catch (...) {
265     llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
266   }
267   return 1;
268 }