af1c0e74236c76a6f066738ff20edbf04f326a90
[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 "llvm/Transforms/Vectorize.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <map>
45
46 using namespace llvm;
47
48 static cl::opt<int>
49     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50                      cl::desc("Only vectorize if you gain more than this "
51                               "number "));
52
53 static cl::opt<bool>
54 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55                    cl::desc("Attempt to vectorize horizontal reductions"));
56
57 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
58     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
59     cl::desc(
60         "Attempt to vectorize horizontal reductions feeding into a store"));
61
62 namespace {
63
64 static const unsigned MinVecRegSize = 128;
65
66 static const unsigned RecursionMaxDepth = 12;
67
68 /// A helper class for numbering instructions in multiple blocks.
69 /// Numbers start at zero for each basic block.
70 struct BlockNumbering {
71
72   BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
73
74   BlockNumbering() : BB(0), Valid(false) {}
75
76   void numberInstructions() {
77     unsigned Loc = 0;
78     InstrIdx.clear();
79     InstrVec.clear();
80     // Number the instructions in the block.
81     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
82       InstrIdx[it] = Loc++;
83       InstrVec.push_back(it);
84       assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
85     }
86     Valid = true;
87   }
88
89   int getIndex(Instruction *I) {
90     assert(I->getParent() == BB && "Invalid instruction");
91     if (!Valid)
92       numberInstructions();
93     assert(InstrIdx.count(I) && "Unknown instruction");
94     return InstrIdx[I];
95   }
96
97   Instruction *getInstruction(unsigned loc) {
98     if (!Valid)
99       numberInstructions();
100     assert(InstrVec.size() > loc && "Invalid Index");
101     return InstrVec[loc];
102   }
103
104   void forget() { Valid = false; }
105
106 private:
107   /// The block we are numbering.
108   BasicBlock *BB;
109   /// Is the block numbered.
110   bool Valid;
111   /// Maps instructions to numbers and back.
112   SmallDenseMap<Instruction *, int> InstrIdx;
113   /// Maps integers to Instructions.
114   SmallVector<Instruction *, 32> InstrVec;
115 };
116
117 /// \returns the parent basic block if all of the instructions in \p VL
118 /// are in the same block or null otherwise.
119 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
120   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
121   if (!I0)
122     return 0;
123   BasicBlock *BB = I0->getParent();
124   for (int i = 1, e = VL.size(); i < e; i++) {
125     Instruction *I = dyn_cast<Instruction>(VL[i]);
126     if (!I)
127       return 0;
128
129     if (BB != I->getParent())
130       return 0;
131   }
132   return BB;
133 }
134
135 /// \returns True if all of the values in \p VL are constants.
136 static bool allConstant(ArrayRef<Value *> VL) {
137   for (unsigned i = 0, e = VL.size(); i < e; ++i)
138     if (!isa<Constant>(VL[i]))
139       return false;
140   return true;
141 }
142
143 /// \returns True if all of the values in \p VL are identical.
144 static bool isSplat(ArrayRef<Value *> VL) {
145   for (unsigned i = 1, e = VL.size(); i < e; ++i)
146     if (VL[i] != VL[0])
147       return false;
148   return true;
149 }
150
151 /// \returns The opcode if all of the Instructions in \p VL have the same
152 /// opcode, or zero.
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
155   if (!I0)
156     return 0;
157   unsigned Opcode = I0->getOpcode();
158   for (int i = 1, e = VL.size(); i < e; i++) {
159     Instruction *I = dyn_cast<Instruction>(VL[i]);
160     if (!I || Opcode != I->getOpcode())
161       return 0;
162   }
163   return Opcode;
164 }
165
166 /// \returns The type that all of the values in \p VL have or null if there
167 /// are different types.
168 static Type* getSameType(ArrayRef<Value *> VL) {
169   Type *Ty = VL[0]->getType();
170   for (int i = 1, e = VL.size(); i < e; i++)
171     if (VL[i]->getType() != Ty)
172       return 0;
173
174   return Ty;
175 }
176
177 /// \returns True if the ExtractElement instructions in VL can be vectorized
178 /// to use the original vector.
179 static bool CanReuseExtract(ArrayRef<Value *> VL) {
180   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
181   // Check if all of the extracts come from the same vector and from the
182   // correct offset.
183   Value *VL0 = VL[0];
184   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
185   Value *Vec = E0->getOperand(0);
186
187   // We have to extract from the same vector type.
188   unsigned NElts = Vec->getType()->getVectorNumElements();
189
190   if (NElts != VL.size())
191     return false;
192
193   // Check that all of the indices extract from the correct offset.
194   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
195   if (!CI || CI->getZExtValue())
196     return false;
197
198   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
199     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
200     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
201
202     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
203       return false;
204   }
205
206   return true;
207 }
208
209 static bool all_equal(SmallVectorImpl<Value *> &V) {
210   Value *First = V[0];
211   for (int i = 1, e = V.size(); i != e; ++i)
212     if (V[i] != First)
213       return false;
214   return true;
215 }
216
217 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
218                                            SmallVectorImpl<Value *> &Left,
219                                            SmallVectorImpl<Value *> &Right) {
220
221   SmallVector<Value *, 16> OrigLeft, OrigRight;
222
223   bool AllSameOpcodeLeft = true;
224   bool AllSameOpcodeRight = true;
225   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
226     Instruction *I = cast<Instruction>(VL[i]);
227     Value *V0 = I->getOperand(0);
228     Value *V1 = I->getOperand(1);
229
230     OrigLeft.push_back(V0);
231     OrigRight.push_back(V1);
232
233     Instruction *I0 = dyn_cast<Instruction>(V0);
234     Instruction *I1 = dyn_cast<Instruction>(V1);
235
236     // Check whether all operands on one side have the same opcode. In this case
237     // we want to preserve the original order and not make things worse by
238     // reordering.
239     AllSameOpcodeLeft = I0;
240     AllSameOpcodeRight = I1;
241
242     if (i && AllSameOpcodeLeft) {
243       if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
244         if(P0->getOpcode() != I0->getOpcode())
245           AllSameOpcodeLeft = false;
246       } else
247         AllSameOpcodeLeft = false;
248     }
249     if (i && AllSameOpcodeRight) {
250       if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
251         if(P1->getOpcode() != I1->getOpcode())
252           AllSameOpcodeRight = false;
253       } else
254         AllSameOpcodeRight = false;
255     }
256
257     // Sort two opcodes. In the code below we try to preserve the ability to use
258     // broadcast of values instead of individual inserts.
259     // vl1 = load
260     // vl2 = phi
261     // vr1 = load
262     // vr2 = vr2
263     //    = vl1 x vr1
264     //    = vl2 x vr2
265     // If we just sorted according to opcode we would leave the first line in
266     // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
267     //    = vl1 x vr1
268     //    = vr2 x vl2
269     // Because vr2 and vr1 are from the same load we loose the opportunity of a
270     // broadcast for the packed right side in the backend: we have [vr1, vl2]
271     // instead of [vr1, vr2=vr1].
272     if (I0 && I1) {
273        if(!i && I0->getOpcode() > I1->getOpcode()) {
274          Left.push_back(I1);
275          Right.push_back(I0);
276        } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
277          // Try not to destroy a broad cast for no apparent benefit.
278          Left.push_back(I1);
279          Right.push_back(I0);
280        } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] ==  I0) {
281          // Try preserve broadcasts.
282          Left.push_back(I1);
283          Right.push_back(I0);
284        } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
285          // Try preserve broadcasts.
286          Left.push_back(I1);
287          Right.push_back(I0);
288        } else {
289          Left.push_back(I0);
290          Right.push_back(I1);
291        }
292        continue;
293     }
294     // One opcode, put the instruction on the right.
295     if (I0) {
296       Left.push_back(V1);
297       Right.push_back(I0);
298       continue;
299     }
300     Left.push_back(V0);
301     Right.push_back(V1);
302   }
303
304   bool LeftBroadcast = all_equal(Left);
305   bool RightBroadcast = all_equal(Right);
306
307   // Don't reorder if the operands where good to begin with.
308   if (!(LeftBroadcast || RightBroadcast) &&
309       (AllSameOpcodeRight || AllSameOpcodeLeft)) {
310     Left = OrigLeft;
311     Right = OrigRight;
312   }
313 }
314
315 /// Bottom Up SLP Vectorizer.
316 class BoUpSLP {
317 public:
318   typedef SmallVector<Value *, 8> ValueList;
319   typedef SmallVector<Instruction *, 16> InstrList;
320   typedef SmallPtrSet<Value *, 16> ValueSet;
321   typedef SmallVector<StoreInst *, 8> StoreList;
322
323   BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
324           TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
325           DominatorTree *Dt) :
326     F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
327     Builder(Se->getContext()) {
328       // Setup the block numbering utility for all of the blocks in the
329       // function.
330       for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
331         BasicBlock *BB = it;
332         BlocksNumbers[BB] = BlockNumbering(BB);
333       }
334     }
335
336   /// \brief Vectorize the tree that starts with the elements in \p VL.
337   /// Returns the vectorized root.
338   Value *vectorizeTree();
339
340   /// \returns the vectorization cost of the subtree that starts at \p VL.
341   /// A negative number means that this is profitable.
342   int getTreeCost();
343
344   /// Construct a vectorizable tree that starts at \p Roots and is possibly
345   /// used by a reduction of \p RdxOps.
346   void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
347
348   /// Clear the internal data structures that are created by 'buildTree'.
349   void deleteTree() {
350     RdxOps = 0;
351     VectorizableTree.clear();
352     ScalarToTreeEntry.clear();
353     MustGather.clear();
354     ExternalUses.clear();
355     MemBarrierIgnoreList.clear();
356   }
357
358   /// \returns true if the memory operations A and B are consecutive.
359   bool isConsecutiveAccess(Value *A, Value *B);
360
361   /// \brief Perform LICM and CSE on the newly generated gather sequences.
362   void optimizeGatherSequence();
363 private:
364   struct TreeEntry;
365
366   /// \returns the cost of the vectorizable entry.
367   int getEntryCost(TreeEntry *E);
368
369   /// This is the recursive part of buildTree.
370   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
371
372   /// Vectorize a single entry in the tree.
373   Value *vectorizeTree(TreeEntry *E);
374
375   /// Vectorize a single entry in the tree, starting in \p VL.
376   Value *vectorizeTree(ArrayRef<Value *> VL);
377
378   /// \returns the pointer to the vectorized value if \p VL is already
379   /// vectorized, or NULL. They may happen in cycles.
380   Value *alreadyVectorized(ArrayRef<Value *> VL) const;
381
382   /// \brief Take the pointer operand from the Load/Store instruction.
383   /// \returns NULL if this is not a valid Load/Store instruction.
384   static Value *getPointerOperand(Value *I);
385
386   /// \brief Take the address space operand from the Load/Store instruction.
387   /// \returns -1 if this is not a valid Load/Store instruction.
388   static unsigned getAddressSpaceOperand(Value *I);
389
390   /// \returns the scalarization cost for this type. Scalarization in this
391   /// context means the creation of vectors from a group of scalars.
392   int getGatherCost(Type *Ty);
393
394   /// \returns the scalarization cost for this list of values. Assuming that
395   /// this subtree gets vectorized, we may need to extract the values from the
396   /// roots. This method calculates the cost of extracting the values.
397   int getGatherCost(ArrayRef<Value *> VL);
398
399   /// \returns the AA location that is being access by the instruction.
400   AliasAnalysis::Location getLocation(Instruction *I);
401
402   /// \brief Checks if it is possible to sink an instruction from
403   /// \p Src to \p Dst.
404   /// \returns the pointer to the barrier instruction if we can't sink.
405   Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
406
407   /// \returns the index of the last instruction in the BB from \p VL.
408   int getLastIndex(ArrayRef<Value *> VL);
409
410   /// \returns the Instruction in the bundle \p VL.
411   Instruction *getLastInstruction(ArrayRef<Value *> VL);
412
413   /// \brief Set the Builder insert point to one after the last instruction in
414   /// the bundle
415   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
416
417   /// \returns a vector from a collection of scalars in \p VL.
418   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
419
420   /// \returns whether the VectorizableTree is fully vectoriable and will
421   /// be beneficial even the tree height is tiny.
422   bool isFullyVectorizableTinyTree(); 
423
424   struct TreeEntry {
425     TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
426     NeedToGather(0) {}
427
428     /// \returns true if the scalars in VL are equal to this entry.
429     bool isSame(ArrayRef<Value *> VL) const {
430       assert(VL.size() == Scalars.size() && "Invalid size");
431       return std::equal(VL.begin(), VL.end(), Scalars.begin());
432     }
433
434     /// A vector of scalars.
435     ValueList Scalars;
436
437     /// The Scalars are vectorized into this value. It is initialized to Null.
438     Value *VectorizedValue;
439
440     /// The index in the basic block of the last scalar.
441     int LastScalarIndex;
442
443     /// Do we need to gather this sequence ?
444     bool NeedToGather;
445   };
446
447   /// Create a new VectorizableTree entry.
448   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
449     VectorizableTree.push_back(TreeEntry());
450     int idx = VectorizableTree.size() - 1;
451     TreeEntry *Last = &VectorizableTree[idx];
452     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
453     Last->NeedToGather = !Vectorized;
454     if (Vectorized) {
455       Last->LastScalarIndex = getLastIndex(VL);
456       for (int i = 0, e = VL.size(); i != e; ++i) {
457         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
458         ScalarToTreeEntry[VL[i]] = idx;
459       }
460     } else {
461       Last->LastScalarIndex = 0;
462       MustGather.insert(VL.begin(), VL.end());
463     }
464     return Last;
465   }
466
467   /// -- Vectorization State --
468   /// Holds all of the tree entries.
469   std::vector<TreeEntry> VectorizableTree;
470
471   /// Maps a specific scalar to its tree entry.
472   SmallDenseMap<Value*, int> ScalarToTreeEntry;
473
474   /// A list of scalars that we found that we need to keep as scalars.
475   ValueSet MustGather;
476
477   /// This POD struct describes one external user in the vectorized tree.
478   struct ExternalUser {
479     ExternalUser (Value *S, llvm::User *U, int L) :
480       Scalar(S), User(U), Lane(L){};
481     // Which scalar in our function.
482     Value *Scalar;
483     // Which user that uses the scalar.
484     llvm::User *User;
485     // Which lane does the scalar belong to.
486     int Lane;
487   };
488   typedef SmallVector<ExternalUser, 16> UserList;
489
490   /// A list of values that need to extracted out of the tree.
491   /// This list holds pairs of (Internal Scalar : External User).
492   UserList ExternalUses;
493
494   /// A list of instructions to ignore while sinking
495   /// memory instructions. This map must be reset between runs of getCost.
496   ValueSet MemBarrierIgnoreList;
497
498   /// Holds all of the instructions that we gathered.
499   SetVector<Instruction *> GatherSeq;
500
501   /// Numbers instructions in different blocks.
502   DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
503
504   /// Reduction operators.
505   ValueSet *RdxOps;
506
507   // Analysis and block reference.
508   Function *F;
509   ScalarEvolution *SE;
510   DataLayout *DL;
511   TargetTransformInfo *TTI;
512   AliasAnalysis *AA;
513   LoopInfo *LI;
514   DominatorTree *DT;
515   /// Instruction builder to construct the vectorized tree.
516   IRBuilder<> Builder;
517 };
518
519 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
520   deleteTree();
521   RdxOps = Rdx;
522   if (!getSameType(Roots))
523     return;
524   buildTree_rec(Roots, 0);
525
526   // Collect the values that we need to extract from the tree.
527   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
528     TreeEntry *Entry = &VectorizableTree[EIdx];
529
530     // For each lane:
531     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
532       Value *Scalar = Entry->Scalars[Lane];
533
534       // No need to handle users of gathered values.
535       if (Entry->NeedToGather)
536         continue;
537
538       for (Value::use_iterator User = Scalar->use_begin(),
539            UE = Scalar->use_end(); User != UE; ++User) {
540         DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
541
542         bool Gathered = MustGather.count(*User);
543
544         // Skip in-tree scalars that become vectors.
545         if (ScalarToTreeEntry.count(*User) && !Gathered) {
546           DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
547                 **User << ".\n");
548           int Idx = ScalarToTreeEntry[*User]; (void) Idx;
549           assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
550           continue;
551         }
552         Instruction *UserInst = dyn_cast<Instruction>(*User);
553         if (!UserInst)
554           continue;
555
556         // Ignore uses that are part of the reduction.
557         if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
558           continue;
559
560         DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
561               Lane << " from " << *Scalar << ".\n");
562         ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
563       }
564     }
565   }
566 }
567
568
569 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
570   bool SameTy = getSameType(VL); (void)SameTy;
571   assert(SameTy && "Invalid types!");
572
573   if (Depth == RecursionMaxDepth) {
574     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
575     newTreeEntry(VL, false);
576     return;
577   }
578
579   // Don't handle vectors.
580   if (VL[0]->getType()->isVectorTy()) {
581     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
582     newTreeEntry(VL, false);
583     return;
584   }
585
586   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
587     if (SI->getValueOperand()->getType()->isVectorTy()) {
588       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
589       newTreeEntry(VL, false);
590       return;
591     }
592
593   // If all of the operands are identical or constant we have a simple solution.
594   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
595       !getSameOpcode(VL)) {
596     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
597     newTreeEntry(VL, false);
598     return;
599   }
600
601   // We now know that this is a vector of instructions of the same type from
602   // the same block.
603
604   // Check if this is a duplicate of another entry.
605   if (ScalarToTreeEntry.count(VL[0])) {
606     int Idx = ScalarToTreeEntry[VL[0]];
607     TreeEntry *E = &VectorizableTree[Idx];
608     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
609       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
610       if (E->Scalars[i] != VL[i]) {
611         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
612         newTreeEntry(VL, false);
613         return;
614       }
615     }
616     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
617     return;
618   }
619
620   // Check that none of the instructions in the bundle are already in the tree.
621   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
622     if (ScalarToTreeEntry.count(VL[i])) {
623       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
624             ") is already in tree.\n");
625       newTreeEntry(VL, false);
626       return;
627     }
628   }
629
630   // If any of the scalars appears in the table OR it is marked as a value that
631   // needs to stat scalar then we need to gather the scalars.
632   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
633     if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
634       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
635       newTreeEntry(VL, false);
636       return;
637     }
638   }
639
640   // Check that all of the users of the scalars that we want to vectorize are
641   // schedulable.
642   Instruction *VL0 = cast<Instruction>(VL[0]);
643   int MyLastIndex = getLastIndex(VL);
644   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
645
646   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
647     Instruction *Scalar = cast<Instruction>(VL[i]);
648     DEBUG(dbgs() << "SLP: Checking users of  " << *Scalar << ". \n");
649     for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
650          U != UE; ++U) {
651       DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
652       Instruction *User = dyn_cast<Instruction>(*U);
653       if (!User) {
654         DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
655         newTreeEntry(VL, false);
656         return;
657       }
658
659       // We don't care if the user is in a different basic block.
660       BasicBlock *UserBlock = User->getParent();
661       if (UserBlock != BB) {
662         DEBUG(dbgs() << "SLP: User from a different basic block "
663               << *User << ". \n");
664         continue;
665       }
666
667       // If this is a PHINode within this basic block then we can place the
668       // extract wherever we want.
669       if (isa<PHINode>(*User)) {
670         DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
671         continue;
672       }
673
674       // Check if this is a safe in-tree user.
675       if (ScalarToTreeEntry.count(User)) {
676         int Idx = ScalarToTreeEntry[User];
677         int VecLocation = VectorizableTree[Idx].LastScalarIndex;
678         if (VecLocation <= MyLastIndex) {
679           DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
680           newTreeEntry(VL, false);
681           return;
682         }
683         DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
684               VecLocation << " vector value (" << *Scalar << ") at #"
685               << MyLastIndex << ".\n");
686         continue;
687       }
688
689       // This user is part of the reduction.
690       if (RdxOps && RdxOps->count(User))
691         continue;
692
693       // Make sure that we can schedule this unknown user.
694       BlockNumbering &BN = BlocksNumbers[BB];
695       int UserIndex = BN.getIndex(User);
696       if (UserIndex < MyLastIndex) {
697
698         DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
699               << *User << ". \n");
700         newTreeEntry(VL, false);
701         return;
702       }
703     }
704   }
705
706   // Check that every instructions appears once in this bundle.
707   for (unsigned i = 0, e = VL.size(); i < e; ++i)
708     for (unsigned j = i+1; j < e; ++j)
709       if (VL[i] == VL[j]) {
710         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
711         newTreeEntry(VL, false);
712         return;
713       }
714
715   // Check that instructions in this bundle don't reference other instructions.
716   // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
717   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
718     for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
719          U != UE; ++U) {
720       for (unsigned j = 0; j < e; ++j) {
721         if (i != j && *U == VL[j]) {
722           DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
723           newTreeEntry(VL, false);
724           return;
725         }
726       }
727     }
728   }
729
730   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
731
732   unsigned Opcode = getSameOpcode(VL);
733
734   // Check if it is safe to sink the loads or the stores.
735   if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
736     Instruction *Last = getLastInstruction(VL);
737
738     for (unsigned i = 0, e = VL.size(); i < e; ++i) {
739       if (VL[i] == Last)
740         continue;
741       Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
742       if (Barrier) {
743         DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
744               << "\n because of " << *Barrier << ".  Gathering.\n");
745         newTreeEntry(VL, false);
746         return;
747       }
748     }
749   }
750
751   switch (Opcode) {
752     case Instruction::PHI: {
753       PHINode *PH = dyn_cast<PHINode>(VL0);
754
755       // Check for terminator values (e.g. invoke).
756       for (unsigned j = 0; j < VL.size(); ++j)
757         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
758           TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
759           if (Term) {
760             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
761             newTreeEntry(VL, false);
762             return;
763           }
764         }
765
766       newTreeEntry(VL, true);
767       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
768
769       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
770         ValueList Operands;
771         // Prepare the operand vector.
772         for (unsigned j = 0; j < VL.size(); ++j)
773           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
774
775         buildTree_rec(Operands, Depth + 1);
776       }
777       return;
778     }
779     case Instruction::ExtractElement: {
780       bool Reuse = CanReuseExtract(VL);
781       if (Reuse) {
782         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
783       }
784       newTreeEntry(VL, Reuse);
785       return;
786     }
787     case Instruction::Load: {
788       // Check if the loads are consecutive or of we need to swizzle them.
789       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
790         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
791           newTreeEntry(VL, false);
792           DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
793           return;
794         }
795
796       newTreeEntry(VL, true);
797       DEBUG(dbgs() << "SLP: added a vector of loads.\n");
798       return;
799     }
800     case Instruction::ZExt:
801     case Instruction::SExt:
802     case Instruction::FPToUI:
803     case Instruction::FPToSI:
804     case Instruction::FPExt:
805     case Instruction::PtrToInt:
806     case Instruction::IntToPtr:
807     case Instruction::SIToFP:
808     case Instruction::UIToFP:
809     case Instruction::Trunc:
810     case Instruction::FPTrunc:
811     case Instruction::BitCast: {
812       Type *SrcTy = VL0->getOperand(0)->getType();
813       for (unsigned i = 0; i < VL.size(); ++i) {
814         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
815         if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
816           newTreeEntry(VL, false);
817           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
818           return;
819         }
820       }
821       newTreeEntry(VL, true);
822       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
823
824       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
825         ValueList Operands;
826         // Prepare the operand vector.
827         for (unsigned j = 0; j < VL.size(); ++j)
828           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
829
830         buildTree_rec(Operands, Depth+1);
831       }
832       return;
833     }
834     case Instruction::ICmp:
835     case Instruction::FCmp: {
836       // Check that all of the compares have the same predicate.
837       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
838       Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
839       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
840         CmpInst *Cmp = cast<CmpInst>(VL[i]);
841         if (Cmp->getPredicate() != P0 ||
842             Cmp->getOperand(0)->getType() != ComparedTy) {
843           newTreeEntry(VL, false);
844           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
845           return;
846         }
847       }
848
849       newTreeEntry(VL, true);
850       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
851
852       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
853         ValueList Operands;
854         // Prepare the operand vector.
855         for (unsigned j = 0; j < VL.size(); ++j)
856           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
857
858         buildTree_rec(Operands, Depth+1);
859       }
860       return;
861     }
862     case Instruction::Select:
863     case Instruction::Add:
864     case Instruction::FAdd:
865     case Instruction::Sub:
866     case Instruction::FSub:
867     case Instruction::Mul:
868     case Instruction::FMul:
869     case Instruction::UDiv:
870     case Instruction::SDiv:
871     case Instruction::FDiv:
872     case Instruction::URem:
873     case Instruction::SRem:
874     case Instruction::FRem:
875     case Instruction::Shl:
876     case Instruction::LShr:
877     case Instruction::AShr:
878     case Instruction::And:
879     case Instruction::Or:
880     case Instruction::Xor: {
881       newTreeEntry(VL, true);
882       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
883
884       // Sort operands of the instructions so that each side is more likely to
885       // have the same opcode.
886       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
887         ValueList Left, Right;
888         reorderInputsAccordingToOpcode(VL, Left, Right);
889         buildTree_rec(Left, Depth + 1);
890         buildTree_rec(Right, Depth + 1);
891         return;
892       }
893
894       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
895         ValueList Operands;
896         // Prepare the operand vector.
897         for (unsigned j = 0; j < VL.size(); ++j)
898           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
899
900         buildTree_rec(Operands, Depth+1);
901       }
902       return;
903     }
904     case Instruction::Store: {
905       // Check if the stores are consecutive or of we need to swizzle them.
906       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
907         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
908           newTreeEntry(VL, false);
909           DEBUG(dbgs() << "SLP: Non consecutive store.\n");
910           return;
911         }
912
913       newTreeEntry(VL, true);
914       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
915
916       ValueList Operands;
917       for (unsigned j = 0; j < VL.size(); ++j)
918         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
919
920       // We can ignore these values because we are sinking them down.
921       MemBarrierIgnoreList.insert(VL.begin(), VL.end());
922       buildTree_rec(Operands, Depth + 1);
923       return;
924     }
925     default:
926       newTreeEntry(VL, false);
927       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
928       return;
929   }
930 }
931
932 int BoUpSLP::getEntryCost(TreeEntry *E) {
933   ArrayRef<Value*> VL = E->Scalars;
934
935   Type *ScalarTy = VL[0]->getType();
936   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
937     ScalarTy = SI->getValueOperand()->getType();
938   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
939
940   if (E->NeedToGather) {
941     if (allConstant(VL))
942       return 0;
943     if (isSplat(VL)) {
944       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
945     }
946     return getGatherCost(E->Scalars);
947   }
948
949   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
950          "Invalid VL");
951   Instruction *VL0 = cast<Instruction>(VL[0]);
952   unsigned Opcode = VL0->getOpcode();
953   switch (Opcode) {
954     case Instruction::PHI: {
955       return 0;
956     }
957     case Instruction::ExtractElement: {
958       if (CanReuseExtract(VL))
959         return 0;
960       return getGatherCost(VecTy);
961     }
962     case Instruction::ZExt:
963     case Instruction::SExt:
964     case Instruction::FPToUI:
965     case Instruction::FPToSI:
966     case Instruction::FPExt:
967     case Instruction::PtrToInt:
968     case Instruction::IntToPtr:
969     case Instruction::SIToFP:
970     case Instruction::UIToFP:
971     case Instruction::Trunc:
972     case Instruction::FPTrunc:
973     case Instruction::BitCast: {
974       Type *SrcTy = VL0->getOperand(0)->getType();
975
976       // Calculate the cost of this instruction.
977       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
978                                                          VL0->getType(), SrcTy);
979
980       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
981       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
982       return VecCost - ScalarCost;
983     }
984     case Instruction::FCmp:
985     case Instruction::ICmp:
986     case Instruction::Select:
987     case Instruction::Add:
988     case Instruction::FAdd:
989     case Instruction::Sub:
990     case Instruction::FSub:
991     case Instruction::Mul:
992     case Instruction::FMul:
993     case Instruction::UDiv:
994     case Instruction::SDiv:
995     case Instruction::FDiv:
996     case Instruction::URem:
997     case Instruction::SRem:
998     case Instruction::FRem:
999     case Instruction::Shl:
1000     case Instruction::LShr:
1001     case Instruction::AShr:
1002     case Instruction::And:
1003     case Instruction::Or:
1004     case Instruction::Xor: {
1005       // Calculate the cost of this instruction.
1006       int ScalarCost = 0;
1007       int VecCost = 0;
1008       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1009           Opcode == Instruction::Select) {
1010         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1011         ScalarCost = VecTy->getNumElements() *
1012         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1013         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1014       } else {
1015         ScalarCost = VecTy->getNumElements() *
1016         TTI->getArithmeticInstrCost(Opcode, ScalarTy);
1017         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
1018       }
1019       return VecCost - ScalarCost;
1020     }
1021     case Instruction::Load: {
1022       // Cost of wide load - cost of scalar loads.
1023       int ScalarLdCost = VecTy->getNumElements() *
1024       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1025       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1026       return VecLdCost - ScalarLdCost;
1027     }
1028     case Instruction::Store: {
1029       // We know that we can merge the stores. Calculate the cost.
1030       int ScalarStCost = VecTy->getNumElements() *
1031       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1032       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1033       return VecStCost - ScalarStCost;
1034     }
1035     default:
1036       llvm_unreachable("Unknown instruction");
1037   }
1038 }
1039
1040 bool BoUpSLP::isFullyVectorizableTinyTree() {
1041   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1042         VectorizableTree.size() << " is fully vectorizable .\n");
1043
1044   // We only handle trees of height 2.
1045   if (VectorizableTree.size() != 2)
1046     return false;
1047
1048   // Gathering cost would be too much for tiny trees.
1049   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather) 
1050     return false; 
1051
1052   return true; 
1053 }
1054
1055 int BoUpSLP::getTreeCost() {
1056   int Cost = 0;
1057   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1058         VectorizableTree.size() << ".\n");
1059
1060   // We only vectorize tiny trees if it is fully vectorizable.
1061   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1062     if (!VectorizableTree.size()) {
1063       assert(!ExternalUses.size() && "We should not have any external users");
1064     }
1065     return INT_MAX;
1066   }
1067
1068   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1069
1070   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1071     int C = getEntryCost(&VectorizableTree[i]);
1072     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1073           << *VectorizableTree[i].Scalars[0] << " .\n");
1074     Cost += C;
1075   }
1076
1077   int ExtractCost = 0;
1078   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1079        I != E; ++I) {
1080
1081     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1082     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1083                                            I->Lane);
1084   }
1085
1086
1087   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1088   return  Cost + ExtractCost;
1089 }
1090
1091 int BoUpSLP::getGatherCost(Type *Ty) {
1092   int Cost = 0;
1093   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1094     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1095   return Cost;
1096 }
1097
1098 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1099   // Find the type of the operands in VL.
1100   Type *ScalarTy = VL[0]->getType();
1101   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1102     ScalarTy = SI->getValueOperand()->getType();
1103   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1104   // Find the cost of inserting/extracting values from the vector.
1105   return getGatherCost(VecTy);
1106 }
1107
1108 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1109   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1110     return AA->getLocation(SI);
1111   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1112     return AA->getLocation(LI);
1113   return AliasAnalysis::Location();
1114 }
1115
1116 Value *BoUpSLP::getPointerOperand(Value *I) {
1117   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1118     return LI->getPointerOperand();
1119   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1120     return SI->getPointerOperand();
1121   return 0;
1122 }
1123
1124 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1125   if (LoadInst *L = dyn_cast<LoadInst>(I))
1126     return L->getPointerAddressSpace();
1127   if (StoreInst *S = dyn_cast<StoreInst>(I))
1128     return S->getPointerAddressSpace();
1129   return -1;
1130 }
1131
1132 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1133   Value *PtrA = getPointerOperand(A);
1134   Value *PtrB = getPointerOperand(B);
1135   unsigned ASA = getAddressSpaceOperand(A);
1136   unsigned ASB = getAddressSpaceOperand(B);
1137
1138   // Check that the address spaces match and that the pointers are valid.
1139   if (!PtrA || !PtrB || (ASA != ASB))
1140     return false;
1141
1142   // Make sure that A and B are different pointers of the same type.
1143   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1144     return false;
1145
1146   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1147   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1148   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1149
1150   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1151   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1152   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1153
1154   APInt OffsetDelta = OffsetB - OffsetA;
1155
1156   // Check if they are based on the same pointer. That makes the offsets
1157   // sufficient.
1158   if (PtrA == PtrB)
1159     return OffsetDelta == Size;
1160
1161   // Compute the necessary base pointer delta to have the necessary final delta
1162   // equal to the size.
1163   APInt BaseDelta = Size - OffsetDelta;
1164
1165   // Otherwise compute the distance with SCEV between the base pointers.
1166   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1167   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1168   const SCEV *C = SE->getConstant(BaseDelta);
1169   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1170   return X == PtrSCEVB;
1171 }
1172
1173 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1174   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1175   BasicBlock::iterator I = Src, E = Dst;
1176   /// Scan all of the instruction from SRC to DST and check if
1177   /// the source may alias.
1178   for (++I; I != E; ++I) {
1179     // Ignore store instructions that are marked as 'ignore'.
1180     if (MemBarrierIgnoreList.count(I))
1181       continue;
1182     if (Src->mayWriteToMemory()) /* Write */ {
1183       if (!I->mayReadOrWriteMemory())
1184         continue;
1185     } else /* Read */ {
1186       if (!I->mayWriteToMemory())
1187         continue;
1188     }
1189     AliasAnalysis::Location A = getLocation(&*I);
1190     AliasAnalysis::Location B = getLocation(Src);
1191
1192     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1193       return I;
1194   }
1195   return 0;
1196 }
1197
1198 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1199   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1200   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1201   BlockNumbering &BN = BlocksNumbers[BB];
1202
1203   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1204   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1205     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1206   return MaxIdx;
1207 }
1208
1209 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1210   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1211   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1212   BlockNumbering &BN = BlocksNumbers[BB];
1213
1214   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1215   for (unsigned i = 1, e = VL.size(); i < e; ++i)
1216     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1217   Instruction *I = BN.getInstruction(MaxIdx);
1218   assert(I && "bad location");
1219   return I;
1220 }
1221
1222 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1223   Instruction *VL0 = cast<Instruction>(VL[0]);
1224   Instruction *LastInst = getLastInstruction(VL);
1225   BasicBlock::iterator NextInst = LastInst;
1226   ++NextInst;
1227   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1228   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1229 }
1230
1231 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1232   Value *Vec = UndefValue::get(Ty);
1233   // Generate the 'InsertElement' instruction.
1234   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1235     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1236     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1237       GatherSeq.insert(Insrt);
1238
1239       // Add to our 'need-to-extract' list.
1240       if (ScalarToTreeEntry.count(VL[i])) {
1241         int Idx = ScalarToTreeEntry[VL[i]];
1242         TreeEntry *E = &VectorizableTree[Idx];
1243         // Find which lane we need to extract.
1244         int FoundLane = -1;
1245         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1246           // Is this the lane of the scalar that we are looking for ?
1247           if (E->Scalars[Lane] == VL[i]) {
1248             FoundLane = Lane;
1249             break;
1250           }
1251         }
1252         assert(FoundLane >= 0 && "Could not find the correct lane");
1253         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1254       }
1255     }
1256   }
1257
1258   return Vec;
1259 }
1260
1261 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1262   SmallDenseMap<Value*, int>::const_iterator Entry
1263     = ScalarToTreeEntry.find(VL[0]);
1264   if (Entry != ScalarToTreeEntry.end()) {
1265     int Idx = Entry->second;
1266     const TreeEntry *En = &VectorizableTree[Idx];
1267     if (En->isSame(VL) && En->VectorizedValue)
1268       return En->VectorizedValue;
1269   }
1270   return 0;
1271 }
1272
1273 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1274   if (ScalarToTreeEntry.count(VL[0])) {
1275     int Idx = ScalarToTreeEntry[VL[0]];
1276     TreeEntry *E = &VectorizableTree[Idx];
1277     if (E->isSame(VL))
1278       return vectorizeTree(E);
1279   }
1280
1281   Type *ScalarTy = VL[0]->getType();
1282   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1283     ScalarTy = SI->getValueOperand()->getType();
1284   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1285
1286   return Gather(VL, VecTy);
1287 }
1288
1289 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1290   IRBuilder<>::InsertPointGuard Guard(Builder);
1291
1292   if (E->VectorizedValue) {
1293     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1294     return E->VectorizedValue;
1295   }
1296
1297   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1298   Type *ScalarTy = VL0->getType();
1299   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1300     ScalarTy = SI->getValueOperand()->getType();
1301   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1302
1303   if (E->NeedToGather) {
1304     setInsertPointAfterBundle(E->Scalars);
1305     return Gather(E->Scalars, VecTy);
1306   }
1307
1308   unsigned Opcode = VL0->getOpcode();
1309   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1310
1311   switch (Opcode) {
1312     case Instruction::PHI: {
1313       PHINode *PH = dyn_cast<PHINode>(VL0);
1314       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1315       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1316       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1317       E->VectorizedValue = NewPhi;
1318
1319       // PHINodes may have multiple entries from the same block. We want to
1320       // visit every block once.
1321       SmallSet<BasicBlock*, 4> VisitedBBs;
1322
1323       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1324         ValueList Operands;
1325         BasicBlock *IBB = PH->getIncomingBlock(i);
1326
1327         if (!VisitedBBs.insert(IBB)) {
1328           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1329           continue;
1330         }
1331
1332         // Prepare the operand vector.
1333         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1334           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1335                              getIncomingValueForBlock(IBB));
1336
1337         Builder.SetInsertPoint(IBB->getTerminator());
1338         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1339         Value *Vec = vectorizeTree(Operands);
1340         NewPhi->addIncoming(Vec, IBB);
1341       }
1342
1343       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1344              "Invalid number of incoming values");
1345       return NewPhi;
1346     }
1347
1348     case Instruction::ExtractElement: {
1349       if (CanReuseExtract(E->Scalars)) {
1350         Value *V = VL0->getOperand(0);
1351         E->VectorizedValue = V;
1352         return V;
1353       }
1354       return Gather(E->Scalars, VecTy);
1355     }
1356     case Instruction::ZExt:
1357     case Instruction::SExt:
1358     case Instruction::FPToUI:
1359     case Instruction::FPToSI:
1360     case Instruction::FPExt:
1361     case Instruction::PtrToInt:
1362     case Instruction::IntToPtr:
1363     case Instruction::SIToFP:
1364     case Instruction::UIToFP:
1365     case Instruction::Trunc:
1366     case Instruction::FPTrunc:
1367     case Instruction::BitCast: {
1368       ValueList INVL;
1369       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1370         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1371
1372       setInsertPointAfterBundle(E->Scalars);
1373
1374       Value *InVec = vectorizeTree(INVL);
1375
1376       if (Value *V = alreadyVectorized(E->Scalars))
1377         return V;
1378
1379       CastInst *CI = dyn_cast<CastInst>(VL0);
1380       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1381       E->VectorizedValue = V;
1382       return V;
1383     }
1384     case Instruction::FCmp:
1385     case Instruction::ICmp: {
1386       ValueList LHSV, RHSV;
1387       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1388         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1389         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1390       }
1391
1392       setInsertPointAfterBundle(E->Scalars);
1393
1394       Value *L = vectorizeTree(LHSV);
1395       Value *R = vectorizeTree(RHSV);
1396
1397       if (Value *V = alreadyVectorized(E->Scalars))
1398         return V;
1399
1400       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1401       Value *V;
1402       if (Opcode == Instruction::FCmp)
1403         V = Builder.CreateFCmp(P0, L, R);
1404       else
1405         V = Builder.CreateICmp(P0, L, R);
1406
1407       E->VectorizedValue = V;
1408       return V;
1409     }
1410     case Instruction::Select: {
1411       ValueList TrueVec, FalseVec, CondVec;
1412       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1413         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1414         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1415         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1416       }
1417
1418       setInsertPointAfterBundle(E->Scalars);
1419
1420       Value *Cond = vectorizeTree(CondVec);
1421       Value *True = vectorizeTree(TrueVec);
1422       Value *False = vectorizeTree(FalseVec);
1423
1424       if (Value *V = alreadyVectorized(E->Scalars))
1425         return V;
1426
1427       Value *V = Builder.CreateSelect(Cond, True, False);
1428       E->VectorizedValue = V;
1429       return V;
1430     }
1431     case Instruction::Add:
1432     case Instruction::FAdd:
1433     case Instruction::Sub:
1434     case Instruction::FSub:
1435     case Instruction::Mul:
1436     case Instruction::FMul:
1437     case Instruction::UDiv:
1438     case Instruction::SDiv:
1439     case Instruction::FDiv:
1440     case Instruction::URem:
1441     case Instruction::SRem:
1442     case Instruction::FRem:
1443     case Instruction::Shl:
1444     case Instruction::LShr:
1445     case Instruction::AShr:
1446     case Instruction::And:
1447     case Instruction::Or:
1448     case Instruction::Xor: {
1449       ValueList LHSVL, RHSVL;
1450       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1451         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1452       else
1453         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1454           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1455           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1456         }
1457
1458       setInsertPointAfterBundle(E->Scalars);
1459
1460       Value *LHS = vectorizeTree(LHSVL);
1461       Value *RHS = vectorizeTree(RHSVL);
1462
1463       if (LHS == RHS && isa<Instruction>(LHS)) {
1464         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1465       }
1466
1467       if (Value *V = alreadyVectorized(E->Scalars))
1468         return V;
1469
1470       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1471       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1472       E->VectorizedValue = V;
1473       return V;
1474     }
1475     case Instruction::Load: {
1476       // Loads are inserted at the head of the tree because we don't want to
1477       // sink them all the way down past store instructions.
1478       setInsertPointAfterBundle(E->Scalars);
1479
1480       LoadInst *LI = cast<LoadInst>(VL0);
1481       unsigned AS = LI->getPointerAddressSpace();
1482
1483       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1484                                             VecTy->getPointerTo(AS));
1485       unsigned Alignment = LI->getAlignment();
1486       LI = Builder.CreateLoad(VecPtr);
1487       LI->setAlignment(Alignment);
1488       E->VectorizedValue = LI;
1489       return LI;
1490     }
1491     case Instruction::Store: {
1492       StoreInst *SI = cast<StoreInst>(VL0);
1493       unsigned Alignment = SI->getAlignment();
1494       unsigned AS = SI->getPointerAddressSpace();
1495
1496       ValueList ValueOp;
1497       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1498         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1499
1500       setInsertPointAfterBundle(E->Scalars);
1501
1502       Value *VecValue = vectorizeTree(ValueOp);
1503       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1504                                             VecTy->getPointerTo(AS));
1505       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1506       S->setAlignment(Alignment);
1507       E->VectorizedValue = S;
1508       return S;
1509     }
1510     default:
1511     llvm_unreachable("unknown inst");
1512   }
1513   return 0;
1514 }
1515
1516 Value *BoUpSLP::vectorizeTree() {
1517   Builder.SetInsertPoint(F->getEntryBlock().begin());
1518   vectorizeTree(&VectorizableTree[0]);
1519
1520   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1521
1522   // Extract all of the elements with the external uses.
1523   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1524        it != e; ++it) {
1525     Value *Scalar = it->Scalar;
1526     llvm::User *User = it->User;
1527
1528     // Skip users that we already RAUW. This happens when one instruction
1529     // has multiple uses of the same value.
1530     if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1531         Scalar->use_end())
1532       continue;
1533     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1534
1535     int Idx = ScalarToTreeEntry[Scalar];
1536     TreeEntry *E = &VectorizableTree[Idx];
1537     assert(!E->NeedToGather && "Extracting from a gather list");
1538
1539     Value *Vec = E->VectorizedValue;
1540     assert(Vec && "Can't find vectorizable value");
1541
1542     Value *Lane = Builder.getInt32(it->Lane);
1543     // Generate extracts for out-of-tree users.
1544     // Find the insertion point for the extractelement lane.
1545     if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1546       Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1547       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1548       User->replaceUsesOfWith(Scalar, Ex);
1549     } else if (isa<Instruction>(Vec)){
1550       if (PHINode *PH = dyn_cast<PHINode>(User)) {
1551         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1552           if (PH->getIncomingValue(i) == Scalar) {
1553             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1554             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1555             PH->setOperand(i, Ex);
1556           }
1557         }
1558       } else {
1559         Builder.SetInsertPoint(cast<Instruction>(User));
1560         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1561         User->replaceUsesOfWith(Scalar, Ex);
1562      }
1563     } else {
1564       Builder.SetInsertPoint(F->getEntryBlock().begin());
1565       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1566       User->replaceUsesOfWith(Scalar, Ex);
1567     }
1568
1569     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1570   }
1571
1572   // For each vectorized value:
1573   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1574     TreeEntry *Entry = &VectorizableTree[EIdx];
1575
1576     // For each lane:
1577     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1578       Value *Scalar = Entry->Scalars[Lane];
1579
1580       // No need to handle users of gathered values.
1581       if (Entry->NeedToGather)
1582         continue;
1583
1584       assert(Entry->VectorizedValue && "Can't find vectorizable value");
1585
1586       Type *Ty = Scalar->getType();
1587       if (!Ty->isVoidTy()) {
1588         for (Value::use_iterator User = Scalar->use_begin(),
1589              UE = Scalar->use_end(); User != UE; ++User) {
1590           DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1591           assert(!MustGather.count(*User) &&
1592                  "Replacing gathered value with undef");
1593
1594           assert((ScalarToTreeEntry.count(*User) ||
1595                   // It is legal to replace the reduction users by undef.
1596                   (RdxOps && RdxOps->count(*User))) &&
1597                  "Replacing out-of-tree value with undef");
1598         }
1599         Value *Undef = UndefValue::get(Ty);
1600         Scalar->replaceAllUsesWith(Undef);
1601       }
1602       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1603       cast<Instruction>(Scalar)->eraseFromParent();
1604     }
1605   }
1606
1607   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1608     BlocksNumbers[it].forget();
1609   }
1610   Builder.ClearInsertionPoint();
1611
1612   return VectorizableTree[0].VectorizedValue;
1613 }
1614
1615 void BoUpSLP::optimizeGatherSequence() {
1616   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1617         << " gather sequences instructions.\n");
1618   // LICM InsertElementInst sequences.
1619   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1620        e = GatherSeq.end(); it != e; ++it) {
1621     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1622
1623     if (!Insert)
1624       continue;
1625
1626     // Check if this block is inside a loop.
1627     Loop *L = LI->getLoopFor(Insert->getParent());
1628     if (!L)
1629       continue;
1630
1631     // Check if it has a preheader.
1632     BasicBlock *PreHeader = L->getLoopPreheader();
1633     if (!PreHeader)
1634       continue;
1635
1636     // If the vector or the element that we insert into it are
1637     // instructions that are defined in this basic block then we can't
1638     // hoist this instruction.
1639     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1640     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1641     if (CurrVec && L->contains(CurrVec))
1642       continue;
1643     if (NewElem && L->contains(NewElem))
1644       continue;
1645
1646     // We can hoist this instruction. Move it to the pre-header.
1647     Insert->moveBefore(PreHeader->getTerminator());
1648   }
1649
1650   // Perform O(N^2) search over the gather sequences and merge identical
1651   // instructions. TODO: We can further optimize this scan if we split the
1652   // instructions into different buckets based on the insert lane.
1653   SmallPtrSet<Instruction*, 16> Visited;
1654   SmallVector<Instruction*, 16> ToRemove;
1655   ReversePostOrderTraversal<Function*> RPOT(F);
1656   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1657        E = RPOT.end(); I != E; ++I) {
1658     BasicBlock *BB = *I;
1659     // For all instructions in the function:
1660     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1661       Instruction *In = it;
1662       if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) ||
1663           !GatherSeq.count(In))
1664         continue;
1665
1666       // Check if we can replace this instruction with any of the
1667       // visited instructions.
1668       for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1669            ve = Visited.end(); v != ve; ++v) {
1670         if (In->isIdenticalTo(*v) &&
1671             DT->dominates((*v)->getParent(), In->getParent())) {
1672           In->replaceAllUsesWith(*v);
1673           ToRemove.push_back(In);
1674           In = 0;
1675           break;
1676         }
1677       }
1678       if (In)
1679         Visited.insert(In);
1680     }
1681   }
1682
1683   // Erase all of the instructions that we RAUWed.
1684   for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1685        ve = ToRemove.end(); v != ve; ++v) {
1686     assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1687     (*v)->eraseFromParent();
1688   }
1689 }
1690
1691 /// The SLPVectorizer Pass.
1692 struct SLPVectorizer : public FunctionPass {
1693   typedef SmallVector<StoreInst *, 8> StoreList;
1694   typedef MapVector<Value *, StoreList> StoreListMap;
1695
1696   /// Pass identification, replacement for typeid
1697   static char ID;
1698
1699   explicit SLPVectorizer() : FunctionPass(ID) {
1700     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1701   }
1702
1703   ScalarEvolution *SE;
1704   DataLayout *DL;
1705   TargetTransformInfo *TTI;
1706   AliasAnalysis *AA;
1707   LoopInfo *LI;
1708   DominatorTree *DT;
1709
1710   virtual bool runOnFunction(Function &F) {
1711     SE = &getAnalysis<ScalarEvolution>();
1712     DL = getAnalysisIfAvailable<DataLayout>();
1713     TTI = &getAnalysis<TargetTransformInfo>();
1714     AA = &getAnalysis<AliasAnalysis>();
1715     LI = &getAnalysis<LoopInfo>();
1716     DT = &getAnalysis<DominatorTree>();
1717
1718     StoreRefs.clear();
1719     bool Changed = false;
1720
1721     // If the target claims to have no vector registers don't attempt
1722     // vectorization.
1723     if (!TTI->getNumberOfRegisters(true))
1724       return false;
1725
1726     // Must have DataLayout. We can't require it because some tests run w/o
1727     // triple.
1728     if (!DL)
1729       return false;
1730
1731     // Don't vectorize when the attribute NoImplicitFloat is used.
1732     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1733       return false;
1734
1735     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1736
1737     // Use the bollom up slp vectorizer to construct chains that start with
1738     // he store instructions.
1739     BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1740
1741     // Scan the blocks in the function in post order.
1742     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1743          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1744       BasicBlock *BB = *it;
1745
1746       // Vectorize trees that end at stores.
1747       if (unsigned count = collectStores(BB, R)) {
1748         (void)count;
1749         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1750         Changed |= vectorizeStoreChains(R);
1751       }
1752
1753       // Vectorize trees that end at reductions.
1754       Changed |= vectorizeChainsInBlock(BB, R);
1755     }
1756
1757     if (Changed) {
1758       R.optimizeGatherSequence();
1759       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1760       DEBUG(verifyFunction(F));
1761     }
1762     return Changed;
1763   }
1764
1765   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1766     FunctionPass::getAnalysisUsage(AU);
1767     AU.addRequired<ScalarEvolution>();
1768     AU.addRequired<AliasAnalysis>();
1769     AU.addRequired<TargetTransformInfo>();
1770     AU.addRequired<LoopInfo>();
1771     AU.addRequired<DominatorTree>();
1772     AU.addPreserved<LoopInfo>();
1773     AU.addPreserved<DominatorTree>();
1774     AU.setPreservesCFG();
1775   }
1776
1777 private:
1778
1779   /// \brief Collect memory references and sort them according to their base
1780   /// object. We sort the stores to their base objects to reduce the cost of the
1781   /// quadratic search on the stores. TODO: We can further reduce this cost
1782   /// if we flush the chain creation every time we run into a memory barrier.
1783   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1784
1785   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1786   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1787
1788   /// \brief Try to vectorize a list of operands.
1789   /// \returns true if a value was vectorized.
1790   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1791
1792   /// \brief Try to vectorize a chain that may start at the operands of \V;
1793   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1794
1795   /// \brief Vectorize the stores that were collected in StoreRefs.
1796   bool vectorizeStoreChains(BoUpSLP &R);
1797
1798   /// \brief Scan the basic block and look for patterns that are likely to start
1799   /// a vectorization chain.
1800   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1801
1802   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1803                            BoUpSLP &R);
1804
1805   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1806                        BoUpSLP &R);
1807 private:
1808   StoreListMap StoreRefs;
1809 };
1810
1811 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1812                                           int CostThreshold, BoUpSLP &R) {
1813   unsigned ChainLen = Chain.size();
1814   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1815         << "\n");
1816   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1817   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1818   unsigned VF = MinVecRegSize / Sz;
1819
1820   if (!isPowerOf2_32(Sz) || VF < 2)
1821     return false;
1822
1823   bool Changed = false;
1824   // Look for profitable vectorizable trees at all offsets, starting at zero.
1825   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1826     if (i + VF > e)
1827       break;
1828     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1829           << "\n");
1830     ArrayRef<Value *> Operands = Chain.slice(i, VF);
1831
1832     R.buildTree(Operands);
1833
1834     int Cost = R.getTreeCost();
1835
1836     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1837     if (Cost < CostThreshold) {
1838       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1839       R.vectorizeTree();
1840
1841       // Move to the next bundle.
1842       i += VF - 1;
1843       Changed = true;
1844     }
1845   }
1846
1847     return Changed;
1848 }
1849
1850 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1851                                     int costThreshold, BoUpSLP &R) {
1852   SetVector<Value *> Heads, Tails;
1853   SmallDenseMap<Value *, Value *> ConsecutiveChain;
1854
1855   // We may run into multiple chains that merge into a single chain. We mark the
1856   // stores that we vectorized so that we don't visit the same store twice.
1857   BoUpSLP::ValueSet VectorizedStores;
1858   bool Changed = false;
1859
1860   // Do a quadratic search on all of the given stores and find
1861   // all of the pairs of stores that follow each other.
1862   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1863     for (unsigned j = 0; j < e; ++j) {
1864       if (i == j)
1865         continue;
1866
1867       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1868         Tails.insert(Stores[j]);
1869         Heads.insert(Stores[i]);
1870         ConsecutiveChain[Stores[i]] = Stores[j];
1871       }
1872     }
1873   }
1874
1875   // For stores that start but don't end a link in the chain:
1876   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1877        it != e; ++it) {
1878     if (Tails.count(*it))
1879       continue;
1880
1881     // We found a store instr that starts a chain. Now follow the chain and try
1882     // to vectorize it.
1883     BoUpSLP::ValueList Operands;
1884     Value *I = *it;
1885     // Collect the chain into a list.
1886     while (Tails.count(I) || Heads.count(I)) {
1887       if (VectorizedStores.count(I))
1888         break;
1889       Operands.push_back(I);
1890       // Move to the next value in the chain.
1891       I = ConsecutiveChain[I];
1892     }
1893
1894     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1895
1896     // Mark the vectorized stores so that we don't vectorize them again.
1897     if (Vectorized)
1898       VectorizedStores.insert(Operands.begin(), Operands.end());
1899     Changed |= Vectorized;
1900   }
1901
1902   return Changed;
1903 }
1904
1905
1906 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1907   unsigned count = 0;
1908   StoreRefs.clear();
1909   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1910     StoreInst *SI = dyn_cast<StoreInst>(it);
1911     if (!SI)
1912       continue;
1913
1914     // Check that the pointer points to scalars.
1915     Type *Ty = SI->getValueOperand()->getType();
1916     if (Ty->isAggregateType() || Ty->isVectorTy())
1917       return 0;
1918
1919     // Find the base pointer.
1920     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
1921
1922     // Save the store locations.
1923     StoreRefs[Ptr].push_back(SI);
1924     count++;
1925   }
1926   return count;
1927 }
1928
1929 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1930   if (!A || !B)
1931     return false;
1932   Value *VL[] = { A, B };
1933   return tryToVectorizeList(VL, R);
1934 }
1935
1936 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
1937   if (VL.size() < 2)
1938     return false;
1939
1940   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1941
1942   // Check that all of the parts are scalar instructions of the same type.
1943   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1944   if (!I0)
1945     return false;
1946
1947   unsigned Opcode0 = I0->getOpcode();
1948   
1949   Type *Ty0 = I0->getType();
1950   unsigned Sz = DL->getTypeSizeInBits(Ty0);
1951   unsigned VF = MinVecRegSize / Sz;
1952
1953   for (int i = 0, e = VL.size(); i < e; ++i) {
1954     Type *Ty = VL[i]->getType();
1955     if (Ty->isAggregateType() || Ty->isVectorTy())
1956       return false;
1957     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1958     if (!Inst || Inst->getOpcode() != Opcode0)
1959       return false;
1960   }
1961
1962   bool Changed = false;
1963     
1964   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1965     unsigned OpsWidth = 0;
1966       
1967     if (i + VF > e) 
1968       OpsWidth = e - i;
1969     else
1970       OpsWidth = VF;
1971
1972     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
1973       break;
1974
1975     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n");
1976     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
1977       
1978     R.buildTree(Ops);
1979     int Cost = R.getTreeCost();
1980        
1981     if (Cost < -SLPCostThreshold) {
1982       DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
1983       R.vectorizeTree();
1984         
1985       // Move to the next bundle.
1986       i += VF - 1;
1987       Changed = true;
1988     }
1989   }
1990     
1991   return Changed; 
1992 }
1993
1994 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1995   if (!V)
1996     return false;
1997
1998   // Try to vectorize V.
1999   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2000     return true;
2001
2002   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2003   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2004   // Try to skip B.
2005   if (B && B->hasOneUse()) {
2006     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2007     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2008     if (tryToVectorizePair(A, B0, R)) {
2009       B->moveBefore(V);
2010       return true;
2011     }
2012     if (tryToVectorizePair(A, B1, R)) {
2013       B->moveBefore(V);
2014       return true;
2015     }
2016   }
2017
2018   // Try to skip A.
2019   if (A && A->hasOneUse()) {
2020     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2021     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2022     if (tryToVectorizePair(A0, B, R)) {
2023       A->moveBefore(V);
2024       return true;
2025     }
2026     if (tryToVectorizePair(A1, B, R)) {
2027       A->moveBefore(V);
2028       return true;
2029     }
2030   }
2031   return 0;
2032 }
2033
2034 /// \brief Generate a shuffle mask to be used in a reduction tree.
2035 ///
2036 /// \param VecLen The length of the vector to be reduced.
2037 /// \param NumEltsToRdx The number of elements that should be reduced in the
2038 ///        vector.
2039 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2040 ///        reduction. A pairwise reduction will generate a mask of 
2041 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
2042 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2043 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2044 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2045                                    bool IsPairwise, bool IsLeft,
2046                                    IRBuilder<> &Builder) {
2047   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2048
2049   SmallVector<Constant *, 32> ShuffleMask(
2050       VecLen, UndefValue::get(Builder.getInt32Ty()));
2051
2052   if (IsPairwise)
2053     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2054     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2055       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2056   else
2057     // Move the upper half of the vector to the lower half.
2058     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2059       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2060
2061   return ConstantVector::get(ShuffleMask);
2062 }
2063
2064
2065 /// Model horizontal reductions.
2066 ///
2067 /// A horizontal reduction is a tree of reduction operations (currently add and
2068 /// fadd) that has operations that can be put into a vector as its leaf.
2069 /// For example, this tree:
2070 ///
2071 /// mul mul mul mul
2072 ///  \  /    \  /
2073 ///   +       +
2074 ///    \     /
2075 ///       +
2076 /// This tree has "mul" as its reduced values and "+" as its reduction
2077 /// operations. A reduction might be feeding into a store or a binary operation
2078 /// feeding a phi.
2079 ///    ...
2080 ///    \  /
2081 ///     +
2082 ///     |
2083 ///  phi +=
2084 ///
2085 ///  Or:
2086 ///    ...
2087 ///    \  /
2088 ///     +
2089 ///     |
2090 ///   *p =
2091 ///
2092 class HorizontalReduction {
2093   SmallPtrSet<Value *, 16> ReductionOps;
2094   SmallVector<Value *, 32> ReducedVals;
2095
2096   BinaryOperator *ReductionRoot;
2097   PHINode *ReductionPHI;
2098
2099   /// The opcode of the reduction.
2100   unsigned ReductionOpcode;
2101   /// The opcode of the values we perform a reduction on.
2102   unsigned ReducedValueOpcode;
2103   /// The width of one full horizontal reduction operation.
2104   unsigned ReduxWidth;
2105   /// Should we model this reduction as a pairwise reduction tree or a tree that
2106   /// splits the vector in halves and adds those halves.
2107   bool IsPairwiseReduction;
2108
2109 public:
2110   HorizontalReduction()
2111     : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2112     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2113
2114   /// \brief Try to find a reduction tree.
2115   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2116                                  DataLayout *DL) {
2117     assert((!Phi ||
2118             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2119            "Thi phi needs to use the binary operator");
2120
2121     // We could have a initial reductions that is not an add.
2122     //  r *= v1 + v2 + v3 + v4
2123     // In such a case start looking for a tree rooted in the first '+'.
2124     if (Phi) {
2125       if (B->getOperand(0) == Phi) {
2126         Phi = 0;
2127         B = dyn_cast<BinaryOperator>(B->getOperand(1));
2128       } else if (B->getOperand(1) == Phi) {
2129         Phi = 0;
2130         B = dyn_cast<BinaryOperator>(B->getOperand(0));
2131       }
2132     }
2133
2134     if (!B)
2135       return false;
2136
2137     Type *Ty = B->getType();
2138     if (Ty->isVectorTy())
2139       return false;
2140
2141     ReductionOpcode = B->getOpcode();
2142     ReducedValueOpcode = 0;
2143     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2144     ReductionRoot = B;
2145     ReductionPHI = Phi;
2146
2147     if (ReduxWidth < 4)
2148       return false;
2149
2150     // We currently only support adds.
2151     if (ReductionOpcode != Instruction::Add &&
2152         ReductionOpcode != Instruction::FAdd)
2153       return false;
2154
2155     // Post order traverse the reduction tree starting at B. We only handle true
2156     // trees containing only binary operators.
2157     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2158     Stack.push_back(std::make_pair(B, 0));
2159     while (!Stack.empty()) {
2160       BinaryOperator *TreeN = Stack.back().first;
2161       unsigned EdgeToVist = Stack.back().second++;
2162       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2163
2164       // Only handle trees in the current basic block.
2165       if (TreeN->getParent() != B->getParent())
2166         return false;
2167
2168       // Each tree node needs to have one user except for the ultimate
2169       // reduction.
2170       if (!TreeN->hasOneUse() && TreeN != B)
2171         return false;
2172
2173       // Postorder vist.
2174       if (EdgeToVist == 2 || IsReducedValue) {
2175         if (IsReducedValue) {
2176           // Make sure that the opcodes of the operations that we are going to
2177           // reduce match.
2178           if (!ReducedValueOpcode)
2179             ReducedValueOpcode = TreeN->getOpcode();
2180           else if (ReducedValueOpcode != TreeN->getOpcode())
2181             return false;
2182           ReducedVals.push_back(TreeN);
2183         } else {
2184           // We need to be able to reassociate the adds.
2185           if (!TreeN->isAssociative())
2186             return false;
2187           ReductionOps.insert(TreeN);
2188         }
2189         // Retract.
2190         Stack.pop_back();
2191         continue;
2192       }
2193
2194       // Visit left or right.
2195       Value *NextV = TreeN->getOperand(EdgeToVist);
2196       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2197       if (Next)
2198         Stack.push_back(std::make_pair(Next, 0));
2199       else if (NextV != Phi)
2200         return false;
2201     }
2202     return true;
2203   }
2204
2205   /// \brief Attempt to vectorize the tree found by
2206   /// matchAssociativeReduction.
2207   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2208     if (ReducedVals.empty())
2209       return false;
2210
2211     unsigned NumReducedVals = ReducedVals.size();
2212     if (NumReducedVals < ReduxWidth)
2213       return false;
2214
2215     Value *VectorizedTree = 0;
2216     IRBuilder<> Builder(ReductionRoot);
2217     FastMathFlags Unsafe;
2218     Unsafe.setUnsafeAlgebra();
2219     Builder.SetFastMathFlags(Unsafe);
2220     unsigned i = 0;
2221
2222     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2223       ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2224       V.buildTree(ValsToReduce, &ReductionOps);
2225
2226       // Estimate cost.
2227       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2228       if (Cost >= -SLPCostThreshold)
2229         break;
2230
2231       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2232                    << ". (HorRdx)\n");
2233
2234       // Vectorize a tree.
2235       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2236       Value *VectorizedRoot = V.vectorizeTree();
2237
2238       // Emit a reduction.
2239       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2240       if (VectorizedTree) {
2241         Builder.SetCurrentDebugLocation(Loc);
2242         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2243                                      ReducedSubTree, "bin.rdx");
2244       } else
2245         VectorizedTree = ReducedSubTree;
2246     }
2247
2248     if (VectorizedTree) {
2249       // Finish the reduction.
2250       for (; i < NumReducedVals; ++i) {
2251         Builder.SetCurrentDebugLocation(
2252           cast<Instruction>(ReducedVals[i])->getDebugLoc());
2253         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2254                                      ReducedVals[i]);
2255       }
2256       // Update users.
2257       if (ReductionPHI) {
2258         assert(ReductionRoot != NULL && "Need a reduction operation");
2259         ReductionRoot->setOperand(0, VectorizedTree);
2260         ReductionRoot->setOperand(1, ReductionPHI);
2261       } else
2262         ReductionRoot->replaceAllUsesWith(VectorizedTree);
2263     }
2264     return VectorizedTree != 0;
2265   }
2266
2267 private:
2268
2269   /// \brief Calcuate the cost of a reduction.
2270   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2271     Type *ScalarTy = FirstReducedVal->getType();
2272     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2273
2274     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2275     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2276
2277     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2278     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2279
2280     int ScalarReduxCost =
2281         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2282
2283     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2284                  << " for reduction that starts with " << *FirstReducedVal
2285                  << " (It is a "
2286                  << (IsPairwiseReduction ? "pairwise" : "splitting")
2287                  << " reduction)\n");
2288
2289     return VecReduxCost - ScalarReduxCost;
2290   }
2291
2292   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2293                             Value *R, const Twine &Name = "") {
2294     if (Opcode == Instruction::FAdd)
2295       return Builder.CreateFAdd(L, R, Name);
2296     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2297   }
2298
2299   /// \brief Emit a horizontal reduction of the vectorized value.
2300   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2301     assert(VectorizedValue && "Need to have a vectorized tree node");
2302     Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2303     assert(isPowerOf2_32(ReduxWidth) &&
2304            "We only handle power-of-two reductions for now");
2305
2306     Value *TmpVec = ValToReduce;
2307     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2308       if (IsPairwiseReduction) {
2309         Value *LeftMask =
2310           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2311         Value *RightMask =
2312           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2313
2314         Value *LeftShuf = Builder.CreateShuffleVector(
2315           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2316         Value *RightShuf = Builder.CreateShuffleVector(
2317           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2318           "rdx.shuf.r");
2319         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2320                              "bin.rdx");
2321       } else {
2322         Value *UpperHalf =
2323           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2324         Value *Shuf = Builder.CreateShuffleVector(
2325           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2326         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2327       }
2328     }
2329
2330     // The result is in the first element of the vector.
2331     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2332   }
2333 };
2334
2335 /// \brief Recognize construction of vectors like
2336 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2337 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2338 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2339 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2340 ///
2341 /// Returns true if it matches
2342 ///
2343 static bool findBuildVector(InsertElementInst *IE,
2344                             SmallVectorImpl<Value *> &Ops) {
2345   if (!isa<UndefValue>(IE->getOperand(0)))
2346     return false;
2347
2348   while (true) {
2349     Ops.push_back(IE->getOperand(1));
2350
2351     if (IE->use_empty())
2352       return false;
2353
2354     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2355     if (!NextUse)
2356       return true;
2357
2358     // If this isn't the final use, make sure the next insertelement is the only
2359     // use. It's OK if the final constructed vector is used multiple times
2360     if (!IE->hasOneUse())
2361       return false;
2362
2363     IE = NextUse;
2364   }
2365
2366   return false;
2367 }
2368
2369 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2370   return V->getType() < V2->getType();
2371 }
2372
2373 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2374   bool Changed = false;
2375   SmallVector<Value *, 4> Incoming;
2376   SmallSet<Value *, 16> VisitedInstrs;
2377
2378   bool HaveVectorizedPhiNodes = true;
2379   while (HaveVectorizedPhiNodes) {
2380     HaveVectorizedPhiNodes = false;
2381
2382     // Collect the incoming values from the PHIs.
2383     Incoming.clear();
2384     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2385          ++instr) {
2386       PHINode *P = dyn_cast<PHINode>(instr);
2387       if (!P)
2388         break;
2389
2390       if (!VisitedInstrs.count(P))
2391         Incoming.push_back(P);
2392     }
2393
2394     // Sort by type.
2395     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2396
2397     // Try to vectorize elements base on their type.
2398     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2399                                            E = Incoming.end();
2400          IncIt != E;) {
2401
2402       // Look for the next elements with the same type.
2403       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2404       while (SameTypeIt != E &&
2405              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2406         VisitedInstrs.insert(*SameTypeIt);
2407         ++SameTypeIt;
2408       }
2409
2410       // Try to vectorize them.
2411       unsigned NumElts = (SameTypeIt - IncIt);
2412       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2413       if (NumElts > 1 &&
2414           tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2415         // Success start over because instructions might have been changed.
2416         HaveVectorizedPhiNodes = true;
2417         Changed = true;
2418         break;
2419       }
2420
2421       // Start over at the next instruction of a differnt type (or the end).
2422       IncIt = SameTypeIt;
2423     }
2424   }
2425
2426   VisitedInstrs.clear();
2427
2428   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2429     // We may go through BB multiple times so skip the one we have checked.
2430     if (!VisitedInstrs.insert(it))
2431       continue;
2432
2433     if (isa<DbgInfoIntrinsic>(it))
2434       continue;
2435
2436     // Try to vectorize reductions that use PHINodes.
2437     if (PHINode *P = dyn_cast<PHINode>(it)) {
2438       // Check that the PHI is a reduction PHI.
2439       if (P->getNumIncomingValues() != 2)
2440         return Changed;
2441       Value *Rdx =
2442           (P->getIncomingBlock(0) == BB
2443                ? (P->getIncomingValue(0))
2444                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2445       // Check if this is a Binary Operator.
2446       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2447       if (!BI)
2448         continue;
2449
2450       // Try to match and vectorize a horizontal reduction.
2451       HorizontalReduction HorRdx;
2452       if (ShouldVectorizeHor &&
2453           HorRdx.matchAssociativeReduction(P, BI, DL) &&
2454           HorRdx.tryToReduce(R, TTI)) {
2455         Changed = true;
2456         it = BB->begin();
2457         e = BB->end();
2458         continue;
2459       }
2460
2461      Value *Inst = BI->getOperand(0);
2462       if (Inst == P)
2463         Inst = BI->getOperand(1);
2464
2465       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2466         // We would like to start over since some instructions are deleted
2467         // and the iterator may become invalid value.
2468         Changed = true;
2469         it = BB->begin();
2470         e = BB->end();
2471         continue;
2472       }
2473
2474       continue;
2475     }
2476
2477     // Try to vectorize horizontal reductions feeding into a store.
2478     if (ShouldStartVectorizeHorAtStore)
2479       if (StoreInst *SI = dyn_cast<StoreInst>(it))
2480         if (BinaryOperator *BinOp =
2481                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2482           HorizontalReduction HorRdx;
2483           if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2484                 HorRdx.tryToReduce(R, TTI)) ||
2485                tryToVectorize(BinOp, R))) {
2486             Changed = true;
2487             it = BB->begin();
2488             e = BB->end();
2489             continue;
2490           }
2491         }
2492
2493     // Try to vectorize trees that start at compare instructions.
2494     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2495       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2496         Changed = true;
2497         // We would like to start over since some instructions are deleted
2498         // and the iterator may become invalid value.
2499         it = BB->begin();
2500         e = BB->end();
2501         continue;
2502       }
2503
2504       for (int i = 0; i < 2; ++i) {
2505          if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2506             if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2507               Changed = true;
2508               // We would like to start over since some instructions are deleted
2509               // and the iterator may become invalid value.
2510               it = BB->begin();
2511               e = BB->end();
2512             }
2513          }
2514       }
2515       continue;
2516     }
2517
2518     // Try to vectorize trees that start at insertelement instructions.
2519     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2520       SmallVector<Value *, 8> Ops;
2521       if (!findBuildVector(IE, Ops))
2522         continue;
2523
2524       if (tryToVectorizeList(Ops, R)) {
2525         Changed = true;
2526         it = BB->begin();
2527         e = BB->end();
2528       }
2529
2530       continue;
2531     }
2532   }
2533
2534   return Changed;
2535 }
2536
2537 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2538   bool Changed = false;
2539   // Attempt to sort and vectorize each of the store-groups.
2540   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2541        it != e; ++it) {
2542     if (it->second.size() < 2)
2543       continue;
2544
2545     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2546           << it->second.size() << ".\n");
2547
2548     // Process the stores in chunks of 16.
2549     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2550       unsigned Len = std::min<unsigned>(CE - CI, 16);
2551       ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2552       Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2553     }
2554   }
2555   return Changed;
2556 }
2557
2558 } // end anonymous namespace
2559
2560 char SLPVectorizer::ID = 0;
2561 static const char lv_name[] = "SLP Vectorizer";
2562 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2563 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2564 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2565 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2566 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2567 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2568
2569 namespace llvm {
2570 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2571 }