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