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