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