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/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"
40 // Opts enum - All of the transformations we can do...
42 // Basic optimizations
43 dce, die, constprop, gcse, inlining, constmerge, strip, mstrip, mergereturn,
45 // Miscellaneous Transformations
46 raiseallocs, funcresolve, cleangcc, lowerrefs,
48 // Printing and verifying...
49 print, printm, verify,
51 // More powerful optimizations
52 indvars, instcombine, sccp, adce, raise, mem2reg,
57 // Interprocedural optimizations...
58 internalize, globaldce, swapstructs, sortstructs, poolalloc,
61 static Pass *createPrintFunctionPass() {
62 return new PrintFunctionPass("Current Function: \n", &cerr);
65 static Pass *createPrintModulePass() {
66 return new PrintModulePass(&cerr);
69 // OptTable - Correlate enum Opts to Pass constructors...
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 },
85 { indvars , createIndVarSimplifyPass },
86 { instcombine, createInstructionCombiningPass },
87 { sccp , createSCCPPass },
88 { adce , createAgressiveDCEPass },
89 { raise , createRaisePointerReferencesPass },
90 { mem2reg , createPromoteMemoryToRegister },
91 { lowerrefs, createDecomposeMultiDimRefsPass },
93 { trace , createTraceValuesPassForBasicBlocks },
94 { tracem , createTraceValuesPassForFunction },
95 { paths , createProfilePathsPass },
97 { print , createPrintFunctionPass },
98 { printm , createPrintModulePass },
99 { verify , createVerifierPass },
101 { raiseallocs, createRaiseAllocationsPass },
102 { cleangcc , createCleanupGCCOutputPass },
103 { funcresolve, createFunctionResolvingPass },
105 { internalize, createInternalizePass },
106 { globaldce , createGlobalDCEPass },
107 { swapstructs, createSwapElementsPass },
108 { sortstructs, createSortElementsPass },
109 { poolalloc , createPoolAllocatePass },
113 // Command line option handling code...
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"),
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"),
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"),
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"),
159 int main(int argc, char **argv) {
160 cl::ParseCommandLineOptions(argc, argv,
161 " llvm .bc -> .bc modular optimizer\n");
163 // Load the input module...
164 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
166 cerr << "bytecode didn't read correctly.\n";
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";
179 Out = new std::ofstream(OutputFilename.c_str());
182 cerr << "Error opening " << OutputFilename << "!\n";
186 // Make sure that the Output file gets unlink'd from the disk if we get a
188 RemoveFileOnSignal(OutputFilename);
191 // Create a PassManager to hold and optimize the collection of passes we are
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());
206 Passes.add(new PrintModulePass(&std::cerr));
209 // Check that the module is well formed on completion of optimization
210 Passes.add(createVerifierPass());
212 // Write bytecode out to disk or cout as the last step...
213 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
215 // Now that we have all of the passes ready, run them.
216 if (Passes.run(M.get()) && !Quiet)
217 cerr << "Program modified.\n";