Add an AlignmentFromAssumptions Pass
[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   // After vectorization and unrolling, assume intrinsics may tell us more
314   // about pointer alignments.
315   MPM.add(createAlignmentFromAssumptionsPass());
316
317   if (!DisableUnitAtATime) {
318     // FIXME: We shouldn't bother with this anymore.
319     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
320
321     // GlobalOpt already deletes dead functions and globals, at -O2 try a
322     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
323     if (OptLevel > 1) {
324       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
325       MPM.add(createConstantMergePass());     // Merge dup global constants
326     }
327   }
328   addExtensionsToPM(EP_OptimizerLast, MPM);
329 }
330
331 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
332   // Provide AliasAnalysis services for optimizations.
333   addInitialAliasAnalysisPasses(PM);
334
335   // Propagate constants at call sites into the functions they call.  This
336   // opens opportunities for globalopt (and inlining) by substituting function
337   // pointers passed as arguments to direct uses of functions.
338   PM.add(createIPSCCPPass());
339
340   // Now that we internalized some globals, see if we can hack on them!
341   PM.add(createGlobalOptimizerPass());
342
343   // Linking modules together can lead to duplicated global constants, only
344   // keep one copy of each constant.
345   PM.add(createConstantMergePass());
346
347   // Remove unused arguments from functions.
348   PM.add(createDeadArgEliminationPass());
349
350   // Reduce the code after globalopt and ipsccp.  Both can open up significant
351   // simplification opportunities, and both can propagate functions through
352   // function pointers.  When this happens, we often have to resolve varargs
353   // calls, etc, so let instcombine do this.
354   PM.add(createInstructionCombiningPass());
355   addExtensionsToPM(EP_Peephole, PM);
356
357   // Inline small functions
358   bool RunInliner = Inliner;
359   if (RunInliner) {
360     PM.add(Inliner);
361     Inliner = nullptr;
362   }
363
364   PM.add(createPruneEHPass());   // Remove dead EH info.
365
366   // Optimize globals again if we ran the inliner.
367   if (RunInliner)
368     PM.add(createGlobalOptimizerPass());
369   PM.add(createGlobalDCEPass()); // Remove dead functions.
370
371   // If we didn't decide to inline a function, check to see if we can
372   // transform it to pass arguments by value instead of by reference.
373   PM.add(createArgumentPromotionPass());
374
375   // The IPO passes may leave cruft around.  Clean up after them.
376   PM.add(createInstructionCombiningPass());
377   addExtensionsToPM(EP_Peephole, PM);
378   PM.add(createJumpThreadingPass());
379
380   // Break up allocas
381   if (UseNewSROA)
382     PM.add(createSROAPass());
383   else
384     PM.add(createScalarReplAggregatesPass());
385
386   // Run a few AA driven optimizations here and now, to cleanup the code.
387   PM.add(createFunctionAttrsPass()); // Add nocapture.
388   PM.add(createGlobalsModRefPass()); // IP alias analysis.
389
390   PM.add(createLICMPass());                 // Hoist loop invariants.
391   PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
392   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
393   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
394
395   // Nuke dead stores.
396   PM.add(createDeadStoreEliminationPass());
397
398   // More loops are countable; try to optimize them.
399   PM.add(createIndVarSimplifyPass());
400   PM.add(createLoopDeletionPass());
401   PM.add(createLoopVectorizePass(true, true));
402
403   // More scalar chains could be vectorized due to more alias information
404   PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
405
406   // After vectorization, assume intrinsics may tell us more about pointer
407   // alignments.
408   PM.add(createAlignmentFromAssumptionsPass());
409
410   if (LoadCombine)
411     PM.add(createLoadCombinePass());
412
413   // Cleanup and simplify the code after the scalar optimizations.
414   PM.add(createInstructionCombiningPass());
415   addExtensionsToPM(EP_Peephole, PM);
416
417   PM.add(createJumpThreadingPass());
418
419   // Delete basic blocks, which optimization passes may have killed.
420   PM.add(createCFGSimplificationPass());
421
422   // Now that we have optimized the program, discard unreachable functions.
423   PM.add(createGlobalDCEPass());
424 }
425
426 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
427                                                 TargetMachine *TM) {
428   if (TM) {
429     const DataLayout *DL = TM->getSubtargetImpl()->getDataLayout();
430     PM.add(new DataLayoutPass(*DL));
431     TM->addAnalysisPasses(PM);
432   }
433
434   if (LibraryInfo)
435     PM.add(new TargetLibraryInfo(*LibraryInfo));
436
437   if (VerifyInput)
438     PM.add(createVerifierPass());
439
440   if (StripDebug)
441     PM.add(createStripSymbolsPass(true));
442
443   if (VerifyInput)
444     PM.add(createDebugInfoVerifierPass());
445
446   if (OptLevel != 0)
447     addLTOOptimizationPasses(PM);
448
449   if (VerifyOutput) {
450     PM.add(createVerifierPass());
451     PM.add(createDebugInfoVerifierPass());
452   }
453 }
454
455 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
456     return reinterpret_cast<PassManagerBuilder*>(P);
457 }
458
459 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
460   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
461 }
462
463 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
464   PassManagerBuilder *PMB = new PassManagerBuilder();
465   return wrap(PMB);
466 }
467
468 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
469   PassManagerBuilder *Builder = unwrap(PMB);
470   delete Builder;
471 }
472
473 void
474 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
475                                   unsigned OptLevel) {
476   PassManagerBuilder *Builder = unwrap(PMB);
477   Builder->OptLevel = OptLevel;
478 }
479
480 void
481 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
482                                    unsigned SizeLevel) {
483   PassManagerBuilder *Builder = unwrap(PMB);
484   Builder->SizeLevel = SizeLevel;
485 }
486
487 void
488 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
489                                             LLVMBool Value) {
490   PassManagerBuilder *Builder = unwrap(PMB);
491   Builder->DisableUnitAtATime = Value;
492 }
493
494 void
495 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
496                                             LLVMBool Value) {
497   PassManagerBuilder *Builder = unwrap(PMB);
498   Builder->DisableUnrollLoops = Value;
499 }
500
501 void
502 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
503                                                  LLVMBool Value) {
504   // NOTE: The simplify-libcalls pass has been removed.
505 }
506
507 void
508 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
509                                               unsigned Threshold) {
510   PassManagerBuilder *Builder = unwrap(PMB);
511   Builder->Inliner = createFunctionInliningPass(Threshold);
512 }
513
514 void
515 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
516                                                   LLVMPassManagerRef PM) {
517   PassManagerBuilder *Builder = unwrap(PMB);
518   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
519   Builder->populateFunctionPassManager(*FPM);
520 }
521
522 void
523 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
524                                                 LLVMPassManagerRef PM) {
525   PassManagerBuilder *Builder = unwrap(PMB);
526   PassManagerBase *MPM = unwrap(PM);
527   Builder->populateModulePassManager(*MPM);
528 }
529
530 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
531                                                   LLVMPassManagerRef PM,
532                                                   LLVMBool Internalize,
533                                                   LLVMBool RunInliner) {
534   PassManagerBuilder *Builder = unwrap(PMB);
535   PassManagerBase *LPM = unwrap(PM);
536
537   // A small backwards compatibility hack. populateLTOPassManager used to take
538   // an RunInliner option.
539   if (RunInliner && !Builder->Inliner)
540     Builder->Inliner = createFunctionInliningPass();
541
542   Builder->populateLTOPassManager(*LPM);
543 }