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