bd9c5c75cc31f5e37b4ad4b5b7bd53ccee638143
[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     case Instruction::Call: {
950       // Check if the calls are all to the same vectorizable intrinsic.
951       IntrinsicInst *II = dyn_cast<IntrinsicInst>(VL[0]);
952       if (II==NULL) {
953         newTreeEntry(VL, false);
954         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
955         return;
956       }
957
958       Intrinsic::ID ID = II->getIntrinsicID();
959
960       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
961         IntrinsicInst *II2 = dyn_cast<IntrinsicInst>(VL[i]);
962         if (!II2 || II2->getIntrinsicID() != ID) {
963           newTreeEntry(VL, false);
964           DEBUG(dbgs() << "SLP: mismatched calls:" << *II << "!=" << *VL[i]
965                        << "\n");
966           return;
967         }
968       }
969
970       newTreeEntry(VL, true);
971       for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i) {
972         ValueList Operands;
973         // Prepare the operand vector.
974         for (unsigned j = 0; j < VL.size(); ++j) {
975           IntrinsicInst *II2 = dyn_cast<IntrinsicInst>(VL[j]);
976           Operands.push_back(II2->getArgOperand(i));
977         }
978         buildTree_rec(Operands, Depth + 1);
979       }
980       return;
981     }
982     default:
983       newTreeEntry(VL, false);
984       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
985       return;
986   }
987 }
988
989 int BoUpSLP::getEntryCost(TreeEntry *E) {
990   ArrayRef<Value*> VL = E->Scalars;
991
992   Type *ScalarTy = VL[0]->getType();
993   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
994     ScalarTy = SI->getValueOperand()->getType();
995   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
996
997   if (E->NeedToGather) {
998     if (allConstant(VL))
999       return 0;
1000     if (isSplat(VL)) {
1001       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1002     }
1003     return getGatherCost(E->Scalars);
1004   }
1005
1006   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
1007          "Invalid VL");
1008   Instruction *VL0 = cast<Instruction>(VL[0]);
1009   unsigned Opcode = VL0->getOpcode();
1010   switch (Opcode) {
1011     case Instruction::PHI: {
1012       return 0;
1013     }
1014     case Instruction::ExtractElement: {
1015       if (CanReuseExtract(VL))
1016         return 0;
1017       return getGatherCost(VecTy);
1018     }
1019     case Instruction::ZExt:
1020     case Instruction::SExt:
1021     case Instruction::FPToUI:
1022     case Instruction::FPToSI:
1023     case Instruction::FPExt:
1024     case Instruction::PtrToInt:
1025     case Instruction::IntToPtr:
1026     case Instruction::SIToFP:
1027     case Instruction::UIToFP:
1028     case Instruction::Trunc:
1029     case Instruction::FPTrunc:
1030     case Instruction::BitCast: {
1031       Type *SrcTy = VL0->getOperand(0)->getType();
1032
1033       // Calculate the cost of this instruction.
1034       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1035                                                          VL0->getType(), SrcTy);
1036
1037       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1038       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1039       return VecCost - ScalarCost;
1040     }
1041     case Instruction::FCmp:
1042     case Instruction::ICmp:
1043     case Instruction::Select:
1044     case Instruction::Add:
1045     case Instruction::FAdd:
1046     case Instruction::Sub:
1047     case Instruction::FSub:
1048     case Instruction::Mul:
1049     case Instruction::FMul:
1050     case Instruction::UDiv:
1051     case Instruction::SDiv:
1052     case Instruction::FDiv:
1053     case Instruction::URem:
1054     case Instruction::SRem:
1055     case Instruction::FRem:
1056     case Instruction::Shl:
1057     case Instruction::LShr:
1058     case Instruction::AShr:
1059     case Instruction::And:
1060     case Instruction::Or:
1061     case Instruction::Xor: {
1062       // Calculate the cost of this instruction.
1063       int ScalarCost = 0;
1064       int VecCost = 0;
1065       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1066           Opcode == Instruction::Select) {
1067         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1068         ScalarCost = VecTy->getNumElements() *
1069         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1070         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1071       } else {
1072         // Certain instructions can be cheaper to vectorize if they have a
1073         // constant second vector operand.
1074         TargetTransformInfo::OperandValueKind Op1VK =
1075             TargetTransformInfo::OK_AnyValue;
1076         TargetTransformInfo::OperandValueKind Op2VK =
1077             TargetTransformInfo::OK_UniformConstantValue;
1078
1079         // If all operands are exactly the same ConstantInt then set the
1080         // operand kind to OK_UniformConstantValue.
1081         // If instead not all operands are constants, then set the operand kind
1082         // to OK_AnyValue. If all operands are constants but not the same,
1083         // then set the operand kind to OK_NonUniformConstantValue.
1084         ConstantInt *CInt = NULL;
1085         for (unsigned i = 0; i < VL.size(); ++i) {
1086           const Instruction *I = cast<Instruction>(VL[i]);
1087           if (!isa<ConstantInt>(I->getOperand(1))) {
1088             Op2VK = TargetTransformInfo::OK_AnyValue;
1089             break;
1090           }
1091           if (i == 0) {
1092             CInt = cast<ConstantInt>(I->getOperand(1));
1093             continue;
1094           }
1095           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1096               CInt != cast<ConstantInt>(I->getOperand(1)))
1097             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1098         }
1099
1100         ScalarCost =
1101             VecTy->getNumElements() *
1102             TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1103         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1104       }
1105       return VecCost - ScalarCost;
1106     }
1107     case Instruction::Load: {
1108       // Cost of wide load - cost of scalar loads.
1109       int ScalarLdCost = VecTy->getNumElements() *
1110       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1111       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1112       return VecLdCost - ScalarLdCost;
1113     }
1114     case Instruction::Store: {
1115       // We know that we can merge the stores. Calculate the cost.
1116       int ScalarStCost = VecTy->getNumElements() *
1117       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1118       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1119       return VecStCost - ScalarStCost;
1120     }
1121     case Instruction::Call: {
1122       CallInst *CI = cast<CallInst>(VL0);
1123       IntrinsicInst *II = cast<IntrinsicInst>(CI);
1124       Intrinsic::ID ID = II->getIntrinsicID();
1125
1126       // Calculate the cost of the scalar and vector calls.
1127       SmallVector<Type*, 4> ScalarTys, VecTys;
1128       for (unsigned op = 0, opc = II->getNumArgOperands(); op!= opc; ++op) {
1129         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1130         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1131                                          VecTy->getNumElements()));
1132       }
1133
1134       int ScalarCallCost = VecTy->getNumElements() *
1135           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1136
1137       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1138
1139       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1140             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1141             << " for " << *II << "\n");
1142
1143       return VecCallCost - ScalarCallCost;
1144     }
1145     default:
1146       llvm_unreachable("Unknown instruction");
1147   }
1148 }
1149
1150 bool BoUpSLP::isFullyVectorizableTinyTree() {
1151   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1152         VectorizableTree.size() << " is fully vectorizable .\n");
1153
1154   // We only handle trees of height 2.
1155   if (VectorizableTree.size() != 2)
1156     return false;
1157
1158   // Handle splat stores.
1159   if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1160     return true;
1161
1162   // Gathering cost would be too much for tiny trees.
1163   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1164     return false;
1165
1166   return true;
1167 }
1168
1169 int BoUpSLP::getTreeCost() {
1170   int Cost = 0;
1171   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1172         VectorizableTree.size() << ".\n");
1173
1174   // We only vectorize tiny trees if it is fully vectorizable.
1175   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1176     if (!VectorizableTree.size()) {
1177       assert(!ExternalUses.size() && "We should not have any external users");
1178     }
1179     return INT_MAX;
1180   }
1181
1182   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1183
1184   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1185     int C = getEntryCost(&VectorizableTree[i]);
1186     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1187           << *VectorizableTree[i].Scalars[0] << " .\n");
1188     Cost += C;
1189   }
1190
1191   SmallSet<Value *, 16> ExtractCostCalculated;
1192   int ExtractCost = 0;
1193   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1194        I != E; ++I) {
1195     // We only add extract cost once for the same scalar.
1196     if (!ExtractCostCalculated.insert(I->Scalar))
1197       continue;
1198
1199     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1200     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1201                                            I->Lane);
1202   }
1203
1204   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1205   return  Cost + ExtractCost;
1206 }
1207
1208 int BoUpSLP::getGatherCost(Type *Ty) {
1209   int Cost = 0;
1210   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1211     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1212   return Cost;
1213 }
1214
1215 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1216   // Find the type of the operands in VL.
1217   Type *ScalarTy = VL[0]->getType();
1218   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1219     ScalarTy = SI->getValueOperand()->getType();
1220   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1221   // Find the cost of inserting/extracting values from the vector.
1222   return getGatherCost(VecTy);
1223 }
1224
1225 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1226   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1227     return AA->getLocation(SI);
1228   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1229     return AA->getLocation(LI);
1230   return AliasAnalysis::Location();
1231 }
1232
1233 Value *BoUpSLP::getPointerOperand(Value *I) {
1234   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1235     return LI->getPointerOperand();
1236   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1237     return SI->getPointerOperand();
1238   return 0;
1239 }
1240
1241 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1242   if (LoadInst *L = dyn_cast<LoadInst>(I))
1243     return L->getPointerAddressSpace();
1244   if (StoreInst *S = dyn_cast<StoreInst>(I))
1245     return S->getPointerAddressSpace();
1246   return -1;
1247 }
1248
1249 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1250   Value *PtrA = getPointerOperand(A);
1251   Value *PtrB = getPointerOperand(B);
1252   unsigned ASA = getAddressSpaceOperand(A);
1253   unsigned ASB = getAddressSpaceOperand(B);
1254
1255   // Check that the address spaces match and that the pointers are valid.
1256   if (!PtrA || !PtrB || (ASA != ASB))
1257     return false;
1258
1259   // Make sure that A and B are different pointers of the same type.
1260   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1261     return false;
1262
1263   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1264   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1265   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1266
1267   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1268   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1269   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1270
1271   APInt OffsetDelta = OffsetB - OffsetA;
1272
1273   // Check if they are based on the same pointer. That makes the offsets
1274   // sufficient.
1275   if (PtrA == PtrB)
1276     return OffsetDelta == Size;
1277
1278   // Compute the necessary base pointer delta to have the necessary final delta
1279   // equal to the size.
1280   APInt BaseDelta = Size - OffsetDelta;
1281
1282   // Otherwise compute the distance with SCEV between the base pointers.
1283   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1284   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1285   const SCEV *C = SE->getConstant(BaseDelta);
1286   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1287   return X == PtrSCEVB;
1288 }
1289
1290 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1291   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1292   BasicBlock::iterator I = Src, E = Dst;
1293   /// Scan all of the instruction from SRC to DST and check if
1294   /// the source may alias.
1295   for (++I; I != E; ++I) {
1296     // Ignore store instructions that are marked as 'ignore'.
1297     if (MemBarrierIgnoreList.count(I))
1298       continue;
1299     if (Src->mayWriteToMemory()) /* Write */ {
1300       if (!I->mayReadOrWriteMemory())
1301         continue;
1302     } else /* Read */ {
1303       if (!I->mayWriteToMemory())
1304         continue;
1305     }
1306     AliasAnalysis::Location A = getLocation(&*I);
1307     AliasAnalysis::Location B = getLocation(Src);
1308
1309     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1310       return I;
1311   }
1312   return 0;
1313 }
1314
1315 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1316   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1317   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1318   BlockNumbering &BN = BlocksNumbers[BB];
1319
1320   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1321   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1322     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1323   return MaxIdx;
1324 }
1325
1326 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1327   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1328   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1329   BlockNumbering &BN = BlocksNumbers[BB];
1330
1331   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1332   for (unsigned i = 1, e = VL.size(); i < e; ++i)
1333     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1334   Instruction *I = BN.getInstruction(MaxIdx);
1335   assert(I && "bad location");
1336   return I;
1337 }
1338
1339 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1340   Instruction *VL0 = cast<Instruction>(VL[0]);
1341   Instruction *LastInst = getLastInstruction(VL);
1342   BasicBlock::iterator NextInst = LastInst;
1343   ++NextInst;
1344   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1345   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1346 }
1347
1348 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1349   Value *Vec = UndefValue::get(Ty);
1350   // Generate the 'InsertElement' instruction.
1351   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1352     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1353     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1354       GatherSeq.insert(Insrt);
1355       CSEBlocks.insert(Insrt->getParent());
1356
1357       // Add to our 'need-to-extract' list.
1358       if (ScalarToTreeEntry.count(VL[i])) {
1359         int Idx = ScalarToTreeEntry[VL[i]];
1360         TreeEntry *E = &VectorizableTree[Idx];
1361         // Find which lane we need to extract.
1362         int FoundLane = -1;
1363         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1364           // Is this the lane of the scalar that we are looking for ?
1365           if (E->Scalars[Lane] == VL[i]) {
1366             FoundLane = Lane;
1367             break;
1368           }
1369         }
1370         assert(FoundLane >= 0 && "Could not find the correct lane");
1371         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1372       }
1373     }
1374   }
1375
1376   return Vec;
1377 }
1378
1379 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1380   SmallDenseMap<Value*, int>::const_iterator Entry
1381     = ScalarToTreeEntry.find(VL[0]);
1382   if (Entry != ScalarToTreeEntry.end()) {
1383     int Idx = Entry->second;
1384     const TreeEntry *En = &VectorizableTree[Idx];
1385     if (En->isSame(VL) && En->VectorizedValue)
1386       return En->VectorizedValue;
1387   }
1388   return 0;
1389 }
1390
1391 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1392   if (ScalarToTreeEntry.count(VL[0])) {
1393     int Idx = ScalarToTreeEntry[VL[0]];
1394     TreeEntry *E = &VectorizableTree[Idx];
1395     if (E->isSame(VL))
1396       return vectorizeTree(E);
1397   }
1398
1399   Type *ScalarTy = VL[0]->getType();
1400   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1401     ScalarTy = SI->getValueOperand()->getType();
1402   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1403
1404   return Gather(VL, VecTy);
1405 }
1406
1407 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1408   IRBuilder<>::InsertPointGuard Guard(Builder);
1409
1410   if (E->VectorizedValue) {
1411     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1412     return E->VectorizedValue;
1413   }
1414
1415   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1416   Type *ScalarTy = VL0->getType();
1417   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1418     ScalarTy = SI->getValueOperand()->getType();
1419   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1420
1421   if (E->NeedToGather) {
1422     setInsertPointAfterBundle(E->Scalars);
1423     return Gather(E->Scalars, VecTy);
1424   }
1425
1426   unsigned Opcode = VL0->getOpcode();
1427   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1428
1429   switch (Opcode) {
1430     case Instruction::PHI: {
1431       PHINode *PH = dyn_cast<PHINode>(VL0);
1432       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1433       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1434       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1435       E->VectorizedValue = NewPhi;
1436
1437       // PHINodes may have multiple entries from the same block. We want to
1438       // visit every block once.
1439       SmallSet<BasicBlock*, 4> VisitedBBs;
1440
1441       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1442         ValueList Operands;
1443         BasicBlock *IBB = PH->getIncomingBlock(i);
1444
1445         if (!VisitedBBs.insert(IBB)) {
1446           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1447           continue;
1448         }
1449
1450         // Prepare the operand vector.
1451         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1452           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1453                              getIncomingValueForBlock(IBB));
1454
1455         Builder.SetInsertPoint(IBB->getTerminator());
1456         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1457         Value *Vec = vectorizeTree(Operands);
1458         NewPhi->addIncoming(Vec, IBB);
1459       }
1460
1461       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1462              "Invalid number of incoming values");
1463       return NewPhi;
1464     }
1465
1466     case Instruction::ExtractElement: {
1467       if (CanReuseExtract(E->Scalars)) {
1468         Value *V = VL0->getOperand(0);
1469         E->VectorizedValue = V;
1470         return V;
1471       }
1472       return Gather(E->Scalars, VecTy);
1473     }
1474     case Instruction::ZExt:
1475     case Instruction::SExt:
1476     case Instruction::FPToUI:
1477     case Instruction::FPToSI:
1478     case Instruction::FPExt:
1479     case Instruction::PtrToInt:
1480     case Instruction::IntToPtr:
1481     case Instruction::SIToFP:
1482     case Instruction::UIToFP:
1483     case Instruction::Trunc:
1484     case Instruction::FPTrunc:
1485     case Instruction::BitCast: {
1486       ValueList INVL;
1487       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1488         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1489
1490       setInsertPointAfterBundle(E->Scalars);
1491
1492       Value *InVec = vectorizeTree(INVL);
1493
1494       if (Value *V = alreadyVectorized(E->Scalars))
1495         return V;
1496
1497       CastInst *CI = dyn_cast<CastInst>(VL0);
1498       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1499       E->VectorizedValue = V;
1500       return V;
1501     }
1502     case Instruction::FCmp:
1503     case Instruction::ICmp: {
1504       ValueList LHSV, RHSV;
1505       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1506         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1507         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1508       }
1509
1510       setInsertPointAfterBundle(E->Scalars);
1511
1512       Value *L = vectorizeTree(LHSV);
1513       Value *R = vectorizeTree(RHSV);
1514
1515       if (Value *V = alreadyVectorized(E->Scalars))
1516         return V;
1517
1518       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1519       Value *V;
1520       if (Opcode == Instruction::FCmp)
1521         V = Builder.CreateFCmp(P0, L, R);
1522       else
1523         V = Builder.CreateICmp(P0, L, R);
1524
1525       E->VectorizedValue = V;
1526       return V;
1527     }
1528     case Instruction::Select: {
1529       ValueList TrueVec, FalseVec, CondVec;
1530       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1531         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1532         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1533         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1534       }
1535
1536       setInsertPointAfterBundle(E->Scalars);
1537
1538       Value *Cond = vectorizeTree(CondVec);
1539       Value *True = vectorizeTree(TrueVec);
1540       Value *False = vectorizeTree(FalseVec);
1541
1542       if (Value *V = alreadyVectorized(E->Scalars))
1543         return V;
1544
1545       Value *V = Builder.CreateSelect(Cond, True, False);
1546       E->VectorizedValue = V;
1547       return V;
1548     }
1549     case Instruction::Add:
1550     case Instruction::FAdd:
1551     case Instruction::Sub:
1552     case Instruction::FSub:
1553     case Instruction::Mul:
1554     case Instruction::FMul:
1555     case Instruction::UDiv:
1556     case Instruction::SDiv:
1557     case Instruction::FDiv:
1558     case Instruction::URem:
1559     case Instruction::SRem:
1560     case Instruction::FRem:
1561     case Instruction::Shl:
1562     case Instruction::LShr:
1563     case Instruction::AShr:
1564     case Instruction::And:
1565     case Instruction::Or:
1566     case Instruction::Xor: {
1567       ValueList LHSVL, RHSVL;
1568       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1569         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1570       else
1571         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1572           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1573           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1574         }
1575
1576       setInsertPointAfterBundle(E->Scalars);
1577
1578       Value *LHS = vectorizeTree(LHSVL);
1579       Value *RHS = vectorizeTree(RHSVL);
1580
1581       if (LHS == RHS && isa<Instruction>(LHS)) {
1582         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1583       }
1584
1585       if (Value *V = alreadyVectorized(E->Scalars))
1586         return V;
1587
1588       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1589       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1590       E->VectorizedValue = V;
1591
1592       if (Instruction *I = dyn_cast<Instruction>(V))
1593         return propagateMetadata(I, E->Scalars);
1594
1595       return V;
1596     }
1597     case Instruction::Load: {
1598       // Loads are inserted at the head of the tree because we don't want to
1599       // sink them all the way down past store instructions.
1600       setInsertPointAfterBundle(E->Scalars);
1601
1602       LoadInst *LI = cast<LoadInst>(VL0);
1603       unsigned AS = LI->getPointerAddressSpace();
1604
1605       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1606                                             VecTy->getPointerTo(AS));
1607       unsigned Alignment = LI->getAlignment();
1608       LI = Builder.CreateLoad(VecPtr);
1609       LI->setAlignment(Alignment);
1610       E->VectorizedValue = LI;
1611       return propagateMetadata(LI, E->Scalars);
1612     }
1613     case Instruction::Store: {
1614       StoreInst *SI = cast<StoreInst>(VL0);
1615       unsigned Alignment = SI->getAlignment();
1616       unsigned AS = SI->getPointerAddressSpace();
1617
1618       ValueList ValueOp;
1619       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1620         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1621
1622       setInsertPointAfterBundle(E->Scalars);
1623
1624       Value *VecValue = vectorizeTree(ValueOp);
1625       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1626                                             VecTy->getPointerTo(AS));
1627       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1628       S->setAlignment(Alignment);
1629       E->VectorizedValue = S;
1630       return propagateMetadata(S, E->Scalars);
1631     }
1632     case Instruction::Call: {
1633       CallInst *CI = cast<CallInst>(VL0);
1634
1635       setInsertPointAfterBundle(E->Scalars);
1636       std::vector<Value *> OpVecs;
1637       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1638         ValueList OpVL;
1639         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1640           CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1641           OpVL.push_back(CEI->getArgOperand(j));
1642         }
1643
1644         Value *OpVec = vectorizeTree(OpVL);
1645         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1646         OpVecs.push_back(OpVec);
1647       }
1648
1649       Module *M = F->getParent();
1650       IntrinsicInst *II = cast<IntrinsicInst>(CI);
1651       Intrinsic::ID ID = II->getIntrinsicID();
1652       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1653       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1654       Value *V = Builder.CreateCall(CF, OpVecs);
1655       E->VectorizedValue = V;
1656       return V;
1657     }
1658     default:
1659     llvm_unreachable("unknown inst");
1660   }
1661   return 0;
1662 }
1663
1664 Value *BoUpSLP::vectorizeTree() {
1665   Builder.SetInsertPoint(F->getEntryBlock().begin());
1666   vectorizeTree(&VectorizableTree[0]);
1667
1668   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1669
1670   // Extract all of the elements with the external uses.
1671   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1672        it != e; ++it) {
1673     Value *Scalar = it->Scalar;
1674     llvm::User *User = it->User;
1675
1676     // Skip users that we already RAUW. This happens when one instruction
1677     // has multiple uses of the same value.
1678     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1679         Scalar->user_end())
1680       continue;
1681     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1682
1683     int Idx = ScalarToTreeEntry[Scalar];
1684     TreeEntry *E = &VectorizableTree[Idx];
1685     assert(!E->NeedToGather && "Extracting from a gather list");
1686
1687     Value *Vec = E->VectorizedValue;
1688     assert(Vec && "Can't find vectorizable value");
1689
1690     Value *Lane = Builder.getInt32(it->Lane);
1691     // Generate extracts for out-of-tree users.
1692     // Find the insertion point for the extractelement lane.
1693     if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1694       Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1695       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1696       CSEBlocks.insert(PN->getParent());
1697       User->replaceUsesOfWith(Scalar, Ex);
1698     } else if (isa<Instruction>(Vec)){
1699       if (PHINode *PH = dyn_cast<PHINode>(User)) {
1700         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1701           if (PH->getIncomingValue(i) == Scalar) {
1702             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1703             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1704             CSEBlocks.insert(PH->getIncomingBlock(i));
1705             PH->setOperand(i, Ex);
1706           }
1707         }
1708       } else {
1709         Builder.SetInsertPoint(cast<Instruction>(User));
1710         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1711         CSEBlocks.insert(cast<Instruction>(User)->getParent());
1712         User->replaceUsesOfWith(Scalar, Ex);
1713      }
1714     } else {
1715       Builder.SetInsertPoint(F->getEntryBlock().begin());
1716       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1717       CSEBlocks.insert(&F->getEntryBlock());
1718       User->replaceUsesOfWith(Scalar, Ex);
1719     }
1720
1721     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1722   }
1723
1724   // For each vectorized value:
1725   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1726     TreeEntry *Entry = &VectorizableTree[EIdx];
1727
1728     // For each lane:
1729     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1730       Value *Scalar = Entry->Scalars[Lane];
1731
1732       // No need to handle users of gathered values.
1733       if (Entry->NeedToGather)
1734         continue;
1735
1736       assert(Entry->VectorizedValue && "Can't find vectorizable value");
1737
1738       Type *Ty = Scalar->getType();
1739       if (!Ty->isVoidTy()) {
1740 #ifndef NDEBUG
1741         for (User *U : Scalar->users()) {
1742           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
1743
1744           assert((ScalarToTreeEntry.count(U) ||
1745                   // It is legal to replace the reduction users by undef.
1746                   (RdxOps && RdxOps->count(U))) &&
1747                  "Replacing out-of-tree value with undef");
1748         }
1749 #endif
1750         Value *Undef = UndefValue::get(Ty);
1751         Scalar->replaceAllUsesWith(Undef);
1752       }
1753       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1754       cast<Instruction>(Scalar)->eraseFromParent();
1755     }
1756   }
1757
1758   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1759     BlocksNumbers[it].forget();
1760   }
1761   Builder.ClearInsertionPoint();
1762
1763   return VectorizableTree[0].VectorizedValue;
1764 }
1765
1766 void BoUpSLP::optimizeGatherSequence() {
1767   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1768         << " gather sequences instructions.\n");
1769   // LICM InsertElementInst sequences.
1770   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1771        e = GatherSeq.end(); it != e; ++it) {
1772     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1773
1774     if (!Insert)
1775       continue;
1776
1777     // Check if this block is inside a loop.
1778     Loop *L = LI->getLoopFor(Insert->getParent());
1779     if (!L)
1780       continue;
1781
1782     // Check if it has a preheader.
1783     BasicBlock *PreHeader = L->getLoopPreheader();
1784     if (!PreHeader)
1785       continue;
1786
1787     // If the vector or the element that we insert into it are
1788     // instructions that are defined in this basic block then we can't
1789     // hoist this instruction.
1790     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1791     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1792     if (CurrVec && L->contains(CurrVec))
1793       continue;
1794     if (NewElem && L->contains(NewElem))
1795       continue;
1796
1797     // We can hoist this instruction. Move it to the pre-header.
1798     Insert->moveBefore(PreHeader->getTerminator());
1799   }
1800
1801   // Sort blocks by domination. This ensures we visit a block after all blocks
1802   // dominating it are visited.
1803   SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1804   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
1805                    [this](const BasicBlock *A, const BasicBlock *B) {
1806     return DT->properlyDominates(A, B);
1807   });
1808
1809   // Perform O(N^2) search over the gather sequences and merge identical
1810   // instructions. TODO: We can further optimize this scan if we split the
1811   // instructions into different buckets based on the insert lane.
1812   SmallVector<Instruction *, 16> Visited;
1813   for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1814                                                E = CSEWorkList.end();
1815        I != E; ++I) {
1816     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
1817            "Worklist not sorted properly!");
1818     BasicBlock *BB = *I;
1819     // For all instructions in blocks containing gather sequences:
1820     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1821       Instruction *In = it++;
1822       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1823         continue;
1824
1825       // Check if we can replace this instruction with any of the
1826       // visited instructions.
1827       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1828                                                     ve = Visited.end();
1829            v != ve; ++v) {
1830         if (In->isIdenticalTo(*v) &&
1831             DT->dominates((*v)->getParent(), In->getParent())) {
1832           In->replaceAllUsesWith(*v);
1833           In->eraseFromParent();
1834           In = 0;
1835           break;
1836         }
1837       }
1838       if (In) {
1839         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1840         Visited.push_back(In);
1841       }
1842     }
1843   }
1844   CSEBlocks.clear();
1845   GatherSeq.clear();
1846 }
1847
1848 /// The SLPVectorizer Pass.
1849 struct SLPVectorizer : public FunctionPass {
1850   typedef SmallVector<StoreInst *, 8> StoreList;
1851   typedef MapVector<Value *, StoreList> StoreListMap;
1852
1853   /// Pass identification, replacement for typeid
1854   static char ID;
1855
1856   explicit SLPVectorizer() : FunctionPass(ID) {
1857     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1858   }
1859
1860   ScalarEvolution *SE;
1861   const DataLayout *DL;
1862   TargetTransformInfo *TTI;
1863   AliasAnalysis *AA;
1864   LoopInfo *LI;
1865   DominatorTree *DT;
1866
1867   bool runOnFunction(Function &F) override {
1868     if (skipOptnoneFunction(F))
1869       return false;
1870
1871     SE = &getAnalysis<ScalarEvolution>();
1872     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1873     DL = DLP ? &DLP->getDataLayout() : 0;
1874     TTI = &getAnalysis<TargetTransformInfo>();
1875     AA = &getAnalysis<AliasAnalysis>();
1876     LI = &getAnalysis<LoopInfo>();
1877     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1878
1879     StoreRefs.clear();
1880     bool Changed = false;
1881
1882     // If the target claims to have no vector registers don't attempt
1883     // vectorization.
1884     if (!TTI->getNumberOfRegisters(true))
1885       return false;
1886
1887     // Must have DataLayout. We can't require it because some tests run w/o
1888     // triple.
1889     if (!DL)
1890       return false;
1891
1892     // Don't vectorize when the attribute NoImplicitFloat is used.
1893     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1894       return false;
1895
1896     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1897
1898     // Use the bottom up slp vectorizer to construct chains that start with
1899     // he store instructions.
1900     BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1901
1902     // Scan the blocks in the function in post order.
1903     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1904          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1905       BasicBlock *BB = *it;
1906
1907       // Vectorize trees that end at stores.
1908       if (unsigned count = collectStores(BB, R)) {
1909         (void)count;
1910         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1911         Changed |= vectorizeStoreChains(R);
1912       }
1913
1914       // Vectorize trees that end at reductions.
1915       Changed |= vectorizeChainsInBlock(BB, R);
1916     }
1917
1918     if (Changed) {
1919       R.optimizeGatherSequence();
1920       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1921       DEBUG(verifyFunction(F));
1922     }
1923     return Changed;
1924   }
1925
1926   void getAnalysisUsage(AnalysisUsage &AU) const override {
1927     FunctionPass::getAnalysisUsage(AU);
1928     AU.addRequired<ScalarEvolution>();
1929     AU.addRequired<AliasAnalysis>();
1930     AU.addRequired<TargetTransformInfo>();
1931     AU.addRequired<LoopInfo>();
1932     AU.addRequired<DominatorTreeWrapperPass>();
1933     AU.addPreserved<LoopInfo>();
1934     AU.addPreserved<DominatorTreeWrapperPass>();
1935     AU.setPreservesCFG();
1936   }
1937
1938 private:
1939
1940   /// \brief Collect memory references and sort them according to their base
1941   /// object. We sort the stores to their base objects to reduce the cost of the
1942   /// quadratic search on the stores. TODO: We can further reduce this cost
1943   /// if we flush the chain creation every time we run into a memory barrier.
1944   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1945
1946   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1947   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1948
1949   /// \brief Try to vectorize a list of operands.
1950   /// \returns true if a value was vectorized.
1951   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1952
1953   /// \brief Try to vectorize a chain that may start at the operands of \V;
1954   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1955
1956   /// \brief Vectorize the stores that were collected in StoreRefs.
1957   bool vectorizeStoreChains(BoUpSLP &R);
1958
1959   /// \brief Scan the basic block and look for patterns that are likely to start
1960   /// a vectorization chain.
1961   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1962
1963   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1964                            BoUpSLP &R);
1965
1966   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1967                        BoUpSLP &R);
1968 private:
1969   StoreListMap StoreRefs;
1970 };
1971
1972 /// \brief Check that the Values in the slice in VL array are still existent in
1973 /// the WeakVH array.
1974 /// Vectorization of part of the VL array may cause later values in the VL array
1975 /// to become invalid. We track when this has happened in the WeakVH array.
1976 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1977                                SmallVectorImpl<WeakVH> &VH,
1978                                unsigned SliceBegin,
1979                                unsigned SliceSize) {
1980   for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1981     if (VH[i] != VL[i])
1982       return true;
1983
1984   return false;
1985 }
1986
1987 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1988                                           int CostThreshold, BoUpSLP &R) {
1989   unsigned ChainLen = Chain.size();
1990   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1991         << "\n");
1992   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1993   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1994   unsigned VF = MinVecRegSize / Sz;
1995
1996   if (!isPowerOf2_32(Sz) || VF < 2)
1997     return false;
1998
1999   // Keep track of values that were delete by vectorizing in the loop below.
2000   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2001
2002   bool Changed = false;
2003   // Look for profitable vectorizable trees at all offsets, starting at zero.
2004   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2005     if (i + VF > e)
2006       break;
2007
2008     // Check that a previous iteration of this loop did not delete the Value.
2009     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2010       continue;
2011
2012     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2013           << "\n");
2014     ArrayRef<Value *> Operands = Chain.slice(i, VF);
2015
2016     R.buildTree(Operands);
2017
2018     int Cost = R.getTreeCost();
2019
2020     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2021     if (Cost < CostThreshold) {
2022       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2023       R.vectorizeTree();
2024
2025       // Move to the next bundle.
2026       i += VF - 1;
2027       Changed = true;
2028     }
2029   }
2030
2031   return Changed;
2032 }
2033
2034 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2035                                     int costThreshold, BoUpSLP &R) {
2036   SetVector<Value *> Heads, Tails;
2037   SmallDenseMap<Value *, Value *> ConsecutiveChain;
2038
2039   // We may run into multiple chains that merge into a single chain. We mark the
2040   // stores that we vectorized so that we don't visit the same store twice.
2041   BoUpSLP::ValueSet VectorizedStores;
2042   bool Changed = false;
2043
2044   // Do a quadratic search on all of the given stores and find
2045   // all of the pairs of stores that follow each other.
2046   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2047     for (unsigned j = 0; j < e; ++j) {
2048       if (i == j)
2049         continue;
2050
2051       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2052         Tails.insert(Stores[j]);
2053         Heads.insert(Stores[i]);
2054         ConsecutiveChain[Stores[i]] = Stores[j];
2055       }
2056     }
2057   }
2058
2059   // For stores that start but don't end a link in the chain:
2060   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2061        it != e; ++it) {
2062     if (Tails.count(*it))
2063       continue;
2064
2065     // We found a store instr that starts a chain. Now follow the chain and try
2066     // to vectorize it.
2067     BoUpSLP::ValueList Operands;
2068     Value *I = *it;
2069     // Collect the chain into a list.
2070     while (Tails.count(I) || Heads.count(I)) {
2071       if (VectorizedStores.count(I))
2072         break;
2073       Operands.push_back(I);
2074       // Move to the next value in the chain.
2075       I = ConsecutiveChain[I];
2076     }
2077
2078     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2079
2080     // Mark the vectorized stores so that we don't vectorize them again.
2081     if (Vectorized)
2082       VectorizedStores.insert(Operands.begin(), Operands.end());
2083     Changed |= Vectorized;
2084   }
2085
2086   return Changed;
2087 }
2088
2089
2090 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2091   unsigned count = 0;
2092   StoreRefs.clear();
2093   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2094     StoreInst *SI = dyn_cast<StoreInst>(it);
2095     if (!SI)
2096       continue;
2097
2098     // Don't touch volatile stores.
2099     if (!SI->isSimple())
2100       continue;
2101
2102     // Check that the pointer points to scalars.
2103     Type *Ty = SI->getValueOperand()->getType();
2104     if (Ty->isAggregateType() || Ty->isVectorTy())
2105       return 0;
2106
2107     // Find the base pointer.
2108     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2109
2110     // Save the store locations.
2111     StoreRefs[Ptr].push_back(SI);
2112     count++;
2113   }
2114   return count;
2115 }
2116
2117 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2118   if (!A || !B)
2119     return false;
2120   Value *VL[] = { A, B };
2121   return tryToVectorizeList(VL, R);
2122 }
2123
2124 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2125   if (VL.size() < 2)
2126     return false;
2127
2128   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2129
2130   // Check that all of the parts are scalar instructions of the same type.
2131   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2132   if (!I0)
2133     return false;
2134
2135   unsigned Opcode0 = I0->getOpcode();
2136
2137   Type *Ty0 = I0->getType();
2138   unsigned Sz = DL->getTypeSizeInBits(Ty0);
2139   unsigned VF = MinVecRegSize / Sz;
2140
2141   for (int i = 0, e = VL.size(); i < e; ++i) {
2142     Type *Ty = VL[i]->getType();
2143     if (Ty->isAggregateType() || Ty->isVectorTy())
2144       return false;
2145     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2146     if (!Inst || Inst->getOpcode() != Opcode0)
2147       return false;
2148   }
2149
2150   bool Changed = false;
2151
2152   // Keep track of values that were delete by vectorizing in the loop below.
2153   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2154
2155   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2156     unsigned OpsWidth = 0;
2157
2158     if (i + VF > e)
2159       OpsWidth = e - i;
2160     else
2161       OpsWidth = VF;
2162
2163     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2164       break;
2165
2166     // Check that a previous iteration of this loop did not delete the Value.
2167     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2168       continue;
2169
2170     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2171                  << "\n");
2172     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2173
2174     R.buildTree(Ops);
2175     int Cost = R.getTreeCost();
2176
2177     if (Cost < -SLPCostThreshold) {
2178       DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2179       R.vectorizeTree();
2180
2181       // Move to the next bundle.
2182       i += VF - 1;
2183       Changed = true;
2184     }
2185   }
2186
2187   return Changed;
2188 }
2189
2190 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2191   if (!V)
2192     return false;
2193
2194   // Try to vectorize V.
2195   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2196     return true;
2197
2198   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2199   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2200   // Try to skip B.
2201   if (B && B->hasOneUse()) {
2202     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2203     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2204     if (tryToVectorizePair(A, B0, R)) {
2205       B->moveBefore(V);
2206       return true;
2207     }
2208     if (tryToVectorizePair(A, B1, R)) {
2209       B->moveBefore(V);
2210       return true;
2211     }
2212   }
2213
2214   // Try to skip A.
2215   if (A && A->hasOneUse()) {
2216     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2217     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2218     if (tryToVectorizePair(A0, B, R)) {
2219       A->moveBefore(V);
2220       return true;
2221     }
2222     if (tryToVectorizePair(A1, B, R)) {
2223       A->moveBefore(V);
2224       return true;
2225     }
2226   }
2227   return 0;
2228 }
2229
2230 /// \brief Generate a shuffle mask to be used in a reduction tree.
2231 ///
2232 /// \param VecLen The length of the vector to be reduced.
2233 /// \param NumEltsToRdx The number of elements that should be reduced in the
2234 ///        vector.
2235 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2236 ///        reduction. A pairwise reduction will generate a mask of 
2237 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
2238 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2239 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2240 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2241                                    bool IsPairwise, bool IsLeft,
2242                                    IRBuilder<> &Builder) {
2243   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2244
2245   SmallVector<Constant *, 32> ShuffleMask(
2246       VecLen, UndefValue::get(Builder.getInt32Ty()));
2247
2248   if (IsPairwise)
2249     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2250     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2251       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2252   else
2253     // Move the upper half of the vector to the lower half.
2254     for (unsigned i = 0; i != NumEltsToRdx; ++i)
2255       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2256
2257   return ConstantVector::get(ShuffleMask);
2258 }
2259
2260
2261 /// Model horizontal reductions.
2262 ///
2263 /// A horizontal reduction is a tree of reduction operations (currently add and
2264 /// fadd) that has operations that can be put into a vector as its leaf.
2265 /// For example, this tree:
2266 ///
2267 /// mul mul mul mul
2268 ///  \  /    \  /
2269 ///   +       +
2270 ///    \     /
2271 ///       +
2272 /// This tree has "mul" as its reduced values and "+" as its reduction
2273 /// operations. A reduction might be feeding into a store or a binary operation
2274 /// feeding a phi.
2275 ///    ...
2276 ///    \  /
2277 ///     +
2278 ///     |
2279 ///  phi +=
2280 ///
2281 ///  Or:
2282 ///    ...
2283 ///    \  /
2284 ///     +
2285 ///     |
2286 ///   *p =
2287 ///
2288 class HorizontalReduction {
2289   SmallPtrSet<Value *, 16> ReductionOps;
2290   SmallVector<Value *, 32> ReducedVals;
2291
2292   BinaryOperator *ReductionRoot;
2293   PHINode *ReductionPHI;
2294
2295   /// The opcode of the reduction.
2296   unsigned ReductionOpcode;
2297   /// The opcode of the values we perform a reduction on.
2298   unsigned ReducedValueOpcode;
2299   /// The width of one full horizontal reduction operation.
2300   unsigned ReduxWidth;
2301   /// Should we model this reduction as a pairwise reduction tree or a tree that
2302   /// splits the vector in halves and adds those halves.
2303   bool IsPairwiseReduction;
2304
2305 public:
2306   HorizontalReduction()
2307     : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2308     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2309
2310   /// \brief Try to find a reduction tree.
2311   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2312                                  const DataLayout *DL) {
2313     assert((!Phi ||
2314             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2315            "Thi phi needs to use the binary operator");
2316
2317     // We could have a initial reductions that is not an add.
2318     //  r *= v1 + v2 + v3 + v4
2319     // In such a case start looking for a tree rooted in the first '+'.
2320     if (Phi) {
2321       if (B->getOperand(0) == Phi) {
2322         Phi = 0;
2323         B = dyn_cast<BinaryOperator>(B->getOperand(1));
2324       } else if (B->getOperand(1) == Phi) {
2325         Phi = 0;
2326         B = dyn_cast<BinaryOperator>(B->getOperand(0));
2327       }
2328     }
2329
2330     if (!B)
2331       return false;
2332
2333     Type *Ty = B->getType();
2334     if (Ty->isVectorTy())
2335       return false;
2336
2337     ReductionOpcode = B->getOpcode();
2338     ReducedValueOpcode = 0;
2339     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2340     ReductionRoot = B;
2341     ReductionPHI = Phi;
2342
2343     if (ReduxWidth < 4)
2344       return false;
2345
2346     // We currently only support adds.
2347     if (ReductionOpcode != Instruction::Add &&
2348         ReductionOpcode != Instruction::FAdd)
2349       return false;
2350
2351     // Post order traverse the reduction tree starting at B. We only handle true
2352     // trees containing only binary operators.
2353     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2354     Stack.push_back(std::make_pair(B, 0));
2355     while (!Stack.empty()) {
2356       BinaryOperator *TreeN = Stack.back().first;
2357       unsigned EdgeToVist = Stack.back().second++;
2358       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2359
2360       // Only handle trees in the current basic block.
2361       if (TreeN->getParent() != B->getParent())
2362         return false;
2363
2364       // Each tree node needs to have one user except for the ultimate
2365       // reduction.
2366       if (!TreeN->hasOneUse() && TreeN != B)
2367         return false;
2368
2369       // Postorder vist.
2370       if (EdgeToVist == 2 || IsReducedValue) {
2371         if (IsReducedValue) {
2372           // Make sure that the opcodes of the operations that we are going to
2373           // reduce match.
2374           if (!ReducedValueOpcode)
2375             ReducedValueOpcode = TreeN->getOpcode();
2376           else if (ReducedValueOpcode != TreeN->getOpcode())
2377             return false;
2378           ReducedVals.push_back(TreeN);
2379         } else {
2380           // We need to be able to reassociate the adds.
2381           if (!TreeN->isAssociative())
2382             return false;
2383           ReductionOps.insert(TreeN);
2384         }
2385         // Retract.
2386         Stack.pop_back();
2387         continue;
2388       }
2389
2390       // Visit left or right.
2391       Value *NextV = TreeN->getOperand(EdgeToVist);
2392       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2393       if (Next)
2394         Stack.push_back(std::make_pair(Next, 0));
2395       else if (NextV != Phi)
2396         return false;
2397     }
2398     return true;
2399   }
2400
2401   /// \brief Attempt to vectorize the tree found by
2402   /// matchAssociativeReduction.
2403   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2404     if (ReducedVals.empty())
2405       return false;
2406
2407     unsigned NumReducedVals = ReducedVals.size();
2408     if (NumReducedVals < ReduxWidth)
2409       return false;
2410
2411     Value *VectorizedTree = 0;
2412     IRBuilder<> Builder(ReductionRoot);
2413     FastMathFlags Unsafe;
2414     Unsafe.setUnsafeAlgebra();
2415     Builder.SetFastMathFlags(Unsafe);
2416     unsigned i = 0;
2417
2418     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2419       ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2420       V.buildTree(ValsToReduce, &ReductionOps);
2421
2422       // Estimate cost.
2423       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2424       if (Cost >= -SLPCostThreshold)
2425         break;
2426
2427       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2428                    << ". (HorRdx)\n");
2429
2430       // Vectorize a tree.
2431       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2432       Value *VectorizedRoot = V.vectorizeTree();
2433
2434       // Emit a reduction.
2435       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2436       if (VectorizedTree) {
2437         Builder.SetCurrentDebugLocation(Loc);
2438         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2439                                      ReducedSubTree, "bin.rdx");
2440       } else
2441         VectorizedTree = ReducedSubTree;
2442     }
2443
2444     if (VectorizedTree) {
2445       // Finish the reduction.
2446       for (; i < NumReducedVals; ++i) {
2447         Builder.SetCurrentDebugLocation(
2448           cast<Instruction>(ReducedVals[i])->getDebugLoc());
2449         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2450                                      ReducedVals[i]);
2451       }
2452       // Update users.
2453       if (ReductionPHI) {
2454         assert(ReductionRoot != NULL && "Need a reduction operation");
2455         ReductionRoot->setOperand(0, VectorizedTree);
2456         ReductionRoot->setOperand(1, ReductionPHI);
2457       } else
2458         ReductionRoot->replaceAllUsesWith(VectorizedTree);
2459     }
2460     return VectorizedTree != 0;
2461   }
2462
2463 private:
2464
2465   /// \brief Calcuate the cost of a reduction.
2466   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2467     Type *ScalarTy = FirstReducedVal->getType();
2468     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2469
2470     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2471     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2472
2473     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2474     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2475
2476     int ScalarReduxCost =
2477         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2478
2479     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2480                  << " for reduction that starts with " << *FirstReducedVal
2481                  << " (It is a "
2482                  << (IsPairwiseReduction ? "pairwise" : "splitting")
2483                  << " reduction)\n");
2484
2485     return VecReduxCost - ScalarReduxCost;
2486   }
2487
2488   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2489                             Value *R, const Twine &Name = "") {
2490     if (Opcode == Instruction::FAdd)
2491       return Builder.CreateFAdd(L, R, Name);
2492     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2493   }
2494
2495   /// \brief Emit a horizontal reduction of the vectorized value.
2496   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2497     assert(VectorizedValue && "Need to have a vectorized tree node");
2498     Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2499     assert(isPowerOf2_32(ReduxWidth) &&
2500            "We only handle power-of-two reductions for now");
2501
2502     Value *TmpVec = ValToReduce;
2503     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2504       if (IsPairwiseReduction) {
2505         Value *LeftMask =
2506           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2507         Value *RightMask =
2508           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2509
2510         Value *LeftShuf = Builder.CreateShuffleVector(
2511           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2512         Value *RightShuf = Builder.CreateShuffleVector(
2513           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2514           "rdx.shuf.r");
2515         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2516                              "bin.rdx");
2517       } else {
2518         Value *UpperHalf =
2519           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2520         Value *Shuf = Builder.CreateShuffleVector(
2521           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2522         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2523       }
2524     }
2525
2526     // The result is in the first element of the vector.
2527     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2528   }
2529 };
2530
2531 /// \brief Recognize construction of vectors like
2532 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2533 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2534 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2535 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2536 ///
2537 /// Returns true if it matches
2538 ///
2539 static bool findBuildVector(InsertElementInst *IE,
2540                             SmallVectorImpl<Value *> &Ops) {
2541   if (!isa<UndefValue>(IE->getOperand(0)))
2542     return false;
2543
2544   while (true) {
2545     Ops.push_back(IE->getOperand(1));
2546
2547     if (IE->use_empty())
2548       return false;
2549
2550     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2551     if (!NextUse)
2552       return true;
2553
2554     // If this isn't the final use, make sure the next insertelement is the only
2555     // use. It's OK if the final constructed vector is used multiple times
2556     if (!IE->hasOneUse())
2557       return false;
2558
2559     IE = NextUse;
2560   }
2561
2562   return false;
2563 }
2564
2565 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2566   return V->getType() < V2->getType();
2567 }
2568
2569 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2570   bool Changed = false;
2571   SmallVector<Value *, 4> Incoming;
2572   SmallSet<Value *, 16> VisitedInstrs;
2573
2574   bool HaveVectorizedPhiNodes = true;
2575   while (HaveVectorizedPhiNodes) {
2576     HaveVectorizedPhiNodes = false;
2577
2578     // Collect the incoming values from the PHIs.
2579     Incoming.clear();
2580     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2581          ++instr) {
2582       PHINode *P = dyn_cast<PHINode>(instr);
2583       if (!P)
2584         break;
2585
2586       if (!VisitedInstrs.count(P))
2587         Incoming.push_back(P);
2588     }
2589
2590     // Sort by type.
2591     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2592
2593     // Try to vectorize elements base on their type.
2594     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2595                                            E = Incoming.end();
2596          IncIt != E;) {
2597
2598       // Look for the next elements with the same type.
2599       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2600       while (SameTypeIt != E &&
2601              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2602         VisitedInstrs.insert(*SameTypeIt);
2603         ++SameTypeIt;
2604       }
2605
2606       // Try to vectorize them.
2607       unsigned NumElts = (SameTypeIt - IncIt);
2608       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2609       if (NumElts > 1 &&
2610           tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2611         // Success start over because instructions might have been changed.
2612         HaveVectorizedPhiNodes = true;
2613         Changed = true;
2614         break;
2615       }
2616
2617       // Start over at the next instruction of a different type (or the end).
2618       IncIt = SameTypeIt;
2619     }
2620   }
2621
2622   VisitedInstrs.clear();
2623
2624   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2625     // We may go through BB multiple times so skip the one we have checked.
2626     if (!VisitedInstrs.insert(it))
2627       continue;
2628
2629     if (isa<DbgInfoIntrinsic>(it))
2630       continue;
2631
2632     // Try to vectorize reductions that use PHINodes.
2633     if (PHINode *P = dyn_cast<PHINode>(it)) {
2634       // Check that the PHI is a reduction PHI.
2635       if (P->getNumIncomingValues() != 2)
2636         return Changed;
2637       Value *Rdx =
2638           (P->getIncomingBlock(0) == BB
2639                ? (P->getIncomingValue(0))
2640                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2641       // Check if this is a Binary Operator.
2642       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2643       if (!BI)
2644         continue;
2645
2646       // Try to match and vectorize a horizontal reduction.
2647       HorizontalReduction HorRdx;
2648       if (ShouldVectorizeHor &&
2649           HorRdx.matchAssociativeReduction(P, BI, DL) &&
2650           HorRdx.tryToReduce(R, TTI)) {
2651         Changed = true;
2652         it = BB->begin();
2653         e = BB->end();
2654         continue;
2655       }
2656
2657      Value *Inst = BI->getOperand(0);
2658       if (Inst == P)
2659         Inst = BI->getOperand(1);
2660
2661       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2662         // We would like to start over since some instructions are deleted
2663         // and the iterator may become invalid value.
2664         Changed = true;
2665         it = BB->begin();
2666         e = BB->end();
2667         continue;
2668       }
2669
2670       continue;
2671     }
2672
2673     // Try to vectorize horizontal reductions feeding into a store.
2674     if (ShouldStartVectorizeHorAtStore)
2675       if (StoreInst *SI = dyn_cast<StoreInst>(it))
2676         if (BinaryOperator *BinOp =
2677                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2678           HorizontalReduction HorRdx;
2679           if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2680                 HorRdx.tryToReduce(R, TTI)) ||
2681                tryToVectorize(BinOp, R))) {
2682             Changed = true;
2683             it = BB->begin();
2684             e = BB->end();
2685             continue;
2686           }
2687         }
2688
2689     // Try to vectorize trees that start at compare instructions.
2690     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2691       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2692         Changed = true;
2693         // We would like to start over since some instructions are deleted
2694         // and the iterator may become invalid value.
2695         it = BB->begin();
2696         e = BB->end();
2697         continue;
2698       }
2699
2700       for (int i = 0; i < 2; ++i) {
2701          if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2702             if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2703               Changed = true;
2704               // We would like to start over since some instructions are deleted
2705               // and the iterator may become invalid value.
2706               it = BB->begin();
2707               e = BB->end();
2708             }
2709          }
2710       }
2711       continue;
2712     }
2713
2714     // Try to vectorize trees that start at insertelement instructions.
2715     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2716       SmallVector<Value *, 8> Ops;
2717       if (!findBuildVector(IE, Ops))
2718         continue;
2719
2720       if (tryToVectorizeList(Ops, R)) {
2721         Changed = true;
2722         it = BB->begin();
2723         e = BB->end();
2724       }
2725
2726       continue;
2727     }
2728   }
2729
2730   return Changed;
2731 }
2732
2733 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2734   bool Changed = false;
2735   // Attempt to sort and vectorize each of the store-groups.
2736   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2737        it != e; ++it) {
2738     if (it->second.size() < 2)
2739       continue;
2740
2741     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2742           << it->second.size() << ".\n");
2743
2744     // Process the stores in chunks of 16.
2745     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2746       unsigned Len = std::min<unsigned>(CE - CI, 16);
2747       ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2748       Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2749     }
2750   }
2751   return Changed;
2752 }
2753
2754 } // end anonymous namespace
2755
2756 char SLPVectorizer::ID = 0;
2757 static const char lv_name[] = "SLP Vectorizer";
2758 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2759 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2760 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2761 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2762 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2763 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2764
2765 namespace llvm {
2766 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2767 }