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