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