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