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