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