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