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