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