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/Target/TargetData.h"
29 #include "Support/CommandLine.h"
30 #include "Support/Signals.h"
34 // FIXME: This should be parameterizable eventually for different target
36 static TargetData TD("opt target");
38 // Opts enum - All of the transformations we can do...
40 // Basic optimizations
41 dce, die, constprop, gcse, licm, inlining, constmerge,
42 strip, mstrip, mergereturn,
44 // Miscellaneous Transformations
45 raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs,
47 // Printing and verifying...
48 print, printm, verify,
50 // More powerful optimizations
51 indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes,
56 // Interprocedural optimizations...
57 internalize, globaldce, swapstructs, sortstructs, poolalloc,
60 static Pass *createPrintFunctionPass() {
61 return new PrintFunctionPass("Current Function: \n", &cerr);
64 static Pass *createPrintModulePass() {
65 return new PrintModulePass(&cerr);
68 static Pass *createLowerAllocationsPassNT() {
69 return createLowerAllocationsPass(TD);
72 // OptTable - Correlate enum Opts to Pass constructors...
78 { dce , createDeadCodeEliminationPass },
79 { die , createDeadInstEliminationPass },
80 { constprop , createConstantPropogationPass },
81 { gcse , createGCSEPass },
82 { licm , createLICMPass },
83 { inlining , createFunctionInliningPass },
84 { constmerge , createConstantMergePass },
85 { strip , createSymbolStrippingPass },
86 { mstrip , createFullSymbolStrippingPass },
87 { mergereturn, createUnifyFunctionExitNodesPass },
89 { indvars , createIndVarSimplifyPass },
90 { instcombine, createInstructionCombiningPass },
91 { sccp , createSCCPPass },
92 { adce , createAggressiveDCEPass },
93 { raise , createRaisePointerReferencesPass },
94 { reassociate, createReassociatePass },
95 { mem2reg , createPromoteMemoryToRegister },
96 { pinodes , createPiNodeInsertionPass },
97 { lowerrefs , createDecomposeMultiDimRefsPass },
99 { trace , createTraceValuesPassForBasicBlocks },
100 { tracem , createTraceValuesPassForFunction },
101 { paths , createProfilePathsPass },
103 { print , createPrintFunctionPass },
104 { printm , createPrintModulePass },
105 { verify , createVerifierPass },
107 { raiseallocs, createRaiseAllocationsPass },
108 { lowerallocs, createLowerAllocationsPassNT },
109 { cleangcc , createCleanupGCCOutputPass },
110 { funcresolve, createFunctionResolvingPass },
112 { internalize, createInternalizePass },
113 { globaldce , createGlobalDCEPass },
114 { swapstructs, createSwapElementsPass },
115 { sortstructs, createSortElementsPass },
116 { poolalloc , createPoolAllocatePass },
120 // Command line option handling code...
122 cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-");
123 cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
124 cl::Flag Force ("f", "Overwrite output files", cl::NoFlags, false);
125 cl::Flag PrintEachXForm("p", "Print module after each transformation");
126 cl::Flag Quiet ("q", "Don't print modifying pass names", 0, false);
127 cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet);
128 cl::EnumList<enum Opts> OptimizationList(cl::NoFlags,
129 clEnumVal(dce , "Dead Code Elimination"),
130 clEnumVal(die , "Dead Instruction Elimination"),
131 clEnumVal(constprop , "Simple constant propogation"),
132 clEnumVal(gcse , "Global Common Subexpression Elimination"),
133 clEnumVal(licm , "Loop Invariant Code Motion"),
134 clEnumValN(inlining , "inline", "Function integration"),
135 clEnumVal(constmerge , "Merge identical global constants"),
136 clEnumVal(strip , "Strip symbols"),
137 clEnumVal(mstrip , "Strip module symbols"),
138 clEnumVal(mergereturn, "Unify function exit nodes"),
140 clEnumVal(indvars , "Simplify Induction Variables"),
141 clEnumVal(instcombine, "Combine redundant instructions"),
142 clEnumVal(sccp , "Sparse Conditional Constant Propogation"),
143 clEnumVal(adce , "Aggressive DCE"),
144 clEnumVal(reassociate, "Reassociate expressions"),
145 clEnumVal(mem2reg , "Promote alloca locations to registers"),
146 clEnumVal(pinodes , "Insert Pi nodes after definitions"),
148 clEnumVal(internalize, "Mark all fn's internal except for main"),
149 clEnumVal(globaldce , "Remove unreachable globals"),
150 clEnumVal(swapstructs, "Swap structure types around"),
151 clEnumVal(sortstructs, "Sort structure elements"),
152 clEnumVal(poolalloc , "Pool allocate disjoint datastructures"),
154 clEnumVal(raiseallocs, "Raise allocations from calls to instructions"),
155 clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"),
156 clEnumVal(cleangcc , "Cleanup GCC Output"),
157 clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"),
158 clEnumVal(raise , "Raise to Higher Level"),
159 clEnumVal(trace , "Insert BB and Function trace code"),
160 clEnumVal(tracem , "Insert Function trace code only"),
161 clEnumVal(paths , "Insert path profiling instrumentation"),
162 clEnumVal(print , "Print working function to stderr"),
163 clEnumVal(printm , "Print working module to stderr"),
164 clEnumVal(verify , "Verify module is well formed"),
165 clEnumVal(lowerrefs , "Decompose multi-dimensional structure/array refs to use one index per instruction"),
170 int main(int argc, char **argv) {
171 cl::ParseCommandLineOptions(argc, argv,
172 " llvm .bc -> .bc modular optimizer\n");
174 // Load the input module...
175 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
177 cerr << "bytecode didn't read correctly.\n";
181 // Figure out what stream we are supposed to write to...
182 std::ostream *Out = &std::cout; // Default to printing to stdout...
183 if (OutputFilename != "") {
184 if (!Force && std::ifstream(OutputFilename.c_str())) {
185 // If force is not specified, make sure not to overwrite a file!
186 cerr << "Error opening '" << OutputFilename << "': File exists!\n"
187 << "Use -f command line argument to force output\n";
190 Out = new std::ofstream(OutputFilename.c_str());
193 cerr << "Error opening " << OutputFilename << "!\n";
197 // Make sure that the Output file gets unlink'd from the disk if we get a
199 RemoveFileOnSignal(OutputFilename);
202 // Create a PassManager to hold and optimize the collection of passes we are
207 // Create a new optimization pass for each one specified on the command line
208 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
209 enum Opts Opt = OptimizationList[i];
210 for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
211 if (Opt == OptTable[j].OptID) {
212 Passes.add(OptTable[j].PassCtor());
217 Passes.add(new PrintModulePass(&std::cerr));
220 // Check that the module is well formed on completion of optimization
221 Passes.add(createVerifierPass());
223 // Write bytecode out to disk or cout as the last step...
224 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
226 // Now that we have all of the passes ready, run them.
227 if (Passes.run(M.get()) && !Quiet)
228 cerr << "Program modified.\n";