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