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