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