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