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