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