Add a loop vectorizer.
[oota-llvm.git] / lib / Transforms / IPO / PassManagerBuilder.cpp
1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PassManagerBuilder class, which is used to set up a
11 // "standard" optimization sequence suitable for languages like C and C++.
12 //
13 //===----------------------------------------------------------------------===//
14
15
16 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
17
18 #include "llvm-c/Transforms/PassManagerBuilder.h"
19
20 #include "llvm/PassManager.h"
21 #include "llvm/DefaultPasses.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Target/TargetLibraryInfo.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Vectorize.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/ManagedStatic.h"
32
33 using namespace llvm;
34
35 static cl::opt<bool>
36 RunVectorization("vectorize", cl::desc("Run vectorization passes"));
37
38 static cl::opt<bool>
39 UseGVNAfterVectorization("use-gvn-after-vectorization",
40   cl::init(false), cl::Hidden,
41   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
42
43 static cl::opt<bool> UseNewSROA("use-new-sroa",
44   cl::init(true), cl::Hidden,
45   cl::desc("Enable the new, experimental SROA pass"));
46
47 PassManagerBuilder::PassManagerBuilder() {
48     OptLevel = 2;
49     SizeLevel = 0;
50     LibraryInfo = 0;
51     Inliner = 0;
52     DisableSimplifyLibCalls = false;
53     DisableUnitAtATime = false;
54     DisableUnrollLoops = false;
55     Vectorize = RunVectorization;
56 }
57
58 PassManagerBuilder::~PassManagerBuilder() {
59   delete LibraryInfo;
60   delete Inliner;
61 }
62
63 /// Set of global extensions, automatically added as part of the standard set.
64 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
65    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
66
67 void PassManagerBuilder::addGlobalExtension(
68     PassManagerBuilder::ExtensionPointTy Ty,
69     PassManagerBuilder::ExtensionFn Fn) {
70   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
71 }
72
73 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
74   Extensions.push_back(std::make_pair(Ty, Fn));
75 }
76
77 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
78                                            PassManagerBase &PM) const {
79   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
80     if ((*GlobalExtensions)[i].first == ETy)
81       (*GlobalExtensions)[i].second(*this, PM);
82   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
83     if (Extensions[i].first == ETy)
84       Extensions[i].second(*this, PM);
85 }
86
87 void
88 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
89   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
90   // BasicAliasAnalysis wins if they disagree. This is intended to help
91   // support "obvious" type-punning idioms.
92   PM.add(createTypeBasedAliasAnalysisPass());
93   PM.add(createBasicAliasAnalysisPass());
94 }
95
96 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
97   addExtensionsToPM(EP_EarlyAsPossible, FPM);
98
99   // Add LibraryInfo if we have some.
100   if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
101
102   if (OptLevel == 0) return;
103
104   addInitialAliasAnalysisPasses(FPM);
105
106   FPM.add(createCFGSimplificationPass());
107   if (UseNewSROA)
108     FPM.add(createSROAPass());
109   else
110     FPM.add(createScalarReplAggregatesPass());
111   FPM.add(createEarlyCSEPass());
112   FPM.add(createLowerExpectIntrinsicPass());
113 }
114
115 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
116   // If all optimizations are disabled, just run the always-inline pass.
117   if (OptLevel == 0) {
118     if (Inliner) {
119       MPM.add(Inliner);
120       Inliner = 0;
121     }
122     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
123     return;
124   }
125
126   // Add LibraryInfo if we have some.
127   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
128
129   addInitialAliasAnalysisPasses(MPM);
130
131   if (!DisableUnitAtATime) {
132     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
133
134     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
135
136     MPM.add(createIPSCCPPass());              // IP SCCP
137     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
138
139     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
140     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
141   }
142
143   // Start of CallGraph SCC passes.
144   if (!DisableUnitAtATime)
145     MPM.add(createPruneEHPass());             // Remove dead EH info
146   if (Inliner) {
147     MPM.add(Inliner);
148     Inliner = 0;
149   }
150   if (!DisableUnitAtATime)
151     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
152   if (OptLevel > 2)
153     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
154
155   // Start of function pass.
156   // Break up aggregate allocas, using SSAUpdater.
157   if (UseNewSROA)
158     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
159   else
160     MPM.add(createScalarReplAggregatesPass(-1, false));
161   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
162   if (!DisableSimplifyLibCalls)
163     MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
164   MPM.add(createJumpThreadingPass());         // Thread jumps.
165   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
166   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
167   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
168
169   MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
170   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
171   MPM.add(createReassociatePass());           // Reassociate expressions
172   MPM.add(createLoopRotatePass());            // Rotate Loop
173   MPM.add(createLICMPass());                  // Hoist loop invariants
174   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
175   MPM.add(createInstructionCombiningPass());
176   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
177   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
178   MPM.add(createLoopDeletionPass());          // Delete dead loops
179
180   if (Vectorize) {
181     MPM.add(createLoopVectorizePass());
182     MPM.add(createLICMPass());
183   }
184
185   if (!DisableUnrollLoops)
186     MPM.add(createLoopUnrollPass());          // Unroll small loops
187   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
188
189   if (OptLevel > 1)
190     MPM.add(createGVNPass());                 // Remove redundancies
191   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
192   MPM.add(createSCCPPass());                  // Constant prop with SCCP
193
194   // Run instcombine after redundancy elimination to exploit opportunities
195   // opened up by them.
196   MPM.add(createInstructionCombiningPass());
197   MPM.add(createJumpThreadingPass());         // Thread jumps
198   MPM.add(createCorrelatedValuePropagationPass());
199   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
200
201   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
202
203   if (Vectorize) {
204     MPM.add(createBBVectorizePass());
205     MPM.add(createInstructionCombiningPass());
206     if (OptLevel > 1 && UseGVNAfterVectorization)
207       MPM.add(createGVNPass());                   // Remove redundancies
208     else
209       MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
210   }
211
212   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
213   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
214   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
215
216   if (!DisableUnitAtATime) {
217     // FIXME: We shouldn't bother with this anymore.
218     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
219
220     // GlobalOpt already deletes dead functions and globals, at -O2 try a
221     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
222     if (OptLevel > 1) {
223       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
224       MPM.add(createConstantMergePass());     // Merge dup global constants
225     }
226   }
227   addExtensionsToPM(EP_OptimizerLast, MPM);
228 }
229
230 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
231                                                 bool Internalize,
232                                                 bool RunInliner,
233                                                 bool DisableGVNLoadPRE) {
234   // Provide AliasAnalysis services for optimizations.
235   addInitialAliasAnalysisPasses(PM);
236
237   // Now that composite has been compiled, scan through the module, looking
238   // for a main function.  If main is defined, mark all other functions
239   // internal.
240   if (Internalize)
241     PM.add(createInternalizePass(true));
242
243   // Propagate constants at call sites into the functions they call.  This
244   // opens opportunities for globalopt (and inlining) by substituting function
245   // pointers passed as arguments to direct uses of functions.
246   PM.add(createIPSCCPPass());
247
248   // Now that we internalized some globals, see if we can hack on them!
249   PM.add(createGlobalOptimizerPass());
250
251   // Linking modules together can lead to duplicated global constants, only
252   // keep one copy of each constant.
253   PM.add(createConstantMergePass());
254
255   // Remove unused arguments from functions.
256   PM.add(createDeadArgEliminationPass());
257
258   // Reduce the code after globalopt and ipsccp.  Both can open up significant
259   // simplification opportunities, and both can propagate functions through
260   // function pointers.  When this happens, we often have to resolve varargs
261   // calls, etc, so let instcombine do this.
262   PM.add(createInstructionCombiningPass());
263
264   // Inline small functions
265   if (RunInliner)
266     PM.add(createFunctionInliningPass());
267
268   PM.add(createPruneEHPass());   // Remove dead EH info.
269
270   // Optimize globals again if we ran the inliner.
271   if (RunInliner)
272     PM.add(createGlobalOptimizerPass());
273   PM.add(createGlobalDCEPass()); // Remove dead functions.
274
275   // If we didn't decide to inline a function, check to see if we can
276   // transform it to pass arguments by value instead of by reference.
277   PM.add(createArgumentPromotionPass());
278
279   // The IPO passes may leave cruft around.  Clean up after them.
280   PM.add(createInstructionCombiningPass());
281   PM.add(createJumpThreadingPass());
282   // Break up allocas
283   if (UseNewSROA)
284     PM.add(createSROAPass());
285   else
286     PM.add(createScalarReplAggregatesPass());
287
288   // Run a few AA driven optimizations here and now, to cleanup the code.
289   PM.add(createFunctionAttrsPass()); // Add nocapture.
290   PM.add(createGlobalsModRefPass()); // IP alias analysis.
291
292   PM.add(createLICMPass());                 // Hoist loop invariants.
293   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
294   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
295   // Nuke dead stores.
296   PM.add(createDeadStoreEliminationPass());
297
298   // Cleanup and simplify the code after the scalar optimizations.
299   PM.add(createInstructionCombiningPass());
300
301   PM.add(createJumpThreadingPass());
302
303   // Delete basic blocks, which optimization passes may have killed.
304   PM.add(createCFGSimplificationPass());
305
306   // Now that we have optimized the program, discard unreachable functions.
307   PM.add(createGlobalDCEPass());
308 }
309
310 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void) {
311   PassManagerBuilder *PMB = new PassManagerBuilder();
312   return wrap(PMB);
313 }
314
315 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
316   PassManagerBuilder *Builder = unwrap(PMB);
317   delete Builder;
318 }
319
320 void
321 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
322                                   unsigned OptLevel) {
323   PassManagerBuilder *Builder = unwrap(PMB);
324   Builder->OptLevel = OptLevel;
325 }
326
327 void
328 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
329                                    unsigned SizeLevel) {
330   PassManagerBuilder *Builder = unwrap(PMB);
331   Builder->SizeLevel = SizeLevel;
332 }
333
334 void
335 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
336                                             LLVMBool Value) {
337   PassManagerBuilder *Builder = unwrap(PMB);
338   Builder->DisableUnitAtATime = Value;
339 }
340
341 void
342 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
343                                             LLVMBool Value) {
344   PassManagerBuilder *Builder = unwrap(PMB);
345   Builder->DisableUnrollLoops = Value;
346 }
347
348 void
349 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
350                                                  LLVMBool Value) {
351   PassManagerBuilder *Builder = unwrap(PMB);
352   Builder->DisableSimplifyLibCalls = Value;
353 }
354
355 void
356 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
357                                               unsigned Threshold) {
358   PassManagerBuilder *Builder = unwrap(PMB);
359   Builder->Inliner = createFunctionInliningPass(Threshold);
360 }
361
362 void
363 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
364                                                   LLVMPassManagerRef PM) {
365   PassManagerBuilder *Builder = unwrap(PMB);
366   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
367   Builder->populateFunctionPassManager(*FPM);
368 }
369
370 void
371 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
372                                                 LLVMPassManagerRef PM) {
373   PassManagerBuilder *Builder = unwrap(PMB);
374   PassManagerBase *MPM = unwrap(PM);
375   Builder->populateModulePassManager(*MPM);
376 }
377
378 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
379                                                   LLVMPassManagerRef PM,
380                                                   bool Internalize,
381                                                   bool RunInliner) {
382   PassManagerBuilder *Builder = unwrap(PMB);
383   PassManagerBase *LPM = unwrap(PM);
384   Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
385 }