1 //===----------------------------------------------------------------------===//
4 // Optimizations may be specified an arbitrary number of times on the command
5 // line, they are run in the order specified.
7 //===----------------------------------------------------------------------===//
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/Scalar.h"
21 #include "llvm/Transforms/IPO/SimpleStructMutation.h"
22 #include "llvm/Transforms/IPO/Internalize.h"
23 #include "llvm/Transforms/IPO/GlobalDCE.h"
24 #include "llvm/Transforms/IPO/PoolAllocate.h"
25 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
26 #include "llvm/Transforms/Instrumentation/TraceValues.h"
27 #include "llvm/Transforms/Instrumentation/ProfilePaths.h"
28 #include "llvm/Transforms/Instrumentation/EmitFunctions.h"
29 #include "llvm/Target/TargetData.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Signals.h"
37 // FIXME: This should be parameterizable eventually for different target
39 static TargetData TD("opt target");
41 // Opts enum - All of the transformations we can do...
43 // Basic optimizations
44 dce, die, constprop, gcse, licm, inlining, constmerge,
45 strip, mstrip, mergereturn, simplifycfg,
47 // Miscellaneous Transformations
48 raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs,
50 // Printing and verifying...
51 print, printm, verify,
53 // More powerful optimizations
54 indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes,
57 trace, tracem, paths, emitfuncs,
59 // Interprocedural optimizations...
60 internalize, globaldce, swapstructs, sortstructs, poolalloc,
63 static Pass *createPrintFunctionPass() {
64 return new PrintFunctionPass("Current Function: \n", &cerr);
67 static Pass *createPrintModulePass() {
68 return new PrintModulePass(&cerr);
71 static Pass *createLowerAllocationsPassNT() {
72 return createLowerAllocationsPass(TD);
75 // OptTable - Correlate enum Opts to Pass constructors...
81 { dce , createDeadCodeEliminationPass },
82 { die , createDeadInstEliminationPass },
83 { constprop , createConstantPropogationPass },
84 { gcse , createGCSEPass },
85 { licm , createLICMPass },
86 { inlining , createFunctionInliningPass },
87 { constmerge , createConstantMergePass },
88 { strip , createSymbolStrippingPass },
89 { mstrip , createFullSymbolStrippingPass },
90 { mergereturn, createUnifyFunctionExitNodesPass },
91 { simplifycfg, createCFGSimplificationPass },
93 { indvars , createIndVarSimplifyPass },
94 { instcombine, createInstructionCombiningPass },
95 { sccp , createSCCPPass },
96 { adce , createAggressiveDCEPass },
97 { raise , createRaisePointerReferencesPass },
98 /* { reassociate, createReassociatePass },*/
99 { mem2reg , createPromoteMemoryToRegister },
100 { pinodes , createPiNodeInsertionPass },
101 { lowerrefs , createDecomposeMultiDimRefsPass },
103 { trace , createTraceValuesPassForBasicBlocks },
104 { tracem , createTraceValuesPassForFunction },
105 { paths , createProfilePathsPass },
106 { emitfuncs , createEmitFunctionTablePass },
107 { print , createPrintFunctionPass },
108 { printm , createPrintModulePass },
109 { verify , createVerifierPass },
111 { raiseallocs, createRaiseAllocationsPass },
112 { lowerallocs, createLowerAllocationsPassNT },
113 { cleangcc , createCleanupGCCOutputPass },
114 { funcresolve, createFunctionResolvingPass },
116 { internalize, createInternalizePass },
117 { globaldce , createGlobalDCEPass },
118 { swapstructs, createSwapElementsPass },
119 { sortstructs, createSortElementsPass },
120 { poolalloc , createPoolAllocatePass },
124 // Command line option handling code...
126 static cl::opt<string>
127 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
129 static cl::opt<string>
130 OutputFilename("o", cl::desc("Override output filename"),
131 cl::value_desc("filename"));
134 Force("f", cl::desc("Overwrite output files"));
137 PrintEachXForm("p", cl::desc("Print module after each transformation"));
140 Quiet("q", cl::desc("Don't print modifying pass names"));
143 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
145 static cl::list<enum Opts>
146 OptimizationList(cl::desc("Optimizations available:"), cl::values(
147 clEnumVal(dce , "Dead Code Elimination"),
148 clEnumVal(die , "Dead Instruction Elimination"),
149 clEnumVal(constprop , "Simple constant propogation"),
150 clEnumVal(gcse , "Global Common Subexpression Elimination"),
151 clEnumVal(licm , "Loop Invariant Code Motion"),
152 clEnumValN(inlining , "inline", "Function integration"),
153 clEnumVal(constmerge , "Merge identical global constants"),
154 clEnumVal(strip , "Strip symbols"),
155 clEnumVal(mstrip , "Strip module symbols"),
156 clEnumVal(mergereturn, "Unify function exit nodes"),
157 clEnumVal(simplifycfg, "CFG Simplification"),
159 clEnumVal(indvars , "Simplify Induction Variables"),
160 clEnumVal(instcombine, "Combine redundant instructions"),
161 clEnumVal(sccp , "Sparse Conditional Constant Propogation"),
162 clEnumVal(adce , "Aggressive DCE"),
163 clEnumVal(reassociate, "Reassociate expressions"),
164 clEnumVal(mem2reg , "Promote alloca locations to registers"),
165 clEnumVal(pinodes , "Insert Pi nodes after definitions"),
167 clEnumVal(internalize, "Mark all fn's internal except for main"),
168 clEnumVal(globaldce , "Remove unreachable globals"),
169 clEnumVal(swapstructs, "Swap structure types around"),
170 clEnumVal(sortstructs, "Sort structure elements"),
171 clEnumVal(poolalloc , "Pool allocate disjoint datastructures"),
173 clEnumVal(raiseallocs, "Raise allocations from calls to instructions"),
174 clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"),
175 clEnumVal(cleangcc , "Cleanup GCC Output"),
176 clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"),
177 clEnumVal(raise , "Raise to Higher Level"),
178 clEnumVal(trace , "Insert BB and Function trace code"),
179 clEnumVal(tracem , "Insert Function trace code only"),
180 clEnumVal(paths , "Insert path profiling instrumentation"),
181 clEnumVal(emitfuncs , "Insert function pointer table"),
182 clEnumVal(print , "Print working function to stderr"),
183 clEnumVal(printm , "Print working module to stderr"),
184 clEnumVal(verify , "Verify module is well formed"),
185 clEnumVal(lowerrefs , "Decompose multi-dimensional structure/array refs to use one index per instruction"),
190 int main(int argc, char **argv) {
191 cl::ParseCommandLineOptions(argc, argv,
192 " llvm .bc -> .bc modular optimizer\n");
194 // Load the input module...
195 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
197 cerr << "bytecode didn't read correctly.\n";
201 // Figure out what stream we are supposed to write to...
202 std::ostream *Out = &std::cout; // Default to printing to stdout...
203 if (OutputFilename != "") {
204 if (!Force && std::ifstream(OutputFilename.c_str())) {
205 // If force is not specified, make sure not to overwrite a file!
206 cerr << "Error opening '" << OutputFilename << "': File exists!\n"
207 << "Use -f command line argument to force output\n";
210 Out = new std::ofstream(OutputFilename.c_str());
213 cerr << "Error opening " << OutputFilename << "!\n";
217 // Make sure that the Output file gets unlink'd from the disk if we get a
219 RemoveFileOnSignal(OutputFilename);
222 // Create a PassManager to hold and optimize the collection of passes we are
227 // Create a new optimization pass for each one specified on the command line
228 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
229 enum Opts Opt = OptimizationList[i];
230 for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
231 if (Opt == OptTable[j].OptID) {
232 Passes.add(OptTable[j].PassCtor());
237 Passes.add(new PrintModulePass(&std::cerr));
240 // Check that the module is well formed on completion of optimization
241 Passes.add(createVerifierPass());
243 // Write bytecode out to disk or cout as the last step...
244 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
246 // Now that we have all of the passes ready, run them.
247 if (Passes.run(*M.get()) && !Quiet)
248 cerr << "Program modified.\n";