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