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