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