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