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