Move DisableGVNLoadPRE from populateLTOPassManager to PassManagerBuilder.
[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/IR/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", cl::Hidden,
33                      cl::desc("Run the Loop vectorization passes"));
34
35 static cl::opt<bool>
36 RunSLPVectorization("vectorize-slp", cl::Hidden,
37                     cl::desc("Run the SLP vectorization passes"));
38
39 static cl::opt<bool>
40 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
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 static cl::opt<bool>
53 RunLoopRerolling("reroll-loops", cl::Hidden,
54                  cl::desc("Run the loop rerolling pass"));
55
56 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
57                                     cl::Hidden,
58                                     cl::desc("Run the load combining pass"));
59
60 static cl::opt<bool>
61 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
62   cl::init(false), cl::Hidden,
63   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
64            "vectorizer instead of before"));
65
66
67 PassManagerBuilder::PassManagerBuilder() {
68     OptLevel = 2;
69     SizeLevel = 0;
70     LibraryInfo = nullptr;
71     Inliner = nullptr;
72     DisableTailCalls = false;
73     DisableUnitAtATime = false;
74     DisableUnrollLoops = false;
75     BBVectorize = RunBBVectorization;
76     SLPVectorize = RunSLPVectorization;
77     LoopVectorize = RunLoopVectorization;
78     RerollLoops = RunLoopRerolling;
79     LoadCombine = RunLoadCombine;
80     DisableGVNLoadPRE = false;
81 }
82
83 PassManagerBuilder::~PassManagerBuilder() {
84   delete LibraryInfo;
85   delete Inliner;
86 }
87
88 /// Set of global extensions, automatically added as part of the standard set.
89 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
90    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
91
92 void PassManagerBuilder::addGlobalExtension(
93     PassManagerBuilder::ExtensionPointTy Ty,
94     PassManagerBuilder::ExtensionFn Fn) {
95   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
96 }
97
98 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
99   Extensions.push_back(std::make_pair(Ty, Fn));
100 }
101
102 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
103                                            PassManagerBase &PM) const {
104   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
105     if ((*GlobalExtensions)[i].first == ETy)
106       (*GlobalExtensions)[i].second(*this, PM);
107   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
108     if (Extensions[i].first == ETy)
109       Extensions[i].second(*this, PM);
110 }
111
112 void
113 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
114   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
115   // BasicAliasAnalysis wins if they disagree. This is intended to help
116   // support "obvious" type-punning idioms.
117   PM.add(createTypeBasedAliasAnalysisPass());
118   PM.add(createScopedNoAliasAAPass());
119   PM.add(createBasicAliasAnalysisPass());
120 }
121
122 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
123   addExtensionsToPM(EP_EarlyAsPossible, FPM);
124
125   // Add LibraryInfo if we have some.
126   if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
127
128   if (OptLevel == 0) return;
129
130   addInitialAliasAnalysisPasses(FPM);
131
132   FPM.add(createCFGSimplificationPass());
133   if (UseNewSROA)
134     FPM.add(createSROAPass());
135   else
136     FPM.add(createScalarReplAggregatesPass());
137   FPM.add(createEarlyCSEPass());
138   FPM.add(createLowerExpectIntrinsicPass());
139 }
140
141 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
142   // If all optimizations are disabled, just run the always-inline pass.
143   if (OptLevel == 0) {
144     if (Inliner) {
145       MPM.add(Inliner);
146       Inliner = nullptr;
147     }
148
149     // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
150     // pass manager, but we don't want to add extensions into that pass manager.
151     // To prevent this we must insert a no-op module pass to reset the pass
152     // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
153     if (!GlobalExtensions->empty() || !Extensions.empty())
154       MPM.add(createBarrierNoopPass());
155
156     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
157     return;
158   }
159
160   // Add LibraryInfo if we have some.
161   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
162
163   addInitialAliasAnalysisPasses(MPM);
164
165   if (!DisableUnitAtATime) {
166     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
167
168     MPM.add(createIPSCCPPass());              // IP SCCP
169     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
170
171     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
172
173     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
174     addExtensionsToPM(EP_Peephole, MPM);
175     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
176   }
177
178   // Start of CallGraph SCC passes.
179   if (!DisableUnitAtATime)
180     MPM.add(createPruneEHPass());             // Remove dead EH info
181   if (Inliner) {
182     MPM.add(Inliner);
183     Inliner = nullptr;
184   }
185   if (!DisableUnitAtATime)
186     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
187   if (OptLevel > 2)
188     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
189
190   // Start of function pass.
191   // Break up aggregate allocas, using SSAUpdater.
192   if (UseNewSROA)
193     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
194   else
195     MPM.add(createScalarReplAggregatesPass(-1, false));
196   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
197   MPM.add(createJumpThreadingPass());         // Thread jumps.
198   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
199   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
200   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
201   addExtensionsToPM(EP_Peephole, MPM);
202
203   if (!DisableTailCalls)
204     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
205   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
206   MPM.add(createReassociatePass());           // Reassociate expressions
207   MPM.add(createLoopRotatePass());            // Rotate Loop
208   MPM.add(createLICMPass());                  // Hoist loop invariants
209   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
210   MPM.add(createInstructionCombiningPass());
211   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
212   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
213   MPM.add(createLoopDeletionPass());          // Delete dead loops
214
215   if (!DisableUnrollLoops)
216     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
217   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
218
219   if (OptLevel > 1) {
220     MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
221     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
222   }
223   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
224   MPM.add(createSCCPPass());                  // Constant prop with SCCP
225
226   // Run instcombine after redundancy elimination to exploit opportunities
227   // opened up by them.
228   MPM.add(createInstructionCombiningPass());
229   addExtensionsToPM(EP_Peephole, MPM);
230   MPM.add(createJumpThreadingPass());         // Thread jumps
231   MPM.add(createCorrelatedValuePropagationPass());
232   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
233
234   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
235
236   if (RerollLoops)
237     MPM.add(createLoopRerollPass());
238   if (!RunSLPAfterLoopVectorization) {
239     if (SLPVectorize)
240       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
241
242     if (BBVectorize) {
243       MPM.add(createBBVectorizePass());
244       MPM.add(createInstructionCombiningPass());
245       addExtensionsToPM(EP_Peephole, MPM);
246       if (OptLevel > 1 && UseGVNAfterVectorization)
247         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
248       else
249         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
250
251       // BBVectorize may have significantly shortened a loop body; unroll again.
252       if (!DisableUnrollLoops)
253         MPM.add(createLoopUnrollPass());
254     }
255   }
256
257   if (LoadCombine)
258     MPM.add(createLoadCombinePass());
259
260   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
261   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
262   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
263   addExtensionsToPM(EP_Peephole, MPM);
264
265   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
266   // pass manager that we are specifically trying to avoid. To prevent this
267   // we must insert a no-op module pass to reset the pass manager.
268   MPM.add(createBarrierNoopPass());
269   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
270   // FIXME: Because of #pragma vectorize enable, the passes below are always
271   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
272   // on -O1 and no #pragma is found). Would be good to have these two passes
273   // as function calls, so that we can only pass them when the vectorizer
274   // changed the code.
275   MPM.add(createInstructionCombiningPass());
276
277   if (RunSLPAfterLoopVectorization) {
278     if (SLPVectorize)
279       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
280
281     if (BBVectorize) {
282       MPM.add(createBBVectorizePass());
283       MPM.add(createInstructionCombiningPass());
284       addExtensionsToPM(EP_Peephole, MPM);
285       if (OptLevel > 1 && UseGVNAfterVectorization)
286         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
287       else
288         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
289
290       // BBVectorize may have significantly shortened a loop body; unroll again.
291       if (!DisableUnrollLoops)
292         MPM.add(createLoopUnrollPass());
293     }
294   }
295
296   addExtensionsToPM(EP_Peephole, MPM);
297   MPM.add(createCFGSimplificationPass());
298
299   if (!DisableUnrollLoops)
300     MPM.add(createLoopUnrollPass());    // Unroll small loops
301
302   if (!DisableUnitAtATime) {
303     // FIXME: We shouldn't bother with this anymore.
304     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
305
306     // GlobalOpt already deletes dead functions and globals, at -O2 try a
307     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
308     if (OptLevel > 1) {
309       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
310       MPM.add(createConstantMergePass());     // Merge dup global constants
311     }
312   }
313   addExtensionsToPM(EP_OptimizerLast, MPM);
314 }
315
316 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
317                                                 bool RunInliner) {
318   // Provide AliasAnalysis services for optimizations.
319   addInitialAliasAnalysisPasses(PM);
320
321   // Propagate constants at call sites into the functions they call.  This
322   // opens opportunities for globalopt (and inlining) by substituting function
323   // pointers passed as arguments to direct uses of functions.
324   PM.add(createIPSCCPPass());
325
326   // Now that we internalized some globals, see if we can hack on them!
327   PM.add(createGlobalOptimizerPass());
328
329   // Linking modules together can lead to duplicated global constants, only
330   // keep one copy of each constant.
331   PM.add(createConstantMergePass());
332
333   // Remove unused arguments from functions.
334   PM.add(createDeadArgEliminationPass());
335
336   // Reduce the code after globalopt and ipsccp.  Both can open up significant
337   // simplification opportunities, and both can propagate functions through
338   // function pointers.  When this happens, we often have to resolve varargs
339   // calls, etc, so let instcombine do this.
340   PM.add(createInstructionCombiningPass());
341   addExtensionsToPM(EP_Peephole, PM);
342
343   // Inline small functions
344   if (RunInliner)
345     PM.add(createFunctionInliningPass());
346
347   PM.add(createPruneEHPass());   // Remove dead EH info.
348
349   // Optimize globals again if we ran the inliner.
350   if (RunInliner)
351     PM.add(createGlobalOptimizerPass());
352   PM.add(createGlobalDCEPass()); // Remove dead functions.
353
354   // If we didn't decide to inline a function, check to see if we can
355   // transform it to pass arguments by value instead of by reference.
356   PM.add(createArgumentPromotionPass());
357
358   // The IPO passes may leave cruft around.  Clean up after them.
359   PM.add(createInstructionCombiningPass());
360   addExtensionsToPM(EP_Peephole, PM);
361   PM.add(createJumpThreadingPass());
362
363   // Break up allocas
364   if (UseNewSROA)
365     PM.add(createSROAPass());
366   else
367     PM.add(createScalarReplAggregatesPass());
368
369   // Run a few AA driven optimizations here and now, to cleanup the code.
370   PM.add(createFunctionAttrsPass()); // Add nocapture.
371   PM.add(createGlobalsModRefPass()); // IP alias analysis.
372
373   PM.add(createLICMPass());                 // Hoist loop invariants.
374   PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
375   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
376   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
377
378   // Nuke dead stores.
379   PM.add(createDeadStoreEliminationPass());
380
381   // More loops are countable; try to optimize them.
382   PM.add(createIndVarSimplifyPass());
383   PM.add(createLoopDeletionPass());
384   PM.add(createLoopVectorizePass(true, true));
385
386   // More scalar chains could be vectorized due to more alias information
387   PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
388
389   if (LoadCombine)
390     PM.add(createLoadCombinePass());
391
392   // Cleanup and simplify the code after the scalar optimizations.
393   PM.add(createInstructionCombiningPass());
394   addExtensionsToPM(EP_Peephole, PM);
395
396   PM.add(createJumpThreadingPass());
397
398   // Delete basic blocks, which optimization passes may have killed.
399   PM.add(createCFGSimplificationPass());
400
401   // Now that we have optimized the program, discard unreachable functions.
402   PM.add(createGlobalDCEPass());
403 }
404
405 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
406     return reinterpret_cast<PassManagerBuilder*>(P);
407 }
408
409 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
410   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
411 }
412
413 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
414   PassManagerBuilder *PMB = new PassManagerBuilder();
415   return wrap(PMB);
416 }
417
418 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
419   PassManagerBuilder *Builder = unwrap(PMB);
420   delete Builder;
421 }
422
423 void
424 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
425                                   unsigned OptLevel) {
426   PassManagerBuilder *Builder = unwrap(PMB);
427   Builder->OptLevel = OptLevel;
428 }
429
430 void
431 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
432                                    unsigned SizeLevel) {
433   PassManagerBuilder *Builder = unwrap(PMB);
434   Builder->SizeLevel = SizeLevel;
435 }
436
437 void
438 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
439                                             LLVMBool Value) {
440   PassManagerBuilder *Builder = unwrap(PMB);
441   Builder->DisableUnitAtATime = Value;
442 }
443
444 void
445 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
446                                             LLVMBool Value) {
447   PassManagerBuilder *Builder = unwrap(PMB);
448   Builder->DisableUnrollLoops = Value;
449 }
450
451 void
452 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
453                                                  LLVMBool Value) {
454   // NOTE: The simplify-libcalls pass has been removed.
455 }
456
457 void
458 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
459                                               unsigned Threshold) {
460   PassManagerBuilder *Builder = unwrap(PMB);
461   Builder->Inliner = createFunctionInliningPass(Threshold);
462 }
463
464 void
465 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
466                                                   LLVMPassManagerRef PM) {
467   PassManagerBuilder *Builder = unwrap(PMB);
468   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
469   Builder->populateFunctionPassManager(*FPM);
470 }
471
472 void
473 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
474                                                 LLVMPassManagerRef PM) {
475   PassManagerBuilder *Builder = unwrap(PMB);
476   PassManagerBase *MPM = unwrap(PM);
477   Builder->populateModulePassManager(*MPM);
478 }
479
480 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
481                                                   LLVMPassManagerRef PM,
482                                                   LLVMBool Internalize,
483                                                   LLVMBool RunInliner) {
484   PassManagerBuilder *Builder = unwrap(PMB);
485   PassManagerBase *LPM = unwrap(PM);
486   Builder->populateLTOPassManager(*LPM, RunInliner != 0);
487 }