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