Change the debug type to match the debug type that is used by vecutils.cpp.
[oota-llvm.git] / lib / Transforms / Vectorize / SLPVectorizer.cpp
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
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 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 #define SV_NAME "slp-vectorizer"
19 #define DEBUG_TYPE "SLP"
20
21 #include "VecUtils.h"
22 #include "llvm/Transforms/Vectorize.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/Verifier.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <map>
40
41 using namespace llvm;
42
43 static cl::opt<int>
44 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
45                  cl::desc("Only vectorize trees if the gain is above this "
46                           "number. (gain = -cost of vectorization)"));
47 namespace {
48
49 /// The SLPVectorizer Pass.
50 struct SLPVectorizer : public FunctionPass {
51   typedef MapVector<Value*, BoUpSLP::StoreList> StoreListMap;
52
53   /// Pass identification, replacement for typeid
54   static char ID;
55
56   explicit SLPVectorizer() : FunctionPass(ID) {
57     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
58   }
59
60   ScalarEvolution *SE;
61   DataLayout *DL;
62   TargetTransformInfo *TTI;
63   AliasAnalysis *AA;
64   LoopInfo *LI;
65
66   virtual bool runOnFunction(Function &F) {
67     SE = &getAnalysis<ScalarEvolution>();
68     DL = getAnalysisIfAvailable<DataLayout>();
69     TTI = &getAnalysis<TargetTransformInfo>();
70     AA = &getAnalysis<AliasAnalysis>();
71     LI = &getAnalysis<LoopInfo>();
72
73     StoreRefs.clear();
74     bool Changed = false;
75
76     // Must have DataLayout. We can't require it because some tests run w/o
77     // triple.
78     if (!DL)
79       return false;
80
81     DEBUG(dbgs()<<"SLP: Analyzing blocks in " << F.getName() << ".\n");
82
83     for (Function::iterator it = F.begin(), e = F.end(); it != e; ++it) {
84       BasicBlock *BB = it;
85       bool BBChanged = false;
86
87       // Use the bollom up slp vectorizer to construct chains that start with
88       // he store instructions.
89       BoUpSLP R(BB, SE, DL, TTI, AA, LI->getLoopFor(BB));
90
91       // Vectorize trees that end at reductions.
92       BBChanged |= vectorizeChainsInBlock(BB, R);
93
94       // Vectorize trees that end at stores.
95       if (unsigned count = collectStores(BB, R)) {
96         (void)count;
97         DEBUG(dbgs()<<"SLP: Found " << count << " stores to vectorize.\n");
98         BBChanged |= vectorizeStoreChains(R);
99       }
100
101       // Try to hoist some of the scalarization code to the preheader.
102       if (BBChanged) hoistGatherSequence(LI, BB, R);
103
104       Changed |= BBChanged;
105     }
106
107     if (Changed) {
108       DEBUG(dbgs()<<"SLP: vectorized \""<<F.getName()<<"\"\n");
109       DEBUG(verifyFunction(F));
110     }
111     return Changed;
112   }
113
114   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115     FunctionPass::getAnalysisUsage(AU);
116     AU.addRequired<ScalarEvolution>();
117     AU.addRequired<AliasAnalysis>();
118     AU.addRequired<TargetTransformInfo>();
119     AU.addRequired<LoopInfo>();
120   }
121
122 private:
123
124   /// \brief Collect memory references and sort them according to their base
125   /// object. We sort the stores to their base objects to reduce the cost of the
126   /// quadratic search on the stores. TODO: We can further reduce this cost
127   /// if we flush the chain creation every time we run into a memory barrier.
128   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
129
130   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
131   bool tryToVectorizePair(Value *A, Value *B,  BoUpSLP &R);
132
133   /// \brief Try to vectorize a list of operands.
134   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
135
136   /// \brief Try to vectorize a chain that may start at the operands of \V;
137   bool tryToVectorize(BinaryOperator *V,  BoUpSLP &R);
138
139   /// \brief Vectorize the stores that were collected in StoreRefs.
140   bool vectorizeStoreChains(BoUpSLP &R);
141
142   /// \brief Try to hoist gather sequences outside of the loop in cases where
143   /// all of the sources are loop invariant.
144   void hoistGatherSequence(LoopInfo *LI, BasicBlock *BB, BoUpSLP &R);
145
146   /// \brief Scan the basic block and look for patterns that are likely to start
147   /// a vectorization chain.
148   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
149
150 private:
151   StoreListMap StoreRefs;
152 };
153
154 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
155   unsigned count = 0;
156   StoreRefs.clear();
157   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
158     StoreInst *SI = dyn_cast<StoreInst>(it);
159     if (!SI)
160       continue;
161
162     // Check that the pointer points to scalars.
163     Type *Ty = SI->getValueOperand()->getType();
164     if (Ty->isAggregateType() || Ty->isVectorTy())
165       return 0;
166
167     // Find the base of the GEP.
168     Value *Ptr = SI->getPointerOperand();
169     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
170       Ptr = GEP->getPointerOperand();
171
172     // Save the store locations.
173     StoreRefs[Ptr].push_back(SI);
174     count++;
175   }
176   return count;
177 }
178
179 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B,  BoUpSLP &R) {
180   if (!A || !B) return false;
181   Value *VL[] = { A, B };
182   return tryToVectorizeList(VL, R);
183 }
184
185 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
186   if (VL.size() < 2)
187     return false;
188
189   DEBUG(dbgs()<<"SLP: Vectorizing a list of length = " << VL.size() << ".\n");
190
191   // Check that all of the parts are scalar instructions of the same type.
192   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
193   if (!I0) return 0;
194
195   unsigned Opcode0 = I0->getOpcode();
196
197   for (int i = 0, e = VL.size(); i < e; ++i) {
198     Type *Ty = VL[i]->getType();
199     if (Ty->isAggregateType() || Ty->isVectorTy())
200       return 0;
201     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
202     if (!Inst || Inst->getOpcode() != Opcode0)
203       return 0;
204   }
205
206   int Cost = R.getTreeCost(VL);
207   int ExtrCost = R.getScalarizationCost(VL);
208   DEBUG(dbgs()<<"SLP: Cost of pair:" << Cost <<
209         " Cost of extract:" << ExtrCost << ".\n");
210   if ((Cost+ExtrCost) >= -SLPCostThreshold) return false;
211   DEBUG(dbgs()<<"SLP: Vectorizing pair.\n");
212   R.vectorizeArith(VL);
213   return true;
214 }
215
216 bool SLPVectorizer::tryToVectorize(BinaryOperator *V,  BoUpSLP &R) {
217   if (!V) return false;
218   // Try to vectorize V.
219   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
220     return true;
221
222   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
223   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
224   // Try to skip B.
225   if (B && B->hasOneUse()) {
226     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
227     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
228     if (tryToVectorizePair(A, B0, R)) {
229       B->moveBefore(V);
230       return true;
231     }
232     if (tryToVectorizePair(A, B1, R)) {
233       B->moveBefore(V);
234       return true;
235     }
236   }
237
238   // Try to skip A.
239   if (A && A->hasOneUse()) {
240     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
241     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
242     if (tryToVectorizePair(A0, B, R)) {
243       A->moveBefore(V);
244       return true;
245     }
246     if (tryToVectorizePair(A1, B, R)) {
247       A->moveBefore(V);
248       return true;
249     }
250   }
251   return 0;
252 }
253
254 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
255   bool Changed = false;
256   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
257     if (isa<DbgInfoIntrinsic>(it)) continue;
258
259     // Try to vectorize reductions that use PHINodes.
260     if (PHINode *P = dyn_cast<PHINode>(it)) {
261       // Check that the PHI is a reduction PHI.
262       if (P->getNumIncomingValues() != 2) return Changed;
263       Value *Rdx = (P->getIncomingBlock(0) == BB ? P->getIncomingValue(0) :
264                     (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) :
265                      0));
266       // Check if this is a Binary Operator.
267       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
268       if (!BI)
269         continue;
270
271       Value *Inst = BI->getOperand(0);
272       if (Inst == P) Inst = BI->getOperand(1);
273       Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
274       continue;
275     }
276
277     // Try to vectorize trees that start at compare instructions.
278     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
279       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
280         Changed |= true;
281         continue;
282       }
283       for (int i = 0; i < 2; ++i)
284         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
285           Changed |= tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
286       continue;
287     }
288   }
289
290   // Scan the PHINodes in our successors in search for pairing hints.
291   for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
292     BasicBlock *Succ = *it;
293     SmallVector<Value*, 4> Incoming;
294
295     // Collect the incoming values from the PHIs.
296     for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
297          instr != ie; ++instr) {
298       PHINode *P = dyn_cast<PHINode>(instr);
299
300       if (!P)
301         break;
302
303       Value *V = P->getIncomingValueForBlock(BB);
304       if (Instruction *I = dyn_cast<Instruction>(V))
305         if (I->getParent() == BB)
306           Incoming.push_back(I);
307     }
308
309     if (Incoming.size() > 1)
310       Changed |= tryToVectorizeList(Incoming, R);
311   }
312   
313   return Changed;
314 }
315
316 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
317   bool Changed = false;
318   // Attempt to sort and vectorize each of the store-groups.
319   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
320        it != e; ++it) {
321     if (it->second.size() < 2)
322       continue;
323
324     DEBUG(dbgs()<<"SLP: Analyzing a store chain of length " <<
325           it->second.size() << ".\n");
326
327     Changed |= R.vectorizeStores(it->second, -SLPCostThreshold);
328   }
329   return Changed;
330 }
331
332 void SLPVectorizer::hoistGatherSequence(LoopInfo *LI, BasicBlock *BB,
333                                         BoUpSLP &R) {
334   // Check if this block is inside a loop.
335   Loop *L = LI->getLoopFor(BB);
336   if (!L)
337     return;
338
339   // Check if it has a preheader.
340   BasicBlock *PreHeader = L->getLoopPreheader();
341   if (!PreHeader)
342     return;
343
344   // Mark the insertion point for the block.
345   Instruction *Location = PreHeader->getTerminator();
346
347   BoUpSLP::ValueList &Gathers = R.getGatherSeqInstructions();
348   for (BoUpSLP::ValueList::iterator it = Gathers.begin(), e = Gathers.end();
349        it != e; ++it) {
350     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
351
352     // The InsertElement sequence can be simplified into a constant.
353     if (!Insert)
354       continue;
355
356     // If the vector or the element that we insert into it are
357     // instructions that are defined in this basic block then we can't
358     // hoist this instruction.
359     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
360     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
361     if (CurrVec && L->contains(CurrVec)) continue;
362     if (NewElem && L->contains(NewElem)) continue;
363
364     // We can hoist this instruction. Move it to the pre-header.
365     Insert->moveBefore(Location);
366   }
367 }
368
369 } // end anonymous namespace
370
371 char SLPVectorizer::ID = 0;
372 static const char lv_name[] = "SLP Vectorizer";
373 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
374 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
375 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
376 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
377 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
378 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
379
380 namespace llvm {
381   Pass *createSLPVectorizerPass() {
382     return new SLPVectorizer();
383   }
384 }
385