revert accidental change
[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
123     // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
124     // pass manager, but we don't want to add extensions into that pass manager.
125     // To prevent this we must insert a no-op module pass to reset the pass
126     // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
127     if (!GlobalExtensions->empty() || !Extensions.empty())
128       MPM.add(createBarrierNoopPass());
129
130     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
131     return;
132   }
133
134   // Add LibraryInfo if we have some.
135   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
136
137   addInitialAliasAnalysisPasses(MPM);
138
139   if (!DisableUnitAtATime) {
140     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
141
142     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
143
144     MPM.add(createIPSCCPPass());              // IP SCCP
145     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
146
147     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
148     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
149   }
150
151   // Start of CallGraph SCC passes.
152   if (!DisableUnitAtATime)
153     MPM.add(createPruneEHPass());             // Remove dead EH info
154   if (Inliner) {
155     MPM.add(Inliner);
156     Inliner = 0;
157   }
158   if (!DisableUnitAtATime)
159     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
160   if (OptLevel > 2)
161     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
162
163   // Start of function pass.
164   // Break up aggregate allocas, using SSAUpdater.
165   if (UseNewSROA)
166     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
167   else
168     MPM.add(createScalarReplAggregatesPass(-1, false));
169   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
170   if (!DisableSimplifyLibCalls)
171     MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
172   MPM.add(createJumpThreadingPass());         // Thread jumps.
173   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
174   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
175   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
176
177   MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
178   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
179   MPM.add(createReassociatePass());           // Reassociate expressions
180   MPM.add(createLoopRotatePass());            // Rotate Loop
181   MPM.add(createLICMPass());                  // Hoist loop invariants
182   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
183   MPM.add(createInstructionCombiningPass());
184   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
185   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
186   MPM.add(createLoopDeletionPass());          // Delete dead loops
187
188   if (Vectorize) {
189     MPM.add(createLoopVectorizePass());
190     MPM.add(createLICMPass());
191   }
192
193   if (!DisableUnrollLoops)
194     MPM.add(createLoopUnrollPass());          // Unroll small loops
195   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
196
197   if (OptLevel > 1)
198     MPM.add(createGVNPass());                 // Remove redundancies
199   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
200   MPM.add(createSCCPPass());                  // Constant prop with SCCP
201
202   // Run instcombine after redundancy elimination to exploit opportunities
203   // opened up by them.
204   MPM.add(createInstructionCombiningPass());
205   MPM.add(createJumpThreadingPass());         // Thread jumps
206   MPM.add(createCorrelatedValuePropagationPass());
207   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
208
209   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
210
211   if (Vectorize) {
212     MPM.add(createBBVectorizePass());
213     MPM.add(createInstructionCombiningPass());
214     if (OptLevel > 1 && UseGVNAfterVectorization)
215       MPM.add(createGVNPass());                   // Remove redundancies
216     else
217       MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
218   }
219
220   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
221   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
222   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
223
224   if (!DisableUnitAtATime) {
225     // FIXME: We shouldn't bother with this anymore.
226     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
227
228     // GlobalOpt already deletes dead functions and globals, at -O2 try a
229     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
230     if (OptLevel > 1) {
231       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
232       MPM.add(createConstantMergePass());     // Merge dup global constants
233     }
234   }
235   addExtensionsToPM(EP_OptimizerLast, MPM);
236 }
237
238 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
239                                                 bool Internalize,
240                                                 bool RunInliner,
241                                                 bool DisableGVNLoadPRE) {
242   // Provide AliasAnalysis services for optimizations.
243   addInitialAliasAnalysisPasses(PM);
244
245   // Now that composite has been compiled, scan through the module, looking
246   // for a main function.  If main is defined, mark all other functions
247   // internal.
248   if (Internalize)
249     PM.add(createInternalizePass(true));
250
251   // Propagate constants at call sites into the functions they call.  This
252   // opens opportunities for globalopt (and inlining) by substituting function
253   // pointers passed as arguments to direct uses of functions.
254   PM.add(createIPSCCPPass());
255
256   // Now that we internalized some globals, see if we can hack on them!
257   PM.add(createGlobalOptimizerPass());
258
259   // Linking modules together can lead to duplicated global constants, only
260   // keep one copy of each constant.
261   PM.add(createConstantMergePass());
262
263   // Remove unused arguments from functions.
264   PM.add(createDeadArgEliminationPass());
265
266   // Reduce the code after globalopt and ipsccp.  Both can open up significant
267   // simplification opportunities, and both can propagate functions through
268   // function pointers.  When this happens, we often have to resolve varargs
269   // calls, etc, so let instcombine do this.
270   PM.add(createInstructionCombiningPass());
271
272   // Inline small functions
273   if (RunInliner)
274     PM.add(createFunctionInliningPass());
275
276   PM.add(createPruneEHPass());   // Remove dead EH info.
277
278   // Optimize globals again if we ran the inliner.
279   if (RunInliner)
280     PM.add(createGlobalOptimizerPass());
281   PM.add(createGlobalDCEPass()); // Remove dead functions.
282
283   // If we didn't decide to inline a function, check to see if we can
284   // transform it to pass arguments by value instead of by reference.
285   PM.add(createArgumentPromotionPass());
286
287   // The IPO passes may leave cruft around.  Clean up after them.
288   PM.add(createInstructionCombiningPass());
289   PM.add(createJumpThreadingPass());
290   // Break up allocas
291   if (UseNewSROA)
292     PM.add(createSROAPass());
293   else
294     PM.add(createScalarReplAggregatesPass());
295
296   // Run a few AA driven optimizations here and now, to cleanup the code.
297   PM.add(createFunctionAttrsPass()); // Add nocapture.
298   PM.add(createGlobalsModRefPass()); // IP alias analysis.
299
300   PM.add(createLICMPass());                 // Hoist loop invariants.
301   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
302   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
303   // Nuke dead stores.
304   PM.add(createDeadStoreEliminationPass());
305
306   // Cleanup and simplify the code after the scalar optimizations.
307   PM.add(createInstructionCombiningPass());
308
309   PM.add(createJumpThreadingPass());
310
311   // Delete basic blocks, which optimization passes may have killed.
312   PM.add(createCFGSimplificationPass());
313
314   // Now that we have optimized the program, discard unreachable functions.
315   PM.add(createGlobalDCEPass());
316 }
317
318 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void) {
319   PassManagerBuilder *PMB = new PassManagerBuilder();
320   return wrap(PMB);
321 }
322
323 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
324   PassManagerBuilder *Builder = unwrap(PMB);
325   delete Builder;
326 }
327
328 void
329 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
330                                   unsigned OptLevel) {
331   PassManagerBuilder *Builder = unwrap(PMB);
332   Builder->OptLevel = OptLevel;
333 }
334
335 void
336 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
337                                    unsigned SizeLevel) {
338   PassManagerBuilder *Builder = unwrap(PMB);
339   Builder->SizeLevel = SizeLevel;
340 }
341
342 void
343 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
344                                             LLVMBool Value) {
345   PassManagerBuilder *Builder = unwrap(PMB);
346   Builder->DisableUnitAtATime = Value;
347 }
348
349 void
350 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
351                                             LLVMBool Value) {
352   PassManagerBuilder *Builder = unwrap(PMB);
353   Builder->DisableUnrollLoops = Value;
354 }
355
356 void
357 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
358                                                  LLVMBool Value) {
359   PassManagerBuilder *Builder = unwrap(PMB);
360   Builder->DisableSimplifyLibCalls = Value;
361 }
362
363 void
364 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
365                                               unsigned Threshold) {
366   PassManagerBuilder *Builder = unwrap(PMB);
367   Builder->Inliner = createFunctionInliningPass(Threshold);
368 }
369
370 void
371 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
372                                                   LLVMPassManagerRef PM) {
373   PassManagerBuilder *Builder = unwrap(PMB);
374   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
375   Builder->populateFunctionPassManager(*FPM);
376 }
377
378 void
379 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
380                                                 LLVMPassManagerRef PM) {
381   PassManagerBuilder *Builder = unwrap(PMB);
382   PassManagerBase *MPM = unwrap(PM);
383   Builder->populateModulePassManager(*MPM);
384 }
385
386 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
387                                                   LLVMPassManagerRef PM,
388                                                   bool Internalize,
389                                                   bool RunInliner) {
390   PassManagerBuilder *Builder = unwrap(PMB);
391   PassManagerBase *LPM = unwrap(PM);
392   Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
393 }