2b2447b155be2b1947c72aacc4bdf0a63198145f
[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/Transforms/UnifyMethodExitNodes.h"
16 #include "llvm/Transforms/ConstantMerge.h"
17 #include "llvm/Transforms/CleanupGCCOutput.h"
18 #include "llvm/Transforms/LevelChange.h"
19 #include "llvm/Transforms/MethodInlining.h"
20 #include "llvm/Transforms/SymbolStripping.h"
21 #include "llvm/Transforms/ChangeAllocations.h"
22 #include "llvm/Transforms/IPO/SimpleStructMutation.h"
23 #include "llvm/Transforms/IPO/GlobalDCE.h"
24 #include "llvm/Transforms/Scalar/DCE.h"
25 #include "llvm/Transforms/Scalar/ConstantProp.h"
26 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
27 #include "llvm/Transforms/Scalar/InstructionCombining.h"
28 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
29 #include "llvm/Transforms/Instrumentation/TraceValues.h"
30 #include "llvm/Transforms/Instrumentation/ProfilePaths.h"
31 #include "Support/CommandLine.h"
32 #include <fstream>
33 #include <memory>
34
35 // Opts enum - All of the transformations we can do...
36 enum Opts {
37   // Basic optimizations
38   dce, constprop, inlining, constmerge, strip, mstrip, mergereturn,
39
40   // Miscellaneous Transformations
41   raiseallocs, cleangcc,
42
43   // Printing and verifying...
44   print, verify,
45
46   // More powerful optimizations
47   indvars, instcombine, sccp, adce, raise, mem2reg,
48
49   // Instrumentation
50   trace, tracem, paths,
51
52   // Interprocedural optimizations...
53   globaldce, swapstructs, sortstructs,
54 };
55
56
57 // New template functions - Provide functions that return passes of specified
58 // types, with specified arguments...
59 //
60 template<class PassClass>
61 Pass *New() {
62   return new PassClass();
63 }
64
65 template<class PassClass, typename ArgTy1, ArgTy1 Arg1>
66 Pass *New() {
67   return new PassClass(Arg1);
68 }
69
70 template<class PassClass, typename ArgTy1, ArgTy1 Arg1, 
71                           typename ArgTy2, ArgTy1 Arg2>
72 Pass *New() {
73   return new PassClass(Arg1, Arg2);
74 }
75
76 static Pass *NewPrintMethodPass() {
77   return new PrintMethodPass("Current Method: \n", &cerr);
78 }
79
80 // OptTable - Correlate enum Opts to Pass constructors...
81 //
82 struct {
83   enum Opts OptID;
84   Pass * (*PassCtor)();
85 } OptTable[] = {
86   { dce        , New<DeadCodeElimination> },
87   { constprop  , New<ConstantPropogation> }, 
88   { inlining   , New<MethodInlining> },
89   { constmerge , New<ConstantMerge> },
90   { strip      , New<SymbolStripping> },
91   { mstrip     , New<FullSymbolStripping> },
92   { mergereturn, New<UnifyMethodExitNodes> },
93
94   { indvars    , New<InductionVariableSimplify> },
95   { instcombine, New<InstructionCombining> },
96   { sccp       , New<SCCPPass> },
97   { adce       , New<AgressiveDCE> },
98   { raise      , New<RaisePointerReferences> },
99   { mem2reg    , newPromoteMemoryToRegister },
100
101   { trace      , New<InsertTraceCode, bool, true, bool, true> },
102   { tracem     , New<InsertTraceCode, bool, false, bool, true> },
103   { paths      , createProfilePathsPass },
104
105   { print      , NewPrintMethodPass },
106   { verify     , createVerifierPass },
107
108   { raiseallocs, New<RaiseAllocations> },
109   { cleangcc   , New<CleanupGCCOutput> },
110   { globaldce  , New<GlobalDCE> },
111   { swapstructs, New<SimpleStructMutation, SimpleStructMutation::Transform,
112                      SimpleStructMutation::SwapElements>},
113   { sortstructs, New<SimpleStructMutation, SimpleStructMutation::Transform,
114                      SimpleStructMutation::SortElements>},
115 };
116
117 // Command line option handling code...
118 //
119 cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-");
120 cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
121 cl::Flag   Force         ("f", "Overwrite output files", cl::NoFlags, false);
122 cl::Flag   PrintEachXForm("p", "Print module after each transformation");
123 cl::Flag   Quiet         ("q", "Don't print modifying pass names", 0, false);
124 cl::Alias  QuietA        ("quiet", "Alias for -q", cl::NoFlags, Quiet);
125 cl::EnumList<enum Opts> OptimizationList(cl::NoFlags,
126   clEnumVal(dce        , "Dead Code Elimination"),
127   clEnumVal(constprop  , "Simple constant propogation"),
128  clEnumValN(inlining   , "inline", "Method integration"),
129   clEnumVal(constmerge , "Merge identical global constants"),
130   clEnumVal(strip      , "Strip symbols"),
131   clEnumVal(mstrip     , "Strip module symbols"),
132   clEnumVal(mergereturn, "Unify method exit nodes"),
133
134   clEnumVal(indvars    , "Simplify Induction Variables"),
135   clEnumVal(instcombine, "Combine redundant instructions"),
136   clEnumVal(sccp       , "Sparse Conditional Constant Propogation"),
137   clEnumVal(adce       , "Agressive DCE"),
138   clEnumVal(mem2reg    , "Promote alloca locations to registers"),
139
140   clEnumVal(globaldce  , "Remove unreachable globals"),
141   clEnumVal(swapstructs, "Swap structure types around"),
142   clEnumVal(sortstructs, "Sort structure elements"),
143
144   clEnumVal(raiseallocs, "Raise allocations from calls to instructions"),
145   clEnumVal(cleangcc   , "Cleanup GCC Output"),
146   clEnumVal(raise      , "Raise to Higher Level"),
147   clEnumVal(trace      , "Insert BB & Method trace code"),
148   clEnumVal(tracem     , "Insert Method trace code only"),
149   clEnumVal(paths      , "Insert path profiling instrumentation"),
150   clEnumVal(print      , "Print working method to stderr"),
151   clEnumVal(verify     , "Verify module is well formed"),
152 0);
153
154
155
156 int main(int argc, char **argv) {
157   cl::ParseCommandLineOptions(argc, argv,
158                               " llvm .bc -> .bc modular optimizer\n");
159
160   // Load the input module...
161   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
162   if (M.get() == 0) {
163     cerr << "bytecode didn't read correctly.\n";
164     return 1;
165   }
166
167   // Figure out what stream we are supposed to write to...
168   std::ostream *Out = &std::cout;  // Default to printing to stdout...
169   if (OutputFilename != "") {
170     if (!Force && std::ifstream(OutputFilename.c_str())) {
171       // If force is not specified, make sure not to overwrite a file!
172       cerr << "Error opening '" << OutputFilename << "': File exists!\n"
173            << "Use -f command line argument to force output\n";
174       return 1;
175     }
176     Out = new std::ofstream(OutputFilename.c_str());
177
178     if (!Out->good()) {
179       cerr << "Error opening " << OutputFilename << "!\n";
180       return 1;
181     }
182   }
183
184   // Create a PassManager to hold and optimize the collection of passes we are
185   // about to build...
186   //
187   PassManager Passes;
188
189   // Create a new optimization pass for each one specified on the command line
190   for (unsigned i = 0; i < OptimizationList.size(); ++i) {
191     enum Opts Opt = OptimizationList[i];
192     for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
193       if (Opt == OptTable[j].OptID) {
194         Passes.add(OptTable[j].PassCtor());
195         break;
196       }
197
198     if (PrintEachXForm)
199       Passes.add(new PrintModulePass(&std::cerr));
200   }
201
202   // Check that the module is well formed on completion of optimization
203   Passes.add(createVerifierPass());
204
205   // Write bytecode out to disk or cout as the last step...
206   Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
207
208   // Now that we have all of the passes ready, run them.
209   if (Passes.run(M.get()) && !Quiet)
210     cerr << "Program modified.\n";
211
212   return 0;
213 }