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 (unsigned i = 0, e = VL.size(); i < e; ++i)
135     if (!isa<Constant>(VL[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 (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
962     TreeEntry *Entry = &VectorizableTree[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 (unsigned j = 0; j < VL.size(); ++j)
1163           Operands.push_back(cast<PHINode>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1252           Operands.push_back(cast<Instruction>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1281           Operands.push_back(cast<Instruction>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1323           Operands.push_back(cast<Instruction>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1371           Operands.push_back(cast<Instruction>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1392         Operands.push_back(cast<Instruction>(VL[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 (unsigned j = 0; j < VL.size(); ++j) {
1455           CallInst *CI2 = dyn_cast<CallInst>(VL[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 (unsigned j = 0; j < VL.size(); ++j)
1487           Operands.push_back(cast<Instruction>(VL[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 (unsigned i = 0; i < VL.size(); ++i) {
1774         Instruction *I = cast<Instruction>(VL[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 (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1830     Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[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 (unsigned i = 0, e = VL.size(); i < e; ++i) {
1971     Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
1972     Right.push_back(cast<Instruction>(VL[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 (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2660        it != e; ++it) {
2661     Value *Scalar = it->Scalar;
2662     llvm::User *User = it->User;
2663 
2664     // Skip users that we already RAUW. This happens when one instruction
2665     // has multiple uses of the same value.
2666     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2667         Scalar->user_end())
2668       continue;
2669     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2670 
2671     int Idx = ScalarToTreeEntry[Scalar];
2672     TreeEntry *E = &VectorizableTree[Idx];
2673     assert(!E->NeedToGather && "Extracting from a gather list");
2674 
2675     Value *Vec = E->VectorizedValue;
2676     assert(Vec && "Can't find vectorizable value");
2677 
2678     Value *Lane = Builder.getInt32(it->Lane);
2679     // Generate extracts for out-of-tree users.
2680     // Find the insertion point for the extractelement lane.
2681     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2682       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2683         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2684           if (PH->getIncomingValue(i) == Scalar) {
2685             TerminatorInst *IncomingTerminator =
2686                 PH->getIncomingBlock(i)->getTerminator();
2687             if (isa<CatchSwitchInst>(IncomingTerminator)) {
2688               Builder.SetInsertPoint(VecI->getParent(),
2689                                      std::next(VecI->getIterator()));
2690             } else {
2691               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2692             }
2693             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2694             if (MinBWs.count(ScalarRoot))
2695               Ex = Builder.CreateSExt(Ex, Scalar->getType());
2696             CSEBlocks.insert(PH->getIncomingBlock(i));
2697             PH->setOperand(i, Ex);
2698           }
2699         }
2700       } else {
2701         Builder.SetInsertPoint(cast<Instruction>(User));
2702         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2703         if (MinBWs.count(ScalarRoot))
2704           Ex = Builder.CreateSExt(Ex, Scalar->getType());
2705         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2706         User->replaceUsesOfWith(Scalar, Ex);
2707      }
2708     } else {
2709       Builder.SetInsertPoint(&F->getEntryBlock().front());
2710       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2711       if (MinBWs.count(ScalarRoot))
2712         Ex = Builder.CreateSExt(Ex, Scalar->getType());
2713       CSEBlocks.insert(&F->getEntryBlock());
2714       User->replaceUsesOfWith(Scalar, Ex);
2715     }
2716 
2717     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2718   }
2719 
2720   // For each vectorized value:
2721   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2722     TreeEntry *Entry = &VectorizableTree[EIdx];
2723 
2724     // For each lane:
2725     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2726       Value *Scalar = Entry->Scalars[Lane];
2727       // No need to handle users of gathered values.
2728       if (Entry->NeedToGather)
2729         continue;
2730 
2731       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2732 
2733       Type *Ty = Scalar->getType();
2734       if (!Ty->isVoidTy()) {
2735 #ifndef NDEBUG
2736         for (User *U : Scalar->users()) {
2737           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2738 
2739           assert((ScalarToTreeEntry.count(U) ||
2740                   // It is legal to replace users in the ignorelist by undef.
2741                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2742                    UserIgnoreList.end())) &&
2743                  "Replacing out-of-tree value with undef");
2744         }
2745 #endif
2746         Value *Undef = UndefValue::get(Ty);
2747         Scalar->replaceAllUsesWith(Undef);
2748       }
2749       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2750       eraseInstruction(cast<Instruction>(Scalar));
2751     }
2752   }
2753 
2754   Builder.ClearInsertionPoint();
2755 
2756   return VectorizableTree[0].VectorizedValue;
2757 }
2758 
2759 void BoUpSLP::optimizeGatherSequence() {
2760   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2761         << " gather sequences instructions.\n");
2762   // LICM InsertElementInst sequences.
2763   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2764        e = GatherSeq.end(); it != e; ++it) {
2765     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2766 
2767     if (!Insert)
2768       continue;
2769 
2770     // Check if this block is inside a loop.
2771     Loop *L = LI->getLoopFor(Insert->getParent());
2772     if (!L)
2773       continue;
2774 
2775     // Check if it has a preheader.
2776     BasicBlock *PreHeader = L->getLoopPreheader();
2777     if (!PreHeader)
2778       continue;
2779 
2780     // If the vector or the element that we insert into it are
2781     // instructions that are defined in this basic block then we can't
2782     // hoist this instruction.
2783     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2784     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2785     if (CurrVec && L->contains(CurrVec))
2786       continue;
2787     if (NewElem && L->contains(NewElem))
2788       continue;
2789 
2790     // We can hoist this instruction. Move it to the pre-header.
2791     Insert->moveBefore(PreHeader->getTerminator());
2792   }
2793 
2794   // Make a list of all reachable blocks in our CSE queue.
2795   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2796   CSEWorkList.reserve(CSEBlocks.size());
2797   for (BasicBlock *BB : CSEBlocks)
2798     if (DomTreeNode *N = DT->getNode(BB)) {
2799       assert(DT->isReachableFromEntry(N));
2800       CSEWorkList.push_back(N);
2801     }
2802 
2803   // Sort blocks by domination. This ensures we visit a block after all blocks
2804   // dominating it are visited.
2805   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2806                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2807     return DT->properlyDominates(A, B);
2808   });
2809 
2810   // Perform O(N^2) search over the gather sequences and merge identical
2811   // instructions. TODO: We can further optimize this scan if we split the
2812   // instructions into different buckets based on the insert lane.
2813   SmallVector<Instruction *, 16> Visited;
2814   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2815     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2816            "Worklist not sorted properly!");
2817     BasicBlock *BB = (*I)->getBlock();
2818     // For all instructions in blocks containing gather sequences:
2819     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2820       Instruction *In = &*it++;
2821       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2822         continue;
2823 
2824       // Check if we can replace this instruction with any of the
2825       // visited instructions.
2826       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2827                                                     ve = Visited.end();
2828            v != ve; ++v) {
2829         if (In->isIdenticalTo(*v) &&
2830             DT->dominates((*v)->getParent(), In->getParent())) {
2831           In->replaceAllUsesWith(*v);
2832           eraseInstruction(In);
2833           In = nullptr;
2834           break;
2835         }
2836       }
2837       if (In) {
2838         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2839         Visited.push_back(In);
2840       }
2841     }
2842   }
2843   CSEBlocks.clear();
2844   GatherSeq.clear();
2845 }
2846 
2847 // Groups the instructions to a bundle (which is then a single scheduling entity)
2848 // and schedules instructions until the bundle gets ready.
2849 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2850                                                  BoUpSLP *SLP) {
2851   if (isa<PHINode>(VL[0]))
2852     return true;
2853 
2854   // Initialize the instruction bundle.
2855   Instruction *OldScheduleEnd = ScheduleEnd;
2856   ScheduleData *PrevInBundle = nullptr;
2857   ScheduleData *Bundle = nullptr;
2858   bool ReSchedule = false;
2859   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2860 
2861   // Make sure that the scheduling region contains all
2862   // instructions of the bundle.
2863   for (Value *V : VL) {
2864     if (!extendSchedulingRegion(V))
2865       return false;
2866   }
2867 
2868   for (Value *V : VL) {
2869     ScheduleData *BundleMember = getScheduleData(V);
2870     assert(BundleMember &&
2871            "no ScheduleData for bundle member (maybe not in same basic block)");
2872     if (BundleMember->IsScheduled) {
2873       // A bundle member was scheduled as single instruction before and now
2874       // needs to be scheduled as part of the bundle. We just get rid of the
2875       // existing schedule.
2876       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2877                    << " was already scheduled\n");
2878       ReSchedule = true;
2879     }
2880     assert(BundleMember->isSchedulingEntity() &&
2881            "bundle member already part of other bundle");
2882     if (PrevInBundle) {
2883       PrevInBundle->NextInBundle = BundleMember;
2884     } else {
2885       Bundle = BundleMember;
2886     }
2887     BundleMember->UnscheduledDepsInBundle = 0;
2888     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2889 
2890     // Group the instructions to a bundle.
2891     BundleMember->FirstInBundle = Bundle;
2892     PrevInBundle = BundleMember;
2893   }
2894   if (ScheduleEnd != OldScheduleEnd) {
2895     // The scheduling region got new instructions at the lower end (or it is a
2896     // new region for the first bundle). This makes it necessary to
2897     // recalculate all dependencies.
2898     // It is seldom that this needs to be done a second time after adding the
2899     // initial bundle to the region.
2900     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2901       ScheduleData *SD = getScheduleData(I);
2902       SD->clearDependencies();
2903     }
2904     ReSchedule = true;
2905   }
2906   if (ReSchedule) {
2907     resetSchedule();
2908     initialFillReadyList(ReadyInsts);
2909   }
2910 
2911   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2912                << BB->getName() << "\n");
2913 
2914   calculateDependencies(Bundle, true, SLP);
2915 
2916   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2917   // means that there are no cyclic dependencies and we can schedule it.
2918   // Note that's important that we don't "schedule" the bundle yet (see
2919   // cancelScheduling).
2920   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2921 
2922     ScheduleData *pickedSD = ReadyInsts.back();
2923     ReadyInsts.pop_back();
2924 
2925     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2926       schedule(pickedSD, ReadyInsts);
2927     }
2928   }
2929   if (!Bundle->isReady()) {
2930     cancelScheduling(VL);
2931     return false;
2932   }
2933   return true;
2934 }
2935 
2936 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2937   if (isa<PHINode>(VL[0]))
2938     return;
2939 
2940   ScheduleData *Bundle = getScheduleData(VL[0]);
2941   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2942   assert(!Bundle->IsScheduled &&
2943          "Can't cancel bundle which is already scheduled");
2944   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2945          "tried to unbundle something which is not a bundle");
2946 
2947   // Un-bundle: make single instructions out of the bundle.
2948   ScheduleData *BundleMember = Bundle;
2949   while (BundleMember) {
2950     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2951     BundleMember->FirstInBundle = BundleMember;
2952     ScheduleData *Next = BundleMember->NextInBundle;
2953     BundleMember->NextInBundle = nullptr;
2954     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2955     if (BundleMember->UnscheduledDepsInBundle == 0) {
2956       ReadyInsts.insert(BundleMember);
2957     }
2958     BundleMember = Next;
2959   }
2960 }
2961 
2962 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2963   if (getScheduleData(V))
2964     return true;
2965   Instruction *I = dyn_cast<Instruction>(V);
2966   assert(I && "bundle member must be an instruction");
2967   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2968   if (!ScheduleStart) {
2969     // It's the first instruction in the new region.
2970     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2971     ScheduleStart = I;
2972     ScheduleEnd = I->getNextNode();
2973     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2974     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2975     return true;
2976   }
2977   // Search up and down at the same time, because we don't know if the new
2978   // instruction is above or below the existing scheduling region.
2979   BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
2980   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2981   BasicBlock::iterator DownIter(ScheduleEnd);
2982   BasicBlock::iterator LowerEnd = BB->end();
2983   for (;;) {
2984     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
2985       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
2986       return false;
2987     }
2988 
2989     if (UpIter != UpperEnd) {
2990       if (&*UpIter == I) {
2991         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2992         ScheduleStart = I;
2993         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2994         return true;
2995       }
2996       UpIter++;
2997     }
2998     if (DownIter != LowerEnd) {
2999       if (&*DownIter == I) {
3000         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3001                          nullptr);
3002         ScheduleEnd = I->getNextNode();
3003         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3004         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
3005         return true;
3006       }
3007       DownIter++;
3008     }
3009     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3010            "instruction not found in block");
3011   }
3012   return true;
3013 }
3014 
3015 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3016                                                 Instruction *ToI,
3017                                                 ScheduleData *PrevLoadStore,
3018                                                 ScheduleData *NextLoadStore) {
3019   ScheduleData *CurrentLoadStore = PrevLoadStore;
3020   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3021     ScheduleData *SD = ScheduleDataMap[I];
3022     if (!SD) {
3023       // Allocate a new ScheduleData for the instruction.
3024       if (ChunkPos >= ChunkSize) {
3025         ScheduleDataChunks.push_back(
3026             llvm::make_unique<ScheduleData[]>(ChunkSize));
3027         ChunkPos = 0;
3028       }
3029       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3030       ScheduleDataMap[I] = SD;
3031       SD->Inst = I;
3032     }
3033     assert(!isInSchedulingRegion(SD) &&
3034            "new ScheduleData already in scheduling region");
3035     SD->init(SchedulingRegionID);
3036 
3037     if (I->mayReadOrWriteMemory()) {
3038       // Update the linked list of memory accessing instructions.
3039       if (CurrentLoadStore) {
3040         CurrentLoadStore->NextLoadStore = SD;
3041       } else {
3042         FirstLoadStoreInRegion = SD;
3043       }
3044       CurrentLoadStore = SD;
3045     }
3046   }
3047   if (NextLoadStore) {
3048     if (CurrentLoadStore)
3049       CurrentLoadStore->NextLoadStore = NextLoadStore;
3050   } else {
3051     LastLoadStoreInRegion = CurrentLoadStore;
3052   }
3053 }
3054 
3055 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3056                                                      bool InsertInReadyList,
3057                                                      BoUpSLP *SLP) {
3058   assert(SD->isSchedulingEntity());
3059 
3060   SmallVector<ScheduleData *, 10> WorkList;
3061   WorkList.push_back(SD);
3062 
3063   while (!WorkList.empty()) {
3064     ScheduleData *SD = WorkList.back();
3065     WorkList.pop_back();
3066 
3067     ScheduleData *BundleMember = SD;
3068     while (BundleMember) {
3069       assert(isInSchedulingRegion(BundleMember));
3070       if (!BundleMember->hasValidDependencies()) {
3071 
3072         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
3073         BundleMember->Dependencies = 0;
3074         BundleMember->resetUnscheduledDeps();
3075 
3076         // Handle def-use chain dependencies.
3077         for (User *U : BundleMember->Inst->users()) {
3078           if (isa<Instruction>(U)) {
3079             ScheduleData *UseSD = getScheduleData(U);
3080             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3081               BundleMember->Dependencies++;
3082               ScheduleData *DestBundle = UseSD->FirstInBundle;
3083               if (!DestBundle->IsScheduled) {
3084                 BundleMember->incrementUnscheduledDeps(1);
3085               }
3086               if (!DestBundle->hasValidDependencies()) {
3087                 WorkList.push_back(DestBundle);
3088               }
3089             }
3090           } else {
3091             // I'm not sure if this can ever happen. But we need to be safe.
3092             // This lets the instruction/bundle never be scheduled and
3093             // eventually disable vectorization.
3094             BundleMember->Dependencies++;
3095             BundleMember->incrementUnscheduledDeps(1);
3096           }
3097         }
3098 
3099         // Handle the memory dependencies.
3100         ScheduleData *DepDest = BundleMember->NextLoadStore;
3101         if (DepDest) {
3102           Instruction *SrcInst = BundleMember->Inst;
3103           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3104           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3105           unsigned numAliased = 0;
3106           unsigned DistToSrc = 1;
3107 
3108           while (DepDest) {
3109             assert(isInSchedulingRegion(DepDest));
3110 
3111             // We have two limits to reduce the complexity:
3112             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3113             //    SLP->isAliased (which is the expensive part in this loop).
3114             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3115             //    the whole loop (even if the loop is fast, it's quadratic).
3116             //    It's important for the loop break condition (see below) to
3117             //    check this limit even between two read-only instructions.
3118             if (DistToSrc >= MaxMemDepDistance ||
3119                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3120                      (numAliased >= AliasedCheckLimit ||
3121                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3122 
3123               // We increment the counter only if the locations are aliased
3124               // (instead of counting all alias checks). This gives a better
3125               // balance between reduced runtime and accurate dependencies.
3126               numAliased++;
3127 
3128               DepDest->MemoryDependencies.push_back(BundleMember);
3129               BundleMember->Dependencies++;
3130               ScheduleData *DestBundle = DepDest->FirstInBundle;
3131               if (!DestBundle->IsScheduled) {
3132                 BundleMember->incrementUnscheduledDeps(1);
3133               }
3134               if (!DestBundle->hasValidDependencies()) {
3135                 WorkList.push_back(DestBundle);
3136               }
3137             }
3138             DepDest = DepDest->NextLoadStore;
3139 
3140             // Example, explaining the loop break condition: Let's assume our
3141             // starting instruction is i0 and MaxMemDepDistance = 3.
3142             //
3143             //                      +--------v--v--v
3144             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3145             //             +--------^--^--^
3146             //
3147             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3148             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3149             // Previously we already added dependencies from i3 to i6,i7,i8
3150             // (because of MaxMemDepDistance). As we added a dependency from
3151             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3152             // and we can abort this loop at i6.
3153             if (DistToSrc >= 2 * MaxMemDepDistance)
3154                 break;
3155             DistToSrc++;
3156           }
3157         }
3158       }
3159       BundleMember = BundleMember->NextInBundle;
3160     }
3161     if (InsertInReadyList && SD->isReady()) {
3162       ReadyInsts.push_back(SD);
3163       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3164     }
3165   }
3166 }
3167 
3168 void BoUpSLP::BlockScheduling::resetSchedule() {
3169   assert(ScheduleStart &&
3170          "tried to reset schedule on block which has not been scheduled");
3171   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3172     ScheduleData *SD = getScheduleData(I);
3173     assert(isInSchedulingRegion(SD));
3174     SD->IsScheduled = false;
3175     SD->resetUnscheduledDeps();
3176   }
3177   ReadyInsts.clear();
3178 }
3179 
3180 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3181 
3182   if (!BS->ScheduleStart)
3183     return;
3184 
3185   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3186 
3187   BS->resetSchedule();
3188 
3189   // For the real scheduling we use a more sophisticated ready-list: it is
3190   // sorted by the original instruction location. This lets the final schedule
3191   // be as  close as possible to the original instruction order.
3192   struct ScheduleDataCompare {
3193     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
3194       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3195     }
3196   };
3197   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3198 
3199   // Ensure that all dependency data is updated and fill the ready-list with
3200   // initial instructions.
3201   int Idx = 0;
3202   int NumToSchedule = 0;
3203   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3204        I = I->getNextNode()) {
3205     ScheduleData *SD = BS->getScheduleData(I);
3206     assert(
3207         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3208         "scheduler and vectorizer have different opinion on what is a bundle");
3209     SD->FirstInBundle->SchedulingPriority = Idx++;
3210     if (SD->isSchedulingEntity()) {
3211       BS->calculateDependencies(SD, false, this);
3212       NumToSchedule++;
3213     }
3214   }
3215   BS->initialFillReadyList(ReadyInsts);
3216 
3217   Instruction *LastScheduledInst = BS->ScheduleEnd;
3218 
3219   // Do the "real" scheduling.
3220   while (!ReadyInsts.empty()) {
3221     ScheduleData *picked = *ReadyInsts.begin();
3222     ReadyInsts.erase(ReadyInsts.begin());
3223 
3224     // Move the scheduled instruction(s) to their dedicated places, if not
3225     // there yet.
3226     ScheduleData *BundleMember = picked;
3227     while (BundleMember) {
3228       Instruction *pickedInst = BundleMember->Inst;
3229       if (LastScheduledInst->getNextNode() != pickedInst) {
3230         BS->BB->getInstList().remove(pickedInst);
3231         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3232                                      pickedInst);
3233       }
3234       LastScheduledInst = pickedInst;
3235       BundleMember = BundleMember->NextInBundle;
3236     }
3237 
3238     BS->schedule(picked, ReadyInsts);
3239     NumToSchedule--;
3240   }
3241   assert(NumToSchedule == 0 && "could not schedule all instructions");
3242 
3243   // Avoid duplicate scheduling of the block.
3244   BS->ScheduleStart = nullptr;
3245 }
3246 
3247 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3248   // If V is a store, just return the width of the stored value without
3249   // traversing the expression tree. This is the common case.
3250   if (auto *Store = dyn_cast<StoreInst>(V))
3251     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3252 
3253   // If V is not a store, we can traverse the expression tree to find loads
3254   // that feed it. The type of the loaded value may indicate a more suitable
3255   // width than V's type. We want to base the vector element size on the width
3256   // of memory operations where possible.
3257   SmallVector<Instruction *, 16> Worklist;
3258   SmallPtrSet<Instruction *, 16> Visited;
3259   if (auto *I = dyn_cast<Instruction>(V))
3260     Worklist.push_back(I);
3261 
3262   // Traverse the expression tree in bottom-up order looking for loads. If we
3263   // encounter an instruciton we don't yet handle, we give up.
3264   auto MaxWidth = 0u;
3265   auto FoundUnknownInst = false;
3266   while (!Worklist.empty() && !FoundUnknownInst) {
3267     auto *I = Worklist.pop_back_val();
3268     Visited.insert(I);
3269 
3270     // We should only be looking at scalar instructions here. If the current
3271     // instruction has a vector type, give up.
3272     auto *Ty = I->getType();
3273     if (isa<VectorType>(Ty))
3274       FoundUnknownInst = true;
3275 
3276     // If the current instruction is a load, update MaxWidth to reflect the
3277     // width of the loaded value.
3278     else if (isa<LoadInst>(I))
3279       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3280 
3281     // Otherwise, we need to visit the operands of the instruction. We only
3282     // handle the interesting cases from buildTree here. If an operand is an
3283     // instruction we haven't yet visited, we add it to the worklist.
3284     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3285              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3286       for (Use &U : I->operands())
3287         if (auto *J = dyn_cast<Instruction>(U.get()))
3288           if (!Visited.count(J))
3289             Worklist.push_back(J);
3290     }
3291 
3292     // If we don't yet handle the instruction, give up.
3293     else
3294       FoundUnknownInst = true;
3295   }
3296 
3297   // If we didn't encounter a memory access in the expression tree, or if we
3298   // gave up for some reason, just return the width of V.
3299   if (!MaxWidth || FoundUnknownInst)
3300     return DL->getTypeSizeInBits(V->getType());
3301 
3302   // Otherwise, return the maximum width we found.
3303   return MaxWidth;
3304 }
3305 
3306 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3307 // smaller type with a truncation. We collect the values that will be demoted
3308 // in ToDemote and additional roots that require investigating in Roots.
3309 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3310                                   SmallVectorImpl<Value *> &ToDemote,
3311                                   SmallVectorImpl<Value *> &Roots) {
3312 
3313   // We can always demote constants.
3314   if (isa<Constant>(V)) {
3315     ToDemote.push_back(V);
3316     return true;
3317   }
3318 
3319   // If the value is not an instruction in the expression with only one use, it
3320   // cannot be demoted.
3321   auto *I = dyn_cast<Instruction>(V);
3322   if (!I || !I->hasOneUse() || !Expr.count(I))
3323     return false;
3324 
3325   switch (I->getOpcode()) {
3326 
3327   // We can always demote truncations and extensions. Since truncations can
3328   // seed additional demotion, we save the truncated value.
3329   case Instruction::Trunc:
3330     Roots.push_back(I->getOperand(0));
3331   case Instruction::ZExt:
3332   case Instruction::SExt:
3333     break;
3334 
3335   // We can demote certain binary operations if we can demote both of their
3336   // operands.
3337   case Instruction::Add:
3338   case Instruction::Sub:
3339   case Instruction::Mul:
3340   case Instruction::And:
3341   case Instruction::Or:
3342   case Instruction::Xor:
3343     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3344         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3345       return false;
3346     break;
3347 
3348   // We can demote selects if we can demote their true and false values.
3349   case Instruction::Select: {
3350     SelectInst *SI = cast<SelectInst>(I);
3351     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3352         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3353       return false;
3354     break;
3355   }
3356 
3357   // We can demote phis if we can demote all their incoming operands. Note that
3358   // we don't need to worry about cycles since we ensure single use above.
3359   case Instruction::PHI: {
3360     PHINode *PN = cast<PHINode>(I);
3361     for (Value *IncValue : PN->incoming_values())
3362       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3363         return false;
3364     break;
3365   }
3366 
3367   // Otherwise, conservatively give up.
3368   default:
3369     return false;
3370   }
3371 
3372   // Record the value that we can demote.
3373   ToDemote.push_back(V);
3374   return true;
3375 }
3376 
3377 void BoUpSLP::computeMinimumValueSizes() {
3378   // If there are no external uses, the expression tree must be rooted by a
3379   // store. We can't demote in-memory values, so there is nothing to do here.
3380   if (ExternalUses.empty())
3381     return;
3382 
3383   // We only attempt to truncate integer expressions.
3384   auto &TreeRoot = VectorizableTree[0].Scalars;
3385   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3386   if (!TreeRootIT)
3387     return;
3388 
3389   // If the expression is not rooted by a store, these roots should have
3390   // external uses. We will rely on InstCombine to rewrite the expression in
3391   // the narrower type. However, InstCombine only rewrites single-use values.
3392   // This means that if a tree entry other than a root is used externally, it
3393   // must have multiple uses and InstCombine will not rewrite it. The code
3394   // below ensures that only the roots are used externally.
3395   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3396   for (auto &EU : ExternalUses)
3397     if (!Expr.erase(EU.Scalar))
3398       return;
3399   if (!Expr.empty())
3400     return;
3401 
3402   // Collect the scalar values of the vectorizable expression. We will use this
3403   // context to determine which values can be demoted. If we see a truncation,
3404   // we mark it as seeding another demotion.
3405   for (auto &Entry : VectorizableTree)
3406     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3407 
3408   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3409   // have a single external user that is not in the vectorizable tree.
3410   for (auto *Root : TreeRoot)
3411     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3412       return;
3413 
3414   // Conservatively determine if we can actually truncate the roots of the
3415   // expression. Collect the values that can be demoted in ToDemote and
3416   // additional roots that require investigating in Roots.
3417   SmallVector<Value *, 32> ToDemote;
3418   SmallVector<Value *, 4> Roots;
3419   for (auto *Root : TreeRoot)
3420     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3421       return;
3422 
3423   // The maximum bit width required to represent all the values that can be
3424   // demoted without loss of precision. It would be safe to truncate the roots
3425   // of the expression to this width.
3426   auto MaxBitWidth = 8u;
3427 
3428   // We first check if all the bits of the roots are demanded. If they're not,
3429   // we can truncate the roots to this narrower type.
3430   for (auto *Root : TreeRoot) {
3431     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3432     MaxBitWidth = std::max<unsigned>(
3433         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3434   }
3435 
3436   // If all the bits of the roots are demanded, we can try a little harder to
3437   // compute a narrower type. This can happen, for example, if the roots are
3438   // getelementptr indices. InstCombine promotes these indices to the pointer
3439   // width. Thus, all their bits are technically demanded even though the
3440   // address computation might be vectorized in a smaller type.
3441   //
3442   // We start by looking at each entry that can be demoted. We compute the
3443   // maximum bit width required to store the scalar by using ValueTracking to
3444   // compute the number of high-order bits we can truncate.
3445   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3446     MaxBitWidth = 8u;
3447     for (auto *Scalar : ToDemote) {
3448       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3449       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3450       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3451     }
3452   }
3453 
3454   // Round MaxBitWidth up to the next power-of-two.
3455   if (!isPowerOf2_64(MaxBitWidth))
3456     MaxBitWidth = NextPowerOf2(MaxBitWidth);
3457 
3458   // If the maximum bit width we compute is less than the with of the roots'
3459   // type, we can proceed with the narrowing. Otherwise, do nothing.
3460   if (MaxBitWidth >= TreeRootIT->getBitWidth())
3461     return;
3462 
3463   // If we can truncate the root, we must collect additional values that might
3464   // be demoted as a result. That is, those seeded by truncations we will
3465   // modify.
3466   while (!Roots.empty())
3467     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3468 
3469   // Finally, map the values we can demote to the maximum bit with we computed.
3470   for (auto *Scalar : ToDemote)
3471     MinBWs[Scalar] = MaxBitWidth;
3472 }
3473 
3474 /// The SLPVectorizer Pass.
3475 struct SLPVectorizer : public FunctionPass {
3476   SLPVectorizerPass Impl;
3477 
3478   /// Pass identification, replacement for typeid
3479   static char ID;
3480 
3481   explicit SLPVectorizer() : FunctionPass(ID) {
3482     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3483   }
3484 
3485 
3486   bool doInitialization(Module &M) override {
3487     return false;
3488   }
3489 
3490   bool runOnFunction(Function &F) override {
3491     if (skipFunction(F))
3492       return false;
3493 
3494     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3495     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3496     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3497     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
3498     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3499     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3500     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3501     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3502     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3503 
3504     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3505   }
3506 
3507   void getAnalysisUsage(AnalysisUsage &AU) const override {
3508     FunctionPass::getAnalysisUsage(AU);
3509     AU.addRequired<AssumptionCacheTracker>();
3510     AU.addRequired<ScalarEvolutionWrapperPass>();
3511     AU.addRequired<AAResultsWrapperPass>();
3512     AU.addRequired<TargetTransformInfoWrapperPass>();
3513     AU.addRequired<LoopInfoWrapperPass>();
3514     AU.addRequired<DominatorTreeWrapperPass>();
3515     AU.addRequired<DemandedBitsWrapperPass>();
3516     AU.addPreserved<LoopInfoWrapperPass>();
3517     AU.addPreserved<DominatorTreeWrapperPass>();
3518     AU.addPreserved<AAResultsWrapperPass>();
3519     AU.addPreserved<GlobalsAAWrapperPass>();
3520     AU.setPreservesCFG();
3521   }
3522 };
3523 
3524 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
3525   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
3526   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
3527   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
3528   auto *AA = &AM.getResult<AAManager>(F);
3529   auto *LI = &AM.getResult<LoopAnalysis>(F);
3530   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
3531   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
3532   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
3533 
3534   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3535   if (!Changed)
3536     return PreservedAnalyses::all();
3537   PreservedAnalyses PA;
3538   PA.preserve<LoopAnalysis>();
3539   PA.preserve<DominatorTreeAnalysis>();
3540   PA.preserve<AAManager>();
3541   PA.preserve<GlobalsAA>();
3542   return PA;
3543 }
3544 
3545 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
3546                                 TargetTransformInfo *TTI_,
3547                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
3548                                 LoopInfo *LI_, DominatorTree *DT_,
3549                                 AssumptionCache *AC_, DemandedBits *DB_) {
3550   SE = SE_;
3551   TTI = TTI_;
3552   TLI = TLI_;
3553   AA = AA_;
3554   LI = LI_;
3555   DT = DT_;
3556   AC = AC_;
3557   DB = DB_;
3558   DL = &F.getParent()->getDataLayout();
3559 
3560   Stores.clear();
3561   GEPs.clear();
3562   bool Changed = false;
3563 
3564   // If the target claims to have no vector registers don't attempt
3565   // vectorization.
3566   if (!TTI->getNumberOfRegisters(true))
3567     return false;
3568 
3569   // Don't vectorize when the attribute NoImplicitFloat is used.
3570   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3571     return false;
3572 
3573   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3574 
3575   // Use the bottom up slp vectorizer to construct chains that start with
3576   // store instructions.
3577   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
3578 
3579   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3580   // delete instructions.
3581 
3582   // Scan the blocks in the function in post order.
3583   for (auto BB : post_order(&F.getEntryBlock())) {
3584     collectSeedInstructions(BB);
3585 
3586     // Vectorize trees that end at stores.
3587     if (!Stores.empty()) {
3588       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3589                    << " underlying objects.\n");
3590       Changed |= vectorizeStoreChains(R);
3591     }
3592 
3593     // Vectorize trees that end at reductions.
3594     Changed |= vectorizeChainsInBlock(BB, R);
3595 
3596     // Vectorize the index computations of getelementptr instructions. This
3597     // is primarily intended to catch gather-like idioms ending at
3598     // non-consecutive loads.
3599     if (!GEPs.empty()) {
3600       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3601                    << " underlying objects.\n");
3602       Changed |= vectorizeGEPIndices(BB, R);
3603     }
3604   }
3605 
3606   if (Changed) {
3607     R.optimizeGatherSequence();
3608     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3609     DEBUG(verifyFunction(F));
3610   }
3611   return Changed;
3612 }
3613 
3614 /// \brief Check that the Values in the slice in VL array are still existent in
3615 /// the WeakVH array.
3616 /// Vectorization of part of the VL array may cause later values in the VL array
3617 /// to become invalid. We track when this has happened in the WeakVH array.
3618 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
3619                                unsigned SliceBegin, unsigned SliceSize) {
3620   VL = VL.slice(SliceBegin, SliceSize);
3621   VH = VH.slice(SliceBegin, SliceSize);
3622   return !std::equal(VL.begin(), VL.end(), VH.begin());
3623 }
3624 
3625 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain,
3626                                             int CostThreshold, BoUpSLP &R,
3627                                             unsigned VecRegSize) {
3628   unsigned ChainLen = Chain.size();
3629   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3630         << "\n");
3631   unsigned Sz = R.getVectorElementSize(Chain[0]);
3632   unsigned VF = VecRegSize / Sz;
3633 
3634   if (!isPowerOf2_32(Sz) || VF < 2)
3635     return false;
3636 
3637   // Keep track of values that were deleted by vectorizing in the loop below.
3638   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3639 
3640   bool Changed = false;
3641   // Look for profitable vectorizable trees at all offsets, starting at zero.
3642   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3643     if (i + VF > e)
3644       break;
3645 
3646     // Check that a previous iteration of this loop did not delete the Value.
3647     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3648       continue;
3649 
3650     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3651           << "\n");
3652     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3653 
3654     R.buildTree(Operands);
3655     R.computeMinimumValueSizes();
3656 
3657     int Cost = R.getTreeCost();
3658 
3659     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3660     if (Cost < CostThreshold) {
3661       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3662       R.vectorizeTree();
3663 
3664       // Move to the next bundle.
3665       i += VF - 1;
3666       Changed = true;
3667     }
3668   }
3669 
3670   return Changed;
3671 }
3672 
3673 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3674                                         int costThreshold, BoUpSLP &R) {
3675   SetVector<StoreInst *> Heads, Tails;
3676   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3677 
3678   // We may run into multiple chains that merge into a single chain. We mark the
3679   // stores that we vectorized so that we don't visit the same store twice.
3680   BoUpSLP::ValueSet VectorizedStores;
3681   bool Changed = false;
3682 
3683   // Do a quadratic search on all of the given stores and find
3684   // all of the pairs of stores that follow each other.
3685   SmallVector<unsigned, 16> IndexQueue;
3686   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3687     IndexQueue.clear();
3688     // If a store has multiple consecutive store candidates, search Stores
3689     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3690     // This is because usually pairing with immediate succeeding or preceding
3691     // candidate create the best chance to find slp vectorization opportunity.
3692     unsigned j = 0;
3693     for (j = i + 1; j < e; ++j)
3694       IndexQueue.push_back(j);
3695     for (j = i; j > 0; --j)
3696       IndexQueue.push_back(j - 1);
3697 
3698     for (auto &k : IndexQueue) {
3699       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3700         Tails.insert(Stores[k]);
3701         Heads.insert(Stores[i]);
3702         ConsecutiveChain[Stores[i]] = Stores[k];
3703         break;
3704       }
3705     }
3706   }
3707 
3708   // For stores that start but don't end a link in the chain:
3709   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3710        it != e; ++it) {
3711     if (Tails.count(*it))
3712       continue;
3713 
3714     // We found a store instr that starts a chain. Now follow the chain and try
3715     // to vectorize it.
3716     BoUpSLP::ValueList Operands;
3717     StoreInst *I = *it;
3718     // Collect the chain into a list.
3719     while (Tails.count(I) || Heads.count(I)) {
3720       if (VectorizedStores.count(I))
3721         break;
3722       Operands.push_back(I);
3723       // Move to the next value in the chain.
3724       I = ConsecutiveChain[I];
3725     }
3726 
3727     // FIXME: Is division-by-2 the correct step? Should we assert that the
3728     // register size is a power-of-2?
3729     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize(); Size /= 2) {
3730       if (vectorizeStoreChain(Operands, costThreshold, R, Size)) {
3731         // Mark the vectorized stores so that we don't vectorize them again.
3732         VectorizedStores.insert(Operands.begin(), Operands.end());
3733         Changed = true;
3734         break;
3735       }
3736     }
3737   }
3738 
3739   return Changed;
3740 }
3741 
3742 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
3743 
3744   // Initialize the collections. We will make a single pass over the block.
3745   Stores.clear();
3746   GEPs.clear();
3747 
3748   // Visit the store and getelementptr instructions in BB and organize them in
3749   // Stores and GEPs according to the underlying objects of their pointer
3750   // operands.
3751   for (Instruction &I : *BB) {
3752 
3753     // Ignore store instructions that are volatile or have a pointer operand
3754     // that doesn't point to a scalar type.
3755     if (auto *SI = dyn_cast<StoreInst>(&I)) {
3756       if (!SI->isSimple())
3757         continue;
3758       if (!isValidElementType(SI->getValueOperand()->getType()))
3759         continue;
3760       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
3761     }
3762 
3763     // Ignore getelementptr instructions that have more than one index, a
3764     // constant index, or a pointer operand that doesn't point to a scalar
3765     // type.
3766     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3767       auto Idx = GEP->idx_begin()->get();
3768       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
3769         continue;
3770       if (!isValidElementType(Idx->getType()))
3771         continue;
3772       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
3773     }
3774   }
3775 }
3776 
3777 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3778   if (!A || !B)
3779     return false;
3780   Value *VL[] = { A, B };
3781   return tryToVectorizeList(VL, R, None, true);
3782 }
3783 
3784 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3785                                            ArrayRef<Value *> BuildVector,
3786                                            bool allowReorder) {
3787   if (VL.size() < 2)
3788     return false;
3789 
3790   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3791 
3792   // Check that all of the parts are scalar instructions of the same type.
3793   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3794   if (!I0)
3795     return false;
3796 
3797   unsigned Opcode0 = I0->getOpcode();
3798 
3799   // FIXME: Register size should be a parameter to this function, so we can
3800   // try different vectorization factors.
3801   unsigned Sz = R.getVectorElementSize(I0);
3802   unsigned VF = R.getMinVecRegSize() / Sz;
3803 
3804   for (Value *V : VL) {
3805     Type *Ty = V->getType();
3806     if (!isValidElementType(Ty))
3807       return false;
3808     Instruction *Inst = dyn_cast<Instruction>(V);
3809     if (!Inst || Inst->getOpcode() != Opcode0)
3810       return false;
3811   }
3812 
3813   bool Changed = false;
3814 
3815   // Keep track of values that were deleted by vectorizing in the loop below.
3816   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3817 
3818   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3819     unsigned OpsWidth = 0;
3820 
3821     if (i + VF > e)
3822       OpsWidth = e - i;
3823     else
3824       OpsWidth = VF;
3825 
3826     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3827       break;
3828 
3829     // Check that a previous iteration of this loop did not delete the Value.
3830     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3831       continue;
3832 
3833     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3834                  << "\n");
3835     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3836 
3837     ArrayRef<Value *> BuildVectorSlice;
3838     if (!BuildVector.empty())
3839       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3840 
3841     R.buildTree(Ops, BuildVectorSlice);
3842     // TODO: check if we can allow reordering also for other cases than
3843     // tryToVectorizePair()
3844     if (allowReorder && R.shouldReorder()) {
3845       assert(Ops.size() == 2);
3846       assert(BuildVectorSlice.empty());
3847       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3848       R.buildTree(ReorderedOps, None);
3849     }
3850     R.computeMinimumValueSizes();
3851     int Cost = R.getTreeCost();
3852 
3853     if (Cost < -SLPCostThreshold) {
3854       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3855       Value *VectorizedRoot = R.vectorizeTree();
3856 
3857       // Reconstruct the build vector by extracting the vectorized root. This
3858       // way we handle the case where some elements of the vector are undefined.
3859       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3860       if (!BuildVectorSlice.empty()) {
3861         // The insert point is the last build vector instruction. The vectorized
3862         // root will precede it. This guarantees that we get an instruction. The
3863         // vectorized tree could have been constant folded.
3864         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3865         unsigned VecIdx = 0;
3866         for (auto &V : BuildVectorSlice) {
3867           IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
3868                                       ++BasicBlock::iterator(InsertAfter));
3869           Instruction *I = cast<Instruction>(V);
3870           assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
3871           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3872               VectorizedRoot, Builder.getInt32(VecIdx++)));
3873           I->setOperand(1, Extract);
3874           I->removeFromParent();
3875           I->insertAfter(Extract);
3876           InsertAfter = I;
3877         }
3878       }
3879       // Move to the next bundle.
3880       i += VF - 1;
3881       Changed = true;
3882     }
3883   }
3884 
3885   return Changed;
3886 }
3887 
3888 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3889   if (!V)
3890     return false;
3891 
3892   // Try to vectorize V.
3893   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3894     return true;
3895 
3896   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3897   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3898   // Try to skip B.
3899   if (B && B->hasOneUse()) {
3900     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3901     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3902     if (tryToVectorizePair(A, B0, R)) {
3903       return true;
3904     }
3905     if (tryToVectorizePair(A, B1, R)) {
3906       return true;
3907     }
3908   }
3909 
3910   // Try to skip A.
3911   if (A && A->hasOneUse()) {
3912     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3913     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3914     if (tryToVectorizePair(A0, B, R)) {
3915       return true;
3916     }
3917     if (tryToVectorizePair(A1, B, R)) {
3918       return true;
3919     }
3920   }
3921   return 0;
3922 }
3923 
3924 /// \brief Generate a shuffle mask to be used in a reduction tree.
3925 ///
3926 /// \param VecLen The length of the vector to be reduced.
3927 /// \param NumEltsToRdx The number of elements that should be reduced in the
3928 ///        vector.
3929 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3930 ///        reduction. A pairwise reduction will generate a mask of
3931 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
3932 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3933 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3934 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3935                                    bool IsPairwise, bool IsLeft,
3936                                    IRBuilder<> &Builder) {
3937   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3938 
3939   SmallVector<Constant *, 32> ShuffleMask(
3940       VecLen, UndefValue::get(Builder.getInt32Ty()));
3941 
3942   if (IsPairwise)
3943     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3944     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3945       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3946   else
3947     // Move the upper half of the vector to the lower half.
3948     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3949       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3950 
3951   return ConstantVector::get(ShuffleMask);
3952 }
3953 
3954 
3955 /// Model horizontal reductions.
3956 ///
3957 /// A horizontal reduction is a tree of reduction operations (currently add and
3958 /// fadd) that has operations that can be put into a vector as its leaf.
3959 /// For example, this tree:
3960 ///
3961 /// mul mul mul mul
3962 ///  \  /    \  /
3963 ///   +       +
3964 ///    \     /
3965 ///       +
3966 /// This tree has "mul" as its reduced values and "+" as its reduction
3967 /// operations. A reduction might be feeding into a store or a binary operation
3968 /// feeding a phi.
3969 ///    ...
3970 ///    \  /
3971 ///     +
3972 ///     |
3973 ///  phi +=
3974 ///
3975 ///  Or:
3976 ///    ...
3977 ///    \  /
3978 ///     +
3979 ///     |
3980 ///   *p =
3981 ///
3982 class HorizontalReduction {
3983   SmallVector<Value *, 16> ReductionOps;
3984   SmallVector<Value *, 32> ReducedVals;
3985 
3986   BinaryOperator *ReductionRoot;
3987   PHINode *ReductionPHI;
3988 
3989   /// The opcode of the reduction.
3990   unsigned ReductionOpcode;
3991   /// The opcode of the values we perform a reduction on.
3992   unsigned ReducedValueOpcode;
3993   /// Should we model this reduction as a pairwise reduction tree or a tree that
3994   /// splits the vector in halves and adds those halves.
3995   bool IsPairwiseReduction;
3996 
3997 public:
3998   /// The width of one full horizontal reduction operation.
3999   unsigned ReduxWidth;
4000 
4001   /// Minimal width of available vector registers. It's used to determine
4002   /// ReduxWidth.
4003   unsigned MinVecRegSize;
4004 
4005   HorizontalReduction(unsigned MinVecRegSize)
4006       : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
4007         ReducedValueOpcode(0), IsPairwiseReduction(false), ReduxWidth(0),
4008         MinVecRegSize(MinVecRegSize) {}
4009 
4010   /// \brief Try to find a reduction tree.
4011   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4012     assert((!Phi ||
4013             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
4014            "Thi phi needs to use the binary operator");
4015 
4016     // We could have a initial reductions that is not an add.
4017     //  r *= v1 + v2 + v3 + v4
4018     // In such a case start looking for a tree rooted in the first '+'.
4019     if (Phi) {
4020       if (B->getOperand(0) == Phi) {
4021         Phi = nullptr;
4022         B = dyn_cast<BinaryOperator>(B->getOperand(1));
4023       } else if (B->getOperand(1) == Phi) {
4024         Phi = nullptr;
4025         B = dyn_cast<BinaryOperator>(B->getOperand(0));
4026       }
4027     }
4028 
4029     if (!B)
4030       return false;
4031 
4032     Type *Ty = B->getType();
4033     if (!isValidElementType(Ty))
4034       return false;
4035 
4036     const DataLayout &DL = B->getModule()->getDataLayout();
4037     ReductionOpcode = B->getOpcode();
4038     ReducedValueOpcode = 0;
4039     // FIXME: Register size should be a parameter to this function, so we can
4040     // try different vectorization factors.
4041     ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
4042     ReductionRoot = B;
4043     ReductionPHI = Phi;
4044 
4045     if (ReduxWidth < 4)
4046       return false;
4047 
4048     // We currently only support adds.
4049     if (ReductionOpcode != Instruction::Add &&
4050         ReductionOpcode != Instruction::FAdd)
4051       return false;
4052 
4053     // Post order traverse the reduction tree starting at B. We only handle true
4054     // trees containing only binary operators or selects.
4055     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4056     Stack.push_back(std::make_pair(B, 0));
4057     while (!Stack.empty()) {
4058       Instruction *TreeN = Stack.back().first;
4059       unsigned EdgeToVist = Stack.back().second++;
4060       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4061 
4062       // Only handle trees in the current basic block.
4063       if (TreeN->getParent() != B->getParent())
4064         return false;
4065 
4066       // Each tree node needs to have one user except for the ultimate
4067       // reduction.
4068       if (!TreeN->hasOneUse() && TreeN != B)
4069         return false;
4070 
4071       // Postorder vist.
4072       if (EdgeToVist == 2 || IsReducedValue) {
4073         if (IsReducedValue) {
4074           // Make sure that the opcodes of the operations that we are going to
4075           // reduce match.
4076           if (!ReducedValueOpcode)
4077             ReducedValueOpcode = TreeN->getOpcode();
4078           else if (ReducedValueOpcode != TreeN->getOpcode())
4079             return false;
4080           ReducedVals.push_back(TreeN);
4081         } else {
4082           // We need to be able to reassociate the adds.
4083           if (!TreeN->isAssociative())
4084             return false;
4085           ReductionOps.push_back(TreeN);
4086         }
4087         // Retract.
4088         Stack.pop_back();
4089         continue;
4090       }
4091 
4092       // Visit left or right.
4093       Value *NextV = TreeN->getOperand(EdgeToVist);
4094       // We currently only allow BinaryOperator's and SelectInst's as reduction
4095       // values in our tree.
4096       if (isa<BinaryOperator>(NextV) || isa<SelectInst>(NextV))
4097         Stack.push_back(std::make_pair(cast<Instruction>(NextV), 0));
4098       else if (NextV != Phi)
4099         return false;
4100     }
4101     return true;
4102   }
4103 
4104   /// \brief Attempt to vectorize the tree found by
4105   /// matchAssociativeReduction.
4106   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4107     if (ReducedVals.empty())
4108       return false;
4109 
4110     unsigned NumReducedVals = ReducedVals.size();
4111     if (NumReducedVals < ReduxWidth)
4112       return false;
4113 
4114     Value *VectorizedTree = nullptr;
4115     IRBuilder<> Builder(ReductionRoot);
4116     FastMathFlags Unsafe;
4117     Unsafe.setUnsafeAlgebra();
4118     Builder.setFastMathFlags(Unsafe);
4119     unsigned i = 0;
4120 
4121     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
4122       V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
4123       V.computeMinimumValueSizes();
4124 
4125       // Estimate cost.
4126       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
4127       if (Cost >= -SLPCostThreshold)
4128         break;
4129 
4130       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4131                    << ". (HorRdx)\n");
4132 
4133       // Vectorize a tree.
4134       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4135       Value *VectorizedRoot = V.vectorizeTree();
4136 
4137       // Emit a reduction.
4138       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
4139       if (VectorizedTree) {
4140         Builder.SetCurrentDebugLocation(Loc);
4141         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4142                                      ReducedSubTree, "bin.rdx");
4143       } else
4144         VectorizedTree = ReducedSubTree;
4145     }
4146 
4147     if (VectorizedTree) {
4148       // Finish the reduction.
4149       for (; i < NumReducedVals; ++i) {
4150         Builder.SetCurrentDebugLocation(
4151           cast<Instruction>(ReducedVals[i])->getDebugLoc());
4152         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4153                                      ReducedVals[i]);
4154       }
4155       // Update users.
4156       if (ReductionPHI) {
4157         assert(ReductionRoot && "Need a reduction operation");
4158         ReductionRoot->setOperand(0, VectorizedTree);
4159         ReductionRoot->setOperand(1, ReductionPHI);
4160       } else
4161         ReductionRoot->replaceAllUsesWith(VectorizedTree);
4162     }
4163     return VectorizedTree != nullptr;
4164   }
4165 
4166   unsigned numReductionValues() const {
4167     return ReducedVals.size();
4168   }
4169 
4170 private:
4171   /// \brief Calculate the cost of a reduction.
4172   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
4173     Type *ScalarTy = FirstReducedVal->getType();
4174     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4175 
4176     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4177     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4178 
4179     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4180     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4181 
4182     int ScalarReduxCost =
4183         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
4184 
4185     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4186                  << " for reduction that starts with " << *FirstReducedVal
4187                  << " (It is a "
4188                  << (IsPairwiseReduction ? "pairwise" : "splitting")
4189                  << " reduction)\n");
4190 
4191     return VecReduxCost - ScalarReduxCost;
4192   }
4193 
4194   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
4195                             Value *R, const Twine &Name = "") {
4196     if (Opcode == Instruction::FAdd)
4197       return Builder.CreateFAdd(L, R, Name);
4198     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
4199   }
4200 
4201   /// \brief Emit a horizontal reduction of the vectorized value.
4202   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
4203     assert(VectorizedValue && "Need to have a vectorized tree node");
4204     assert(isPowerOf2_32(ReduxWidth) &&
4205            "We only handle power-of-two reductions for now");
4206 
4207     Value *TmpVec = VectorizedValue;
4208     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4209       if (IsPairwiseReduction) {
4210         Value *LeftMask =
4211           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4212         Value *RightMask =
4213           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4214 
4215         Value *LeftShuf = Builder.CreateShuffleVector(
4216           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4217         Value *RightShuf = Builder.CreateShuffleVector(
4218           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4219           "rdx.shuf.r");
4220         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
4221                              "bin.rdx");
4222       } else {
4223         Value *UpperHalf =
4224           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
4225         Value *Shuf = Builder.CreateShuffleVector(
4226           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
4227         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
4228       }
4229     }
4230 
4231     // The result is in the first element of the vector.
4232     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4233   }
4234 };
4235 
4236 /// \brief Recognize construction of vectors like
4237 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
4238 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
4239 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
4240 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
4241 ///
4242 /// Returns true if it matches
4243 ///
4244 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4245                             SmallVectorImpl<Value *> &BuildVector,
4246                             SmallVectorImpl<Value *> &BuildVectorOpds) {
4247   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4248     return false;
4249 
4250   InsertElementInst *IE = FirstInsertElem;
4251   while (true) {
4252     BuildVector.push_back(IE);
4253     BuildVectorOpds.push_back(IE->getOperand(1));
4254 
4255     if (IE->use_empty())
4256       return false;
4257 
4258     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4259     if (!NextUse)
4260       return true;
4261 
4262     // If this isn't the final use, make sure the next insertelement is the only
4263     // use. It's OK if the final constructed vector is used multiple times
4264     if (!IE->hasOneUse())
4265       return false;
4266 
4267     IE = NextUse;
4268   }
4269 
4270   return false;
4271 }
4272 
4273 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4274 ///
4275 /// \return true if it matches.
4276 static bool findBuildAggregate(InsertValueInst *IV,
4277                                SmallVectorImpl<Value *> &BuildVector,
4278                                SmallVectorImpl<Value *> &BuildVectorOpds) {
4279   if (!IV->hasOneUse())
4280     return false;
4281   Value *V = IV->getAggregateOperand();
4282   if (!isa<UndefValue>(V)) {
4283     InsertValueInst *I = dyn_cast<InsertValueInst>(V);
4284     if (!I || !findBuildAggregate(I, BuildVector, BuildVectorOpds))
4285       return false;
4286   }
4287   BuildVector.push_back(IV);
4288   BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4289   return true;
4290 }
4291 
4292 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4293   return V->getType() < V2->getType();
4294 }
4295 
4296 /// \brief Try and get a reduction value from a phi node.
4297 ///
4298 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4299 /// if they come from either \p ParentBB or a containing loop latch.
4300 ///
4301 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4302 /// if not possible.
4303 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4304                                 BasicBlock *ParentBB, LoopInfo *LI) {
4305   // There are situations where the reduction value is not dominated by the
4306   // reduction phi. Vectorizing such cases has been reported to cause
4307   // miscompiles. See PR25787.
4308   auto DominatedReduxValue = [&](Value *R) {
4309     return (
4310         dyn_cast<Instruction>(R) &&
4311         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4312   };
4313 
4314   Value *Rdx = nullptr;
4315 
4316   // Return the incoming value if it comes from the same BB as the phi node.
4317   if (P->getIncomingBlock(0) == ParentBB) {
4318     Rdx = P->getIncomingValue(0);
4319   } else if (P->getIncomingBlock(1) == ParentBB) {
4320     Rdx = P->getIncomingValue(1);
4321   }
4322 
4323   if (Rdx && DominatedReduxValue(Rdx))
4324     return Rdx;
4325 
4326   // Otherwise, check whether we have a loop latch to look at.
4327   Loop *BBL = LI->getLoopFor(ParentBB);
4328   if (!BBL)
4329     return nullptr;
4330   BasicBlock *BBLatch = BBL->getLoopLatch();
4331   if (!BBLatch)
4332     return nullptr;
4333 
4334   // There is a loop latch, return the incoming value if it comes from
4335   // that. This reduction pattern occassionaly turns up.
4336   if (P->getIncomingBlock(0) == BBLatch) {
4337     Rdx = P->getIncomingValue(0);
4338   } else if (P->getIncomingBlock(1) == BBLatch) {
4339     Rdx = P->getIncomingValue(1);
4340   }
4341 
4342   if (Rdx && DominatedReduxValue(Rdx))
4343     return Rdx;
4344 
4345   return nullptr;
4346 }
4347 
4348 /// \brief Attempt to reduce a horizontal reduction.
4349 /// If it is legal to match a horizontal reduction feeding
4350 /// the phi node P with reduction operators BI, then check if it
4351 /// can be done.
4352 /// \returns true if a horizontal reduction was matched and reduced.
4353 /// \returns false if a horizontal reduction was not matched.
4354 static bool canMatchHorizontalReduction(PHINode *P, BinaryOperator *BI,
4355                                         BoUpSLP &R, TargetTransformInfo *TTI,
4356                                         unsigned MinRegSize) {
4357   if (!ShouldVectorizeHor)
4358     return false;
4359 
4360   HorizontalReduction HorRdx(MinRegSize);
4361   if (!HorRdx.matchAssociativeReduction(P, BI))
4362     return false;
4363 
4364   // If there is a sufficient number of reduction values, reduce
4365   // to a nearby power-of-2. Can safely generate oversized
4366   // vectors and rely on the backend to split them to legal sizes.
4367   HorRdx.ReduxWidth =
4368     std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
4369 
4370   return HorRdx.tryToReduce(R, TTI);
4371 }
4372 
4373 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4374   bool Changed = false;
4375   SmallVector<Value *, 4> Incoming;
4376   SmallSet<Value *, 16> VisitedInstrs;
4377 
4378   bool HaveVectorizedPhiNodes = true;
4379   while (HaveVectorizedPhiNodes) {
4380     HaveVectorizedPhiNodes = false;
4381 
4382     // Collect the incoming values from the PHIs.
4383     Incoming.clear();
4384     for (Instruction &I : *BB) {
4385       PHINode *P = dyn_cast<PHINode>(&I);
4386       if (!P)
4387         break;
4388 
4389       if (!VisitedInstrs.count(P))
4390         Incoming.push_back(P);
4391     }
4392 
4393     // Sort by type.
4394     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4395 
4396     // Try to vectorize elements base on their type.
4397     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4398                                            E = Incoming.end();
4399          IncIt != E;) {
4400 
4401       // Look for the next elements with the same type.
4402       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4403       while (SameTypeIt != E &&
4404              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4405         VisitedInstrs.insert(*SameTypeIt);
4406         ++SameTypeIt;
4407       }
4408 
4409       // Try to vectorize them.
4410       unsigned NumElts = (SameTypeIt - IncIt);
4411       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4412       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
4413         // Success start over because instructions might have been changed.
4414         HaveVectorizedPhiNodes = true;
4415         Changed = true;
4416         break;
4417       }
4418 
4419       // Start over at the next instruction of a different type (or the end).
4420       IncIt = SameTypeIt;
4421     }
4422   }
4423 
4424   VisitedInstrs.clear();
4425 
4426   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4427     // We may go through BB multiple times so skip the one we have checked.
4428     if (!VisitedInstrs.insert(&*it).second)
4429       continue;
4430 
4431     if (isa<DbgInfoIntrinsic>(it))
4432       continue;
4433 
4434     // Try to vectorize reductions that use PHINodes.
4435     if (PHINode *P = dyn_cast<PHINode>(it)) {
4436       // Check that the PHI is a reduction PHI.
4437       if (P->getNumIncomingValues() != 2)
4438         return Changed;
4439 
4440       Value *Rdx = getReductionValue(DT, P, BB, LI);
4441 
4442       // Check if this is a Binary Operator.
4443       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
4444       if (!BI)
4445         continue;
4446 
4447       // Try to match and vectorize a horizontal reduction.
4448       if (canMatchHorizontalReduction(P, BI, R, TTI, R.getMinVecRegSize())) {
4449         Changed = true;
4450         it = BB->begin();
4451         e = BB->end();
4452         continue;
4453       }
4454 
4455      Value *Inst = BI->getOperand(0);
4456       if (Inst == P)
4457         Inst = BI->getOperand(1);
4458 
4459       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4460         // We would like to start over since some instructions are deleted
4461         // and the iterator may become invalid value.
4462         Changed = true;
4463         it = BB->begin();
4464         e = BB->end();
4465         continue;
4466       }
4467 
4468       continue;
4469     }
4470 
4471     if (ShouldStartVectorizeHorAtStore)
4472       if (StoreInst *SI = dyn_cast<StoreInst>(it))
4473         if (BinaryOperator *BinOp =
4474                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
4475           if (canMatchHorizontalReduction(nullptr, BinOp, R, TTI,
4476                                           R.getMinVecRegSize()) ||
4477               tryToVectorize(BinOp, R)) {
4478             Changed = true;
4479             it = BB->begin();
4480             e = BB->end();
4481             continue;
4482           }
4483         }
4484 
4485     // Try to vectorize horizontal reductions feeding into a return.
4486     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
4487       if (RI->getNumOperands() != 0)
4488         if (BinaryOperator *BinOp =
4489                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
4490           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
4491           if (tryToVectorizePair(BinOp->getOperand(0),
4492                                  BinOp->getOperand(1), R)) {
4493             Changed = true;
4494             it = BB->begin();
4495             e = BB->end();
4496             continue;
4497           }
4498         }
4499 
4500     // Try to vectorize trees that start at compare instructions.
4501     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4502       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4503         Changed = true;
4504         // We would like to start over since some instructions are deleted
4505         // and the iterator may become invalid value.
4506         it = BB->begin();
4507         e = BB->end();
4508         continue;
4509       }
4510 
4511       for (int i = 0; i < 2; ++i) {
4512         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
4513           if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
4514             Changed = true;
4515             // We would like to start over since some instructions are deleted
4516             // and the iterator may become invalid value.
4517             it = BB->begin();
4518             e = BB->end();
4519             break;
4520           }
4521         }
4522       }
4523       continue;
4524     }
4525 
4526     // Try to vectorize trees that start at insertelement instructions.
4527     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4528       SmallVector<Value *, 16> BuildVector;
4529       SmallVector<Value *, 16> BuildVectorOpds;
4530       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4531         continue;
4532 
4533       // Vectorize starting with the build vector operands ignoring the
4534       // BuildVector instructions for the purpose of scheduling and user
4535       // extraction.
4536       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
4537         Changed = true;
4538         it = BB->begin();
4539         e = BB->end();
4540       }
4541 
4542       continue;
4543     }
4544 
4545     // Try to vectorize trees that start at insertvalue instructions feeding into
4546     // a store.
4547     if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4548       if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
4549         const DataLayout &DL = BB->getModule()->getDataLayout();
4550         if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
4551           SmallVector<Value *, 16> BuildVector;
4552           SmallVector<Value *, 16> BuildVectorOpds;
4553           if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
4554             continue;
4555 
4556           DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
4557           if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
4558             Changed = true;
4559             it = BB->begin();
4560             e = BB->end();
4561           }
4562           continue;
4563         }
4564       }
4565     }
4566   }
4567 
4568   return Changed;
4569 }
4570 
4571 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
4572   auto Changed = false;
4573   for (auto &Entry : GEPs) {
4574 
4575     // If the getelementptr list has fewer than two elements, there's nothing
4576     // to do.
4577     if (Entry.second.size() < 2)
4578       continue;
4579 
4580     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
4581                  << Entry.second.size() << ".\n");
4582 
4583     // We process the getelementptr list in chunks of 16 (like we do for
4584     // stores) to minimize compile-time.
4585     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
4586       auto Len = std::min<unsigned>(BE - BI, 16);
4587       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
4588 
4589       // Initialize a set a candidate getelementptrs. Note that we use a
4590       // SetVector here to preserve program order. If the index computations
4591       // are vectorizable and begin with loads, we want to minimize the chance
4592       // of having to reorder them later.
4593       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
4594 
4595       // Some of the candidates may have already been vectorized after we
4596       // initially collected them. If so, the WeakVHs will have nullified the
4597       // values, so remove them from the set of candidates.
4598       Candidates.remove(nullptr);
4599 
4600       // Remove from the set of candidates all pairs of getelementptrs with
4601       // constant differences. Such getelementptrs are likely not good
4602       // candidates for vectorization in a bottom-up phase since one can be
4603       // computed from the other. We also ensure all candidate getelementptr
4604       // indices are unique.
4605       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
4606         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
4607         if (!Candidates.count(GEPI))
4608           continue;
4609         auto *SCEVI = SE->getSCEV(GEPList[I]);
4610         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
4611           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
4612           auto *SCEVJ = SE->getSCEV(GEPList[J]);
4613           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
4614             Candidates.remove(GEPList[I]);
4615             Candidates.remove(GEPList[J]);
4616           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
4617             Candidates.remove(GEPList[J]);
4618           }
4619         }
4620       }
4621 
4622       // We break out of the above computation as soon as we know there are
4623       // fewer than two candidates remaining.
4624       if (Candidates.size() < 2)
4625         continue;
4626 
4627       // Add the single, non-constant index of each candidate to the bundle. We
4628       // ensured the indices met these constraints when we originally collected
4629       // the getelementptrs.
4630       SmallVector<Value *, 16> Bundle(Candidates.size());
4631       auto BundleIndex = 0u;
4632       for (auto *V : Candidates) {
4633         auto *GEP = cast<GetElementPtrInst>(V);
4634         auto *GEPIdx = GEP->idx_begin()->get();
4635         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
4636         Bundle[BundleIndex++] = GEPIdx;
4637       }
4638 
4639       // Try and vectorize the indices. We are currently only interested in
4640       // gather-like cases of the form:
4641       //
4642       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
4643       //
4644       // where the loads of "a", the loads of "b", and the subtractions can be
4645       // performed in parallel. It's likely that detecting this pattern in a
4646       // bottom-up phase will be simpler and less costly than building a
4647       // full-blown top-down phase beginning at the consecutive loads.
4648       Changed |= tryToVectorizeList(Bundle, R);
4649     }
4650   }
4651   return Changed;
4652 }
4653 
4654 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
4655   bool Changed = false;
4656   // Attempt to sort and vectorize each of the store-groups.
4657   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
4658        ++it) {
4659     if (it->second.size() < 2)
4660       continue;
4661 
4662     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
4663           << it->second.size() << ".\n");
4664 
4665     // Process the stores in chunks of 16.
4666     // TODO: The limit of 16 inhibits greater vectorization factors.
4667     //       For example, AVX2 supports v32i8. Increasing this limit, however,
4668     //       may cause a significant compile-time increase.
4669     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
4670       unsigned Len = std::min<unsigned>(CE - CI, 16);
4671       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
4672                                  -SLPCostThreshold, R);
4673     }
4674   }
4675   return Changed;
4676 }
4677 
4678 char SLPVectorizer::ID = 0;
4679 static const char lv_name[] = "SLP Vectorizer";
4680 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
4681 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4682 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4683 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4684 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
4685 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4686 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
4687 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
4688 
4689 namespace llvm {
4690 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
4691 }
4692