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