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/ADT/Optional.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CodeMetrics.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/VectorUtils.h"
47 #include <algorithm>
48 #include <map>
49 #include <memory>
50 
51 using namespace llvm;
52 
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
55 
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
57 
58 static cl::opt<int>
59     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60                      cl::desc("Only vectorize if you gain more than this "
61                               "number "));
62 
63 static cl::opt<bool>
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
65                    cl::desc("Attempt to vectorize horizontal reductions"));
66 
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
69     cl::desc(
70         "Attempt to vectorize horizontal reductions feeding into a store"));
71 
72 namespace {
73 
74 static const unsigned MinVecRegSize = 128;
75 
76 static const unsigned RecursionMaxDepth = 12;
77 
78 /// \returns the parent basic block if all of the instructions in \p VL
79 /// are in the same block or null otherwise.
80 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
81   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
82   if (!I0)
83     return nullptr;
84   BasicBlock *BB = I0->getParent();
85   for (int i = 1, e = VL.size(); i < e; i++) {
86     Instruction *I = dyn_cast<Instruction>(VL[i]);
87     if (!I)
88       return nullptr;
89 
90     if (BB != I->getParent())
91       return nullptr;
92   }
93   return BB;
94 }
95 
96 /// \returns True if all of the values in \p VL are constants.
97 static bool allConstant(ArrayRef<Value *> VL) {
98   for (unsigned i = 0, e = VL.size(); i < e; ++i)
99     if (!isa<Constant>(VL[i]))
100       return false;
101   return true;
102 }
103 
104 /// \returns True if all of the values in \p VL are identical.
105 static bool isSplat(ArrayRef<Value *> VL) {
106   for (unsigned i = 1, e = VL.size(); i < e; ++i)
107     if (VL[i] != VL[0])
108       return false;
109   return true;
110 }
111 
112 ///\returns Opcode that can be clubbed with \p Op to create an alternate
113 /// sequence which can later be merged as a ShuffleVector instruction.
114 static unsigned getAltOpcode(unsigned Op) {
115   switch (Op) {
116   case Instruction::FAdd:
117     return Instruction::FSub;
118   case Instruction::FSub:
119     return Instruction::FAdd;
120   case Instruction::Add:
121     return Instruction::Sub;
122   case Instruction::Sub:
123     return Instruction::Add;
124   default:
125     return 0;
126   }
127 }
128 
129 ///\returns bool representing if Opcode \p Op can be part
130 /// of an alternate sequence which can later be merged as
131 /// a ShuffleVector instruction.
132 static bool canCombineAsAltInst(unsigned Op) {
133   if (Op == Instruction::FAdd || Op == Instruction::FSub ||
134       Op == Instruction::Sub || Op == Instruction::Add)
135     return true;
136   return false;
137 }
138 
139 /// \returns ShuffleVector instruction if intructions in \p VL have
140 ///  alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
141 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
142 static unsigned isAltInst(ArrayRef<Value *> VL) {
143   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
144   unsigned Opcode = I0->getOpcode();
145   unsigned AltOpcode = getAltOpcode(Opcode);
146   for (int i = 1, e = VL.size(); i < e; i++) {
147     Instruction *I = dyn_cast<Instruction>(VL[i]);
148     if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
149       return 0;
150   }
151   return Instruction::ShuffleVector;
152 }
153 
154 /// \returns The opcode if all of the Instructions in \p VL have the same
155 /// opcode, or zero.
156 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
157   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
158   if (!I0)
159     return 0;
160   unsigned Opcode = I0->getOpcode();
161   for (int i = 1, e = VL.size(); i < e; i++) {
162     Instruction *I = dyn_cast<Instruction>(VL[i]);
163     if (!I || Opcode != I->getOpcode()) {
164       if (canCombineAsAltInst(Opcode) && i == 1)
165         return isAltInst(VL);
166       return 0;
167     }
168   }
169   return Opcode;
170 }
171 
172 /// Get the intersection (logical and) of all of the potential IR flags
173 /// of each scalar operation (VL) that will be converted into a vector (I).
174 /// Flag set: NSW, NUW, exact, and all of fast-math.
175 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
176   if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
177     if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
178       // Intersection is initialized to the 0th scalar,
179       // so start counting from index '1'.
180       for (int i = 1, e = VL.size(); i < e; ++i) {
181         if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
182           Intersection->andIRFlags(Scalar);
183       }
184       VecOp->copyIRFlags(Intersection);
185     }
186   }
187 }
188 
189 /// \returns \p I after propagating metadata from \p VL.
190 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
191   Instruction *I0 = cast<Instruction>(VL[0]);
192   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
193   I0->getAllMetadataOtherThanDebugLoc(Metadata);
194 
195   for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
196     unsigned Kind = Metadata[i].first;
197     MDNode *MD = Metadata[i].second;
198 
199     for (int i = 1, e = VL.size(); MD && i != e; i++) {
200       Instruction *I = cast<Instruction>(VL[i]);
201       MDNode *IMD = I->getMetadata(Kind);
202 
203       switch (Kind) {
204       default:
205         MD = nullptr; // Remove unknown metadata
206         break;
207       case LLVMContext::MD_tbaa:
208         MD = MDNode::getMostGenericTBAA(MD, IMD);
209         break;
210       case LLVMContext::MD_alias_scope:
211       case LLVMContext::MD_noalias:
212         MD = MDNode::intersect(MD, IMD);
213         break;
214       case LLVMContext::MD_fpmath:
215         MD = MDNode::getMostGenericFPMath(MD, IMD);
216         break;
217       }
218     }
219     I->setMetadata(Kind, MD);
220   }
221   return I;
222 }
223 
224 /// \returns The type that all of the values in \p VL have or null if there
225 /// are different types.
226 static Type* getSameType(ArrayRef<Value *> VL) {
227   Type *Ty = VL[0]->getType();
228   for (int i = 1, e = VL.size(); i < e; i++)
229     if (VL[i]->getType() != Ty)
230       return nullptr;
231 
232   return Ty;
233 }
234 
235 /// \returns True if the ExtractElement instructions in VL can be vectorized
236 /// to use the original vector.
237 static bool CanReuseExtract(ArrayRef<Value *> VL) {
238   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
239   // Check if all of the extracts come from the same vector and from the
240   // correct offset.
241   Value *VL0 = VL[0];
242   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
243   Value *Vec = E0->getOperand(0);
244 
245   // We have to extract from the same vector type.
246   unsigned NElts = Vec->getType()->getVectorNumElements();
247 
248   if (NElts != VL.size())
249     return false;
250 
251   // Check that all of the indices extract from the correct offset.
252   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
253   if (!CI || CI->getZExtValue())
254     return false;
255 
256   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
257     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
258     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
259 
260     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
261       return false;
262   }
263 
264   return true;
265 }
266 
267 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
268                                            SmallVectorImpl<Value *> &Left,
269                                            SmallVectorImpl<Value *> &Right) {
270 
271   SmallVector<Value *, 16> OrigLeft, OrigRight;
272 
273   bool AllSameOpcodeLeft = true;
274   bool AllSameOpcodeRight = true;
275   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
276     Instruction *I = cast<Instruction>(VL[i]);
277     Value *V0 = I->getOperand(0);
278     Value *V1 = I->getOperand(1);
279 
280     OrigLeft.push_back(V0);
281     OrigRight.push_back(V1);
282 
283     Instruction *I0 = dyn_cast<Instruction>(V0);
284     Instruction *I1 = dyn_cast<Instruction>(V1);
285 
286     // Check whether all operands on one side have the same opcode. In this case
287     // we want to preserve the original order and not make things worse by
288     // reordering.
289     AllSameOpcodeLeft = I0;
290     AllSameOpcodeRight = I1;
291 
292     if (i && AllSameOpcodeLeft) {
293       if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
294         if(P0->getOpcode() != I0->getOpcode())
295           AllSameOpcodeLeft = false;
296       } else
297         AllSameOpcodeLeft = false;
298     }
299     if (i && AllSameOpcodeRight) {
300       if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
301         if(P1->getOpcode() != I1->getOpcode())
302           AllSameOpcodeRight = false;
303       } else
304         AllSameOpcodeRight = false;
305     }
306 
307     // Sort two opcodes. In the code below we try to preserve the ability to use
308     // broadcast of values instead of individual inserts.
309     // vl1 = load
310     // vl2 = phi
311     // vr1 = load
312     // vr2 = vr2
313     //    = vl1 x vr1
314     //    = vl2 x vr2
315     // If we just sorted according to opcode we would leave the first line in
316     // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
317     //    = vl1 x vr1
318     //    = vr2 x vl2
319     // Because vr2 and vr1 are from the same load we loose the opportunity of a
320     // broadcast for the packed right side in the backend: we have [vr1, vl2]
321     // instead of [vr1, vr2=vr1].
322     if (I0 && I1) {
323        if(!i && I0->getOpcode() > I1->getOpcode()) {
324          Left.push_back(I1);
325          Right.push_back(I0);
326        } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
327          // Try not to destroy a broad cast for no apparent benefit.
328          Left.push_back(I1);
329          Right.push_back(I0);
330        } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] ==  I0) {
331          // Try preserve broadcasts.
332          Left.push_back(I1);
333          Right.push_back(I0);
334        } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
335          // Try preserve broadcasts.
336          Left.push_back(I1);
337          Right.push_back(I0);
338        } else {
339          Left.push_back(I0);
340          Right.push_back(I1);
341        }
342        continue;
343     }
344     // One opcode, put the instruction on the right.
345     if (I0) {
346       Left.push_back(V1);
347       Right.push_back(I0);
348       continue;
349     }
350     Left.push_back(V0);
351     Right.push_back(V1);
352   }
353 
354   bool LeftBroadcast = isSplat(Left);
355   bool RightBroadcast = isSplat(Right);
356 
357   // Don't reorder if the operands where good to begin with.
358   if (!(LeftBroadcast || RightBroadcast) &&
359       (AllSameOpcodeRight || AllSameOpcodeLeft)) {
360     Left = OrigLeft;
361     Right = OrigRight;
362   }
363 }
364 
365 /// \returns True if in-tree use also needs extract. This refers to
366 /// possible scalar operand in vectorized instruction.
367 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
368                                     TargetLibraryInfo *TLI) {
369 
370   unsigned Opcode = UserInst->getOpcode();
371   switch (Opcode) {
372   case Instruction::Load: {
373     LoadInst *LI = cast<LoadInst>(UserInst);
374     return (LI->getPointerOperand() == Scalar);
375   }
376   case Instruction::Store: {
377     StoreInst *SI = cast<StoreInst>(UserInst);
378     return (SI->getPointerOperand() == Scalar);
379   }
380   case Instruction::Call: {
381     CallInst *CI = cast<CallInst>(UserInst);
382     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
383     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
384       return (CI->getArgOperand(1) == Scalar);
385     }
386   }
387   default:
388     return false;
389   }
390 }
391 
392 /// \returns the AA location that is being access by the instruction.
393 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
394   if (StoreInst *SI = dyn_cast<StoreInst>(I))
395     return AA->getLocation(SI);
396   if (LoadInst *LI = dyn_cast<LoadInst>(I))
397     return AA->getLocation(LI);
398   return AliasAnalysis::Location();
399 }
400 
401 /// Bottom Up SLP Vectorizer.
402 class BoUpSLP {
403 public:
404   typedef SmallVector<Value *, 8> ValueList;
405   typedef SmallVector<Instruction *, 16> InstrList;
406   typedef SmallPtrSet<Value *, 16> ValueSet;
407   typedef SmallVector<StoreInst *, 8> StoreList;
408 
409   BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
410           TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
411           LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
412       : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
413         SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
414         Builder(Se->getContext()) {
415     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
416   }
417 
418   /// \brief Vectorize the tree that starts with the elements in \p VL.
419   /// Returns the vectorized root.
420   Value *vectorizeTree();
421 
422   /// \returns the cost incurred by unwanted spills and fills, caused by
423   /// holding live values over call sites.
424   int getSpillCost();
425 
426   /// \returns the vectorization cost of the subtree that starts at \p VL.
427   /// A negative number means that this is profitable.
428   int getTreeCost();
429 
430   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
431   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
432   void buildTree(ArrayRef<Value *> Roots,
433                  ArrayRef<Value *> UserIgnoreLst = None);
434 
435   /// Clear the internal data structures that are created by 'buildTree'.
436   void deleteTree() {
437     VectorizableTree.clear();
438     ScalarToTreeEntry.clear();
439     MustGather.clear();
440     ExternalUses.clear();
441     NumLoadsWantToKeepOrder = 0;
442     NumLoadsWantToChangeOrder = 0;
443     for (auto &Iter : BlocksSchedules) {
444       BlockScheduling *BS = Iter.second.get();
445       BS->clear();
446     }
447   }
448 
449   /// \returns true if the memory operations A and B are consecutive.
450   bool isConsecutiveAccess(Value *A, Value *B);
451 
452   /// \brief Perform LICM and CSE on the newly generated gather sequences.
453   void optimizeGatherSequence();
454 
455   /// \returns true if it is benefitial to reverse the vector order.
456   bool shouldReorder() const {
457     return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
458   }
459 
460 private:
461   struct TreeEntry;
462 
463   /// \returns the cost of the vectorizable entry.
464   int getEntryCost(TreeEntry *E);
465 
466   /// This is the recursive part of buildTree.
467   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
468 
469   /// Vectorize a single entry in the tree.
470   Value *vectorizeTree(TreeEntry *E);
471 
472   /// Vectorize a single entry in the tree, starting in \p VL.
473   Value *vectorizeTree(ArrayRef<Value *> VL);
474 
475   /// \returns the pointer to the vectorized value if \p VL is already
476   /// vectorized, or NULL. They may happen in cycles.
477   Value *alreadyVectorized(ArrayRef<Value *> VL) const;
478 
479   /// \brief Take the pointer operand from the Load/Store instruction.
480   /// \returns NULL if this is not a valid Load/Store instruction.
481   static Value *getPointerOperand(Value *I);
482 
483   /// \brief Take the address space operand from the Load/Store instruction.
484   /// \returns -1 if this is not a valid Load/Store instruction.
485   static unsigned getAddressSpaceOperand(Value *I);
486 
487   /// \returns the scalarization cost for this type. Scalarization in this
488   /// context means the creation of vectors from a group of scalars.
489   int getGatherCost(Type *Ty);
490 
491   /// \returns the scalarization cost for this list of values. Assuming that
492   /// this subtree gets vectorized, we may need to extract the values from the
493   /// roots. This method calculates the cost of extracting the values.
494   int getGatherCost(ArrayRef<Value *> VL);
495 
496   /// \brief Set the Builder insert point to one after the last instruction in
497   /// the bundle
498   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
499 
500   /// \returns a vector from a collection of scalars in \p VL.
501   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
502 
503   /// \returns whether the VectorizableTree is fully vectoriable and will
504   /// be beneficial even the tree height is tiny.
505   bool isFullyVectorizableTinyTree();
506 
507   struct TreeEntry {
508     TreeEntry() : Scalars(), VectorizedValue(nullptr),
509     NeedToGather(0) {}
510 
511     /// \returns true if the scalars in VL are equal to this entry.
512     bool isSame(ArrayRef<Value *> VL) const {
513       assert(VL.size() == Scalars.size() && "Invalid size");
514       return std::equal(VL.begin(), VL.end(), Scalars.begin());
515     }
516 
517     /// A vector of scalars.
518     ValueList Scalars;
519 
520     /// The Scalars are vectorized into this value. It is initialized to Null.
521     Value *VectorizedValue;
522 
523     /// Do we need to gather this sequence ?
524     bool NeedToGather;
525   };
526 
527   /// Create a new VectorizableTree entry.
528   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
529     VectorizableTree.push_back(TreeEntry());
530     int idx = VectorizableTree.size() - 1;
531     TreeEntry *Last = &VectorizableTree[idx];
532     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
533     Last->NeedToGather = !Vectorized;
534     if (Vectorized) {
535       for (int i = 0, e = VL.size(); i != e; ++i) {
536         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
537         ScalarToTreeEntry[VL[i]] = idx;
538       }
539     } else {
540       MustGather.insert(VL.begin(), VL.end());
541     }
542     return Last;
543   }
544 
545   /// -- Vectorization State --
546   /// Holds all of the tree entries.
547   std::vector<TreeEntry> VectorizableTree;
548 
549   /// Maps a specific scalar to its tree entry.
550   SmallDenseMap<Value*, int> ScalarToTreeEntry;
551 
552   /// A list of scalars that we found that we need to keep as scalars.
553   ValueSet MustGather;
554 
555   /// This POD struct describes one external user in the vectorized tree.
556   struct ExternalUser {
557     ExternalUser (Value *S, llvm::User *U, int L) :
558       Scalar(S), User(U), Lane(L){};
559     // Which scalar in our function.
560     Value *Scalar;
561     // Which user that uses the scalar.
562     llvm::User *User;
563     // Which lane does the scalar belong to.
564     int Lane;
565   };
566   typedef SmallVector<ExternalUser, 16> UserList;
567 
568   /// Checks if two instructions may access the same memory.
569   ///
570   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
571   /// is invariant in the calling loop.
572   bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
573                  Instruction *Inst2) {
574 
575     // First check if the result is already in the cache.
576     AliasCacheKey key = std::make_pair(Inst1, Inst2);
577     Optional<bool> &result = AliasCache[key];
578     if (result.hasValue()) {
579       return result.getValue();
580     }
581     AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
582     bool aliased = true;
583     if (Loc1.Ptr && Loc2.Ptr) {
584       // Do the alias check.
585       aliased = AA->alias(Loc1, Loc2);
586     }
587     // Store the result in the cache.
588     result = aliased;
589     return aliased;
590   }
591 
592   typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
593 
594   /// Cache for alias results.
595   /// TODO: consider moving this to the AliasAnalysis itself.
596   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
597 
598   /// Removes an instruction from its block and eventually deletes it.
599   /// It's like Instruction::eraseFromParent() except that the actual deletion
600   /// is delayed until BoUpSLP is destructed.
601   /// This is required to ensure that there are no incorrect collisions in the
602   /// AliasCache, which can happen if a new instruction is allocated at the
603   /// same address as a previously deleted instruction.
604   void eraseInstruction(Instruction *I) {
605     I->removeFromParent();
606     I->dropAllReferences();
607     DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
608   }
609 
610   /// Temporary store for deleted instructions. Instructions will be deleted
611   /// eventually when the BoUpSLP is destructed.
612   SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
613 
614   /// A list of values that need to extracted out of the tree.
615   /// This list holds pairs of (Internal Scalar : External User).
616   UserList ExternalUses;
617 
618   /// Values used only by @llvm.assume calls.
619   SmallPtrSet<const Value *, 32> EphValues;
620 
621   /// Holds all of the instructions that we gathered.
622   SetVector<Instruction *> GatherSeq;
623   /// A list of blocks that we are going to CSE.
624   SetVector<BasicBlock *> CSEBlocks;
625 
626   /// Contains all scheduling relevant data for an instruction.
627   /// A ScheduleData either represents a single instruction or a member of an
628   /// instruction bundle (= a group of instructions which is combined into a
629   /// vector instruction).
630   struct ScheduleData {
631 
632     // The initial value for the dependency counters. It means that the
633     // dependencies are not calculated yet.
634     enum { InvalidDeps = -1 };
635 
636     ScheduleData()
637         : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
638           NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
639           Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
640           UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
641 
642     void init(int BlockSchedulingRegionID) {
643       FirstInBundle = this;
644       NextInBundle = nullptr;
645       NextLoadStore = nullptr;
646       IsScheduled = false;
647       SchedulingRegionID = BlockSchedulingRegionID;
648       UnscheduledDepsInBundle = UnscheduledDeps;
649       clearDependencies();
650     }
651 
652     /// Returns true if the dependency information has been calculated.
653     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
654 
655     /// Returns true for single instructions and for bundle representatives
656     /// (= the head of a bundle).
657     bool isSchedulingEntity() const { return FirstInBundle == this; }
658 
659     /// Returns true if it represents an instruction bundle and not only a
660     /// single instruction.
661     bool isPartOfBundle() const {
662       return NextInBundle != nullptr || FirstInBundle != this;
663     }
664 
665     /// Returns true if it is ready for scheduling, i.e. it has no more
666     /// unscheduled depending instructions/bundles.
667     bool isReady() const {
668       assert(isSchedulingEntity() &&
669              "can't consider non-scheduling entity for ready list");
670       return UnscheduledDepsInBundle == 0 && !IsScheduled;
671     }
672 
673     /// Modifies the number of unscheduled dependencies, also updating it for
674     /// the whole bundle.
675     int incrementUnscheduledDeps(int Incr) {
676       UnscheduledDeps += Incr;
677       return FirstInBundle->UnscheduledDepsInBundle += Incr;
678     }
679 
680     /// Sets the number of unscheduled dependencies to the number of
681     /// dependencies.
682     void resetUnscheduledDeps() {
683       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
684     }
685 
686     /// Clears all dependency information.
687     void clearDependencies() {
688       Dependencies = InvalidDeps;
689       resetUnscheduledDeps();
690       MemoryDependencies.clear();
691     }
692 
693     void dump(raw_ostream &os) const {
694       if (!isSchedulingEntity()) {
695         os << "/ " << *Inst;
696       } else if (NextInBundle) {
697         os << '[' << *Inst;
698         ScheduleData *SD = NextInBundle;
699         while (SD) {
700           os << ';' << *SD->Inst;
701           SD = SD->NextInBundle;
702         }
703         os << ']';
704       } else {
705         os << *Inst;
706       }
707     }
708 
709     Instruction *Inst;
710 
711     /// Points to the head in an instruction bundle (and always to this for
712     /// single instructions).
713     ScheduleData *FirstInBundle;
714 
715     /// Single linked list of all instructions in a bundle. Null if it is a
716     /// single instruction.
717     ScheduleData *NextInBundle;
718 
719     /// Single linked list of all memory instructions (e.g. load, store, call)
720     /// in the block - until the end of the scheduling region.
721     ScheduleData *NextLoadStore;
722 
723     /// The dependent memory instructions.
724     /// This list is derived on demand in calculateDependencies().
725     SmallVector<ScheduleData *, 4> MemoryDependencies;
726 
727     /// This ScheduleData is in the current scheduling region if this matches
728     /// the current SchedulingRegionID of BlockScheduling.
729     int SchedulingRegionID;
730 
731     /// Used for getting a "good" final ordering of instructions.
732     int SchedulingPriority;
733 
734     /// The number of dependencies. Constitutes of the number of users of the
735     /// instruction plus the number of dependent memory instructions (if any).
736     /// This value is calculated on demand.
737     /// If InvalidDeps, the number of dependencies is not calculated yet.
738     ///
739     int Dependencies;
740 
741     /// The number of dependencies minus the number of dependencies of scheduled
742     /// instructions. As soon as this is zero, the instruction/bundle gets ready
743     /// for scheduling.
744     /// Note that this is negative as long as Dependencies is not calculated.
745     int UnscheduledDeps;
746 
747     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
748     /// single instructions.
749     int UnscheduledDepsInBundle;
750 
751     /// True if this instruction is scheduled (or considered as scheduled in the
752     /// dry-run).
753     bool IsScheduled;
754   };
755 
756 #ifndef NDEBUG
757   friend raw_ostream &operator<<(raw_ostream &os,
758                                  const BoUpSLP::ScheduleData &SD);
759 #endif
760 
761   /// Contains all scheduling data for a basic block.
762   ///
763   struct BlockScheduling {
764 
765     BlockScheduling(BasicBlock *BB)
766         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
767           ScheduleStart(nullptr), ScheduleEnd(nullptr),
768           FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
769           // Make sure that the initial SchedulingRegionID is greater than the
770           // initial SchedulingRegionID in ScheduleData (which is 0).
771           SchedulingRegionID(1) {}
772 
773     void clear() {
774       ReadyInsts.clear();
775       ScheduleStart = nullptr;
776       ScheduleEnd = nullptr;
777       FirstLoadStoreInRegion = nullptr;
778       LastLoadStoreInRegion = nullptr;
779 
780       // Make a new scheduling region, i.e. all existing ScheduleData is not
781       // in the new region yet.
782       ++SchedulingRegionID;
783     }
784 
785     ScheduleData *getScheduleData(Value *V) {
786       ScheduleData *SD = ScheduleDataMap[V];
787       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
788         return SD;
789       return nullptr;
790     }
791 
792     bool isInSchedulingRegion(ScheduleData *SD) {
793       return SD->SchedulingRegionID == SchedulingRegionID;
794     }
795 
796     /// Marks an instruction as scheduled and puts all dependent ready
797     /// instructions into the ready-list.
798     template <typename ReadyListType>
799     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
800       SD->IsScheduled = true;
801       DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
802 
803       ScheduleData *BundleMember = SD;
804       while (BundleMember) {
805         // Handle the def-use chain dependencies.
806         for (Use &U : BundleMember->Inst->operands()) {
807           ScheduleData *OpDef = getScheduleData(U.get());
808           if (OpDef && OpDef->hasValidDependencies() &&
809               OpDef->incrementUnscheduledDeps(-1) == 0) {
810             // There are no more unscheduled dependencies after decrementing,
811             // so we can put the dependent instruction into the ready list.
812             ScheduleData *DepBundle = OpDef->FirstInBundle;
813             assert(!DepBundle->IsScheduled &&
814                    "already scheduled bundle gets ready");
815             ReadyList.insert(DepBundle);
816             DEBUG(dbgs() << "SLP:    gets ready (def): " << *DepBundle << "\n");
817           }
818         }
819         // Handle the memory dependencies.
820         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
821           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
822             // There are no more unscheduled dependencies after decrementing,
823             // so we can put the dependent instruction into the ready list.
824             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
825             assert(!DepBundle->IsScheduled &&
826                    "already scheduled bundle gets ready");
827             ReadyList.insert(DepBundle);
828             DEBUG(dbgs() << "SLP:    gets ready (mem): " << *DepBundle << "\n");
829           }
830         }
831         BundleMember = BundleMember->NextInBundle;
832       }
833     }
834 
835     /// Put all instructions into the ReadyList which are ready for scheduling.
836     template <typename ReadyListType>
837     void initialFillReadyList(ReadyListType &ReadyList) {
838       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
839         ScheduleData *SD = getScheduleData(I);
840         if (SD->isSchedulingEntity() && SD->isReady()) {
841           ReadyList.insert(SD);
842           DEBUG(dbgs() << "SLP:    initially in ready list: " << *I << "\n");
843         }
844       }
845     }
846 
847     /// Checks if a bundle of instructions can be scheduled, i.e. has no
848     /// cyclic dependencies. This is only a dry-run, no instructions are
849     /// actually moved at this stage.
850     bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
851 
852     /// Un-bundles a group of instructions.
853     void cancelScheduling(ArrayRef<Value *> VL);
854 
855     /// Extends the scheduling region so that V is inside the region.
856     void extendSchedulingRegion(Value *V);
857 
858     /// Initialize the ScheduleData structures for new instructions in the
859     /// scheduling region.
860     void initScheduleData(Instruction *FromI, Instruction *ToI,
861                           ScheduleData *PrevLoadStore,
862                           ScheduleData *NextLoadStore);
863 
864     /// Updates the dependency information of a bundle and of all instructions/
865     /// bundles which depend on the original bundle.
866     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
867                                BoUpSLP *SLP);
868 
869     /// Sets all instruction in the scheduling region to un-scheduled.
870     void resetSchedule();
871 
872     BasicBlock *BB;
873 
874     /// Simple memory allocation for ScheduleData.
875     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
876 
877     /// The size of a ScheduleData array in ScheduleDataChunks.
878     int ChunkSize;
879 
880     /// The allocator position in the current chunk, which is the last entry
881     /// of ScheduleDataChunks.
882     int ChunkPos;
883 
884     /// Attaches ScheduleData to Instruction.
885     /// Note that the mapping survives during all vectorization iterations, i.e.
886     /// ScheduleData structures are recycled.
887     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
888 
889     struct ReadyList : SmallVector<ScheduleData *, 8> {
890       void insert(ScheduleData *SD) { push_back(SD); }
891     };
892 
893     /// The ready-list for scheduling (only used for the dry-run).
894     ReadyList ReadyInsts;
895 
896     /// The first instruction of the scheduling region.
897     Instruction *ScheduleStart;
898 
899     /// The first instruction _after_ the scheduling region.
900     Instruction *ScheduleEnd;
901 
902     /// The first memory accessing instruction in the scheduling region
903     /// (can be null).
904     ScheduleData *FirstLoadStoreInRegion;
905 
906     /// The last memory accessing instruction in the scheduling region
907     /// (can be null).
908     ScheduleData *LastLoadStoreInRegion;
909 
910     /// The ID of the scheduling region. For a new vectorization iteration this
911     /// is incremented which "removes" all ScheduleData from the region.
912     int SchedulingRegionID;
913   };
914 
915   /// Attaches the BlockScheduling structures to basic blocks.
916   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
917 
918   /// Performs the "real" scheduling. Done before vectorization is actually
919   /// performed in a basic block.
920   void scheduleBlock(BlockScheduling *BS);
921 
922   /// List of users to ignore during scheduling and that don't need extracting.
923   ArrayRef<Value *> UserIgnoreList;
924 
925   // Number of load-bundles, which contain consecutive loads.
926   int NumLoadsWantToKeepOrder;
927 
928   // Number of load-bundles of size 2, which are consecutive loads if reversed.
929   int NumLoadsWantToChangeOrder;
930 
931   // Analysis and block reference.
932   Function *F;
933   ScalarEvolution *SE;
934   const DataLayout *DL;
935   TargetTransformInfo *TTI;
936   TargetLibraryInfo *TLI;
937   AliasAnalysis *AA;
938   LoopInfo *LI;
939   DominatorTree *DT;
940   /// Instruction builder to construct the vectorized tree.
941   IRBuilder<> Builder;
942 };
943 
944 #ifndef NDEBUG
945 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
946   SD.dump(os);
947   return os;
948 }
949 #endif
950 
951 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
952                         ArrayRef<Value *> UserIgnoreLst) {
953   deleteTree();
954   UserIgnoreList = UserIgnoreLst;
955   if (!getSameType(Roots))
956     return;
957   buildTree_rec(Roots, 0);
958 
959   // Collect the values that we need to extract from the tree.
960   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
961     TreeEntry *Entry = &VectorizableTree[EIdx];
962 
963     // For each lane:
964     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
965       Value *Scalar = Entry->Scalars[Lane];
966 
967       // No need to handle users of gathered values.
968       if (Entry->NeedToGather)
969         continue;
970 
971       for (User *U : Scalar->users()) {
972         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
973 
974         Instruction *UserInst = dyn_cast<Instruction>(U);
975         if (!UserInst)
976           continue;
977 
978         // Skip in-tree scalars that become vectors
979         if (ScalarToTreeEntry.count(U)) {
980           int Idx = ScalarToTreeEntry[U];
981           TreeEntry *UseEntry = &VectorizableTree[Idx];
982           Value *UseScalar = UseEntry->Scalars[0];
983           // Some in-tree scalars will remain as scalar in vectorized
984           // instructions. If that is the case, the one in Lane 0 will
985           // be used.
986           if (UseScalar != U ||
987               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
988             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
989                          << ".\n");
990             assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
991             continue;
992           }
993         }
994 
995         // Ignore users in the user ignore list.
996         if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
997             UserIgnoreList.end())
998           continue;
999 
1000         DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1001               Lane << " from " << *Scalar << ".\n");
1002         ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1003       }
1004     }
1005   }
1006 }
1007 
1008 
1009 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
1010   bool SameTy = getSameType(VL); (void)SameTy;
1011   bool isAltShuffle = false;
1012   assert(SameTy && "Invalid types!");
1013 
1014   if (Depth == RecursionMaxDepth) {
1015     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1016     newTreeEntry(VL, false);
1017     return;
1018   }
1019 
1020   // Don't handle vectors.
1021   if (VL[0]->getType()->isVectorTy()) {
1022     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1023     newTreeEntry(VL, false);
1024     return;
1025   }
1026 
1027   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1028     if (SI->getValueOperand()->getType()->isVectorTy()) {
1029       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1030       newTreeEntry(VL, false);
1031       return;
1032     }
1033   unsigned Opcode = getSameOpcode(VL);
1034 
1035   // Check that this shuffle vector refers to the alternate
1036   // sequence of opcodes.
1037   if (Opcode == Instruction::ShuffleVector) {
1038     Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1039     unsigned Op = I0->getOpcode();
1040     if (Op != Instruction::ShuffleVector)
1041       isAltShuffle = true;
1042   }
1043 
1044   // If all of the operands are identical or constant we have a simple solution.
1045   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1046     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1047     newTreeEntry(VL, false);
1048     return;
1049   }
1050 
1051   // We now know that this is a vector of instructions of the same type from
1052   // the same block.
1053 
1054   // Don't vectorize ephemeral values.
1055   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1056     if (EphValues.count(VL[i])) {
1057       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1058             ") is ephemeral.\n");
1059       newTreeEntry(VL, false);
1060       return;
1061     }
1062   }
1063 
1064   // Check if this is a duplicate of another entry.
1065   if (ScalarToTreeEntry.count(VL[0])) {
1066     int Idx = ScalarToTreeEntry[VL[0]];
1067     TreeEntry *E = &VectorizableTree[Idx];
1068     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1069       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1070       if (E->Scalars[i] != VL[i]) {
1071         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1072         newTreeEntry(VL, false);
1073         return;
1074       }
1075     }
1076     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1077     return;
1078   }
1079 
1080   // Check that none of the instructions in the bundle are already in the tree.
1081   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1082     if (ScalarToTreeEntry.count(VL[i])) {
1083       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1084             ") is already in tree.\n");
1085       newTreeEntry(VL, false);
1086       return;
1087     }
1088   }
1089 
1090   // If any of the scalars is marked as a value that needs to stay scalar then
1091   // we need to gather the scalars.
1092   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1093     if (MustGather.count(VL[i])) {
1094       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1095       newTreeEntry(VL, false);
1096       return;
1097     }
1098   }
1099 
1100   // Check that all of the users of the scalars that we want to vectorize are
1101   // schedulable.
1102   Instruction *VL0 = cast<Instruction>(VL[0]);
1103   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1104 
1105   if (!DT->isReachableFromEntry(BB)) {
1106     // Don't go into unreachable blocks. They may contain instructions with
1107     // dependency cycles which confuse the final scheduling.
1108     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1109     newTreeEntry(VL, false);
1110     return;
1111   }
1112 
1113   // Check that every instructions appears once in this bundle.
1114   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1115     for (unsigned j = i+1; j < e; ++j)
1116       if (VL[i] == VL[j]) {
1117         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1118         newTreeEntry(VL, false);
1119         return;
1120       }
1121 
1122   auto &BSRef = BlocksSchedules[BB];
1123   if (!BSRef) {
1124     BSRef = llvm::make_unique<BlockScheduling>(BB);
1125   }
1126   BlockScheduling &BS = *BSRef.get();
1127 
1128   if (!BS.tryScheduleBundle(VL, this)) {
1129     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1130     BS.cancelScheduling(VL);
1131     newTreeEntry(VL, false);
1132     return;
1133   }
1134   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1135 
1136   switch (Opcode) {
1137     case Instruction::PHI: {
1138       PHINode *PH = dyn_cast<PHINode>(VL0);
1139 
1140       // Check for terminator values (e.g. invoke).
1141       for (unsigned j = 0; j < VL.size(); ++j)
1142         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1143           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1144               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1145           if (Term) {
1146             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1147             BS.cancelScheduling(VL);
1148             newTreeEntry(VL, false);
1149             return;
1150           }
1151         }
1152 
1153       newTreeEntry(VL, true);
1154       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1155 
1156       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1157         ValueList Operands;
1158         // Prepare the operand vector.
1159         for (unsigned j = 0; j < VL.size(); ++j)
1160           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1161               PH->getIncomingBlock(i)));
1162 
1163         buildTree_rec(Operands, Depth + 1);
1164       }
1165       return;
1166     }
1167     case Instruction::ExtractElement: {
1168       bool Reuse = CanReuseExtract(VL);
1169       if (Reuse) {
1170         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1171       } else {
1172         BS.cancelScheduling(VL);
1173       }
1174       newTreeEntry(VL, Reuse);
1175       return;
1176     }
1177     case Instruction::Load: {
1178       // Check if the loads are consecutive or of we need to swizzle them.
1179       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1180         LoadInst *L = cast<LoadInst>(VL[i]);
1181         if (!L->isSimple()) {
1182           BS.cancelScheduling(VL);
1183           newTreeEntry(VL, false);
1184           DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1185           return;
1186         }
1187         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1188           if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1189             ++NumLoadsWantToChangeOrder;
1190           }
1191           BS.cancelScheduling(VL);
1192           newTreeEntry(VL, false);
1193           DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1194           return;
1195         }
1196       }
1197       ++NumLoadsWantToKeepOrder;
1198       newTreeEntry(VL, true);
1199       DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1200       return;
1201     }
1202     case Instruction::ZExt:
1203     case Instruction::SExt:
1204     case Instruction::FPToUI:
1205     case Instruction::FPToSI:
1206     case Instruction::FPExt:
1207     case Instruction::PtrToInt:
1208     case Instruction::IntToPtr:
1209     case Instruction::SIToFP:
1210     case Instruction::UIToFP:
1211     case Instruction::Trunc:
1212     case Instruction::FPTrunc:
1213     case Instruction::BitCast: {
1214       Type *SrcTy = VL0->getOperand(0)->getType();
1215       for (unsigned i = 0; i < VL.size(); ++i) {
1216         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1217         if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1218           BS.cancelScheduling(VL);
1219           newTreeEntry(VL, false);
1220           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1221           return;
1222         }
1223       }
1224       newTreeEntry(VL, true);
1225       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1226 
1227       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1228         ValueList Operands;
1229         // Prepare the operand vector.
1230         for (unsigned j = 0; j < VL.size(); ++j)
1231           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1232 
1233         buildTree_rec(Operands, Depth+1);
1234       }
1235       return;
1236     }
1237     case Instruction::ICmp:
1238     case Instruction::FCmp: {
1239       // Check that all of the compares have the same predicate.
1240       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1241       Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1242       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1243         CmpInst *Cmp = cast<CmpInst>(VL[i]);
1244         if (Cmp->getPredicate() != P0 ||
1245             Cmp->getOperand(0)->getType() != ComparedTy) {
1246           BS.cancelScheduling(VL);
1247           newTreeEntry(VL, false);
1248           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1249           return;
1250         }
1251       }
1252 
1253       newTreeEntry(VL, true);
1254       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1255 
1256       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1257         ValueList Operands;
1258         // Prepare the operand vector.
1259         for (unsigned j = 0; j < VL.size(); ++j)
1260           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1261 
1262         buildTree_rec(Operands, Depth+1);
1263       }
1264       return;
1265     }
1266     case Instruction::Select:
1267     case Instruction::Add:
1268     case Instruction::FAdd:
1269     case Instruction::Sub:
1270     case Instruction::FSub:
1271     case Instruction::Mul:
1272     case Instruction::FMul:
1273     case Instruction::UDiv:
1274     case Instruction::SDiv:
1275     case Instruction::FDiv:
1276     case Instruction::URem:
1277     case Instruction::SRem:
1278     case Instruction::FRem:
1279     case Instruction::Shl:
1280     case Instruction::LShr:
1281     case Instruction::AShr:
1282     case Instruction::And:
1283     case Instruction::Or:
1284     case Instruction::Xor: {
1285       newTreeEntry(VL, true);
1286       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1287 
1288       // Sort operands of the instructions so that each side is more likely to
1289       // have the same opcode.
1290       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1291         ValueList Left, Right;
1292         reorderInputsAccordingToOpcode(VL, Left, Right);
1293         buildTree_rec(Left, Depth + 1);
1294         buildTree_rec(Right, Depth + 1);
1295         return;
1296       }
1297 
1298       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1299         ValueList Operands;
1300         // Prepare the operand vector.
1301         for (unsigned j = 0; j < VL.size(); ++j)
1302           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1303 
1304         buildTree_rec(Operands, Depth+1);
1305       }
1306       return;
1307     }
1308     case Instruction::GetElementPtr: {
1309       // We don't combine GEPs with complicated (nested) indexing.
1310       for (unsigned j = 0; j < VL.size(); ++j) {
1311         if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1312           DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1313           BS.cancelScheduling(VL);
1314           newTreeEntry(VL, false);
1315           return;
1316         }
1317       }
1318 
1319       // We can't combine several GEPs into one vector if they operate on
1320       // different types.
1321       Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1322       for (unsigned j = 0; j < VL.size(); ++j) {
1323         Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1324         if (Ty0 != CurTy) {
1325           DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1326           BS.cancelScheduling(VL);
1327           newTreeEntry(VL, false);
1328           return;
1329         }
1330       }
1331 
1332       // We don't combine GEPs with non-constant indexes.
1333       for (unsigned j = 0; j < VL.size(); ++j) {
1334         auto Op = cast<Instruction>(VL[j])->getOperand(1);
1335         if (!isa<ConstantInt>(Op)) {
1336           DEBUG(
1337               dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1338           BS.cancelScheduling(VL);
1339           newTreeEntry(VL, false);
1340           return;
1341         }
1342       }
1343 
1344       newTreeEntry(VL, true);
1345       DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1346       for (unsigned i = 0, e = 2; i < e; ++i) {
1347         ValueList Operands;
1348         // Prepare the operand vector.
1349         for (unsigned j = 0; j < VL.size(); ++j)
1350           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1351 
1352         buildTree_rec(Operands, Depth + 1);
1353       }
1354       return;
1355     }
1356     case Instruction::Store: {
1357       // Check if the stores are consecutive or of we need to swizzle them.
1358       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1359         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1360           BS.cancelScheduling(VL);
1361           newTreeEntry(VL, false);
1362           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1363           return;
1364         }
1365 
1366       newTreeEntry(VL, true);
1367       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1368 
1369       ValueList Operands;
1370       for (unsigned j = 0; j < VL.size(); ++j)
1371         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1372 
1373       buildTree_rec(Operands, Depth + 1);
1374       return;
1375     }
1376     case Instruction::Call: {
1377       // Check if the calls are all to the same vectorizable intrinsic.
1378       CallInst *CI = cast<CallInst>(VL[0]);
1379       // Check if this is an Intrinsic call or something that can be
1380       // represented by an intrinsic call
1381       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1382       if (!isTriviallyVectorizable(ID)) {
1383         BS.cancelScheduling(VL);
1384         newTreeEntry(VL, false);
1385         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1386         return;
1387       }
1388       Function *Int = CI->getCalledFunction();
1389       Value *A1I = nullptr;
1390       if (hasVectorInstrinsicScalarOpd(ID, 1))
1391         A1I = CI->getArgOperand(1);
1392       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1393         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1394         if (!CI2 || CI2->getCalledFunction() != Int ||
1395             getIntrinsicIDForCall(CI2, TLI) != ID) {
1396           BS.cancelScheduling(VL);
1397           newTreeEntry(VL, false);
1398           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1399                        << "\n");
1400           return;
1401         }
1402         // ctlz,cttz and powi are special intrinsics whose second argument
1403         // should be same in order for them to be vectorized.
1404         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1405           Value *A1J = CI2->getArgOperand(1);
1406           if (A1I != A1J) {
1407             BS.cancelScheduling(VL);
1408             newTreeEntry(VL, false);
1409             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1410                          << " argument "<< A1I<<"!=" << A1J
1411                          << "\n");
1412             return;
1413           }
1414         }
1415       }
1416 
1417       newTreeEntry(VL, true);
1418       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1419         ValueList Operands;
1420         // Prepare the operand vector.
1421         for (unsigned j = 0; j < VL.size(); ++j) {
1422           CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1423           Operands.push_back(CI2->getArgOperand(i));
1424         }
1425         buildTree_rec(Operands, Depth + 1);
1426       }
1427       return;
1428     }
1429     case Instruction::ShuffleVector: {
1430       // If this is not an alternate sequence of opcode like add-sub
1431       // then do not vectorize this instruction.
1432       if (!isAltShuffle) {
1433         BS.cancelScheduling(VL);
1434         newTreeEntry(VL, false);
1435         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1436         return;
1437       }
1438       newTreeEntry(VL, true);
1439       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1440       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1441         ValueList Operands;
1442         // Prepare the operand vector.
1443         for (unsigned j = 0; j < VL.size(); ++j)
1444           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1445 
1446         buildTree_rec(Operands, Depth + 1);
1447       }
1448       return;
1449     }
1450     default:
1451       BS.cancelScheduling(VL);
1452       newTreeEntry(VL, false);
1453       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1454       return;
1455   }
1456 }
1457 
1458 int BoUpSLP::getEntryCost(TreeEntry *E) {
1459   ArrayRef<Value*> VL = E->Scalars;
1460 
1461   Type *ScalarTy = VL[0]->getType();
1462   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1463     ScalarTy = SI->getValueOperand()->getType();
1464   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1465 
1466   if (E->NeedToGather) {
1467     if (allConstant(VL))
1468       return 0;
1469     if (isSplat(VL)) {
1470       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1471     }
1472     return getGatherCost(E->Scalars);
1473   }
1474   unsigned Opcode = getSameOpcode(VL);
1475   assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1476   Instruction *VL0 = cast<Instruction>(VL[0]);
1477   switch (Opcode) {
1478     case Instruction::PHI: {
1479       return 0;
1480     }
1481     case Instruction::ExtractElement: {
1482       if (CanReuseExtract(VL)) {
1483         int DeadCost = 0;
1484         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1485           ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1486           if (E->hasOneUse())
1487             // Take credit for instruction that will become dead.
1488             DeadCost +=
1489                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1490         }
1491         return -DeadCost;
1492       }
1493       return getGatherCost(VecTy);
1494     }
1495     case Instruction::ZExt:
1496     case Instruction::SExt:
1497     case Instruction::FPToUI:
1498     case Instruction::FPToSI:
1499     case Instruction::FPExt:
1500     case Instruction::PtrToInt:
1501     case Instruction::IntToPtr:
1502     case Instruction::SIToFP:
1503     case Instruction::UIToFP:
1504     case Instruction::Trunc:
1505     case Instruction::FPTrunc:
1506     case Instruction::BitCast: {
1507       Type *SrcTy = VL0->getOperand(0)->getType();
1508 
1509       // Calculate the cost of this instruction.
1510       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1511                                                          VL0->getType(), SrcTy);
1512 
1513       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1514       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1515       return VecCost - ScalarCost;
1516     }
1517     case Instruction::FCmp:
1518     case Instruction::ICmp:
1519     case Instruction::Select:
1520     case Instruction::Add:
1521     case Instruction::FAdd:
1522     case Instruction::Sub:
1523     case Instruction::FSub:
1524     case Instruction::Mul:
1525     case Instruction::FMul:
1526     case Instruction::UDiv:
1527     case Instruction::SDiv:
1528     case Instruction::FDiv:
1529     case Instruction::URem:
1530     case Instruction::SRem:
1531     case Instruction::FRem:
1532     case Instruction::Shl:
1533     case Instruction::LShr:
1534     case Instruction::AShr:
1535     case Instruction::And:
1536     case Instruction::Or:
1537     case Instruction::Xor: {
1538       // Calculate the cost of this instruction.
1539       int ScalarCost = 0;
1540       int VecCost = 0;
1541       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1542           Opcode == Instruction::Select) {
1543         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1544         ScalarCost = VecTy->getNumElements() *
1545         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1546         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1547       } else {
1548         // Certain instructions can be cheaper to vectorize if they have a
1549         // constant second vector operand.
1550         TargetTransformInfo::OperandValueKind Op1VK =
1551             TargetTransformInfo::OK_AnyValue;
1552         TargetTransformInfo::OperandValueKind Op2VK =
1553             TargetTransformInfo::OK_UniformConstantValue;
1554         TargetTransformInfo::OperandValueProperties Op1VP =
1555             TargetTransformInfo::OP_None;
1556         TargetTransformInfo::OperandValueProperties Op2VP =
1557             TargetTransformInfo::OP_None;
1558 
1559         // If all operands are exactly the same ConstantInt then set the
1560         // operand kind to OK_UniformConstantValue.
1561         // If instead not all operands are constants, then set the operand kind
1562         // to OK_AnyValue. If all operands are constants but not the same,
1563         // then set the operand kind to OK_NonUniformConstantValue.
1564         ConstantInt *CInt = nullptr;
1565         for (unsigned i = 0; i < VL.size(); ++i) {
1566           const Instruction *I = cast<Instruction>(VL[i]);
1567           if (!isa<ConstantInt>(I->getOperand(1))) {
1568             Op2VK = TargetTransformInfo::OK_AnyValue;
1569             break;
1570           }
1571           if (i == 0) {
1572             CInt = cast<ConstantInt>(I->getOperand(1));
1573             continue;
1574           }
1575           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1576               CInt != cast<ConstantInt>(I->getOperand(1)))
1577             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1578         }
1579         // FIXME: Currently cost of model modification for division by
1580         // power of 2 is handled only for X86. Add support for other targets.
1581         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1582             CInt->getValue().isPowerOf2())
1583           Op2VP = TargetTransformInfo::OP_PowerOf2;
1584 
1585         ScalarCost = VecTy->getNumElements() *
1586                      TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1587                                                  Op1VP, Op2VP);
1588         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1589                                               Op1VP, Op2VP);
1590       }
1591       return VecCost - ScalarCost;
1592     }
1593     case Instruction::GetElementPtr: {
1594       TargetTransformInfo::OperandValueKind Op1VK =
1595           TargetTransformInfo::OK_AnyValue;
1596       TargetTransformInfo::OperandValueKind Op2VK =
1597           TargetTransformInfo::OK_UniformConstantValue;
1598 
1599       int ScalarCost =
1600           VecTy->getNumElements() *
1601           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1602       int VecCost =
1603           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1604 
1605       return VecCost - ScalarCost;
1606     }
1607     case Instruction::Load: {
1608       // Cost of wide load - cost of scalar loads.
1609       int ScalarLdCost = VecTy->getNumElements() *
1610       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1611       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1612       return VecLdCost - ScalarLdCost;
1613     }
1614     case Instruction::Store: {
1615       // We know that we can merge the stores. Calculate the cost.
1616       int ScalarStCost = VecTy->getNumElements() *
1617       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1618       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1619       return VecStCost - ScalarStCost;
1620     }
1621     case Instruction::Call: {
1622       CallInst *CI = cast<CallInst>(VL0);
1623       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1624 
1625       // Calculate the cost of the scalar and vector calls.
1626       SmallVector<Type*, 4> ScalarTys, VecTys;
1627       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1628         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1629         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1630                                          VecTy->getNumElements()));
1631       }
1632 
1633       int ScalarCallCost = VecTy->getNumElements() *
1634           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1635 
1636       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1637 
1638       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1639             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1640             << " for " << *CI << "\n");
1641 
1642       return VecCallCost - ScalarCallCost;
1643     }
1644     case Instruction::ShuffleVector: {
1645       TargetTransformInfo::OperandValueKind Op1VK =
1646           TargetTransformInfo::OK_AnyValue;
1647       TargetTransformInfo::OperandValueKind Op2VK =
1648           TargetTransformInfo::OK_AnyValue;
1649       int ScalarCost = 0;
1650       int VecCost = 0;
1651       for (unsigned i = 0; i < VL.size(); ++i) {
1652         Instruction *I = cast<Instruction>(VL[i]);
1653         if (!I)
1654           break;
1655         ScalarCost +=
1656             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1657       }
1658       // VecCost is equal to sum of the cost of creating 2 vectors
1659       // and the cost of creating shuffle.
1660       Instruction *I0 = cast<Instruction>(VL[0]);
1661       VecCost =
1662           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1663       Instruction *I1 = cast<Instruction>(VL[1]);
1664       VecCost +=
1665           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1666       VecCost +=
1667           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1668       return VecCost - ScalarCost;
1669     }
1670     default:
1671       llvm_unreachable("Unknown instruction");
1672   }
1673 }
1674 
1675 bool BoUpSLP::isFullyVectorizableTinyTree() {
1676   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1677         VectorizableTree.size() << " is fully vectorizable .\n");
1678 
1679   // We only handle trees of height 2.
1680   if (VectorizableTree.size() != 2)
1681     return false;
1682 
1683   // Handle splat stores.
1684   if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1685     return true;
1686 
1687   // Gathering cost would be too much for tiny trees.
1688   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1689     return false;
1690 
1691   return true;
1692 }
1693 
1694 int BoUpSLP::getSpillCost() {
1695   // Walk from the bottom of the tree to the top, tracking which values are
1696   // live. When we see a call instruction that is not part of our tree,
1697   // query TTI to see if there is a cost to keeping values live over it
1698   // (for example, if spills and fills are required).
1699   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1700   int Cost = 0;
1701 
1702   SmallPtrSet<Instruction*, 4> LiveValues;
1703   Instruction *PrevInst = nullptr;
1704 
1705   for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1706     Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1707     if (!Inst)
1708       continue;
1709 
1710     if (!PrevInst) {
1711       PrevInst = Inst;
1712       continue;
1713     }
1714 
1715     DEBUG(
1716       dbgs() << "SLP: #LV: " << LiveValues.size();
1717       for (auto *X : LiveValues)
1718         dbgs() << " " << X->getName();
1719       dbgs() << ", Looking at ";
1720       Inst->dump();
1721       );
1722 
1723     // Update LiveValues.
1724     LiveValues.erase(PrevInst);
1725     for (auto &J : PrevInst->operands()) {
1726       if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1727         LiveValues.insert(cast<Instruction>(&*J));
1728     }
1729 
1730     // Now find the sequence of instructions between PrevInst and Inst.
1731     BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1732     --PrevInstIt;
1733     while (InstIt != PrevInstIt) {
1734       if (PrevInstIt == PrevInst->getParent()->rend()) {
1735         PrevInstIt = Inst->getParent()->rbegin();
1736         continue;
1737       }
1738 
1739       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1740         SmallVector<Type*, 4> V;
1741         for (auto *II : LiveValues)
1742           V.push_back(VectorType::get(II->getType(), BundleWidth));
1743         Cost += TTI->getCostOfKeepingLiveOverCall(V);
1744       }
1745 
1746       ++PrevInstIt;
1747     }
1748 
1749     PrevInst = Inst;
1750   }
1751 
1752   DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1753   return Cost;
1754 }
1755 
1756 int BoUpSLP::getTreeCost() {
1757   int Cost = 0;
1758   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1759         VectorizableTree.size() << ".\n");
1760 
1761   // We only vectorize tiny trees if it is fully vectorizable.
1762   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1763     if (!VectorizableTree.size()) {
1764       assert(!ExternalUses.size() && "We should not have any external users");
1765     }
1766     return INT_MAX;
1767   }
1768 
1769   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1770 
1771   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1772     int C = getEntryCost(&VectorizableTree[i]);
1773     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1774           << *VectorizableTree[i].Scalars[0] << " .\n");
1775     Cost += C;
1776   }
1777 
1778   SmallSet<Value *, 16> ExtractCostCalculated;
1779   int ExtractCost = 0;
1780   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1781        I != E; ++I) {
1782     // We only add extract cost once for the same scalar.
1783     if (!ExtractCostCalculated.insert(I->Scalar).second)
1784       continue;
1785 
1786     // Uses by ephemeral values are free (because the ephemeral value will be
1787     // removed prior to code generation, and so the extraction will be
1788     // removed as well).
1789     if (EphValues.count(I->User))
1790       continue;
1791 
1792     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1793     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1794                                            I->Lane);
1795   }
1796 
1797   Cost += getSpillCost();
1798 
1799   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1800   return  Cost + ExtractCost;
1801 }
1802 
1803 int BoUpSLP::getGatherCost(Type *Ty) {
1804   int Cost = 0;
1805   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1806     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1807   return Cost;
1808 }
1809 
1810 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1811   // Find the type of the operands in VL.
1812   Type *ScalarTy = VL[0]->getType();
1813   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1814     ScalarTy = SI->getValueOperand()->getType();
1815   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1816   // Find the cost of inserting/extracting values from the vector.
1817   return getGatherCost(VecTy);
1818 }
1819 
1820 Value *BoUpSLP::getPointerOperand(Value *I) {
1821   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1822     return LI->getPointerOperand();
1823   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1824     return SI->getPointerOperand();
1825   return nullptr;
1826 }
1827 
1828 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1829   if (LoadInst *L = dyn_cast<LoadInst>(I))
1830     return L->getPointerAddressSpace();
1831   if (StoreInst *S = dyn_cast<StoreInst>(I))
1832     return S->getPointerAddressSpace();
1833   return -1;
1834 }
1835 
1836 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1837   Value *PtrA = getPointerOperand(A);
1838   Value *PtrB = getPointerOperand(B);
1839   unsigned ASA = getAddressSpaceOperand(A);
1840   unsigned ASB = getAddressSpaceOperand(B);
1841 
1842   // Check that the address spaces match and that the pointers are valid.
1843   if (!PtrA || !PtrB || (ASA != ASB))
1844     return false;
1845 
1846   // Make sure that A and B are different pointers of the same type.
1847   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1848     return false;
1849 
1850   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1851   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1852   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1853 
1854   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1855   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1856   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1857 
1858   APInt OffsetDelta = OffsetB - OffsetA;
1859 
1860   // Check if they are based on the same pointer. That makes the offsets
1861   // sufficient.
1862   if (PtrA == PtrB)
1863     return OffsetDelta == Size;
1864 
1865   // Compute the necessary base pointer delta to have the necessary final delta
1866   // equal to the size.
1867   APInt BaseDelta = Size - OffsetDelta;
1868 
1869   // Otherwise compute the distance with SCEV between the base pointers.
1870   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1871   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1872   const SCEV *C = SE->getConstant(BaseDelta);
1873   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1874   return X == PtrSCEVB;
1875 }
1876 
1877 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1878   Instruction *VL0 = cast<Instruction>(VL[0]);
1879   BasicBlock::iterator NextInst = VL0;
1880   ++NextInst;
1881   Builder.SetInsertPoint(VL0->getParent(), NextInst);
1882   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1883 }
1884 
1885 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1886   Value *Vec = UndefValue::get(Ty);
1887   // Generate the 'InsertElement' instruction.
1888   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1889     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1890     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1891       GatherSeq.insert(Insrt);
1892       CSEBlocks.insert(Insrt->getParent());
1893 
1894       // Add to our 'need-to-extract' list.
1895       if (ScalarToTreeEntry.count(VL[i])) {
1896         int Idx = ScalarToTreeEntry[VL[i]];
1897         TreeEntry *E = &VectorizableTree[Idx];
1898         // Find which lane we need to extract.
1899         int FoundLane = -1;
1900         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1901           // Is this the lane of the scalar that we are looking for ?
1902           if (E->Scalars[Lane] == VL[i]) {
1903             FoundLane = Lane;
1904             break;
1905           }
1906         }
1907         assert(FoundLane >= 0 && "Could not find the correct lane");
1908         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1909       }
1910     }
1911   }
1912 
1913   return Vec;
1914 }
1915 
1916 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1917   SmallDenseMap<Value*, int>::const_iterator Entry
1918     = ScalarToTreeEntry.find(VL[0]);
1919   if (Entry != ScalarToTreeEntry.end()) {
1920     int Idx = Entry->second;
1921     const TreeEntry *En = &VectorizableTree[Idx];
1922     if (En->isSame(VL) && En->VectorizedValue)
1923       return En->VectorizedValue;
1924   }
1925   return nullptr;
1926 }
1927 
1928 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1929   if (ScalarToTreeEntry.count(VL[0])) {
1930     int Idx = ScalarToTreeEntry[VL[0]];
1931     TreeEntry *E = &VectorizableTree[Idx];
1932     if (E->isSame(VL))
1933       return vectorizeTree(E);
1934   }
1935 
1936   Type *ScalarTy = VL[0]->getType();
1937   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1938     ScalarTy = SI->getValueOperand()->getType();
1939   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1940 
1941   return Gather(VL, VecTy);
1942 }
1943 
1944 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1945   IRBuilder<>::InsertPointGuard Guard(Builder);
1946 
1947   if (E->VectorizedValue) {
1948     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1949     return E->VectorizedValue;
1950   }
1951 
1952   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1953   Type *ScalarTy = VL0->getType();
1954   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1955     ScalarTy = SI->getValueOperand()->getType();
1956   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1957 
1958   if (E->NeedToGather) {
1959     setInsertPointAfterBundle(E->Scalars);
1960     return Gather(E->Scalars, VecTy);
1961   }
1962 
1963   unsigned Opcode = getSameOpcode(E->Scalars);
1964 
1965   switch (Opcode) {
1966     case Instruction::PHI: {
1967       PHINode *PH = dyn_cast<PHINode>(VL0);
1968       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1969       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1970       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1971       E->VectorizedValue = NewPhi;
1972 
1973       // PHINodes may have multiple entries from the same block. We want to
1974       // visit every block once.
1975       SmallSet<BasicBlock*, 4> VisitedBBs;
1976 
1977       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1978         ValueList Operands;
1979         BasicBlock *IBB = PH->getIncomingBlock(i);
1980 
1981         if (!VisitedBBs.insert(IBB).second) {
1982           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1983           continue;
1984         }
1985 
1986         // Prepare the operand vector.
1987         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1988           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1989                              getIncomingValueForBlock(IBB));
1990 
1991         Builder.SetInsertPoint(IBB->getTerminator());
1992         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1993         Value *Vec = vectorizeTree(Operands);
1994         NewPhi->addIncoming(Vec, IBB);
1995       }
1996 
1997       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1998              "Invalid number of incoming values");
1999       return NewPhi;
2000     }
2001 
2002     case Instruction::ExtractElement: {
2003       if (CanReuseExtract(E->Scalars)) {
2004         Value *V = VL0->getOperand(0);
2005         E->VectorizedValue = V;
2006         return V;
2007       }
2008       return Gather(E->Scalars, VecTy);
2009     }
2010     case Instruction::ZExt:
2011     case Instruction::SExt:
2012     case Instruction::FPToUI:
2013     case Instruction::FPToSI:
2014     case Instruction::FPExt:
2015     case Instruction::PtrToInt:
2016     case Instruction::IntToPtr:
2017     case Instruction::SIToFP:
2018     case Instruction::UIToFP:
2019     case Instruction::Trunc:
2020     case Instruction::FPTrunc:
2021     case Instruction::BitCast: {
2022       ValueList INVL;
2023       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2024         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2025 
2026       setInsertPointAfterBundle(E->Scalars);
2027 
2028       Value *InVec = vectorizeTree(INVL);
2029 
2030       if (Value *V = alreadyVectorized(E->Scalars))
2031         return V;
2032 
2033       CastInst *CI = dyn_cast<CastInst>(VL0);
2034       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2035       E->VectorizedValue = V;
2036       ++NumVectorInstructions;
2037       return V;
2038     }
2039     case Instruction::FCmp:
2040     case Instruction::ICmp: {
2041       ValueList LHSV, RHSV;
2042       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2043         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2044         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2045       }
2046 
2047       setInsertPointAfterBundle(E->Scalars);
2048 
2049       Value *L = vectorizeTree(LHSV);
2050       Value *R = vectorizeTree(RHSV);
2051 
2052       if (Value *V = alreadyVectorized(E->Scalars))
2053         return V;
2054 
2055       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2056       Value *V;
2057       if (Opcode == Instruction::FCmp)
2058         V = Builder.CreateFCmp(P0, L, R);
2059       else
2060         V = Builder.CreateICmp(P0, L, R);
2061 
2062       E->VectorizedValue = V;
2063       ++NumVectorInstructions;
2064       return V;
2065     }
2066     case Instruction::Select: {
2067       ValueList TrueVec, FalseVec, CondVec;
2068       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2069         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2070         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2071         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2072       }
2073 
2074       setInsertPointAfterBundle(E->Scalars);
2075 
2076       Value *Cond = vectorizeTree(CondVec);
2077       Value *True = vectorizeTree(TrueVec);
2078       Value *False = vectorizeTree(FalseVec);
2079 
2080       if (Value *V = alreadyVectorized(E->Scalars))
2081         return V;
2082 
2083       Value *V = Builder.CreateSelect(Cond, True, False);
2084       E->VectorizedValue = V;
2085       ++NumVectorInstructions;
2086       return V;
2087     }
2088     case Instruction::Add:
2089     case Instruction::FAdd:
2090     case Instruction::Sub:
2091     case Instruction::FSub:
2092     case Instruction::Mul:
2093     case Instruction::FMul:
2094     case Instruction::UDiv:
2095     case Instruction::SDiv:
2096     case Instruction::FDiv:
2097     case Instruction::URem:
2098     case Instruction::SRem:
2099     case Instruction::FRem:
2100     case Instruction::Shl:
2101     case Instruction::LShr:
2102     case Instruction::AShr:
2103     case Instruction::And:
2104     case Instruction::Or:
2105     case Instruction::Xor: {
2106       ValueList LHSVL, RHSVL;
2107       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2108         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2109       else
2110         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2111           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2112           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2113         }
2114 
2115       setInsertPointAfterBundle(E->Scalars);
2116 
2117       Value *LHS = vectorizeTree(LHSVL);
2118       Value *RHS = vectorizeTree(RHSVL);
2119 
2120       if (LHS == RHS && isa<Instruction>(LHS)) {
2121         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2122       }
2123 
2124       if (Value *V = alreadyVectorized(E->Scalars))
2125         return V;
2126 
2127       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2128       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2129       E->VectorizedValue = V;
2130       propagateIRFlags(E->VectorizedValue, E->Scalars);
2131       ++NumVectorInstructions;
2132 
2133       if (Instruction *I = dyn_cast<Instruction>(V))
2134         return propagateMetadata(I, E->Scalars);
2135 
2136       return V;
2137     }
2138     case Instruction::Load: {
2139       // Loads are inserted at the head of the tree because we don't want to
2140       // sink them all the way down past store instructions.
2141       setInsertPointAfterBundle(E->Scalars);
2142 
2143       LoadInst *LI = cast<LoadInst>(VL0);
2144       Type *ScalarLoadTy = LI->getType();
2145       unsigned AS = LI->getPointerAddressSpace();
2146 
2147       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2148                                             VecTy->getPointerTo(AS));
2149 
2150       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2151       // ExternalUses list to make sure that an extract will be generated in the
2152       // future.
2153       if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2154         ExternalUses.push_back(
2155             ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2156 
2157       unsigned Alignment = LI->getAlignment();
2158       LI = Builder.CreateLoad(VecPtr);
2159       if (!Alignment)
2160         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2161       LI->setAlignment(Alignment);
2162       E->VectorizedValue = LI;
2163       ++NumVectorInstructions;
2164       return propagateMetadata(LI, E->Scalars);
2165     }
2166     case Instruction::Store: {
2167       StoreInst *SI = cast<StoreInst>(VL0);
2168       unsigned Alignment = SI->getAlignment();
2169       unsigned AS = SI->getPointerAddressSpace();
2170 
2171       ValueList ValueOp;
2172       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2173         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2174 
2175       setInsertPointAfterBundle(E->Scalars);
2176 
2177       Value *VecValue = vectorizeTree(ValueOp);
2178       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2179                                             VecTy->getPointerTo(AS));
2180       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2181 
2182       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2183       // ExternalUses list to make sure that an extract will be generated in the
2184       // future.
2185       if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2186         ExternalUses.push_back(
2187             ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2188 
2189       if (!Alignment)
2190         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2191       S->setAlignment(Alignment);
2192       E->VectorizedValue = S;
2193       ++NumVectorInstructions;
2194       return propagateMetadata(S, E->Scalars);
2195     }
2196     case Instruction::GetElementPtr: {
2197       setInsertPointAfterBundle(E->Scalars);
2198 
2199       ValueList Op0VL;
2200       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2201         Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2202 
2203       Value *Op0 = vectorizeTree(Op0VL);
2204 
2205       std::vector<Value *> OpVecs;
2206       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2207            ++j) {
2208         ValueList OpVL;
2209         for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2210           OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2211 
2212         Value *OpVec = vectorizeTree(OpVL);
2213         OpVecs.push_back(OpVec);
2214       }
2215 
2216       Value *V = Builder.CreateGEP(Op0, OpVecs);
2217       E->VectorizedValue = V;
2218       ++NumVectorInstructions;
2219 
2220       if (Instruction *I = dyn_cast<Instruction>(V))
2221         return propagateMetadata(I, E->Scalars);
2222 
2223       return V;
2224     }
2225     case Instruction::Call: {
2226       CallInst *CI = cast<CallInst>(VL0);
2227       setInsertPointAfterBundle(E->Scalars);
2228       Function *FI;
2229       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
2230       Value *ScalarArg = nullptr;
2231       if (CI && (FI = CI->getCalledFunction())) {
2232         IID = (Intrinsic::ID) FI->getIntrinsicID();
2233       }
2234       std::vector<Value *> OpVecs;
2235       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2236         ValueList OpVL;
2237         // ctlz,cttz and powi are special intrinsics whose second argument is
2238         // a scalar. This argument should not be vectorized.
2239         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2240           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2241           ScalarArg = CEI->getArgOperand(j);
2242           OpVecs.push_back(CEI->getArgOperand(j));
2243           continue;
2244         }
2245         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2246           CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2247           OpVL.push_back(CEI->getArgOperand(j));
2248         }
2249 
2250         Value *OpVec = vectorizeTree(OpVL);
2251         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2252         OpVecs.push_back(OpVec);
2253       }
2254 
2255       Module *M = F->getParent();
2256       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2257       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2258       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2259       Value *V = Builder.CreateCall(CF, OpVecs);
2260 
2261       // The scalar argument uses an in-tree scalar so we add the new vectorized
2262       // call to ExternalUses list to make sure that an extract will be
2263       // generated in the future.
2264       if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2265         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2266 
2267       E->VectorizedValue = V;
2268       ++NumVectorInstructions;
2269       return V;
2270     }
2271     case Instruction::ShuffleVector: {
2272       ValueList LHSVL, RHSVL;
2273       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2274         LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2275         RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2276       }
2277       setInsertPointAfterBundle(E->Scalars);
2278 
2279       Value *LHS = vectorizeTree(LHSVL);
2280       Value *RHS = vectorizeTree(RHSVL);
2281 
2282       if (Value *V = alreadyVectorized(E->Scalars))
2283         return V;
2284 
2285       // Create a vector of LHS op1 RHS
2286       BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2287       Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2288 
2289       // Create a vector of LHS op2 RHS
2290       Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2291       BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2292       Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2293 
2294       // Create shuffle to take alternate operations from the vector.
2295       // Also, gather up odd and even scalar ops to propagate IR flags to
2296       // each vector operation.
2297       ValueList OddScalars, EvenScalars;
2298       unsigned e = E->Scalars.size();
2299       SmallVector<Constant *, 8> Mask(e);
2300       for (unsigned i = 0; i < e; ++i) {
2301         if (i & 1) {
2302           Mask[i] = Builder.getInt32(e + i);
2303           OddScalars.push_back(E->Scalars[i]);
2304         } else {
2305           Mask[i] = Builder.getInt32(i);
2306           EvenScalars.push_back(E->Scalars[i]);
2307         }
2308       }
2309 
2310       Value *ShuffleMask = ConstantVector::get(Mask);
2311       propagateIRFlags(V0, EvenScalars);
2312       propagateIRFlags(V1, OddScalars);
2313 
2314       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2315       E->VectorizedValue = V;
2316       ++NumVectorInstructions;
2317       if (Instruction *I = dyn_cast<Instruction>(V))
2318         return propagateMetadata(I, E->Scalars);
2319 
2320       return V;
2321     }
2322     default:
2323     llvm_unreachable("unknown inst");
2324   }
2325   return nullptr;
2326 }
2327 
2328 Value *BoUpSLP::vectorizeTree() {
2329 
2330   // All blocks must be scheduled before any instructions are inserted.
2331   for (auto &BSIter : BlocksSchedules) {
2332     scheduleBlock(BSIter.second.get());
2333   }
2334 
2335   Builder.SetInsertPoint(F->getEntryBlock().begin());
2336   vectorizeTree(&VectorizableTree[0]);
2337 
2338   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2339 
2340   // Extract all of the elements with the external uses.
2341   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2342        it != e; ++it) {
2343     Value *Scalar = it->Scalar;
2344     llvm::User *User = it->User;
2345 
2346     // Skip users that we already RAUW. This happens when one instruction
2347     // has multiple uses of the same value.
2348     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2349         Scalar->user_end())
2350       continue;
2351     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2352 
2353     int Idx = ScalarToTreeEntry[Scalar];
2354     TreeEntry *E = &VectorizableTree[Idx];
2355     assert(!E->NeedToGather && "Extracting from a gather list");
2356 
2357     Value *Vec = E->VectorizedValue;
2358     assert(Vec && "Can't find vectorizable value");
2359 
2360     Value *Lane = Builder.getInt32(it->Lane);
2361     // Generate extracts for out-of-tree users.
2362     // Find the insertion point for the extractelement lane.
2363     if (isa<Instruction>(Vec)){
2364       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2365         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2366           if (PH->getIncomingValue(i) == Scalar) {
2367             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2368             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2369             CSEBlocks.insert(PH->getIncomingBlock(i));
2370             PH->setOperand(i, Ex);
2371           }
2372         }
2373       } else {
2374         Builder.SetInsertPoint(cast<Instruction>(User));
2375         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2376         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2377         User->replaceUsesOfWith(Scalar, Ex);
2378      }
2379     } else {
2380       Builder.SetInsertPoint(F->getEntryBlock().begin());
2381       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2382       CSEBlocks.insert(&F->getEntryBlock());
2383       User->replaceUsesOfWith(Scalar, Ex);
2384     }
2385 
2386     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2387   }
2388 
2389   // For each vectorized value:
2390   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2391     TreeEntry *Entry = &VectorizableTree[EIdx];
2392 
2393     // For each lane:
2394     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2395       Value *Scalar = Entry->Scalars[Lane];
2396       // No need to handle users of gathered values.
2397       if (Entry->NeedToGather)
2398         continue;
2399 
2400       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2401 
2402       Type *Ty = Scalar->getType();
2403       if (!Ty->isVoidTy()) {
2404 #ifndef NDEBUG
2405         for (User *U : Scalar->users()) {
2406           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2407 
2408           assert((ScalarToTreeEntry.count(U) ||
2409                   // It is legal to replace users in the ignorelist by undef.
2410                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2411                    UserIgnoreList.end())) &&
2412                  "Replacing out-of-tree value with undef");
2413         }
2414 #endif
2415         Value *Undef = UndefValue::get(Ty);
2416         Scalar->replaceAllUsesWith(Undef);
2417       }
2418       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2419       eraseInstruction(cast<Instruction>(Scalar));
2420     }
2421   }
2422 
2423   Builder.ClearInsertionPoint();
2424 
2425   return VectorizableTree[0].VectorizedValue;
2426 }
2427 
2428 void BoUpSLP::optimizeGatherSequence() {
2429   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2430         << " gather sequences instructions.\n");
2431   // LICM InsertElementInst sequences.
2432   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2433        e = GatherSeq.end(); it != e; ++it) {
2434     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2435 
2436     if (!Insert)
2437       continue;
2438 
2439     // Check if this block is inside a loop.
2440     Loop *L = LI->getLoopFor(Insert->getParent());
2441     if (!L)
2442       continue;
2443 
2444     // Check if it has a preheader.
2445     BasicBlock *PreHeader = L->getLoopPreheader();
2446     if (!PreHeader)
2447       continue;
2448 
2449     // If the vector or the element that we insert into it are
2450     // instructions that are defined in this basic block then we can't
2451     // hoist this instruction.
2452     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2453     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2454     if (CurrVec && L->contains(CurrVec))
2455       continue;
2456     if (NewElem && L->contains(NewElem))
2457       continue;
2458 
2459     // We can hoist this instruction. Move it to the pre-header.
2460     Insert->moveBefore(PreHeader->getTerminator());
2461   }
2462 
2463   // Make a list of all reachable blocks in our CSE queue.
2464   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2465   CSEWorkList.reserve(CSEBlocks.size());
2466   for (BasicBlock *BB : CSEBlocks)
2467     if (DomTreeNode *N = DT->getNode(BB)) {
2468       assert(DT->isReachableFromEntry(N));
2469       CSEWorkList.push_back(N);
2470     }
2471 
2472   // Sort blocks by domination. This ensures we visit a block after all blocks
2473   // dominating it are visited.
2474   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2475                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2476     return DT->properlyDominates(A, B);
2477   });
2478 
2479   // Perform O(N^2) search over the gather sequences and merge identical
2480   // instructions. TODO: We can further optimize this scan if we split the
2481   // instructions into different buckets based on the insert lane.
2482   SmallVector<Instruction *, 16> Visited;
2483   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2484     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2485            "Worklist not sorted properly!");
2486     BasicBlock *BB = (*I)->getBlock();
2487     // For all instructions in blocks containing gather sequences:
2488     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2489       Instruction *In = it++;
2490       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2491         continue;
2492 
2493       // Check if we can replace this instruction with any of the
2494       // visited instructions.
2495       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2496                                                     ve = Visited.end();
2497            v != ve; ++v) {
2498         if (In->isIdenticalTo(*v) &&
2499             DT->dominates((*v)->getParent(), In->getParent())) {
2500           In->replaceAllUsesWith(*v);
2501           eraseInstruction(In);
2502           In = nullptr;
2503           break;
2504         }
2505       }
2506       if (In) {
2507         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2508         Visited.push_back(In);
2509       }
2510     }
2511   }
2512   CSEBlocks.clear();
2513   GatherSeq.clear();
2514 }
2515 
2516 // Groups the instructions to a bundle (which is then a single scheduling entity)
2517 // and schedules instructions until the bundle gets ready.
2518 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2519                                                  BoUpSLP *SLP) {
2520   if (isa<PHINode>(VL[0]))
2521     return true;
2522 
2523   // Initialize the instruction bundle.
2524   Instruction *OldScheduleEnd = ScheduleEnd;
2525   ScheduleData *PrevInBundle = nullptr;
2526   ScheduleData *Bundle = nullptr;
2527   bool ReSchedule = false;
2528   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2529   for (Value *V : VL) {
2530     extendSchedulingRegion(V);
2531     ScheduleData *BundleMember = getScheduleData(V);
2532     assert(BundleMember &&
2533            "no ScheduleData for bundle member (maybe not in same basic block)");
2534     if (BundleMember->IsScheduled) {
2535       // A bundle member was scheduled as single instruction before and now
2536       // needs to be scheduled as part of the bundle. We just get rid of the
2537       // existing schedule.
2538       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2539                    << " was already scheduled\n");
2540       ReSchedule = true;
2541     }
2542     assert(BundleMember->isSchedulingEntity() &&
2543            "bundle member already part of other bundle");
2544     if (PrevInBundle) {
2545       PrevInBundle->NextInBundle = BundleMember;
2546     } else {
2547       Bundle = BundleMember;
2548     }
2549     BundleMember->UnscheduledDepsInBundle = 0;
2550     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2551 
2552     // Group the instructions to a bundle.
2553     BundleMember->FirstInBundle = Bundle;
2554     PrevInBundle = BundleMember;
2555   }
2556   if (ScheduleEnd != OldScheduleEnd) {
2557     // The scheduling region got new instructions at the lower end (or it is a
2558     // new region for the first bundle). This makes it necessary to
2559     // recalculate all dependencies.
2560     // It is seldom that this needs to be done a second time after adding the
2561     // initial bundle to the region.
2562     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2563       ScheduleData *SD = getScheduleData(I);
2564       SD->clearDependencies();
2565     }
2566     ReSchedule = true;
2567   }
2568   if (ReSchedule) {
2569     resetSchedule();
2570     initialFillReadyList(ReadyInsts);
2571   }
2572 
2573   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2574                << BB->getName() << "\n");
2575 
2576   calculateDependencies(Bundle, true, SLP);
2577 
2578   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2579   // means that there are no cyclic dependencies and we can schedule it.
2580   // Note that's important that we don't "schedule" the bundle yet (see
2581   // cancelScheduling).
2582   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2583 
2584     ScheduleData *pickedSD = ReadyInsts.back();
2585     ReadyInsts.pop_back();
2586 
2587     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2588       schedule(pickedSD, ReadyInsts);
2589     }
2590   }
2591   return Bundle->isReady();
2592 }
2593 
2594 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2595   if (isa<PHINode>(VL[0]))
2596     return;
2597 
2598   ScheduleData *Bundle = getScheduleData(VL[0]);
2599   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2600   assert(!Bundle->IsScheduled &&
2601          "Can't cancel bundle which is already scheduled");
2602   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2603          "tried to unbundle something which is not a bundle");
2604 
2605   // Un-bundle: make single instructions out of the bundle.
2606   ScheduleData *BundleMember = Bundle;
2607   while (BundleMember) {
2608     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2609     BundleMember->FirstInBundle = BundleMember;
2610     ScheduleData *Next = BundleMember->NextInBundle;
2611     BundleMember->NextInBundle = nullptr;
2612     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2613     if (BundleMember->UnscheduledDepsInBundle == 0) {
2614       ReadyInsts.insert(BundleMember);
2615     }
2616     BundleMember = Next;
2617   }
2618 }
2619 
2620 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2621   if (getScheduleData(V))
2622     return;
2623   Instruction *I = dyn_cast<Instruction>(V);
2624   assert(I && "bundle member must be an instruction");
2625   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2626   if (!ScheduleStart) {
2627     // It's the first instruction in the new region.
2628     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2629     ScheduleStart = I;
2630     ScheduleEnd = I->getNextNode();
2631     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2632     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2633     return;
2634   }
2635   // Search up and down at the same time, because we don't know if the new
2636   // instruction is above or below the existing scheduling region.
2637   BasicBlock::reverse_iterator UpIter(ScheduleStart);
2638   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2639   BasicBlock::iterator DownIter(ScheduleEnd);
2640   BasicBlock::iterator LowerEnd = BB->end();
2641   for (;;) {
2642     if (UpIter != UpperEnd) {
2643       if (&*UpIter == I) {
2644         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2645         ScheduleStart = I;
2646         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2647         return;
2648       }
2649       UpIter++;
2650     }
2651     if (DownIter != LowerEnd) {
2652       if (&*DownIter == I) {
2653         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2654                          nullptr);
2655         ScheduleEnd = I->getNextNode();
2656         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2657         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
2658         return;
2659       }
2660       DownIter++;
2661     }
2662     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2663            "instruction not found in block");
2664   }
2665 }
2666 
2667 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2668                                                 Instruction *ToI,
2669                                                 ScheduleData *PrevLoadStore,
2670                                                 ScheduleData *NextLoadStore) {
2671   ScheduleData *CurrentLoadStore = PrevLoadStore;
2672   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2673     ScheduleData *SD = ScheduleDataMap[I];
2674     if (!SD) {
2675       // Allocate a new ScheduleData for the instruction.
2676       if (ChunkPos >= ChunkSize) {
2677         ScheduleDataChunks.push_back(
2678             llvm::make_unique<ScheduleData[]>(ChunkSize));
2679         ChunkPos = 0;
2680       }
2681       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2682       ScheduleDataMap[I] = SD;
2683       SD->Inst = I;
2684     }
2685     assert(!isInSchedulingRegion(SD) &&
2686            "new ScheduleData already in scheduling region");
2687     SD->init(SchedulingRegionID);
2688 
2689     if (I->mayReadOrWriteMemory()) {
2690       // Update the linked list of memory accessing instructions.
2691       if (CurrentLoadStore) {
2692         CurrentLoadStore->NextLoadStore = SD;
2693       } else {
2694         FirstLoadStoreInRegion = SD;
2695       }
2696       CurrentLoadStore = SD;
2697     }
2698   }
2699   if (NextLoadStore) {
2700     if (CurrentLoadStore)
2701       CurrentLoadStore->NextLoadStore = NextLoadStore;
2702   } else {
2703     LastLoadStoreInRegion = CurrentLoadStore;
2704   }
2705 }
2706 
2707 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2708                                                      bool InsertInReadyList,
2709                                                      BoUpSLP *SLP) {
2710   assert(SD->isSchedulingEntity());
2711 
2712   SmallVector<ScheduleData *, 10> WorkList;
2713   WorkList.push_back(SD);
2714 
2715   while (!WorkList.empty()) {
2716     ScheduleData *SD = WorkList.back();
2717     WorkList.pop_back();
2718 
2719     ScheduleData *BundleMember = SD;
2720     while (BundleMember) {
2721       assert(isInSchedulingRegion(BundleMember));
2722       if (!BundleMember->hasValidDependencies()) {
2723 
2724         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
2725         BundleMember->Dependencies = 0;
2726         BundleMember->resetUnscheduledDeps();
2727 
2728         // Handle def-use chain dependencies.
2729         for (User *U : BundleMember->Inst->users()) {
2730           if (isa<Instruction>(U)) {
2731             ScheduleData *UseSD = getScheduleData(U);
2732             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2733               BundleMember->Dependencies++;
2734               ScheduleData *DestBundle = UseSD->FirstInBundle;
2735               if (!DestBundle->IsScheduled) {
2736                 BundleMember->incrementUnscheduledDeps(1);
2737               }
2738               if (!DestBundle->hasValidDependencies()) {
2739                 WorkList.push_back(DestBundle);
2740               }
2741             }
2742           } else {
2743             // I'm not sure if this can ever happen. But we need to be safe.
2744             // This lets the instruction/bundle never be scheduled and eventally
2745             // disable vectorization.
2746             BundleMember->Dependencies++;
2747             BundleMember->incrementUnscheduledDeps(1);
2748           }
2749         }
2750 
2751         // Handle the memory dependencies.
2752         ScheduleData *DepDest = BundleMember->NextLoadStore;
2753         if (DepDest) {
2754           Instruction *SrcInst = BundleMember->Inst;
2755           AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2756           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2757 
2758           while (DepDest) {
2759             assert(isInSchedulingRegion(DepDest));
2760             if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2761               if (SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)) {
2762                 DepDest->MemoryDependencies.push_back(BundleMember);
2763                 BundleMember->Dependencies++;
2764                 ScheduleData *DestBundle = DepDest->FirstInBundle;
2765                 if (!DestBundle->IsScheduled) {
2766                   BundleMember->incrementUnscheduledDeps(1);
2767                 }
2768                 if (!DestBundle->hasValidDependencies()) {
2769                   WorkList.push_back(DestBundle);
2770                 }
2771               }
2772             }
2773             DepDest = DepDest->NextLoadStore;
2774           }
2775         }
2776       }
2777       BundleMember = BundleMember->NextInBundle;
2778     }
2779     if (InsertInReadyList && SD->isReady()) {
2780       ReadyInsts.push_back(SD);
2781       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
2782     }
2783   }
2784 }
2785 
2786 void BoUpSLP::BlockScheduling::resetSchedule() {
2787   assert(ScheduleStart &&
2788          "tried to reset schedule on block which has not been scheduled");
2789   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2790     ScheduleData *SD = getScheduleData(I);
2791     assert(isInSchedulingRegion(SD));
2792     SD->IsScheduled = false;
2793     SD->resetUnscheduledDeps();
2794   }
2795   ReadyInsts.clear();
2796 }
2797 
2798 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2799 
2800   if (!BS->ScheduleStart)
2801     return;
2802 
2803   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2804 
2805   BS->resetSchedule();
2806 
2807   // For the real scheduling we use a more sophisticated ready-list: it is
2808   // sorted by the original instruction location. This lets the final schedule
2809   // be as  close as possible to the original instruction order.
2810   struct ScheduleDataCompare {
2811     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2812       return SD2->SchedulingPriority < SD1->SchedulingPriority;
2813     }
2814   };
2815   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2816 
2817   // Ensure that all depencency data is updated and fill the ready-list with
2818   // initial instructions.
2819   int Idx = 0;
2820   int NumToSchedule = 0;
2821   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2822        I = I->getNextNode()) {
2823     ScheduleData *SD = BS->getScheduleData(I);
2824     assert(
2825         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2826         "scheduler and vectorizer have different opinion on what is a bundle");
2827     SD->FirstInBundle->SchedulingPriority = Idx++;
2828     if (SD->isSchedulingEntity()) {
2829       BS->calculateDependencies(SD, false, this);
2830       NumToSchedule++;
2831     }
2832   }
2833   BS->initialFillReadyList(ReadyInsts);
2834 
2835   Instruction *LastScheduledInst = BS->ScheduleEnd;
2836 
2837   // Do the "real" scheduling.
2838   while (!ReadyInsts.empty()) {
2839     ScheduleData *picked = *ReadyInsts.begin();
2840     ReadyInsts.erase(ReadyInsts.begin());
2841 
2842     // Move the scheduled instruction(s) to their dedicated places, if not
2843     // there yet.
2844     ScheduleData *BundleMember = picked;
2845     while (BundleMember) {
2846       Instruction *pickedInst = BundleMember->Inst;
2847       if (LastScheduledInst->getNextNode() != pickedInst) {
2848         BS->BB->getInstList().remove(pickedInst);
2849         BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2850       }
2851       LastScheduledInst = pickedInst;
2852       BundleMember = BundleMember->NextInBundle;
2853     }
2854 
2855     BS->schedule(picked, ReadyInsts);
2856     NumToSchedule--;
2857   }
2858   assert(NumToSchedule == 0 && "could not schedule all instructions");
2859 
2860   // Avoid duplicate scheduling of the block.
2861   BS->ScheduleStart = nullptr;
2862 }
2863 
2864 /// The SLPVectorizer Pass.
2865 struct SLPVectorizer : public FunctionPass {
2866   typedef SmallVector<StoreInst *, 8> StoreList;
2867   typedef MapVector<Value *, StoreList> StoreListMap;
2868 
2869   /// Pass identification, replacement for typeid
2870   static char ID;
2871 
2872   explicit SLPVectorizer() : FunctionPass(ID) {
2873     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2874   }
2875 
2876   ScalarEvolution *SE;
2877   const DataLayout *DL;
2878   TargetTransformInfo *TTI;
2879   TargetLibraryInfo *TLI;
2880   AliasAnalysis *AA;
2881   LoopInfo *LI;
2882   DominatorTree *DT;
2883   AssumptionCache *AC;
2884 
2885   bool runOnFunction(Function &F) override {
2886     if (skipOptnoneFunction(F))
2887       return false;
2888 
2889     SE = &getAnalysis<ScalarEvolution>();
2890     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2891     DL = DLP ? &DLP->getDataLayout() : nullptr;
2892     TTI = &getAnalysis<TargetTransformInfo>();
2893     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2894     AA = &getAnalysis<AliasAnalysis>();
2895     LI = &getAnalysis<LoopInfo>();
2896     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2897     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2898 
2899     StoreRefs.clear();
2900     bool Changed = false;
2901 
2902     // If the target claims to have no vector registers don't attempt
2903     // vectorization.
2904     if (!TTI->getNumberOfRegisters(true))
2905       return false;
2906 
2907     // Must have DataLayout. We can't require it because some tests run w/o
2908     // triple.
2909     if (!DL)
2910       return false;
2911 
2912     // Don't vectorize when the attribute NoImplicitFloat is used.
2913     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2914       return false;
2915 
2916     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2917 
2918     // Use the bottom up slp vectorizer to construct chains that start with
2919     // store instructions.
2920     BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
2921 
2922     // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
2923     // delete instructions.
2924 
2925     // Scan the blocks in the function in post order.
2926     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2927          e = po_end(&F.getEntryBlock()); it != e; ++it) {
2928       BasicBlock *BB = *it;
2929       // Vectorize trees that end at stores.
2930       if (unsigned count = collectStores(BB, R)) {
2931         (void)count;
2932         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2933         Changed |= vectorizeStoreChains(R);
2934       }
2935 
2936       // Vectorize trees that end at reductions.
2937       Changed |= vectorizeChainsInBlock(BB, R);
2938     }
2939 
2940     if (Changed) {
2941       R.optimizeGatherSequence();
2942       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2943       DEBUG(verifyFunction(F));
2944     }
2945     return Changed;
2946   }
2947 
2948   void getAnalysisUsage(AnalysisUsage &AU) const override {
2949     FunctionPass::getAnalysisUsage(AU);
2950     AU.addRequired<AssumptionCacheTracker>();
2951     AU.addRequired<ScalarEvolution>();
2952     AU.addRequired<AliasAnalysis>();
2953     AU.addRequired<TargetTransformInfo>();
2954     AU.addRequired<LoopInfo>();
2955     AU.addRequired<DominatorTreeWrapperPass>();
2956     AU.addPreserved<LoopInfo>();
2957     AU.addPreserved<DominatorTreeWrapperPass>();
2958     AU.setPreservesCFG();
2959   }
2960 
2961 private:
2962 
2963   /// \brief Collect memory references and sort them according to their base
2964   /// object. We sort the stores to their base objects to reduce the cost of the
2965   /// quadratic search on the stores. TODO: We can further reduce this cost
2966   /// if we flush the chain creation every time we run into a memory barrier.
2967   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2968 
2969   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2970   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2971 
2972   /// \brief Try to vectorize a list of operands.
2973   /// \@param BuildVector A list of users to ignore for the purpose of
2974   ///                     scheduling and that don't need extracting.
2975   /// \returns true if a value was vectorized.
2976   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2977                           ArrayRef<Value *> BuildVector = None,
2978                           bool allowReorder = false);
2979 
2980   /// \brief Try to vectorize a chain that may start at the operands of \V;
2981   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2982 
2983   /// \brief Vectorize the stores that were collected in StoreRefs.
2984   bool vectorizeStoreChains(BoUpSLP &R);
2985 
2986   /// \brief Scan the basic block and look for patterns that are likely to start
2987   /// a vectorization chain.
2988   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2989 
2990   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2991                            BoUpSLP &R);
2992 
2993   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2994                        BoUpSLP &R);
2995 private:
2996   StoreListMap StoreRefs;
2997 };
2998 
2999 /// \brief Check that the Values in the slice in VL array are still existent in
3000 /// the WeakVH array.
3001 /// Vectorization of part of the VL array may cause later values in the VL array
3002 /// to become invalid. We track when this has happened in the WeakVH array.
3003 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
3004                                SmallVectorImpl<WeakVH> &VH,
3005                                unsigned SliceBegin,
3006                                unsigned SliceSize) {
3007   for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
3008     if (VH[i] != VL[i])
3009       return true;
3010 
3011   return false;
3012 }
3013 
3014 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3015                                           int CostThreshold, BoUpSLP &R) {
3016   unsigned ChainLen = Chain.size();
3017   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3018         << "\n");
3019   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3020   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3021   unsigned VF = MinVecRegSize / Sz;
3022 
3023   if (!isPowerOf2_32(Sz) || VF < 2)
3024     return false;
3025 
3026   // Keep track of values that were deleted by vectorizing in the loop below.
3027   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3028 
3029   bool Changed = false;
3030   // Look for profitable vectorizable trees at all offsets, starting at zero.
3031   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3032     if (i + VF > e)
3033       break;
3034 
3035     // Check that a previous iteration of this loop did not delete the Value.
3036     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3037       continue;
3038 
3039     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3040           << "\n");
3041     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3042 
3043     R.buildTree(Operands);
3044 
3045     int Cost = R.getTreeCost();
3046 
3047     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3048     if (Cost < CostThreshold) {
3049       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3050       R.vectorizeTree();
3051 
3052       // Move to the next bundle.
3053       i += VF - 1;
3054       Changed = true;
3055     }
3056   }
3057 
3058   return Changed;
3059 }
3060 
3061 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3062                                     int costThreshold, BoUpSLP &R) {
3063   SetVector<Value *> Heads, Tails;
3064   SmallDenseMap<Value *, Value *> ConsecutiveChain;
3065 
3066   // We may run into multiple chains that merge into a single chain. We mark the
3067   // stores that we vectorized so that we don't visit the same store twice.
3068   BoUpSLP::ValueSet VectorizedStores;
3069   bool Changed = false;
3070 
3071   // Do a quadratic search on all of the given stores and find
3072   // all of the pairs of stores that follow each other.
3073   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3074     for (unsigned j = 0; j < e; ++j) {
3075       if (i == j)
3076         continue;
3077 
3078       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3079         Tails.insert(Stores[j]);
3080         Heads.insert(Stores[i]);
3081         ConsecutiveChain[Stores[i]] = Stores[j];
3082       }
3083     }
3084   }
3085 
3086   // For stores that start but don't end a link in the chain:
3087   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3088        it != e; ++it) {
3089     if (Tails.count(*it))
3090       continue;
3091 
3092     // We found a store instr that starts a chain. Now follow the chain and try
3093     // to vectorize it.
3094     BoUpSLP::ValueList Operands;
3095     Value *I = *it;
3096     // Collect the chain into a list.
3097     while (Tails.count(I) || Heads.count(I)) {
3098       if (VectorizedStores.count(I))
3099         break;
3100       Operands.push_back(I);
3101       // Move to the next value in the chain.
3102       I = ConsecutiveChain[I];
3103     }
3104 
3105     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3106 
3107     // Mark the vectorized stores so that we don't vectorize them again.
3108     if (Vectorized)
3109       VectorizedStores.insert(Operands.begin(), Operands.end());
3110     Changed |= Vectorized;
3111   }
3112 
3113   return Changed;
3114 }
3115 
3116 
3117 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3118   unsigned count = 0;
3119   StoreRefs.clear();
3120   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3121     StoreInst *SI = dyn_cast<StoreInst>(it);
3122     if (!SI)
3123       continue;
3124 
3125     // Don't touch volatile stores.
3126     if (!SI->isSimple())
3127       continue;
3128 
3129     // Check that the pointer points to scalars.
3130     Type *Ty = SI->getValueOperand()->getType();
3131     if (Ty->isAggregateType() || Ty->isVectorTy())
3132       continue;
3133 
3134     // Find the base pointer.
3135     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3136 
3137     // Save the store locations.
3138     StoreRefs[Ptr].push_back(SI);
3139     count++;
3140   }
3141   return count;
3142 }
3143 
3144 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3145   if (!A || !B)
3146     return false;
3147   Value *VL[] = { A, B };
3148   return tryToVectorizeList(VL, R, None, true);
3149 }
3150 
3151 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3152                                        ArrayRef<Value *> BuildVector,
3153                                        bool allowReorder) {
3154   if (VL.size() < 2)
3155     return false;
3156 
3157   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3158 
3159   // Check that all of the parts are scalar instructions of the same type.
3160   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3161   if (!I0)
3162     return false;
3163 
3164   unsigned Opcode0 = I0->getOpcode();
3165 
3166   Type *Ty0 = I0->getType();
3167   unsigned Sz = DL->getTypeSizeInBits(Ty0);
3168   unsigned VF = MinVecRegSize / Sz;
3169 
3170   for (int i = 0, e = VL.size(); i < e; ++i) {
3171     Type *Ty = VL[i]->getType();
3172     if (Ty->isAggregateType() || Ty->isVectorTy())
3173       return false;
3174     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3175     if (!Inst || Inst->getOpcode() != Opcode0)
3176       return false;
3177   }
3178 
3179   bool Changed = false;
3180 
3181   // Keep track of values that were deleted by vectorizing in the loop below.
3182   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3183 
3184   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3185     unsigned OpsWidth = 0;
3186 
3187     if (i + VF > e)
3188       OpsWidth = e - i;
3189     else
3190       OpsWidth = VF;
3191 
3192     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3193       break;
3194 
3195     // Check that a previous iteration of this loop did not delete the Value.
3196     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3197       continue;
3198 
3199     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3200                  << "\n");
3201     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3202 
3203     ArrayRef<Value *> BuildVectorSlice;
3204     if (!BuildVector.empty())
3205       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3206 
3207     R.buildTree(Ops, BuildVectorSlice);
3208     // TODO: check if we can allow reordering also for other cases than
3209     // tryToVectorizePair()
3210     if (allowReorder && R.shouldReorder()) {
3211       assert(Ops.size() == 2);
3212       assert(BuildVectorSlice.empty());
3213       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3214       R.buildTree(ReorderedOps, None);
3215     }
3216     int Cost = R.getTreeCost();
3217 
3218     if (Cost < -SLPCostThreshold) {
3219       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3220       Value *VectorizedRoot = R.vectorizeTree();
3221 
3222       // Reconstruct the build vector by extracting the vectorized root. This
3223       // way we handle the case where some elements of the vector are undefined.
3224       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3225       if (!BuildVectorSlice.empty()) {
3226         // The insert point is the last build vector instruction. The vectorized
3227         // root will precede it. This guarantees that we get an instruction. The
3228         // vectorized tree could have been constant folded.
3229         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3230         unsigned VecIdx = 0;
3231         for (auto &V : BuildVectorSlice) {
3232           IRBuilder<true, NoFolder> Builder(
3233               ++BasicBlock::iterator(InsertAfter));
3234           InsertElementInst *IE = cast<InsertElementInst>(V);
3235           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3236               VectorizedRoot, Builder.getInt32(VecIdx++)));
3237           IE->setOperand(1, Extract);
3238           IE->removeFromParent();
3239           IE->insertAfter(Extract);
3240           InsertAfter = IE;
3241         }
3242       }
3243       // Move to the next bundle.
3244       i += VF - 1;
3245       Changed = true;
3246     }
3247   }
3248 
3249   return Changed;
3250 }
3251 
3252 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3253   if (!V)
3254     return false;
3255 
3256   // Try to vectorize V.
3257   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3258     return true;
3259 
3260   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3261   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3262   // Try to skip B.
3263   if (B && B->hasOneUse()) {
3264     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3265     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3266     if (tryToVectorizePair(A, B0, R)) {
3267       return true;
3268     }
3269     if (tryToVectorizePair(A, B1, R)) {
3270       return true;
3271     }
3272   }
3273 
3274   // Try to skip A.
3275   if (A && A->hasOneUse()) {
3276     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3277     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3278     if (tryToVectorizePair(A0, B, R)) {
3279       return true;
3280     }
3281     if (tryToVectorizePair(A1, B, R)) {
3282       return true;
3283     }
3284   }
3285   return 0;
3286 }
3287 
3288 /// \brief Generate a shuffle mask to be used in a reduction tree.
3289 ///
3290 /// \param VecLen The length of the vector to be reduced.
3291 /// \param NumEltsToRdx The number of elements that should be reduced in the
3292 ///        vector.
3293 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3294 ///        reduction. A pairwise reduction will generate a mask of
3295 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
3296 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3297 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3298 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3299                                    bool IsPairwise, bool IsLeft,
3300                                    IRBuilder<> &Builder) {
3301   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3302 
3303   SmallVector<Constant *, 32> ShuffleMask(
3304       VecLen, UndefValue::get(Builder.getInt32Ty()));
3305 
3306   if (IsPairwise)
3307     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3308     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3309       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3310   else
3311     // Move the upper half of the vector to the lower half.
3312     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3313       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3314 
3315   return ConstantVector::get(ShuffleMask);
3316 }
3317 
3318 
3319 /// Model horizontal reductions.
3320 ///
3321 /// A horizontal reduction is a tree of reduction operations (currently add and
3322 /// fadd) that has operations that can be put into a vector as its leaf.
3323 /// For example, this tree:
3324 ///
3325 /// mul mul mul mul
3326 ///  \  /    \  /
3327 ///   +       +
3328 ///    \     /
3329 ///       +
3330 /// This tree has "mul" as its reduced values and "+" as its reduction
3331 /// operations. A reduction might be feeding into a store or a binary operation
3332 /// feeding a phi.
3333 ///    ...
3334 ///    \  /
3335 ///     +
3336 ///     |
3337 ///  phi +=
3338 ///
3339 ///  Or:
3340 ///    ...
3341 ///    \  /
3342 ///     +
3343 ///     |
3344 ///   *p =
3345 ///
3346 class HorizontalReduction {
3347   SmallVector<Value *, 16> ReductionOps;
3348   SmallVector<Value *, 32> ReducedVals;
3349 
3350   BinaryOperator *ReductionRoot;
3351   PHINode *ReductionPHI;
3352 
3353   /// The opcode of the reduction.
3354   unsigned ReductionOpcode;
3355   /// The opcode of the values we perform a reduction on.
3356   unsigned ReducedValueOpcode;
3357   /// The width of one full horizontal reduction operation.
3358   unsigned ReduxWidth;
3359   /// Should we model this reduction as a pairwise reduction tree or a tree that
3360   /// splits the vector in halves and adds those halves.
3361   bool IsPairwiseReduction;
3362 
3363 public:
3364   HorizontalReduction()
3365     : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3366     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3367 
3368   /// \brief Try to find a reduction tree.
3369   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3370                                  const DataLayout *DL) {
3371     assert((!Phi ||
3372             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3373            "Thi phi needs to use the binary operator");
3374 
3375     // We could have a initial reductions that is not an add.
3376     //  r *= v1 + v2 + v3 + v4
3377     // In such a case start looking for a tree rooted in the first '+'.
3378     if (Phi) {
3379       if (B->getOperand(0) == Phi) {
3380         Phi = nullptr;
3381         B = dyn_cast<BinaryOperator>(B->getOperand(1));
3382       } else if (B->getOperand(1) == Phi) {
3383         Phi = nullptr;
3384         B = dyn_cast<BinaryOperator>(B->getOperand(0));
3385       }
3386     }
3387 
3388     if (!B)
3389       return false;
3390 
3391     Type *Ty = B->getType();
3392     if (Ty->isVectorTy())
3393       return false;
3394 
3395     ReductionOpcode = B->getOpcode();
3396     ReducedValueOpcode = 0;
3397     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3398     ReductionRoot = B;
3399     ReductionPHI = Phi;
3400 
3401     if (ReduxWidth < 4)
3402       return false;
3403 
3404     // We currently only support adds.
3405     if (ReductionOpcode != Instruction::Add &&
3406         ReductionOpcode != Instruction::FAdd)
3407       return false;
3408 
3409     // Post order traverse the reduction tree starting at B. We only handle true
3410     // trees containing only binary operators.
3411     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3412     Stack.push_back(std::make_pair(B, 0));
3413     while (!Stack.empty()) {
3414       BinaryOperator *TreeN = Stack.back().first;
3415       unsigned EdgeToVist = Stack.back().second++;
3416       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3417 
3418       // Only handle trees in the current basic block.
3419       if (TreeN->getParent() != B->getParent())
3420         return false;
3421 
3422       // Each tree node needs to have one user except for the ultimate
3423       // reduction.
3424       if (!TreeN->hasOneUse() && TreeN != B)
3425         return false;
3426 
3427       // Postorder vist.
3428       if (EdgeToVist == 2 || IsReducedValue) {
3429         if (IsReducedValue) {
3430           // Make sure that the opcodes of the operations that we are going to
3431           // reduce match.
3432           if (!ReducedValueOpcode)
3433             ReducedValueOpcode = TreeN->getOpcode();
3434           else if (ReducedValueOpcode != TreeN->getOpcode())
3435             return false;
3436           ReducedVals.push_back(TreeN);
3437         } else {
3438           // We need to be able to reassociate the adds.
3439           if (!TreeN->isAssociative())
3440             return false;
3441           ReductionOps.push_back(TreeN);
3442         }
3443         // Retract.
3444         Stack.pop_back();
3445         continue;
3446       }
3447 
3448       // Visit left or right.
3449       Value *NextV = TreeN->getOperand(EdgeToVist);
3450       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3451       if (Next)
3452         Stack.push_back(std::make_pair(Next, 0));
3453       else if (NextV != Phi)
3454         return false;
3455     }
3456     return true;
3457   }
3458 
3459   /// \brief Attempt to vectorize the tree found by
3460   /// matchAssociativeReduction.
3461   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3462     if (ReducedVals.empty())
3463       return false;
3464 
3465     unsigned NumReducedVals = ReducedVals.size();
3466     if (NumReducedVals < ReduxWidth)
3467       return false;
3468 
3469     Value *VectorizedTree = nullptr;
3470     IRBuilder<> Builder(ReductionRoot);
3471     FastMathFlags Unsafe;
3472     Unsafe.setUnsafeAlgebra();
3473     Builder.SetFastMathFlags(Unsafe);
3474     unsigned i = 0;
3475 
3476     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3477       V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3478 
3479       // Estimate cost.
3480       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3481       if (Cost >= -SLPCostThreshold)
3482         break;
3483 
3484       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3485                    << ". (HorRdx)\n");
3486 
3487       // Vectorize a tree.
3488       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3489       Value *VectorizedRoot = V.vectorizeTree();
3490 
3491       // Emit a reduction.
3492       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3493       if (VectorizedTree) {
3494         Builder.SetCurrentDebugLocation(Loc);
3495         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3496                                      ReducedSubTree, "bin.rdx");
3497       } else
3498         VectorizedTree = ReducedSubTree;
3499     }
3500 
3501     if (VectorizedTree) {
3502       // Finish the reduction.
3503       for (; i < NumReducedVals; ++i) {
3504         Builder.SetCurrentDebugLocation(
3505           cast<Instruction>(ReducedVals[i])->getDebugLoc());
3506         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3507                                      ReducedVals[i]);
3508       }
3509       // Update users.
3510       if (ReductionPHI) {
3511         assert(ReductionRoot && "Need a reduction operation");
3512         ReductionRoot->setOperand(0, VectorizedTree);
3513         ReductionRoot->setOperand(1, ReductionPHI);
3514       } else
3515         ReductionRoot->replaceAllUsesWith(VectorizedTree);
3516     }
3517     return VectorizedTree != nullptr;
3518   }
3519 
3520 private:
3521 
3522   /// \brief Calcuate the cost of a reduction.
3523   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3524     Type *ScalarTy = FirstReducedVal->getType();
3525     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3526 
3527     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3528     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3529 
3530     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3531     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3532 
3533     int ScalarReduxCost =
3534         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3535 
3536     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3537                  << " for reduction that starts with " << *FirstReducedVal
3538                  << " (It is a "
3539                  << (IsPairwiseReduction ? "pairwise" : "splitting")
3540                  << " reduction)\n");
3541 
3542     return VecReduxCost - ScalarReduxCost;
3543   }
3544 
3545   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3546                             Value *R, const Twine &Name = "") {
3547     if (Opcode == Instruction::FAdd)
3548       return Builder.CreateFAdd(L, R, Name);
3549     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3550   }
3551 
3552   /// \brief Emit a horizontal reduction of the vectorized value.
3553   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3554     assert(VectorizedValue && "Need to have a vectorized tree node");
3555     assert(isPowerOf2_32(ReduxWidth) &&
3556            "We only handle power-of-two reductions for now");
3557 
3558     Value *TmpVec = VectorizedValue;
3559     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3560       if (IsPairwiseReduction) {
3561         Value *LeftMask =
3562           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3563         Value *RightMask =
3564           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3565 
3566         Value *LeftShuf = Builder.CreateShuffleVector(
3567           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3568         Value *RightShuf = Builder.CreateShuffleVector(
3569           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3570           "rdx.shuf.r");
3571         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3572                              "bin.rdx");
3573       } else {
3574         Value *UpperHalf =
3575           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3576         Value *Shuf = Builder.CreateShuffleVector(
3577           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3578         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3579       }
3580     }
3581 
3582     // The result is in the first element of the vector.
3583     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3584   }
3585 };
3586 
3587 /// \brief Recognize construction of vectors like
3588 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
3589 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
3590 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
3591 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
3592 ///
3593 /// Returns true if it matches
3594 ///
3595 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3596                             SmallVectorImpl<Value *> &BuildVector,
3597                             SmallVectorImpl<Value *> &BuildVectorOpds) {
3598   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3599     return false;
3600 
3601   InsertElementInst *IE = FirstInsertElem;
3602   while (true) {
3603     BuildVector.push_back(IE);
3604     BuildVectorOpds.push_back(IE->getOperand(1));
3605 
3606     if (IE->use_empty())
3607       return false;
3608 
3609     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3610     if (!NextUse)
3611       return true;
3612 
3613     // If this isn't the final use, make sure the next insertelement is the only
3614     // use. It's OK if the final constructed vector is used multiple times
3615     if (!IE->hasOneUse())
3616       return false;
3617 
3618     IE = NextUse;
3619   }
3620 
3621   return false;
3622 }
3623 
3624 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3625   return V->getType() < V2->getType();
3626 }
3627 
3628 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3629   bool Changed = false;
3630   SmallVector<Value *, 4> Incoming;
3631   SmallSet<Value *, 16> VisitedInstrs;
3632 
3633   bool HaveVectorizedPhiNodes = true;
3634   while (HaveVectorizedPhiNodes) {
3635     HaveVectorizedPhiNodes = false;
3636 
3637     // Collect the incoming values from the PHIs.
3638     Incoming.clear();
3639     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3640          ++instr) {
3641       PHINode *P = dyn_cast<PHINode>(instr);
3642       if (!P)
3643         break;
3644 
3645       if (!VisitedInstrs.count(P))
3646         Incoming.push_back(P);
3647     }
3648 
3649     // Sort by type.
3650     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3651 
3652     // Try to vectorize elements base on their type.
3653     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3654                                            E = Incoming.end();
3655          IncIt != E;) {
3656 
3657       // Look for the next elements with the same type.
3658       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3659       while (SameTypeIt != E &&
3660              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3661         VisitedInstrs.insert(*SameTypeIt);
3662         ++SameTypeIt;
3663       }
3664 
3665       // Try to vectorize them.
3666       unsigned NumElts = (SameTypeIt - IncIt);
3667       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3668       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3669         // Success start over because instructions might have been changed.
3670         HaveVectorizedPhiNodes = true;
3671         Changed = true;
3672         break;
3673       }
3674 
3675       // Start over at the next instruction of a different type (or the end).
3676       IncIt = SameTypeIt;
3677     }
3678   }
3679 
3680   VisitedInstrs.clear();
3681 
3682   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3683     // We may go through BB multiple times so skip the one we have checked.
3684     if (!VisitedInstrs.insert(it).second)
3685       continue;
3686 
3687     if (isa<DbgInfoIntrinsic>(it))
3688       continue;
3689 
3690     // Try to vectorize reductions that use PHINodes.
3691     if (PHINode *P = dyn_cast<PHINode>(it)) {
3692       // Check that the PHI is a reduction PHI.
3693       if (P->getNumIncomingValues() != 2)
3694         return Changed;
3695       Value *Rdx =
3696           (P->getIncomingBlock(0) == BB
3697                ? (P->getIncomingValue(0))
3698                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3699                                                : nullptr));
3700       // Check if this is a Binary Operator.
3701       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3702       if (!BI)
3703         continue;
3704 
3705       // Try to match and vectorize a horizontal reduction.
3706       HorizontalReduction HorRdx;
3707       if (ShouldVectorizeHor &&
3708           HorRdx.matchAssociativeReduction(P, BI, DL) &&
3709           HorRdx.tryToReduce(R, TTI)) {
3710         Changed = true;
3711         it = BB->begin();
3712         e = BB->end();
3713         continue;
3714       }
3715 
3716      Value *Inst = BI->getOperand(0);
3717       if (Inst == P)
3718         Inst = BI->getOperand(1);
3719 
3720       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3721         // We would like to start over since some instructions are deleted
3722         // and the iterator may become invalid value.
3723         Changed = true;
3724         it = BB->begin();
3725         e = BB->end();
3726         continue;
3727       }
3728 
3729       continue;
3730     }
3731 
3732     // Try to vectorize horizontal reductions feeding into a store.
3733     if (ShouldStartVectorizeHorAtStore)
3734       if (StoreInst *SI = dyn_cast<StoreInst>(it))
3735         if (BinaryOperator *BinOp =
3736                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3737           HorizontalReduction HorRdx;
3738           if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3739                 HorRdx.tryToReduce(R, TTI)) ||
3740                tryToVectorize(BinOp, R))) {
3741             Changed = true;
3742             it = BB->begin();
3743             e = BB->end();
3744             continue;
3745           }
3746         }
3747 
3748     // Try to vectorize horizontal reductions feeding into a return.
3749     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3750       if (RI->getNumOperands() != 0)
3751         if (BinaryOperator *BinOp =
3752                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3753           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3754           if (tryToVectorizePair(BinOp->getOperand(0),
3755                                  BinOp->getOperand(1), R)) {
3756             Changed = true;
3757             it = BB->begin();
3758             e = BB->end();
3759             continue;
3760           }
3761         }
3762 
3763     // Try to vectorize trees that start at compare instructions.
3764     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3765       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3766         Changed = true;
3767         // We would like to start over since some instructions are deleted
3768         // and the iterator may become invalid value.
3769         it = BB->begin();
3770         e = BB->end();
3771         continue;
3772       }
3773 
3774       for (int i = 0; i < 2; ++i) {
3775         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3776           if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3777             Changed = true;
3778             // We would like to start over since some instructions are deleted
3779             // and the iterator may become invalid value.
3780             it = BB->begin();
3781             e = BB->end();
3782           }
3783         }
3784       }
3785       continue;
3786     }
3787 
3788     // Try to vectorize trees that start at insertelement instructions.
3789     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3790       SmallVector<Value *, 16> BuildVector;
3791       SmallVector<Value *, 16> BuildVectorOpds;
3792       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3793         continue;
3794 
3795       // Vectorize starting with the build vector operands ignoring the
3796       // BuildVector instructions for the purpose of scheduling and user
3797       // extraction.
3798       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3799         Changed = true;
3800         it = BB->begin();
3801         e = BB->end();
3802       }
3803 
3804       continue;
3805     }
3806   }
3807 
3808   return Changed;
3809 }
3810 
3811 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3812   bool Changed = false;
3813   // Attempt to sort and vectorize each of the store-groups.
3814   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3815        it != e; ++it) {
3816     if (it->second.size() < 2)
3817       continue;
3818 
3819     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3820           << it->second.size() << ".\n");
3821 
3822     // Process the stores in chunks of 16.
3823     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3824       unsigned Len = std::min<unsigned>(CE - CI, 16);
3825       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3826                                  -SLPCostThreshold, R);
3827     }
3828   }
3829   return Changed;
3830 }
3831 
3832 } // end anonymous namespace
3833 
3834 char SLPVectorizer::ID = 0;
3835 static const char lv_name[] = "SLP Vectorizer";
3836 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3837 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3838 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3839 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3840 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3841 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3842 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3843 
3844 namespace llvm {
3845 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
3846 }
3847