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