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