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