*** empty log message ***
[oota-llvm.git] / tools / opt / opt.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM 'OPT' UTILITY 
3 //
4 // Optimizations may be specified an arbitrary number of times on the command
5 // line, they are run in the order specified.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Bytecode/Reader.h"
12 #include "llvm/Bytecode/WriteBytecodePass.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/Analysis/Verifier.h"
15 #include "llvm/Target/TargetData.h"
16 #include "Support/CommandLine.h"
17 #include "Support/Signals.h"
18 #include <fstream>
19 #include <memory>
20 #include <algorithm>
21
22 using std::cerr;
23 using std::string;
24
25 //===----------------------------------------------------------------------===//
26 // PassNameParser class - Make use of the pass registration mechanism to
27 // automatically add a command line argument to opt for each pass.
28 //
29 namespace {  // anonymous namespace for local class...
30 class PassNameParser : public PassRegistrationListener, 
31                        public cl::parser<const PassInfo*> {
32   cl::Option *Opt;
33 public:
34   PassNameParser() : Opt(0) {}
35   
36   void initialize(cl::Option &O) {
37     Opt = &O;
38     cl::parser<const PassInfo*>::initialize(O);
39
40     // Add all of the passes to the map that got initialized before 'this' did.
41     enumeratePasses();
42   }
43
44   static inline bool ignorablePass(const PassInfo *P) {
45     // Ignore non-selectable and non-constructible passes!
46     return P->getPassArgument() == 0 ||
47           (P->getNormalCtor() == 0 && P->getDataCtor() == 0);
48   }
49
50   // Implement the PassRegistrationListener callbacks used to populate our map
51   //
52   virtual void passRegistered(const PassInfo *P) {
53     if (ignorablePass(P) || !Opt) return;
54     assert(findOption(P->getPassArgument()) == getNumOptions() &&
55            "Two passes with the same argument attempted to be registered!");
56     addLiteralOption(P->getPassArgument(), P, P->getPassName());
57     Opt->addArgument(P->getPassArgument());
58   }
59   virtual void passEnumerate(const PassInfo *P) { passRegistered(P); }
60
61   virtual void passUnregistered(const PassInfo *P) {
62     if (ignorablePass(P) || !Opt) return;
63     assert(findOption(P->getPassArgument()) != getNumOptions() &&
64            "Registered Pass not in the pass map!");
65     removeLiteralOption(P->getPassArgument());
66     Opt->removeArgument(P->getPassArgument());
67   }
68
69   // ValLessThan - Provide a sorting comparator for Values elements...
70   typedef std::pair<const char*,
71                     std::pair<const PassInfo*, const char*> > ValType;
72   static bool ValLessThan(const ValType &VT1, const ValType &VT2) {
73     return std::string(VT1.first) < std::string(VT2.first);
74   }
75
76   // printOptionInfo - Print out information about this option.  Override the
77   // default implementation to sort the table before we print...
78   virtual void printOptionInfo(const cl::Option &O, unsigned GlobalWidth) const{
79     PassNameParser *PNP = const_cast<PassNameParser*>(this);
80     std::sort(PNP->Values.begin(), PNP->Values.end(), ValLessThan);
81     cl::parser<const PassInfo*>::printOptionInfo(O, GlobalWidth);
82   }
83 };
84 } // end anonymous namespace
85
86
87 // The OptimizationList is automatically populated with registered Passes by the
88 // PassNameParser.
89 //
90 static cl::list<const PassInfo*, bool, PassNameParser>
91 OptimizationList(cl::desc("Optimizations available:"));
92
93
94 // Other command line options...
95 //
96 static cl::opt<string>
97 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
98
99 static cl::opt<string>
100 OutputFilename("o", cl::desc("Override output filename"),
101                cl::value_desc("filename"));
102
103 static cl::opt<bool>
104 Force("f", cl::desc("Overwrite output files"));
105
106 static cl::opt<bool>
107 PrintEachXForm("p", cl::desc("Print module after each transformation"));
108
109 static cl::opt<bool>
110 Quiet("q", cl::desc("Don't print modifying pass names"));
111
112 static cl::alias
113 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
114
115
116 //===----------------------------------------------------------------------===//
117 // main for opt
118 //
119 int main(int argc, char **argv) {
120   cl::ParseCommandLineOptions(argc, argv,
121                               " llvm .bc -> .bc modular optimizer\n");
122
123   // FIXME: This should be parameterizable eventually for different target
124   // types...
125   TargetData TD("opt target");
126
127   // Load the input module...
128   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
129   if (M.get() == 0) {
130     cerr << "bytecode didn't read correctly.\n";
131     return 1;
132   }
133
134   // Figure out what stream we are supposed to write to...
135   std::ostream *Out = &std::cout;  // Default to printing to stdout...
136   if (OutputFilename != "") {
137     if (!Force && std::ifstream(OutputFilename.c_str())) {
138       // If force is not specified, make sure not to overwrite a file!
139       cerr << "Error opening '" << OutputFilename << "': File exists!\n"
140            << "Use -f command line argument to force output\n";
141       return 1;
142     }
143     Out = new std::ofstream(OutputFilename.c_str());
144
145     if (!Out->good()) {
146       cerr << "Error opening " << OutputFilename << "!\n";
147       return 1;
148     }
149
150     // Make sure that the Output file gets unlink'd from the disk if we get a
151     // SIGINT
152     RemoveFileOnSignal(OutputFilename);
153   }
154
155   // Create a PassManager to hold and optimize the collection of passes we are
156   // about to build...
157   //
158   PassManager Passes;
159
160   // Create a new optimization pass for each one specified on the command line
161   for (unsigned i = 0; i < OptimizationList.size(); ++i) {
162     const PassInfo *Opt = OptimizationList[i];
163     
164     if (Opt->getNormalCtor())
165       Passes.add(Opt->getNormalCtor()());
166     else if (Opt->getDataCtor())
167       Passes.add(Opt->getDataCtor()(TD));  // Pass dummy target data...
168     else
169       cerr << "Cannot create pass: " << Opt->getPassName() << "\n";
170
171     if (PrintEachXForm)
172       Passes.add(new PrintModulePass(&cerr));
173   }
174
175   // Check that the module is well formed on completion of optimization
176   Passes.add(createVerifierPass());
177
178   // Write bytecode out to disk or cout as the last step...
179   Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
180
181   // Now that we have all of the passes ready, run them.
182   if (Passes.run(*M.get()) && !Quiet)
183     cerr << "Program modified.\n";
184
185   return 0;
186 }