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