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