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