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       int ScalarCallCost = VecTy->getNumElements() *
1663           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1664 
1665       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1666 
1667       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1668             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1669             << " for " << *CI << "\n");
1670 
1671       return VecCallCost - ScalarCallCost;
1672     }
1673     case Instruction::ShuffleVector: {
1674       TargetTransformInfo::OperandValueKind Op1VK =
1675           TargetTransformInfo::OK_AnyValue;
1676       TargetTransformInfo::OperandValueKind Op2VK =
1677           TargetTransformInfo::OK_AnyValue;
1678       int ScalarCost = 0;
1679       int VecCost = 0;
1680       for (unsigned i = 0; i < VL.size(); ++i) {
1681         Instruction *I = cast<Instruction>(VL[i]);
1682         if (!I)
1683           break;
1684         ScalarCost +=
1685             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1686       }
1687       // VecCost is equal to sum of the cost of creating 2 vectors
1688       // and the cost of creating shuffle.
1689       Instruction *I0 = cast<Instruction>(VL[0]);
1690       VecCost =
1691           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1692       Instruction *I1 = cast<Instruction>(VL[1]);
1693       VecCost +=
1694           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1695       VecCost +=
1696           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1697       return VecCost - ScalarCost;
1698     }
1699     default:
1700       llvm_unreachable("Unknown instruction");
1701   }
1702 }
1703 
1704 bool BoUpSLP::isFullyVectorizableTinyTree() {
1705   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1706         VectorizableTree.size() << " is fully vectorizable .\n");
1707 
1708   // We only handle trees of height 2.
1709   if (VectorizableTree.size() != 2)
1710     return false;
1711 
1712   // Handle splat and all-constants stores.
1713   if (!VectorizableTree[0].NeedToGather &&
1714       (allConstant(VectorizableTree[1].Scalars) ||
1715        isSplat(VectorizableTree[1].Scalars)))
1716     return true;
1717 
1718   // Gathering cost would be too much for tiny trees.
1719   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1720     return false;
1721 
1722   return true;
1723 }
1724 
1725 int BoUpSLP::getSpillCost() {
1726   // Walk from the bottom of the tree to the top, tracking which values are
1727   // live. When we see a call instruction that is not part of our tree,
1728   // query TTI to see if there is a cost to keeping values live over it
1729   // (for example, if spills and fills are required).
1730   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1731   int Cost = 0;
1732 
1733   SmallPtrSet<Instruction*, 4> LiveValues;
1734   Instruction *PrevInst = nullptr;
1735 
1736   for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1737     Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1738     if (!Inst)
1739       continue;
1740 
1741     if (!PrevInst) {
1742       PrevInst = Inst;
1743       continue;
1744     }
1745 
1746     // Update LiveValues.
1747     LiveValues.erase(PrevInst);
1748     for (auto &J : PrevInst->operands()) {
1749       if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1750         LiveValues.insert(cast<Instruction>(&*J));
1751     }
1752 
1753     DEBUG(
1754       dbgs() << "SLP: #LV: " << LiveValues.size();
1755       for (auto *X : LiveValues)
1756         dbgs() << " " << X->getName();
1757       dbgs() << ", Looking at ";
1758       Inst->dump();
1759       );
1760 
1761     // Now find the sequence of instructions between PrevInst and Inst.
1762     BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
1763         PrevInstIt(PrevInst->getIterator());
1764     --PrevInstIt;
1765     while (InstIt != PrevInstIt) {
1766       if (PrevInstIt == PrevInst->getParent()->rend()) {
1767         PrevInstIt = Inst->getParent()->rbegin();
1768         continue;
1769       }
1770 
1771       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1772         SmallVector<Type*, 4> V;
1773         for (auto *II : LiveValues)
1774           V.push_back(VectorType::get(II->getType(), BundleWidth));
1775         Cost += TTI->getCostOfKeepingLiveOverCall(V);
1776       }
1777 
1778       ++PrevInstIt;
1779     }
1780 
1781     PrevInst = Inst;
1782   }
1783 
1784   return Cost;
1785 }
1786 
1787 int BoUpSLP::getTreeCost() {
1788   int Cost = 0;
1789   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1790         VectorizableTree.size() << ".\n");
1791 
1792   // We only vectorize tiny trees if it is fully vectorizable.
1793   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1794     if (VectorizableTree.empty()) {
1795       assert(!ExternalUses.size() && "We should not have any external users");
1796     }
1797     return INT_MAX;
1798   }
1799 
1800   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1801 
1802   for (TreeEntry &TE : VectorizableTree) {
1803     int C = getEntryCost(&TE);
1804     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1805                  << *TE.Scalars[0] << ".\n");
1806     Cost += C;
1807   }
1808 
1809   SmallSet<Value *, 16> ExtractCostCalculated;
1810   int ExtractCost = 0;
1811   for (ExternalUser &EU : ExternalUses) {
1812     // We only add extract cost once for the same scalar.
1813     if (!ExtractCostCalculated.insert(EU.Scalar).second)
1814       continue;
1815 
1816     // Uses by ephemeral values are free (because the ephemeral value will be
1817     // removed prior to code generation, and so the extraction will be
1818     // removed as well).
1819     if (EphValues.count(EU.User))
1820       continue;
1821 
1822     // If we plan to rewrite the tree in a smaller type, we will need to sign
1823     // extend the extracted value back to the original type. Here, we account
1824     // for the extract and the added cost of the sign extend if needed.
1825     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
1826     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
1827     if (MinBWs.count(ScalarRoot)) {
1828       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]);
1829       VecTy = VectorType::get(MinTy, BundleWidth);
1830       ExtractCost +=
1831           TTI->getCastInstrCost(Instruction::SExt, EU.Scalar->getType(), MinTy);
1832     }
1833     ExtractCost +=
1834         TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
1835   }
1836 
1837   int SpillCost = getSpillCost();
1838   Cost += SpillCost + ExtractCost;
1839 
1840   DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n"
1841                << "SLP: Extract Cost = " << ExtractCost << ".\n"
1842                << "SLP: Total Cost = " << Cost << ".\n");
1843   return Cost;
1844 }
1845 
1846 int BoUpSLP::getGatherCost(Type *Ty) {
1847   int Cost = 0;
1848   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1849     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1850   return Cost;
1851 }
1852 
1853 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1854   // Find the type of the operands in VL.
1855   Type *ScalarTy = VL[0]->getType();
1856   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1857     ScalarTy = SI->getValueOperand()->getType();
1858   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1859   // Find the cost of inserting/extracting values from the vector.
1860   return getGatherCost(VecTy);
1861 }
1862 
1863 // Reorder commutative operations in alternate shuffle if the resulting vectors
1864 // are consecutive loads. This would allow us to vectorize the tree.
1865 // If we have something like-
1866 // load a[0] - load b[0]
1867 // load b[1] + load a[1]
1868 // load a[2] - load b[2]
1869 // load a[3] + load b[3]
1870 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
1871 // code.
1872 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1873                                         SmallVectorImpl<Value *> &Left,
1874                                         SmallVectorImpl<Value *> &Right) {
1875   // Push left and right operands of binary operation into Left and Right
1876   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1877     Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
1878     Right.push_back(cast<Instruction>(VL[i])->getOperand(1));
1879   }
1880 
1881   // Reorder if we have a commutative operation and consecutive access
1882   // are on either side of the alternate instructions.
1883   for (unsigned j = 0; j < VL.size() - 1; ++j) {
1884     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1885       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1886         Instruction *VL1 = cast<Instruction>(VL[j]);
1887         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1888         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1889           std::swap(Left[j], Right[j]);
1890           continue;
1891         } else if (VL2->isCommutative() &&
1892                    isConsecutiveAccess(L, L1, *DL, *SE)) {
1893           std::swap(Left[j + 1], Right[j + 1]);
1894           continue;
1895         }
1896         // else unchanged
1897       }
1898     }
1899     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1900       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1901         Instruction *VL1 = cast<Instruction>(VL[j]);
1902         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1903         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
1904           std::swap(Left[j], Right[j]);
1905           continue;
1906         } else if (VL2->isCommutative() &&
1907                    isConsecutiveAccess(L, L1, *DL, *SE)) {
1908           std::swap(Left[j + 1], Right[j + 1]);
1909           continue;
1910         }
1911         // else unchanged
1912       }
1913     }
1914   }
1915 }
1916 
1917 // Return true if I should be commuted before adding it's left and right
1918 // operands to the arrays Left and Right.
1919 //
1920 // The vectorizer is trying to either have all elements one side being
1921 // instruction with the same opcode to enable further vectorization, or having
1922 // a splat to lower the vectorizing cost.
1923 static bool shouldReorderOperands(int i, Instruction &I,
1924                                   SmallVectorImpl<Value *> &Left,
1925                                   SmallVectorImpl<Value *> &Right,
1926                                   bool AllSameOpcodeLeft,
1927                                   bool AllSameOpcodeRight, bool SplatLeft,
1928                                   bool SplatRight) {
1929   Value *VLeft = I.getOperand(0);
1930   Value *VRight = I.getOperand(1);
1931   // If we have "SplatRight", try to see if commuting is needed to preserve it.
1932   if (SplatRight) {
1933     if (VRight == Right[i - 1])
1934       // Preserve SplatRight
1935       return false;
1936     if (VLeft == Right[i - 1]) {
1937       // Commuting would preserve SplatRight, but we don't want to break
1938       // SplatLeft either, i.e. preserve the original order if possible.
1939       // (FIXME: why do we care?)
1940       if (SplatLeft && VLeft == Left[i - 1])
1941         return false;
1942       return true;
1943     }
1944   }
1945   // Symmetrically handle Right side.
1946   if (SplatLeft) {
1947     if (VLeft == Left[i - 1])
1948       // Preserve SplatLeft
1949       return false;
1950     if (VRight == Left[i - 1])
1951       return true;
1952   }
1953 
1954   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
1955   Instruction *IRight = dyn_cast<Instruction>(VRight);
1956 
1957   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
1958   // it and not the right, in this case we want to commute.
1959   if (AllSameOpcodeRight) {
1960     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
1961     if (IRight && RightPrevOpcode == IRight->getOpcode())
1962       // Do not commute, a match on the right preserves AllSameOpcodeRight
1963       return false;
1964     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
1965       // We have a match and may want to commute, but first check if there is
1966       // not also a match on the existing operands on the Left to preserve
1967       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
1968       // (FIXME: why do we care?)
1969       if (AllSameOpcodeLeft && ILeft &&
1970           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
1971         return false;
1972       return true;
1973     }
1974   }
1975   // Symmetrically handle Left side.
1976   if (AllSameOpcodeLeft) {
1977     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
1978     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
1979       return false;
1980     if (IRight && LeftPrevOpcode == IRight->getOpcode())
1981       return true;
1982   }
1983   return false;
1984 }
1985 
1986 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1987                                              SmallVectorImpl<Value *> &Left,
1988                                              SmallVectorImpl<Value *> &Right) {
1989 
1990   if (VL.size()) {
1991     // Peel the first iteration out of the loop since there's nothing
1992     // interesting to do anyway and it simplifies the checks in the loop.
1993     auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
1994     auto VRight = cast<Instruction>(VL[0])->getOperand(1);
1995     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
1996       // Favor having instruction to the right. FIXME: why?
1997       std::swap(VLeft, VRight);
1998     Left.push_back(VLeft);
1999     Right.push_back(VRight);
2000   }
2001 
2002   // Keep track if we have instructions with all the same opcode on one side.
2003   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2004   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2005   // Keep track if we have one side with all the same value (broadcast).
2006   bool SplatLeft = true;
2007   bool SplatRight = true;
2008 
2009   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2010     Instruction *I = cast<Instruction>(VL[i]);
2011     assert(I->isCommutative() && "Can only process commutative instruction");
2012     // Commute to favor either a splat or maximizing having the same opcodes on
2013     // one side.
2014     if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
2015                               AllSameOpcodeRight, SplatLeft, SplatRight)) {
2016       Left.push_back(I->getOperand(1));
2017       Right.push_back(I->getOperand(0));
2018     } else {
2019       Left.push_back(I->getOperand(0));
2020       Right.push_back(I->getOperand(1));
2021     }
2022     // Update Splat* and AllSameOpcode* after the insertion.
2023     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2024     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2025     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2026                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2027                          cast<Instruction>(Left[i])->getOpcode());
2028     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2029                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2030                           cast<Instruction>(Right[i])->getOpcode());
2031   }
2032 
2033   // If one operand end up being broadcast, return this operand order.
2034   if (SplatRight || SplatLeft)
2035     return;
2036 
2037   // Finally check if we can get longer vectorizable chain by reordering
2038   // without breaking the good operand order detected above.
2039   // E.g. If we have something like-
2040   // load a[0]  load b[0]
2041   // load b[1]  load a[1]
2042   // load a[2]  load b[2]
2043   // load a[3]  load b[3]
2044   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2045   // this code and we still retain AllSameOpcode property.
2046   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2047   // such as-
2048   // add a[0],c[0]  load b[0]
2049   // add a[1],c[2]  load b[1]
2050   // b[2]           load b[2]
2051   // add a[3],c[3]  load b[3]
2052   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2053     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2054       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2055         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2056           std::swap(Left[j + 1], Right[j + 1]);
2057           continue;
2058         }
2059       }
2060     }
2061     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2062       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2063         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2064           std::swap(Left[j + 1], Right[j + 1]);
2065           continue;
2066         }
2067       }
2068     }
2069     // else unchanged
2070   }
2071 }
2072 
2073 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
2074   Instruction *VL0 = cast<Instruction>(VL[0]);
2075   BasicBlock::iterator NextInst(VL0);
2076   ++NextInst;
2077   Builder.SetInsertPoint(VL0->getParent(), NextInst);
2078   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
2079 }
2080 
2081 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2082   Value *Vec = UndefValue::get(Ty);
2083   // Generate the 'InsertElement' instruction.
2084   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2085     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2086     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2087       GatherSeq.insert(Insrt);
2088       CSEBlocks.insert(Insrt->getParent());
2089 
2090       // Add to our 'need-to-extract' list.
2091       if (ScalarToTreeEntry.count(VL[i])) {
2092         int Idx = ScalarToTreeEntry[VL[i]];
2093         TreeEntry *E = &VectorizableTree[Idx];
2094         // Find which lane we need to extract.
2095         int FoundLane = -1;
2096         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2097           // Is this the lane of the scalar that we are looking for ?
2098           if (E->Scalars[Lane] == VL[i]) {
2099             FoundLane = Lane;
2100             break;
2101           }
2102         }
2103         assert(FoundLane >= 0 && "Could not find the correct lane");
2104         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2105       }
2106     }
2107   }
2108 
2109   return Vec;
2110 }
2111 
2112 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2113   SmallDenseMap<Value*, int>::const_iterator Entry
2114     = ScalarToTreeEntry.find(VL[0]);
2115   if (Entry != ScalarToTreeEntry.end()) {
2116     int Idx = Entry->second;
2117     const TreeEntry *En = &VectorizableTree[Idx];
2118     if (En->isSame(VL) && En->VectorizedValue)
2119       return En->VectorizedValue;
2120   }
2121   return nullptr;
2122 }
2123 
2124 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2125   if (ScalarToTreeEntry.count(VL[0])) {
2126     int Idx = ScalarToTreeEntry[VL[0]];
2127     TreeEntry *E = &VectorizableTree[Idx];
2128     if (E->isSame(VL))
2129       return vectorizeTree(E);
2130   }
2131 
2132   Type *ScalarTy = VL[0]->getType();
2133   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2134     ScalarTy = SI->getValueOperand()->getType();
2135   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2136 
2137   return Gather(VL, VecTy);
2138 }
2139 
2140 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2141   IRBuilder<>::InsertPointGuard Guard(Builder);
2142 
2143   if (E->VectorizedValue) {
2144     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2145     return E->VectorizedValue;
2146   }
2147 
2148   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2149   Type *ScalarTy = VL0->getType();
2150   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2151     ScalarTy = SI->getValueOperand()->getType();
2152   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2153 
2154   if (E->NeedToGather) {
2155     setInsertPointAfterBundle(E->Scalars);
2156     return Gather(E->Scalars, VecTy);
2157   }
2158 
2159   unsigned Opcode = getSameOpcode(E->Scalars);
2160 
2161   switch (Opcode) {
2162     case Instruction::PHI: {
2163       PHINode *PH = dyn_cast<PHINode>(VL0);
2164       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2165       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2166       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2167       E->VectorizedValue = NewPhi;
2168 
2169       // PHINodes may have multiple entries from the same block. We want to
2170       // visit every block once.
2171       SmallSet<BasicBlock*, 4> VisitedBBs;
2172 
2173       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2174         ValueList Operands;
2175         BasicBlock *IBB = PH->getIncomingBlock(i);
2176 
2177         if (!VisitedBBs.insert(IBB).second) {
2178           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2179           continue;
2180         }
2181 
2182         // Prepare the operand vector.
2183         for (Value *V : E->Scalars)
2184           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2185 
2186         Builder.SetInsertPoint(IBB->getTerminator());
2187         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2188         Value *Vec = vectorizeTree(Operands);
2189         NewPhi->addIncoming(Vec, IBB);
2190       }
2191 
2192       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2193              "Invalid number of incoming values");
2194       return NewPhi;
2195     }
2196 
2197     case Instruction::ExtractElement: {
2198       if (CanReuseExtract(E->Scalars)) {
2199         Value *V = VL0->getOperand(0);
2200         E->VectorizedValue = V;
2201         return V;
2202       }
2203       return Gather(E->Scalars, VecTy);
2204     }
2205     case Instruction::ZExt:
2206     case Instruction::SExt:
2207     case Instruction::FPToUI:
2208     case Instruction::FPToSI:
2209     case Instruction::FPExt:
2210     case Instruction::PtrToInt:
2211     case Instruction::IntToPtr:
2212     case Instruction::SIToFP:
2213     case Instruction::UIToFP:
2214     case Instruction::Trunc:
2215     case Instruction::FPTrunc:
2216     case Instruction::BitCast: {
2217       ValueList INVL;
2218       for (Value *V : E->Scalars)
2219         INVL.push_back(cast<Instruction>(V)->getOperand(0));
2220 
2221       setInsertPointAfterBundle(E->Scalars);
2222 
2223       Value *InVec = vectorizeTree(INVL);
2224 
2225       if (Value *V = alreadyVectorized(E->Scalars))
2226         return V;
2227 
2228       CastInst *CI = dyn_cast<CastInst>(VL0);
2229       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2230       E->VectorizedValue = V;
2231       ++NumVectorInstructions;
2232       return V;
2233     }
2234     case Instruction::FCmp:
2235     case Instruction::ICmp: {
2236       ValueList LHSV, RHSV;
2237       for (Value *V : E->Scalars) {
2238         LHSV.push_back(cast<Instruction>(V)->getOperand(0));
2239         RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2240       }
2241 
2242       setInsertPointAfterBundle(E->Scalars);
2243 
2244       Value *L = vectorizeTree(LHSV);
2245       Value *R = vectorizeTree(RHSV);
2246 
2247       if (Value *V = alreadyVectorized(E->Scalars))
2248         return V;
2249 
2250       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2251       Value *V;
2252       if (Opcode == Instruction::FCmp)
2253         V = Builder.CreateFCmp(P0, L, R);
2254       else
2255         V = Builder.CreateICmp(P0, L, R);
2256 
2257       E->VectorizedValue = V;
2258       ++NumVectorInstructions;
2259       return V;
2260     }
2261     case Instruction::Select: {
2262       ValueList TrueVec, FalseVec, CondVec;
2263       for (Value *V : E->Scalars) {
2264         CondVec.push_back(cast<Instruction>(V)->getOperand(0));
2265         TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2266         FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2267       }
2268 
2269       setInsertPointAfterBundle(E->Scalars);
2270 
2271       Value *Cond = vectorizeTree(CondVec);
2272       Value *True = vectorizeTree(TrueVec);
2273       Value *False = vectorizeTree(FalseVec);
2274 
2275       if (Value *V = alreadyVectorized(E->Scalars))
2276         return V;
2277 
2278       Value *V = Builder.CreateSelect(Cond, True, False);
2279       E->VectorizedValue = V;
2280       ++NumVectorInstructions;
2281       return V;
2282     }
2283     case Instruction::Add:
2284     case Instruction::FAdd:
2285     case Instruction::Sub:
2286     case Instruction::FSub:
2287     case Instruction::Mul:
2288     case Instruction::FMul:
2289     case Instruction::UDiv:
2290     case Instruction::SDiv:
2291     case Instruction::FDiv:
2292     case Instruction::URem:
2293     case Instruction::SRem:
2294     case Instruction::FRem:
2295     case Instruction::Shl:
2296     case Instruction::LShr:
2297     case Instruction::AShr:
2298     case Instruction::And:
2299     case Instruction::Or:
2300     case Instruction::Xor: {
2301       ValueList LHSVL, RHSVL;
2302       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2303         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2304       else
2305         for (Value *V : E->Scalars) {
2306           LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2307           RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2308         }
2309 
2310       setInsertPointAfterBundle(E->Scalars);
2311 
2312       Value *LHS = vectorizeTree(LHSVL);
2313       Value *RHS = vectorizeTree(RHSVL);
2314 
2315       if (LHS == RHS && isa<Instruction>(LHS)) {
2316         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2317       }
2318 
2319       if (Value *V = alreadyVectorized(E->Scalars))
2320         return V;
2321 
2322       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2323       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2324       E->VectorizedValue = V;
2325       propagateIRFlags(E->VectorizedValue, E->Scalars);
2326       ++NumVectorInstructions;
2327 
2328       if (Instruction *I = dyn_cast<Instruction>(V))
2329         return propagateMetadata(I, E->Scalars);
2330 
2331       return V;
2332     }
2333     case Instruction::Load: {
2334       // Loads are inserted at the head of the tree because we don't want to
2335       // sink them all the way down past store instructions.
2336       setInsertPointAfterBundle(E->Scalars);
2337 
2338       LoadInst *LI = cast<LoadInst>(VL0);
2339       Type *ScalarLoadTy = LI->getType();
2340       unsigned AS = LI->getPointerAddressSpace();
2341 
2342       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2343                                             VecTy->getPointerTo(AS));
2344 
2345       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2346       // ExternalUses list to make sure that an extract will be generated in the
2347       // future.
2348       if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2349         ExternalUses.push_back(
2350             ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2351 
2352       unsigned Alignment = LI->getAlignment();
2353       LI = Builder.CreateLoad(VecPtr);
2354       if (!Alignment) {
2355         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2356       }
2357       LI->setAlignment(Alignment);
2358       E->VectorizedValue = LI;
2359       ++NumVectorInstructions;
2360       return propagateMetadata(LI, E->Scalars);
2361     }
2362     case Instruction::Store: {
2363       StoreInst *SI = cast<StoreInst>(VL0);
2364       unsigned Alignment = SI->getAlignment();
2365       unsigned AS = SI->getPointerAddressSpace();
2366 
2367       ValueList ValueOp;
2368       for (Value *V : E->Scalars)
2369         ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2370 
2371       setInsertPointAfterBundle(E->Scalars);
2372 
2373       Value *VecValue = vectorizeTree(ValueOp);
2374       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2375                                             VecTy->getPointerTo(AS));
2376       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2377 
2378       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2379       // ExternalUses list to make sure that an extract will be generated in the
2380       // future.
2381       if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2382         ExternalUses.push_back(
2383             ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2384 
2385       if (!Alignment) {
2386         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2387       }
2388       S->setAlignment(Alignment);
2389       E->VectorizedValue = S;
2390       ++NumVectorInstructions;
2391       return propagateMetadata(S, E->Scalars);
2392     }
2393     case Instruction::GetElementPtr: {
2394       setInsertPointAfterBundle(E->Scalars);
2395 
2396       ValueList Op0VL;
2397       for (Value *V : E->Scalars)
2398         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2399 
2400       Value *Op0 = vectorizeTree(Op0VL);
2401 
2402       std::vector<Value *> OpVecs;
2403       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2404            ++j) {
2405         ValueList OpVL;
2406         for (Value *V : E->Scalars)
2407           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2408 
2409         Value *OpVec = vectorizeTree(OpVL);
2410         OpVecs.push_back(OpVec);
2411       }
2412 
2413       Value *V = Builder.CreateGEP(
2414           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2415       E->VectorizedValue = V;
2416       ++NumVectorInstructions;
2417 
2418       if (Instruction *I = dyn_cast<Instruction>(V))
2419         return propagateMetadata(I, E->Scalars);
2420 
2421       return V;
2422     }
2423     case Instruction::Call: {
2424       CallInst *CI = cast<CallInst>(VL0);
2425       setInsertPointAfterBundle(E->Scalars);
2426       Function *FI;
2427       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
2428       Value *ScalarArg = nullptr;
2429       if (CI && (FI = CI->getCalledFunction())) {
2430         IID = FI->getIntrinsicID();
2431       }
2432       std::vector<Value *> OpVecs;
2433       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2434         ValueList OpVL;
2435         // ctlz,cttz and powi are special intrinsics whose second argument is
2436         // a scalar. This argument should not be vectorized.
2437         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2438           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2439           ScalarArg = CEI->getArgOperand(j);
2440           OpVecs.push_back(CEI->getArgOperand(j));
2441           continue;
2442         }
2443         for (Value *V : E->Scalars) {
2444           CallInst *CEI = cast<CallInst>(V);
2445           OpVL.push_back(CEI->getArgOperand(j));
2446         }
2447 
2448         Value *OpVec = vectorizeTree(OpVL);
2449         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2450         OpVecs.push_back(OpVec);
2451       }
2452 
2453       Module *M = F->getParent();
2454       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2455       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2456       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2457       Value *V = Builder.CreateCall(CF, OpVecs);
2458 
2459       // The scalar argument uses an in-tree scalar so we add the new vectorized
2460       // call to ExternalUses list to make sure that an extract will be
2461       // generated in the future.
2462       if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2463         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2464 
2465       E->VectorizedValue = V;
2466       ++NumVectorInstructions;
2467       return V;
2468     }
2469     case Instruction::ShuffleVector: {
2470       ValueList LHSVL, RHSVL;
2471       assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2472       reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2473       setInsertPointAfterBundle(E->Scalars);
2474 
2475       Value *LHS = vectorizeTree(LHSVL);
2476       Value *RHS = vectorizeTree(RHSVL);
2477 
2478       if (Value *V = alreadyVectorized(E->Scalars))
2479         return V;
2480 
2481       // Create a vector of LHS op1 RHS
2482       BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2483       Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2484 
2485       // Create a vector of LHS op2 RHS
2486       Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2487       BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2488       Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2489 
2490       // Create shuffle to take alternate operations from the vector.
2491       // Also, gather up odd and even scalar ops to propagate IR flags to
2492       // each vector operation.
2493       ValueList OddScalars, EvenScalars;
2494       unsigned e = E->Scalars.size();
2495       SmallVector<Constant *, 8> Mask(e);
2496       for (unsigned i = 0; i < e; ++i) {
2497         if (i & 1) {
2498           Mask[i] = Builder.getInt32(e + i);
2499           OddScalars.push_back(E->Scalars[i]);
2500         } else {
2501           Mask[i] = Builder.getInt32(i);
2502           EvenScalars.push_back(E->Scalars[i]);
2503         }
2504       }
2505 
2506       Value *ShuffleMask = ConstantVector::get(Mask);
2507       propagateIRFlags(V0, EvenScalars);
2508       propagateIRFlags(V1, OddScalars);
2509 
2510       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2511       E->VectorizedValue = V;
2512       ++NumVectorInstructions;
2513       if (Instruction *I = dyn_cast<Instruction>(V))
2514         return propagateMetadata(I, E->Scalars);
2515 
2516       return V;
2517     }
2518     default:
2519     llvm_unreachable("unknown inst");
2520   }
2521   return nullptr;
2522 }
2523 
2524 Value *BoUpSLP::vectorizeTree() {
2525 
2526   // All blocks must be scheduled before any instructions are inserted.
2527   for (auto &BSIter : BlocksSchedules) {
2528     scheduleBlock(BSIter.second.get());
2529   }
2530 
2531   Builder.SetInsertPoint(&F->getEntryBlock().front());
2532   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
2533 
2534   // If the vectorized tree can be rewritten in a smaller type, we truncate the
2535   // vectorized root. InstCombine will then rewrite the entire expression. We
2536   // sign extend the extracted values below.
2537   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2538   if (MinBWs.count(ScalarRoot)) {
2539     if (auto *I = dyn_cast<Instruction>(VectorRoot))
2540       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
2541     auto BundleWidth = VectorizableTree[0].Scalars.size();
2542     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]);
2543     auto *VecTy = VectorType::get(MinTy, BundleWidth);
2544     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
2545     VectorizableTree[0].VectorizedValue = Trunc;
2546   }
2547 
2548   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2549 
2550   // Extract all of the elements with the external uses.
2551   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2552        it != e; ++it) {
2553     Value *Scalar = it->Scalar;
2554     llvm::User *User = it->User;
2555 
2556     // Skip users that we already RAUW. This happens when one instruction
2557     // has multiple uses of the same value.
2558     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2559         Scalar->user_end())
2560       continue;
2561     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2562 
2563     int Idx = ScalarToTreeEntry[Scalar];
2564     TreeEntry *E = &VectorizableTree[Idx];
2565     assert(!E->NeedToGather && "Extracting from a gather list");
2566 
2567     Value *Vec = E->VectorizedValue;
2568     assert(Vec && "Can't find vectorizable value");
2569 
2570     Value *Lane = Builder.getInt32(it->Lane);
2571     // Generate extracts for out-of-tree users.
2572     // Find the insertion point for the extractelement lane.
2573     if (isa<Instruction>(Vec)){
2574       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2575         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2576           if (PH->getIncomingValue(i) == Scalar) {
2577             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2578             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2579             if (MinBWs.count(ScalarRoot))
2580               Ex = Builder.CreateSExt(Ex, Scalar->getType());
2581             CSEBlocks.insert(PH->getIncomingBlock(i));
2582             PH->setOperand(i, Ex);
2583           }
2584         }
2585       } else {
2586         Builder.SetInsertPoint(cast<Instruction>(User));
2587         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2588         if (MinBWs.count(ScalarRoot))
2589           Ex = Builder.CreateSExt(Ex, Scalar->getType());
2590         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2591         User->replaceUsesOfWith(Scalar, Ex);
2592      }
2593     } else {
2594       Builder.SetInsertPoint(&F->getEntryBlock().front());
2595       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2596       if (MinBWs.count(ScalarRoot))
2597         Ex = Builder.CreateSExt(Ex, Scalar->getType());
2598       CSEBlocks.insert(&F->getEntryBlock());
2599       User->replaceUsesOfWith(Scalar, Ex);
2600     }
2601 
2602     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2603   }
2604 
2605   // For each vectorized value:
2606   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2607     TreeEntry *Entry = &VectorizableTree[EIdx];
2608 
2609     // For each lane:
2610     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2611       Value *Scalar = Entry->Scalars[Lane];
2612       // No need to handle users of gathered values.
2613       if (Entry->NeedToGather)
2614         continue;
2615 
2616       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2617 
2618       Type *Ty = Scalar->getType();
2619       if (!Ty->isVoidTy()) {
2620 #ifndef NDEBUG
2621         for (User *U : Scalar->users()) {
2622           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2623 
2624           assert((ScalarToTreeEntry.count(U) ||
2625                   // It is legal to replace users in the ignorelist by undef.
2626                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2627                    UserIgnoreList.end())) &&
2628                  "Replacing out-of-tree value with undef");
2629         }
2630 #endif
2631         Value *Undef = UndefValue::get(Ty);
2632         Scalar->replaceAllUsesWith(Undef);
2633       }
2634       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2635       eraseInstruction(cast<Instruction>(Scalar));
2636     }
2637   }
2638 
2639   Builder.ClearInsertionPoint();
2640 
2641   return VectorizableTree[0].VectorizedValue;
2642 }
2643 
2644 void BoUpSLP::optimizeGatherSequence() {
2645   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2646         << " gather sequences instructions.\n");
2647   // LICM InsertElementInst sequences.
2648   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2649        e = GatherSeq.end(); it != e; ++it) {
2650     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2651 
2652     if (!Insert)
2653       continue;
2654 
2655     // Check if this block is inside a loop.
2656     Loop *L = LI->getLoopFor(Insert->getParent());
2657     if (!L)
2658       continue;
2659 
2660     // Check if it has a preheader.
2661     BasicBlock *PreHeader = L->getLoopPreheader();
2662     if (!PreHeader)
2663       continue;
2664 
2665     // If the vector or the element that we insert into it are
2666     // instructions that are defined in this basic block then we can't
2667     // hoist this instruction.
2668     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2669     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2670     if (CurrVec && L->contains(CurrVec))
2671       continue;
2672     if (NewElem && L->contains(NewElem))
2673       continue;
2674 
2675     // We can hoist this instruction. Move it to the pre-header.
2676     Insert->moveBefore(PreHeader->getTerminator());
2677   }
2678 
2679   // Make a list of all reachable blocks in our CSE queue.
2680   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2681   CSEWorkList.reserve(CSEBlocks.size());
2682   for (BasicBlock *BB : CSEBlocks)
2683     if (DomTreeNode *N = DT->getNode(BB)) {
2684       assert(DT->isReachableFromEntry(N));
2685       CSEWorkList.push_back(N);
2686     }
2687 
2688   // Sort blocks by domination. This ensures we visit a block after all blocks
2689   // dominating it are visited.
2690   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2691                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2692     return DT->properlyDominates(A, B);
2693   });
2694 
2695   // Perform O(N^2) search over the gather sequences and merge identical
2696   // instructions. TODO: We can further optimize this scan if we split the
2697   // instructions into different buckets based on the insert lane.
2698   SmallVector<Instruction *, 16> Visited;
2699   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2700     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2701            "Worklist not sorted properly!");
2702     BasicBlock *BB = (*I)->getBlock();
2703     // For all instructions in blocks containing gather sequences:
2704     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2705       Instruction *In = &*it++;
2706       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2707         continue;
2708 
2709       // Check if we can replace this instruction with any of the
2710       // visited instructions.
2711       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2712                                                     ve = Visited.end();
2713            v != ve; ++v) {
2714         if (In->isIdenticalTo(*v) &&
2715             DT->dominates((*v)->getParent(), In->getParent())) {
2716           In->replaceAllUsesWith(*v);
2717           eraseInstruction(In);
2718           In = nullptr;
2719           break;
2720         }
2721       }
2722       if (In) {
2723         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2724         Visited.push_back(In);
2725       }
2726     }
2727   }
2728   CSEBlocks.clear();
2729   GatherSeq.clear();
2730 }
2731 
2732 // Groups the instructions to a bundle (which is then a single scheduling entity)
2733 // and schedules instructions until the bundle gets ready.
2734 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2735                                                  BoUpSLP *SLP) {
2736   if (isa<PHINode>(VL[0]))
2737     return true;
2738 
2739   // Initialize the instruction bundle.
2740   Instruction *OldScheduleEnd = ScheduleEnd;
2741   ScheduleData *PrevInBundle = nullptr;
2742   ScheduleData *Bundle = nullptr;
2743   bool ReSchedule = false;
2744   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2745 
2746   // Make sure that the scheduling region contains all
2747   // instructions of the bundle.
2748   for (Value *V : VL) {
2749     if (!extendSchedulingRegion(V))
2750       return false;
2751   }
2752 
2753   for (Value *V : VL) {
2754     ScheduleData *BundleMember = getScheduleData(V);
2755     assert(BundleMember &&
2756            "no ScheduleData for bundle member (maybe not in same basic block)");
2757     if (BundleMember->IsScheduled) {
2758       // A bundle member was scheduled as single instruction before and now
2759       // needs to be scheduled as part of the bundle. We just get rid of the
2760       // existing schedule.
2761       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2762                    << " was already scheduled\n");
2763       ReSchedule = true;
2764     }
2765     assert(BundleMember->isSchedulingEntity() &&
2766            "bundle member already part of other bundle");
2767     if (PrevInBundle) {
2768       PrevInBundle->NextInBundle = BundleMember;
2769     } else {
2770       Bundle = BundleMember;
2771     }
2772     BundleMember->UnscheduledDepsInBundle = 0;
2773     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2774 
2775     // Group the instructions to a bundle.
2776     BundleMember->FirstInBundle = Bundle;
2777     PrevInBundle = BundleMember;
2778   }
2779   if (ScheduleEnd != OldScheduleEnd) {
2780     // The scheduling region got new instructions at the lower end (or it is a
2781     // new region for the first bundle). This makes it necessary to
2782     // recalculate all dependencies.
2783     // It is seldom that this needs to be done a second time after adding the
2784     // initial bundle to the region.
2785     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2786       ScheduleData *SD = getScheduleData(I);
2787       SD->clearDependencies();
2788     }
2789     ReSchedule = true;
2790   }
2791   if (ReSchedule) {
2792     resetSchedule();
2793     initialFillReadyList(ReadyInsts);
2794   }
2795 
2796   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2797                << BB->getName() << "\n");
2798 
2799   calculateDependencies(Bundle, true, SLP);
2800 
2801   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2802   // means that there are no cyclic dependencies and we can schedule it.
2803   // Note that's important that we don't "schedule" the bundle yet (see
2804   // cancelScheduling).
2805   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2806 
2807     ScheduleData *pickedSD = ReadyInsts.back();
2808     ReadyInsts.pop_back();
2809 
2810     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2811       schedule(pickedSD, ReadyInsts);
2812     }
2813   }
2814   if (!Bundle->isReady()) {
2815     cancelScheduling(VL);
2816     return false;
2817   }
2818   return true;
2819 }
2820 
2821 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2822   if (isa<PHINode>(VL[0]))
2823     return;
2824 
2825   ScheduleData *Bundle = getScheduleData(VL[0]);
2826   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2827   assert(!Bundle->IsScheduled &&
2828          "Can't cancel bundle which is already scheduled");
2829   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2830          "tried to unbundle something which is not a bundle");
2831 
2832   // Un-bundle: make single instructions out of the bundle.
2833   ScheduleData *BundleMember = Bundle;
2834   while (BundleMember) {
2835     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2836     BundleMember->FirstInBundle = BundleMember;
2837     ScheduleData *Next = BundleMember->NextInBundle;
2838     BundleMember->NextInBundle = nullptr;
2839     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2840     if (BundleMember->UnscheduledDepsInBundle == 0) {
2841       ReadyInsts.insert(BundleMember);
2842     }
2843     BundleMember = Next;
2844   }
2845 }
2846 
2847 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2848   if (getScheduleData(V))
2849     return true;
2850   Instruction *I = dyn_cast<Instruction>(V);
2851   assert(I && "bundle member must be an instruction");
2852   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2853   if (!ScheduleStart) {
2854     // It's the first instruction in the new region.
2855     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2856     ScheduleStart = I;
2857     ScheduleEnd = I->getNextNode();
2858     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2859     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2860     return true;
2861   }
2862   // Search up and down at the same time, because we don't know if the new
2863   // instruction is above or below the existing scheduling region.
2864   BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
2865   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2866   BasicBlock::iterator DownIter(ScheduleEnd);
2867   BasicBlock::iterator LowerEnd = BB->end();
2868   for (;;) {
2869     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
2870       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
2871       return false;
2872     }
2873 
2874     if (UpIter != UpperEnd) {
2875       if (&*UpIter == I) {
2876         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2877         ScheduleStart = I;
2878         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2879         return true;
2880       }
2881       UpIter++;
2882     }
2883     if (DownIter != LowerEnd) {
2884       if (&*DownIter == I) {
2885         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2886                          nullptr);
2887         ScheduleEnd = I->getNextNode();
2888         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2889         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
2890         return true;
2891       }
2892       DownIter++;
2893     }
2894     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2895            "instruction not found in block");
2896   }
2897   return true;
2898 }
2899 
2900 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2901                                                 Instruction *ToI,
2902                                                 ScheduleData *PrevLoadStore,
2903                                                 ScheduleData *NextLoadStore) {
2904   ScheduleData *CurrentLoadStore = PrevLoadStore;
2905   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2906     ScheduleData *SD = ScheduleDataMap[I];
2907     if (!SD) {
2908       // Allocate a new ScheduleData for the instruction.
2909       if (ChunkPos >= ChunkSize) {
2910         ScheduleDataChunks.push_back(
2911             llvm::make_unique<ScheduleData[]>(ChunkSize));
2912         ChunkPos = 0;
2913       }
2914       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2915       ScheduleDataMap[I] = SD;
2916       SD->Inst = I;
2917     }
2918     assert(!isInSchedulingRegion(SD) &&
2919            "new ScheduleData already in scheduling region");
2920     SD->init(SchedulingRegionID);
2921 
2922     if (I->mayReadOrWriteMemory()) {
2923       // Update the linked list of memory accessing instructions.
2924       if (CurrentLoadStore) {
2925         CurrentLoadStore->NextLoadStore = SD;
2926       } else {
2927         FirstLoadStoreInRegion = SD;
2928       }
2929       CurrentLoadStore = SD;
2930     }
2931   }
2932   if (NextLoadStore) {
2933     if (CurrentLoadStore)
2934       CurrentLoadStore->NextLoadStore = NextLoadStore;
2935   } else {
2936     LastLoadStoreInRegion = CurrentLoadStore;
2937   }
2938 }
2939 
2940 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2941                                                      bool InsertInReadyList,
2942                                                      BoUpSLP *SLP) {
2943   assert(SD->isSchedulingEntity());
2944 
2945   SmallVector<ScheduleData *, 10> WorkList;
2946   WorkList.push_back(SD);
2947 
2948   while (!WorkList.empty()) {
2949     ScheduleData *SD = WorkList.back();
2950     WorkList.pop_back();
2951 
2952     ScheduleData *BundleMember = SD;
2953     while (BundleMember) {
2954       assert(isInSchedulingRegion(BundleMember));
2955       if (!BundleMember->hasValidDependencies()) {
2956 
2957         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
2958         BundleMember->Dependencies = 0;
2959         BundleMember->resetUnscheduledDeps();
2960 
2961         // Handle def-use chain dependencies.
2962         for (User *U : BundleMember->Inst->users()) {
2963           if (isa<Instruction>(U)) {
2964             ScheduleData *UseSD = getScheduleData(U);
2965             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2966               BundleMember->Dependencies++;
2967               ScheduleData *DestBundle = UseSD->FirstInBundle;
2968               if (!DestBundle->IsScheduled) {
2969                 BundleMember->incrementUnscheduledDeps(1);
2970               }
2971               if (!DestBundle->hasValidDependencies()) {
2972                 WorkList.push_back(DestBundle);
2973               }
2974             }
2975           } else {
2976             // I'm not sure if this can ever happen. But we need to be safe.
2977             // This lets the instruction/bundle never be scheduled and
2978             // eventually disable vectorization.
2979             BundleMember->Dependencies++;
2980             BundleMember->incrementUnscheduledDeps(1);
2981           }
2982         }
2983 
2984         // Handle the memory dependencies.
2985         ScheduleData *DepDest = BundleMember->NextLoadStore;
2986         if (DepDest) {
2987           Instruction *SrcInst = BundleMember->Inst;
2988           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
2989           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2990           unsigned numAliased = 0;
2991           unsigned DistToSrc = 1;
2992 
2993           while (DepDest) {
2994             assert(isInSchedulingRegion(DepDest));
2995 
2996             // We have two limits to reduce the complexity:
2997             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
2998             //    SLP->isAliased (which is the expensive part in this loop).
2999             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3000             //    the whole loop (even if the loop is fast, it's quadratic).
3001             //    It's important for the loop break condition (see below) to
3002             //    check this limit even between two read-only instructions.
3003             if (DistToSrc >= MaxMemDepDistance ||
3004                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3005                      (numAliased >= AliasedCheckLimit ||
3006                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3007 
3008               // We increment the counter only if the locations are aliased
3009               // (instead of counting all alias checks). This gives a better
3010               // balance between reduced runtime and accurate dependencies.
3011               numAliased++;
3012 
3013               DepDest->MemoryDependencies.push_back(BundleMember);
3014               BundleMember->Dependencies++;
3015               ScheduleData *DestBundle = DepDest->FirstInBundle;
3016               if (!DestBundle->IsScheduled) {
3017                 BundleMember->incrementUnscheduledDeps(1);
3018               }
3019               if (!DestBundle->hasValidDependencies()) {
3020                 WorkList.push_back(DestBundle);
3021               }
3022             }
3023             DepDest = DepDest->NextLoadStore;
3024 
3025             // Example, explaining the loop break condition: Let's assume our
3026             // starting instruction is i0 and MaxMemDepDistance = 3.
3027             //
3028             //                      +--------v--v--v
3029             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3030             //             +--------^--^--^
3031             //
3032             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3033             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3034             // Previously we already added dependencies from i3 to i6,i7,i8
3035             // (because of MaxMemDepDistance). As we added a dependency from
3036             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3037             // and we can abort this loop at i6.
3038             if (DistToSrc >= 2 * MaxMemDepDistance)
3039                 break;
3040             DistToSrc++;
3041           }
3042         }
3043       }
3044       BundleMember = BundleMember->NextInBundle;
3045     }
3046     if (InsertInReadyList && SD->isReady()) {
3047       ReadyInsts.push_back(SD);
3048       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3049     }
3050   }
3051 }
3052 
3053 void BoUpSLP::BlockScheduling::resetSchedule() {
3054   assert(ScheduleStart &&
3055          "tried to reset schedule on block which has not been scheduled");
3056   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3057     ScheduleData *SD = getScheduleData(I);
3058     assert(isInSchedulingRegion(SD));
3059     SD->IsScheduled = false;
3060     SD->resetUnscheduledDeps();
3061   }
3062   ReadyInsts.clear();
3063 }
3064 
3065 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3066 
3067   if (!BS->ScheduleStart)
3068     return;
3069 
3070   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3071 
3072   BS->resetSchedule();
3073 
3074   // For the real scheduling we use a more sophisticated ready-list: it is
3075   // sorted by the original instruction location. This lets the final schedule
3076   // be as  close as possible to the original instruction order.
3077   struct ScheduleDataCompare {
3078     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
3079       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3080     }
3081   };
3082   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3083 
3084   // Ensure that all dependency data is updated and fill the ready-list with
3085   // initial instructions.
3086   int Idx = 0;
3087   int NumToSchedule = 0;
3088   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3089        I = I->getNextNode()) {
3090     ScheduleData *SD = BS->getScheduleData(I);
3091     assert(
3092         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3093         "scheduler and vectorizer have different opinion on what is a bundle");
3094     SD->FirstInBundle->SchedulingPriority = Idx++;
3095     if (SD->isSchedulingEntity()) {
3096       BS->calculateDependencies(SD, false, this);
3097       NumToSchedule++;
3098     }
3099   }
3100   BS->initialFillReadyList(ReadyInsts);
3101 
3102   Instruction *LastScheduledInst = BS->ScheduleEnd;
3103 
3104   // Do the "real" scheduling.
3105   while (!ReadyInsts.empty()) {
3106     ScheduleData *picked = *ReadyInsts.begin();
3107     ReadyInsts.erase(ReadyInsts.begin());
3108 
3109     // Move the scheduled instruction(s) to their dedicated places, if not
3110     // there yet.
3111     ScheduleData *BundleMember = picked;
3112     while (BundleMember) {
3113       Instruction *pickedInst = BundleMember->Inst;
3114       if (LastScheduledInst->getNextNode() != pickedInst) {
3115         BS->BB->getInstList().remove(pickedInst);
3116         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3117                                      pickedInst);
3118       }
3119       LastScheduledInst = pickedInst;
3120       BundleMember = BundleMember->NextInBundle;
3121     }
3122 
3123     BS->schedule(picked, ReadyInsts);
3124     NumToSchedule--;
3125   }
3126   assert(NumToSchedule == 0 && "could not schedule all instructions");
3127 
3128   // Avoid duplicate scheduling of the block.
3129   BS->ScheduleStart = nullptr;
3130 }
3131 
3132 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3133   // If V is a store, just return the width of the stored value without
3134   // traversing the expression tree. This is the common case.
3135   if (auto *Store = dyn_cast<StoreInst>(V))
3136     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3137 
3138   // If V is not a store, we can traverse the expression tree to find loads
3139   // that feed it. The type of the loaded value may indicate a more suitable
3140   // width than V's type. We want to base the vector element size on the width
3141   // of memory operations where possible.
3142   SmallVector<Instruction *, 16> Worklist;
3143   SmallPtrSet<Instruction *, 16> Visited;
3144   if (auto *I = dyn_cast<Instruction>(V))
3145     Worklist.push_back(I);
3146 
3147   // Traverse the expression tree in bottom-up order looking for loads. If we
3148   // encounter an instruciton we don't yet handle, we give up.
3149   auto MaxWidth = 0u;
3150   auto FoundUnknownInst = false;
3151   while (!Worklist.empty() && !FoundUnknownInst) {
3152     auto *I = Worklist.pop_back_val();
3153     Visited.insert(I);
3154 
3155     // We should only be looking at scalar instructions here. If the current
3156     // instruction has a vector type, give up.
3157     auto *Ty = I->getType();
3158     if (isa<VectorType>(Ty))
3159       FoundUnknownInst = true;
3160 
3161     // If the current instruction is a load, update MaxWidth to reflect the
3162     // width of the loaded value.
3163     else if (isa<LoadInst>(I))
3164       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3165 
3166     // Otherwise, we need to visit the operands of the instruction. We only
3167     // handle the interesting cases from buildTree here. If an operand is an
3168     // instruction we haven't yet visited, we add it to the worklist.
3169     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3170              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3171       for (Use &U : I->operands())
3172         if (auto *J = dyn_cast<Instruction>(U.get()))
3173           if (!Visited.count(J))
3174             Worklist.push_back(J);
3175     }
3176 
3177     // If we don't yet handle the instruction, give up.
3178     else
3179       FoundUnknownInst = true;
3180   }
3181 
3182   // If we didn't encounter a memory access in the expression tree, or if we
3183   // gave up for some reason, just return the width of V.
3184   if (!MaxWidth || FoundUnknownInst)
3185     return DL->getTypeSizeInBits(V->getType());
3186 
3187   // Otherwise, return the maximum width we found.
3188   return MaxWidth;
3189 }
3190 
3191 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3192 // smaller type with a truncation. We collect the values that will be demoted
3193 // in ToDemote and additional roots that require investigating in Roots.
3194 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3195                                   SmallVectorImpl<Value *> &ToDemote,
3196                                   SmallVectorImpl<Value *> &Roots) {
3197 
3198   // We can always demote constants.
3199   if (isa<Constant>(V)) {
3200     ToDemote.push_back(V);
3201     return true;
3202   }
3203 
3204   // If the value is not an instruction in the expression with only one use, it
3205   // cannot be demoted.
3206   auto *I = dyn_cast<Instruction>(V);
3207   if (!I || !I->hasOneUse() || !Expr.count(I))
3208     return false;
3209 
3210   switch (I->getOpcode()) {
3211 
3212   // We can always demote truncations and extensions. Since truncations can
3213   // seed additional demotion, we save the truncated value.
3214   case Instruction::Trunc:
3215     Roots.push_back(I->getOperand(0));
3216   case Instruction::ZExt:
3217   case Instruction::SExt:
3218     break;
3219 
3220   // We can demote certain binary operations if we can demote both of their
3221   // operands.
3222   case Instruction::Add:
3223   case Instruction::Sub:
3224   case Instruction::Mul:
3225   case Instruction::And:
3226   case Instruction::Or:
3227   case Instruction::Xor:
3228     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3229         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3230       return false;
3231     break;
3232 
3233   // We can demote selects if we can demote their true and false values.
3234   case Instruction::Select: {
3235     SelectInst *SI = cast<SelectInst>(I);
3236     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3237         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3238       return false;
3239     break;
3240   }
3241 
3242   // We can demote phis if we can demote all their incoming operands. Note that
3243   // we don't need to worry about cycles since we ensure single use above.
3244   case Instruction::PHI: {
3245     PHINode *PN = cast<PHINode>(I);
3246     for (Value *IncValue : PN->incoming_values())
3247       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3248         return false;
3249     break;
3250   }
3251 
3252   // Otherwise, conservatively give up.
3253   default:
3254     return false;
3255   }
3256 
3257   // Record the value that we can demote.
3258   ToDemote.push_back(V);
3259   return true;
3260 }
3261 
3262 void BoUpSLP::computeMinimumValueSizes() {
3263   // If there are no external uses, the expression tree must be rooted by a
3264   // store. We can't demote in-memory values, so there is nothing to do here.
3265   if (ExternalUses.empty())
3266     return;
3267 
3268   // We only attempt to truncate integer expressions.
3269   auto &TreeRoot = VectorizableTree[0].Scalars;
3270   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3271   if (!TreeRootIT)
3272     return;
3273 
3274   // If the expression is not rooted by a store, these roots should have
3275   // external uses. We will rely on InstCombine to rewrite the expression in
3276   // the narrower type. However, InstCombine only rewrites single-use values.
3277   // This means that if a tree entry other than a root is used externally, it
3278   // must have multiple uses and InstCombine will not rewrite it. The code
3279   // below ensures that only the roots are used externally.
3280   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3281   for (auto &EU : ExternalUses)
3282     if (!Expr.erase(EU.Scalar))
3283       return;
3284   if (!Expr.empty())
3285     return;
3286 
3287   // Collect the scalar values of the vectorizable expression. We will use this
3288   // context to determine which values can be demoted. If we see a truncation,
3289   // we mark it as seeding another demotion.
3290   for (auto &Entry : VectorizableTree)
3291     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3292 
3293   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3294   // have a single external user that is not in the vectorizable tree.
3295   for (auto *Root : TreeRoot)
3296     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3297       return;
3298 
3299   // Conservatively determine if we can actually truncate the roots of the
3300   // expression. Collect the values that can be demoted in ToDemote and
3301   // additional roots that require investigating in Roots.
3302   SmallVector<Value *, 32> ToDemote;
3303   SmallVector<Value *, 4> Roots;
3304   for (auto *Root : TreeRoot)
3305     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3306       return;
3307 
3308   // The maximum bit width required to represent all the values that can be
3309   // demoted without loss of precision. It would be safe to truncate the roots
3310   // of the expression to this width.
3311   auto MaxBitWidth = 8u;
3312 
3313   // We first check if all the bits of the roots are demanded. If they're not,
3314   // we can truncate the roots to this narrower type.
3315   for (auto *Root : TreeRoot) {
3316     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3317     MaxBitWidth = std::max<unsigned>(
3318         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3319   }
3320 
3321   // If all the bits of the roots are demanded, we can try a little harder to
3322   // compute a narrower type. This can happen, for example, if the roots are
3323   // getelementptr indices. InstCombine promotes these indices to the pointer
3324   // width. Thus, all their bits are technically demanded even though the
3325   // address computation might be vectorized in a smaller type.
3326   //
3327   // We start by looking at each entry that can be demoted. We compute the
3328   // maximum bit width required to store the scalar by using ValueTracking to
3329   // compute the number of high-order bits we can truncate.
3330   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3331     MaxBitWidth = 8u;
3332     for (auto *Scalar : ToDemote) {
3333       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3334       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3335       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3336     }
3337   }
3338 
3339   // Round MaxBitWidth up to the next power-of-two.
3340   if (!isPowerOf2_64(MaxBitWidth))
3341     MaxBitWidth = NextPowerOf2(MaxBitWidth);
3342 
3343   // If the maximum bit width we compute is less than the with of the roots'
3344   // type, we can proceed with the narrowing. Otherwise, do nothing.
3345   if (MaxBitWidth >= TreeRootIT->getBitWidth())
3346     return;
3347 
3348   // If we can truncate the root, we must collect additional values that might
3349   // be demoted as a result. That is, those seeded by truncations we will
3350   // modify.
3351   while (!Roots.empty())
3352     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3353 
3354   // Finally, map the values we can demote to the maximum bit with we computed.
3355   for (auto *Scalar : ToDemote)
3356     MinBWs[Scalar] = MaxBitWidth;
3357 }
3358 
3359 /// The SLPVectorizer Pass.
3360 struct SLPVectorizer : public FunctionPass {
3361   typedef SmallVector<StoreInst *, 8> StoreList;
3362   typedef MapVector<Value *, StoreList> StoreListMap;
3363   typedef SmallVector<WeakVH, 8> WeakVHList;
3364   typedef MapVector<Value *, WeakVHList> WeakVHListMap;
3365 
3366   /// Pass identification, replacement for typeid
3367   static char ID;
3368 
3369   explicit SLPVectorizer() : FunctionPass(ID) {
3370     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3371   }
3372 
3373   ScalarEvolution *SE;
3374   TargetTransformInfo *TTI;
3375   TargetLibraryInfo *TLI;
3376   AliasAnalysis *AA;
3377   LoopInfo *LI;
3378   DominatorTree *DT;
3379   AssumptionCache *AC;
3380   DemandedBits *DB;
3381   const DataLayout *DL;
3382 
3383   bool doInitialization(Module &M) override {
3384     DL = &M.getDataLayout();
3385     return false;
3386   }
3387 
3388   bool runOnFunction(Function &F) override {
3389     if (skipOptnoneFunction(F))
3390       return false;
3391 
3392     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3393     TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3394     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3395     TLI = TLIP ? &TLIP->getTLI() : nullptr;
3396     AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3397     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3398     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3399     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3400     DB = &getAnalysis<DemandedBits>();
3401 
3402     Stores.clear();
3403     GEPs.clear();
3404     bool Changed = false;
3405 
3406     // If the target claims to have no vector registers don't attempt
3407     // vectorization.
3408     if (!TTI->getNumberOfRegisters(true))
3409       return false;
3410 
3411     // Use the vector register size specified by the target unless overridden
3412     // by a command-line option.
3413     // TODO: It would be better to limit the vectorization factor based on
3414     //       data type rather than just register size. For example, x86 AVX has
3415     //       256-bit registers, but it does not support integer operations
3416     //       at that width (that requires AVX2).
3417     if (MaxVectorRegSizeOption.getNumOccurrences())
3418       MaxVecRegSize = MaxVectorRegSizeOption;
3419     else
3420       MaxVecRegSize = TTI->getRegisterBitWidth(true);
3421 
3422     MinVecRegSize = MinVectorRegSizeOption;
3423 
3424     // Don't vectorize when the attribute NoImplicitFloat is used.
3425     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3426       return false;
3427 
3428     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3429 
3430     // Use the bottom up slp vectorizer to construct chains that start with
3431     // store instructions.
3432     BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
3433 
3434     // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3435     // delete instructions.
3436 
3437     // Scan the blocks in the function in post order.
3438     for (auto BB : post_order(&F.getEntryBlock())) {
3439       collectSeedInstructions(BB);
3440 
3441       // Vectorize trees that end at stores.
3442       if (!Stores.empty()) {
3443         DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3444                      << " underlying objects.\n");
3445         Changed |= vectorizeStoreChains(R);
3446       }
3447 
3448       // Vectorize trees that end at reductions.
3449       Changed |= vectorizeChainsInBlock(BB, R);
3450 
3451       // Vectorize the index computations of getelementptr instructions. This
3452       // is primarily intended to catch gather-like idioms ending at
3453       // non-consecutive loads.
3454       if (!GEPs.empty()) {
3455         DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3456                      << " underlying objects.\n");
3457         Changed |= vectorizeGEPIndices(BB, R);
3458       }
3459     }
3460 
3461     if (Changed) {
3462       R.optimizeGatherSequence();
3463       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3464       DEBUG(verifyFunction(F));
3465     }
3466     return Changed;
3467   }
3468 
3469   void getAnalysisUsage(AnalysisUsage &AU) const override {
3470     FunctionPass::getAnalysisUsage(AU);
3471     AU.addRequired<AssumptionCacheTracker>();
3472     AU.addRequired<ScalarEvolutionWrapperPass>();
3473     AU.addRequired<AAResultsWrapperPass>();
3474     AU.addRequired<TargetTransformInfoWrapperPass>();
3475     AU.addRequired<LoopInfoWrapperPass>();
3476     AU.addRequired<DominatorTreeWrapperPass>();
3477     AU.addRequired<DemandedBits>();
3478     AU.addPreserved<LoopInfoWrapperPass>();
3479     AU.addPreserved<DominatorTreeWrapperPass>();
3480     AU.addPreserved<AAResultsWrapperPass>();
3481     AU.addPreserved<GlobalsAAWrapperPass>();
3482     AU.setPreservesCFG();
3483   }
3484 
3485 private:
3486   /// \brief Collect store and getelementptr instructions and organize them
3487   /// according to the underlying object of their pointer operands. We sort the
3488   /// instructions by their underlying objects to reduce the cost of
3489   /// consecutive access queries.
3490   ///
3491   /// TODO: We can further reduce this cost if we flush the chain creation
3492   ///       every time we run into a memory barrier.
3493   void collectSeedInstructions(BasicBlock *BB);
3494 
3495   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
3496   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
3497 
3498   /// \brief Try to vectorize a list of operands.
3499   /// \@param BuildVector A list of users to ignore for the purpose of
3500   ///                     scheduling and that don't need extracting.
3501   /// \returns true if a value was vectorized.
3502   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3503                           ArrayRef<Value *> BuildVector = None,
3504                           bool allowReorder = false);
3505 
3506   /// \brief Try to vectorize a chain that may start at the operands of \V;
3507   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
3508 
3509   /// \brief Vectorize the store instructions collected in Stores.
3510   bool vectorizeStoreChains(BoUpSLP &R);
3511 
3512   /// \brief Vectorize the index computations of the getelementptr instructions
3513   /// collected in GEPs.
3514   bool vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R);
3515 
3516   /// \brief Scan the basic block and look for patterns that are likely to start
3517   /// a vectorization chain.
3518   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
3519 
3520   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
3521                            BoUpSLP &R, unsigned VecRegSize);
3522 
3523   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
3524                        BoUpSLP &R);
3525 
3526   /// The store instructions in a basic block organized by base pointer.
3527   StoreListMap Stores;
3528 
3529   /// The getelementptr instructions in a basic block organized by base pointer.
3530   WeakVHListMap GEPs;
3531 
3532   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3533   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3534 };
3535 
3536 /// \brief Check that the Values in the slice in VL array are still existent in
3537 /// the WeakVH array.
3538 /// Vectorization of part of the VL array may cause later values in the VL array
3539 /// to become invalid. We track when this has happened in the WeakVH array.
3540 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
3541                                unsigned SliceBegin, unsigned SliceSize) {
3542   VL = VL.slice(SliceBegin, SliceSize);
3543   VH = VH.slice(SliceBegin, SliceSize);
3544   return !std::equal(VL.begin(), VL.end(), VH.begin());
3545 }
3546 
3547 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3548                                         int CostThreshold, BoUpSLP &R,
3549                                         unsigned VecRegSize) {
3550   unsigned ChainLen = Chain.size();
3551   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3552         << "\n");
3553   unsigned Sz = R.getVectorElementSize(Chain[0]);
3554   unsigned VF = VecRegSize / Sz;
3555 
3556   if (!isPowerOf2_32(Sz) || VF < 2)
3557     return false;
3558 
3559   // Keep track of values that were deleted by vectorizing in the loop below.
3560   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3561 
3562   bool Changed = false;
3563   // Look for profitable vectorizable trees at all offsets, starting at zero.
3564   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3565     if (i + VF > e)
3566       break;
3567 
3568     // Check that a previous iteration of this loop did not delete the Value.
3569     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3570       continue;
3571 
3572     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3573           << "\n");
3574     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3575 
3576     R.buildTree(Operands);
3577     R.computeMinimumValueSizes();
3578 
3579     int Cost = R.getTreeCost();
3580 
3581     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3582     if (Cost < CostThreshold) {
3583       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3584       R.vectorizeTree();
3585 
3586       // Move to the next bundle.
3587       i += VF - 1;
3588       Changed = true;
3589     }
3590   }
3591 
3592   return Changed;
3593 }
3594 
3595 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3596                                     int costThreshold, BoUpSLP &R) {
3597   SetVector<StoreInst *> Heads, Tails;
3598   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3599 
3600   // We may run into multiple chains that merge into a single chain. We mark the
3601   // stores that we vectorized so that we don't visit the same store twice.
3602   BoUpSLP::ValueSet VectorizedStores;
3603   bool Changed = false;
3604 
3605   // Do a quadratic search on all of the given stores and find
3606   // all of the pairs of stores that follow each other.
3607   SmallVector<unsigned, 16> IndexQueue;
3608   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3609     IndexQueue.clear();
3610     // If a store has multiple consecutive store candidates, search Stores
3611     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3612     // This is because usually pairing with immediate succeeding or preceding
3613     // candidate create the best chance to find slp vectorization opportunity.
3614     unsigned j = 0;
3615     for (j = i + 1; j < e; ++j)
3616       IndexQueue.push_back(j);
3617     for (j = i; j > 0; --j)
3618       IndexQueue.push_back(j - 1);
3619 
3620     for (auto &k : IndexQueue) {
3621       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3622         Tails.insert(Stores[k]);
3623         Heads.insert(Stores[i]);
3624         ConsecutiveChain[Stores[i]] = Stores[k];
3625         break;
3626       }
3627     }
3628   }
3629 
3630   // For stores that start but don't end a link in the chain:
3631   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3632        it != e; ++it) {
3633     if (Tails.count(*it))
3634       continue;
3635 
3636     // We found a store instr that starts a chain. Now follow the chain and try
3637     // to vectorize it.
3638     BoUpSLP::ValueList Operands;
3639     StoreInst *I = *it;
3640     // Collect the chain into a list.
3641     while (Tails.count(I) || Heads.count(I)) {
3642       if (VectorizedStores.count(I))
3643         break;
3644       Operands.push_back(I);
3645       // Move to the next value in the chain.
3646       I = ConsecutiveChain[I];
3647     }
3648 
3649     // FIXME: Is division-by-2 the correct step? Should we assert that the
3650     // register size is a power-of-2?
3651     for (unsigned Size = MaxVecRegSize; Size >= MinVecRegSize; Size /= 2) {
3652       if (vectorizeStoreChain(Operands, costThreshold, R, Size)) {
3653         // Mark the vectorized stores so that we don't vectorize them again.
3654         VectorizedStores.insert(Operands.begin(), Operands.end());
3655         Changed = true;
3656         break;
3657       }
3658     }
3659   }
3660 
3661   return Changed;
3662 }
3663 
3664 void SLPVectorizer::collectSeedInstructions(BasicBlock *BB) {
3665 
3666   // Initialize the collections. We will make a single pass over the block.
3667   Stores.clear();
3668   GEPs.clear();
3669 
3670   // Visit the store and getelementptr instructions in BB and organize them in
3671   // Stores and GEPs according to the underlying objects of their pointer
3672   // operands.
3673   for (Instruction &I : *BB) {
3674 
3675     // Ignore store instructions that are volatile or have a pointer operand
3676     // that doesn't point to a scalar type.
3677     if (auto *SI = dyn_cast<StoreInst>(&I)) {
3678       if (!SI->isSimple())
3679         continue;
3680       if (!isValidElementType(SI->getValueOperand()->getType()))
3681         continue;
3682       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
3683     }
3684 
3685     // Ignore getelementptr instructions that have more than one index, a
3686     // constant index, or a pointer operand that doesn't point to a scalar
3687     // type.
3688     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3689       auto Idx = GEP->idx_begin()->get();
3690       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
3691         continue;
3692       if (!isValidElementType(Idx->getType()))
3693         continue;
3694       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
3695     }
3696   }
3697 }
3698 
3699 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3700   if (!A || !B)
3701     return false;
3702   Value *VL[] = { A, B };
3703   return tryToVectorizeList(VL, R, None, true);
3704 }
3705 
3706 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3707                                        ArrayRef<Value *> BuildVector,
3708                                        bool allowReorder) {
3709   if (VL.size() < 2)
3710     return false;
3711 
3712   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3713 
3714   // Check that all of the parts are scalar instructions of the same type.
3715   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3716   if (!I0)
3717     return false;
3718 
3719   unsigned Opcode0 = I0->getOpcode();
3720 
3721   // FIXME: Register size should be a parameter to this function, so we can
3722   // try different vectorization factors.
3723   unsigned Sz = R.getVectorElementSize(I0);
3724   unsigned VF = MinVecRegSize / Sz;
3725 
3726   for (Value *V : VL) {
3727     Type *Ty = V->getType();
3728     if (!isValidElementType(Ty))
3729       return false;
3730     Instruction *Inst = dyn_cast<Instruction>(V);
3731     if (!Inst || Inst->getOpcode() != Opcode0)
3732       return false;
3733   }
3734 
3735   bool Changed = false;
3736 
3737   // Keep track of values that were deleted by vectorizing in the loop below.
3738   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3739 
3740   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3741     unsigned OpsWidth = 0;
3742 
3743     if (i + VF > e)
3744       OpsWidth = e - i;
3745     else
3746       OpsWidth = VF;
3747 
3748     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3749       break;
3750 
3751     // Check that a previous iteration of this loop did not delete the Value.
3752     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3753       continue;
3754 
3755     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3756                  << "\n");
3757     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3758 
3759     ArrayRef<Value *> BuildVectorSlice;
3760     if (!BuildVector.empty())
3761       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3762 
3763     R.buildTree(Ops, BuildVectorSlice);
3764     // TODO: check if we can allow reordering also for other cases than
3765     // tryToVectorizePair()
3766     if (allowReorder && R.shouldReorder()) {
3767       assert(Ops.size() == 2);
3768       assert(BuildVectorSlice.empty());
3769       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3770       R.buildTree(ReorderedOps, None);
3771     }
3772     R.computeMinimumValueSizes();
3773     int Cost = R.getTreeCost();
3774 
3775     if (Cost < -SLPCostThreshold) {
3776       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3777       Value *VectorizedRoot = R.vectorizeTree();
3778 
3779       // Reconstruct the build vector by extracting the vectorized root. This
3780       // way we handle the case where some elements of the vector are undefined.
3781       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3782       if (!BuildVectorSlice.empty()) {
3783         // The insert point is the last build vector instruction. The vectorized
3784         // root will precede it. This guarantees that we get an instruction. The
3785         // vectorized tree could have been constant folded.
3786         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3787         unsigned VecIdx = 0;
3788         for (auto &V : BuildVectorSlice) {
3789           IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
3790                                       ++BasicBlock::iterator(InsertAfter));
3791           InsertElementInst *IE = cast<InsertElementInst>(V);
3792           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3793               VectorizedRoot, Builder.getInt32(VecIdx++)));
3794           IE->setOperand(1, Extract);
3795           IE->removeFromParent();
3796           IE->insertAfter(Extract);
3797           InsertAfter = IE;
3798         }
3799       }
3800       // Move to the next bundle.
3801       i += VF - 1;
3802       Changed = true;
3803     }
3804   }
3805 
3806   return Changed;
3807 }
3808 
3809 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3810   if (!V)
3811     return false;
3812 
3813   // Try to vectorize V.
3814   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3815     return true;
3816 
3817   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3818   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3819   // Try to skip B.
3820   if (B && B->hasOneUse()) {
3821     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3822     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3823     if (tryToVectorizePair(A, B0, R)) {
3824       return true;
3825     }
3826     if (tryToVectorizePair(A, B1, R)) {
3827       return true;
3828     }
3829   }
3830 
3831   // Try to skip A.
3832   if (A && A->hasOneUse()) {
3833     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3834     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3835     if (tryToVectorizePair(A0, B, R)) {
3836       return true;
3837     }
3838     if (tryToVectorizePair(A1, B, R)) {
3839       return true;
3840     }
3841   }
3842   return 0;
3843 }
3844 
3845 /// \brief Generate a shuffle mask to be used in a reduction tree.
3846 ///
3847 /// \param VecLen The length of the vector to be reduced.
3848 /// \param NumEltsToRdx The number of elements that should be reduced in the
3849 ///        vector.
3850 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3851 ///        reduction. A pairwise reduction will generate a mask of
3852 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
3853 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3854 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3855 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3856                                    bool IsPairwise, bool IsLeft,
3857                                    IRBuilder<> &Builder) {
3858   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3859 
3860   SmallVector<Constant *, 32> ShuffleMask(
3861       VecLen, UndefValue::get(Builder.getInt32Ty()));
3862 
3863   if (IsPairwise)
3864     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3865     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3866       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3867   else
3868     // Move the upper half of the vector to the lower half.
3869     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3870       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3871 
3872   return ConstantVector::get(ShuffleMask);
3873 }
3874 
3875 
3876 /// Model horizontal reductions.
3877 ///
3878 /// A horizontal reduction is a tree of reduction operations (currently add and
3879 /// fadd) that has operations that can be put into a vector as its leaf.
3880 /// For example, this tree:
3881 ///
3882 /// mul mul mul mul
3883 ///  \  /    \  /
3884 ///   +       +
3885 ///    \     /
3886 ///       +
3887 /// This tree has "mul" as its reduced values and "+" as its reduction
3888 /// operations. A reduction might be feeding into a store or a binary operation
3889 /// feeding a phi.
3890 ///    ...
3891 ///    \  /
3892 ///     +
3893 ///     |
3894 ///  phi +=
3895 ///
3896 ///  Or:
3897 ///    ...
3898 ///    \  /
3899 ///     +
3900 ///     |
3901 ///   *p =
3902 ///
3903 class HorizontalReduction {
3904   SmallVector<Value *, 16> ReductionOps;
3905   SmallVector<Value *, 32> ReducedVals;
3906 
3907   BinaryOperator *ReductionRoot;
3908   PHINode *ReductionPHI;
3909 
3910   /// The opcode of the reduction.
3911   unsigned ReductionOpcode;
3912   /// The opcode of the values we perform a reduction on.
3913   unsigned ReducedValueOpcode;
3914   /// Should we model this reduction as a pairwise reduction tree or a tree that
3915   /// splits the vector in halves and adds those halves.
3916   bool IsPairwiseReduction;
3917 
3918 public:
3919   /// The width of one full horizontal reduction operation.
3920   unsigned ReduxWidth;
3921 
3922   /// Minimal width of available vector registers. It's used to determine
3923   /// ReduxWidth.
3924   unsigned MinVecRegSize;
3925 
3926   HorizontalReduction(unsigned MinVecRegSize)
3927       : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3928         ReducedValueOpcode(0), IsPairwiseReduction(false), ReduxWidth(0),
3929         MinVecRegSize(MinVecRegSize) {}
3930 
3931   /// \brief Try to find a reduction tree.
3932   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
3933     assert((!Phi ||
3934             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3935            "Thi phi needs to use the binary operator");
3936 
3937     // We could have a initial reductions that is not an add.
3938     //  r *= v1 + v2 + v3 + v4
3939     // In such a case start looking for a tree rooted in the first '+'.
3940     if (Phi) {
3941       if (B->getOperand(0) == Phi) {
3942         Phi = nullptr;
3943         B = dyn_cast<BinaryOperator>(B->getOperand(1));
3944       } else if (B->getOperand(1) == Phi) {
3945         Phi = nullptr;
3946         B = dyn_cast<BinaryOperator>(B->getOperand(0));
3947       }
3948     }
3949 
3950     if (!B)
3951       return false;
3952 
3953     Type *Ty = B->getType();
3954     if (!isValidElementType(Ty))
3955       return false;
3956 
3957     const DataLayout &DL = B->getModule()->getDataLayout();
3958     ReductionOpcode = B->getOpcode();
3959     ReducedValueOpcode = 0;
3960     // FIXME: Register size should be a parameter to this function, so we can
3961     // try different vectorization factors.
3962     ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
3963     ReductionRoot = B;
3964     ReductionPHI = Phi;
3965 
3966     if (ReduxWidth < 4)
3967       return false;
3968 
3969     // We currently only support adds.
3970     if (ReductionOpcode != Instruction::Add &&
3971         ReductionOpcode != Instruction::FAdd)
3972       return false;
3973 
3974     // Post order traverse the reduction tree starting at B. We only handle true
3975     // trees containing only binary operators or selects.
3976     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
3977     Stack.push_back(std::make_pair(B, 0));
3978     while (!Stack.empty()) {
3979       Instruction *TreeN = Stack.back().first;
3980       unsigned EdgeToVist = Stack.back().second++;
3981       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3982 
3983       // Only handle trees in the current basic block.
3984       if (TreeN->getParent() != B->getParent())
3985         return false;
3986 
3987       // Each tree node needs to have one user except for the ultimate
3988       // reduction.
3989       if (!TreeN->hasOneUse() && TreeN != B)
3990         return false;
3991 
3992       // Postorder vist.
3993       if (EdgeToVist == 2 || IsReducedValue) {
3994         if (IsReducedValue) {
3995           // Make sure that the opcodes of the operations that we are going to
3996           // reduce match.
3997           if (!ReducedValueOpcode)
3998             ReducedValueOpcode = TreeN->getOpcode();
3999           else if (ReducedValueOpcode != TreeN->getOpcode())
4000             return false;
4001           ReducedVals.push_back(TreeN);
4002         } else {
4003           // We need to be able to reassociate the adds.
4004           if (!TreeN->isAssociative())
4005             return false;
4006           ReductionOps.push_back(TreeN);
4007         }
4008         // Retract.
4009         Stack.pop_back();
4010         continue;
4011       }
4012 
4013       // Visit left or right.
4014       Value *NextV = TreeN->getOperand(EdgeToVist);
4015       // We currently only allow BinaryOperator's and SelectInst's as reduction
4016       // values in our tree.
4017       if (isa<BinaryOperator>(NextV) || isa<SelectInst>(NextV))
4018         Stack.push_back(std::make_pair(cast<Instruction>(NextV), 0));
4019       else if (NextV != Phi)
4020         return false;
4021     }
4022     return true;
4023   }
4024 
4025   /// \brief Attempt to vectorize the tree found by
4026   /// matchAssociativeReduction.
4027   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4028     if (ReducedVals.empty())
4029       return false;
4030 
4031     unsigned NumReducedVals = ReducedVals.size();
4032     if (NumReducedVals < ReduxWidth)
4033       return false;
4034 
4035     Value *VectorizedTree = nullptr;
4036     IRBuilder<> Builder(ReductionRoot);
4037     FastMathFlags Unsafe;
4038     Unsafe.setUnsafeAlgebra();
4039     Builder.setFastMathFlags(Unsafe);
4040     unsigned i = 0;
4041 
4042     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
4043       V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
4044       V.computeMinimumValueSizes();
4045 
4046       // Estimate cost.
4047       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
4048       if (Cost >= -SLPCostThreshold)
4049         break;
4050 
4051       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4052                    << ". (HorRdx)\n");
4053 
4054       // Vectorize a tree.
4055       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4056       Value *VectorizedRoot = V.vectorizeTree();
4057 
4058       // Emit a reduction.
4059       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
4060       if (VectorizedTree) {
4061         Builder.SetCurrentDebugLocation(Loc);
4062         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4063                                      ReducedSubTree, "bin.rdx");
4064       } else
4065         VectorizedTree = ReducedSubTree;
4066     }
4067 
4068     if (VectorizedTree) {
4069       // Finish the reduction.
4070       for (; i < NumReducedVals; ++i) {
4071         Builder.SetCurrentDebugLocation(
4072           cast<Instruction>(ReducedVals[i])->getDebugLoc());
4073         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4074                                      ReducedVals[i]);
4075       }
4076       // Update users.
4077       if (ReductionPHI) {
4078         assert(ReductionRoot && "Need a reduction operation");
4079         ReductionRoot->setOperand(0, VectorizedTree);
4080         ReductionRoot->setOperand(1, ReductionPHI);
4081       } else
4082         ReductionRoot->replaceAllUsesWith(VectorizedTree);
4083     }
4084     return VectorizedTree != nullptr;
4085   }
4086 
4087   unsigned numReductionValues() const {
4088     return ReducedVals.size();
4089   }
4090 
4091 private:
4092   /// \brief Calculate the cost of a reduction.
4093   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
4094     Type *ScalarTy = FirstReducedVal->getType();
4095     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4096 
4097     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4098     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4099 
4100     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4101     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4102 
4103     int ScalarReduxCost =
4104         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
4105 
4106     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4107                  << " for reduction that starts with " << *FirstReducedVal
4108                  << " (It is a "
4109                  << (IsPairwiseReduction ? "pairwise" : "splitting")
4110                  << " reduction)\n");
4111 
4112     return VecReduxCost - ScalarReduxCost;
4113   }
4114 
4115   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
4116                             Value *R, const Twine &Name = "") {
4117     if (Opcode == Instruction::FAdd)
4118       return Builder.CreateFAdd(L, R, Name);
4119     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
4120   }
4121 
4122   /// \brief Emit a horizontal reduction of the vectorized value.
4123   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
4124     assert(VectorizedValue && "Need to have a vectorized tree node");
4125     assert(isPowerOf2_32(ReduxWidth) &&
4126            "We only handle power-of-two reductions for now");
4127 
4128     Value *TmpVec = VectorizedValue;
4129     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4130       if (IsPairwiseReduction) {
4131         Value *LeftMask =
4132           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4133         Value *RightMask =
4134           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4135 
4136         Value *LeftShuf = Builder.CreateShuffleVector(
4137           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4138         Value *RightShuf = Builder.CreateShuffleVector(
4139           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4140           "rdx.shuf.r");
4141         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
4142                              "bin.rdx");
4143       } else {
4144         Value *UpperHalf =
4145           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
4146         Value *Shuf = Builder.CreateShuffleVector(
4147           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
4148         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
4149       }
4150     }
4151 
4152     // The result is in the first element of the vector.
4153     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4154   }
4155 };
4156 
4157 /// \brief Recognize construction of vectors like
4158 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
4159 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
4160 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
4161 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
4162 ///
4163 /// Returns true if it matches
4164 ///
4165 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4166                             SmallVectorImpl<Value *> &BuildVector,
4167                             SmallVectorImpl<Value *> &BuildVectorOpds) {
4168   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4169     return false;
4170 
4171   InsertElementInst *IE = FirstInsertElem;
4172   while (true) {
4173     BuildVector.push_back(IE);
4174     BuildVectorOpds.push_back(IE->getOperand(1));
4175 
4176     if (IE->use_empty())
4177       return false;
4178 
4179     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4180     if (!NextUse)
4181       return true;
4182 
4183     // If this isn't the final use, make sure the next insertelement is the only
4184     // use. It's OK if the final constructed vector is used multiple times
4185     if (!IE->hasOneUse())
4186       return false;
4187 
4188     IE = NextUse;
4189   }
4190 
4191   return false;
4192 }
4193 
4194 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4195   return V->getType() < V2->getType();
4196 }
4197 
4198 /// \brief Try and get a reduction value from a phi node.
4199 ///
4200 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4201 /// if they come from either \p ParentBB or a containing loop latch.
4202 ///
4203 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4204 /// if not possible.
4205 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4206                                 BasicBlock *ParentBB, LoopInfo *LI) {
4207   // There are situations where the reduction value is not dominated by the
4208   // reduction phi. Vectorizing such cases has been reported to cause
4209   // miscompiles. See PR25787.
4210   auto DominatedReduxValue = [&](Value *R) {
4211     return (
4212         dyn_cast<Instruction>(R) &&
4213         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4214   };
4215 
4216   Value *Rdx = nullptr;
4217 
4218   // Return the incoming value if it comes from the same BB as the phi node.
4219   if (P->getIncomingBlock(0) == ParentBB) {
4220     Rdx = P->getIncomingValue(0);
4221   } else if (P->getIncomingBlock(1) == ParentBB) {
4222     Rdx = P->getIncomingValue(1);
4223   }
4224 
4225   if (Rdx && DominatedReduxValue(Rdx))
4226     return Rdx;
4227 
4228   // Otherwise, check whether we have a loop latch to look at.
4229   Loop *BBL = LI->getLoopFor(ParentBB);
4230   if (!BBL)
4231     return nullptr;
4232   BasicBlock *BBLatch = BBL->getLoopLatch();
4233   if (!BBLatch)
4234     return nullptr;
4235 
4236   // There is a loop latch, return the incoming value if it comes from
4237   // that. This reduction pattern occassionaly turns up.
4238   if (P->getIncomingBlock(0) == BBLatch) {
4239     Rdx = P->getIncomingValue(0);
4240   } else if (P->getIncomingBlock(1) == BBLatch) {
4241     Rdx = P->getIncomingValue(1);
4242   }
4243 
4244   if (Rdx && DominatedReduxValue(Rdx))
4245     return Rdx;
4246 
4247   return nullptr;
4248 }
4249 
4250 /// \brief Attempt to reduce a horizontal reduction.
4251 /// If it is legal to match a horizontal reduction feeding
4252 /// the phi node P with reduction operators BI, then check if it
4253 /// can be done.
4254 /// \returns true if a horizontal reduction was matched and reduced.
4255 /// \returns false if a horizontal reduction was not matched.
4256 static bool canMatchHorizontalReduction(PHINode *P, BinaryOperator *BI,
4257                                         BoUpSLP &R, TargetTransformInfo *TTI,
4258                                         unsigned MinRegSize) {
4259   if (!ShouldVectorizeHor)
4260     return false;
4261 
4262   HorizontalReduction HorRdx(MinRegSize);
4263   if (!HorRdx.matchAssociativeReduction(P, BI))
4264     return false;
4265 
4266   // If there is a sufficient number of reduction values, reduce
4267   // to a nearby power-of-2. Can safely generate oversized
4268   // vectors and rely on the backend to split them to legal sizes.
4269   HorRdx.ReduxWidth =
4270     std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
4271 
4272   return HorRdx.tryToReduce(R, TTI);
4273 }
4274 
4275 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4276   bool Changed = false;
4277   SmallVector<Value *, 4> Incoming;
4278   SmallSet<Value *, 16> VisitedInstrs;
4279 
4280   bool HaveVectorizedPhiNodes = true;
4281   while (HaveVectorizedPhiNodes) {
4282     HaveVectorizedPhiNodes = false;
4283 
4284     // Collect the incoming values from the PHIs.
4285     Incoming.clear();
4286     for (Instruction &I : *BB) {
4287       PHINode *P = dyn_cast<PHINode>(&I);
4288       if (!P)
4289         break;
4290 
4291       if (!VisitedInstrs.count(P))
4292         Incoming.push_back(P);
4293     }
4294 
4295     // Sort by type.
4296     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4297 
4298     // Try to vectorize elements base on their type.
4299     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4300                                            E = Incoming.end();
4301          IncIt != E;) {
4302 
4303       // Look for the next elements with the same type.
4304       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4305       while (SameTypeIt != E &&
4306              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4307         VisitedInstrs.insert(*SameTypeIt);
4308         ++SameTypeIt;
4309       }
4310 
4311       // Try to vectorize them.
4312       unsigned NumElts = (SameTypeIt - IncIt);
4313       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4314       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
4315         // Success start over because instructions might have been changed.
4316         HaveVectorizedPhiNodes = true;
4317         Changed = true;
4318         break;
4319       }
4320 
4321       // Start over at the next instruction of a different type (or the end).
4322       IncIt = SameTypeIt;
4323     }
4324   }
4325 
4326   VisitedInstrs.clear();
4327 
4328   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4329     // We may go through BB multiple times so skip the one we have checked.
4330     if (!VisitedInstrs.insert(&*it).second)
4331       continue;
4332 
4333     if (isa<DbgInfoIntrinsic>(it))
4334       continue;
4335 
4336     // Try to vectorize reductions that use PHINodes.
4337     if (PHINode *P = dyn_cast<PHINode>(it)) {
4338       // Check that the PHI is a reduction PHI.
4339       if (P->getNumIncomingValues() != 2)
4340         return Changed;
4341 
4342       Value *Rdx = getReductionValue(DT, P, BB, LI);
4343 
4344       // Check if this is a Binary Operator.
4345       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
4346       if (!BI)
4347         continue;
4348 
4349       // Try to match and vectorize a horizontal reduction.
4350       if (canMatchHorizontalReduction(P, BI, R, TTI, MinVecRegSize)) {
4351         Changed = true;
4352         it = BB->begin();
4353         e = BB->end();
4354         continue;
4355       }
4356 
4357      Value *Inst = BI->getOperand(0);
4358       if (Inst == P)
4359         Inst = BI->getOperand(1);
4360 
4361       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4362         // We would like to start over since some instructions are deleted
4363         // and the iterator may become invalid value.
4364         Changed = true;
4365         it = BB->begin();
4366         e = BB->end();
4367         continue;
4368       }
4369 
4370       continue;
4371     }
4372 
4373     if (ShouldStartVectorizeHorAtStore)
4374       if (StoreInst *SI = dyn_cast<StoreInst>(it))
4375         if (BinaryOperator *BinOp =
4376                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
4377           if (canMatchHorizontalReduction(nullptr, BinOp, R, TTI,
4378                                           MinVecRegSize) ||
4379               tryToVectorize(BinOp, R)) {
4380             Changed = true;
4381             it = BB->begin();
4382             e = BB->end();
4383             continue;
4384           }
4385         }
4386 
4387     // Try to vectorize horizontal reductions feeding into a return.
4388     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
4389       if (RI->getNumOperands() != 0)
4390         if (BinaryOperator *BinOp =
4391                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
4392           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
4393           if (tryToVectorizePair(BinOp->getOperand(0),
4394                                  BinOp->getOperand(1), R)) {
4395             Changed = true;
4396             it = BB->begin();
4397             e = BB->end();
4398             continue;
4399           }
4400         }
4401 
4402     // Try to vectorize trees that start at compare instructions.
4403     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4404       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4405         Changed = true;
4406         // We would like to start over since some instructions are deleted
4407         // and the iterator may become invalid value.
4408         it = BB->begin();
4409         e = BB->end();
4410         continue;
4411       }
4412 
4413       for (int i = 0; i < 2; ++i) {
4414         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
4415           if (tryToVectorizePair(BI->getOperand(0), BI->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             break;
4422           }
4423         }
4424       }
4425       continue;
4426     }
4427 
4428     // Try to vectorize trees that start at insertelement instructions.
4429     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4430       SmallVector<Value *, 16> BuildVector;
4431       SmallVector<Value *, 16> BuildVectorOpds;
4432       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4433         continue;
4434 
4435       // Vectorize starting with the build vector operands ignoring the
4436       // BuildVector instructions for the purpose of scheduling and user
4437       // extraction.
4438       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
4439         Changed = true;
4440         it = BB->begin();
4441         e = BB->end();
4442       }
4443 
4444       continue;
4445     }
4446   }
4447 
4448   return Changed;
4449 }
4450 
4451 bool SLPVectorizer::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
4452   auto Changed = false;
4453   for (auto &Entry : GEPs) {
4454 
4455     // If the getelementptr list has fewer than two elements, there's nothing
4456     // to do.
4457     if (Entry.second.size() < 2)
4458       continue;
4459 
4460     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
4461                  << Entry.second.size() << ".\n");
4462 
4463     // We process the getelementptr list in chunks of 16 (like we do for
4464     // stores) to minimize compile-time.
4465     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
4466       auto Len = std::min<unsigned>(BE - BI, 16);
4467       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
4468 
4469       // Initialize a set a candidate getelementptrs. Note that we use a
4470       // SetVector here to preserve program order. If the index computations
4471       // are vectorizable and begin with loads, we want to minimize the chance
4472       // of having to reorder them later.
4473       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
4474 
4475       // Some of the candidates may have already been vectorized after we
4476       // initially collected them. If so, the WeakVHs will have nullified the
4477       // values, so remove them from the set of candidates.
4478       Candidates.remove(nullptr);
4479 
4480       // Remove from the set of candidates all pairs of getelementptrs with
4481       // constant differences. Such getelementptrs are likely not good
4482       // candidates for vectorization in a bottom-up phase since one can be
4483       // computed from the other. We also ensure all candidate getelementptr
4484       // indices are unique.
4485       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
4486         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
4487         if (!Candidates.count(GEPI))
4488           continue;
4489         auto *SCEVI = SE->getSCEV(GEPList[I]);
4490         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
4491           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
4492           auto *SCEVJ = SE->getSCEV(GEPList[J]);
4493           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
4494             Candidates.remove(GEPList[I]);
4495             Candidates.remove(GEPList[J]);
4496           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
4497             Candidates.remove(GEPList[J]);
4498           }
4499         }
4500       }
4501 
4502       // We break out of the above computation as soon as we know there are
4503       // fewer than two candidates remaining.
4504       if (Candidates.size() < 2)
4505         continue;
4506 
4507       // Add the single, non-constant index of each candidate to the bundle. We
4508       // ensured the indices met these constraints when we originally collected
4509       // the getelementptrs.
4510       SmallVector<Value *, 16> Bundle(Candidates.size());
4511       auto BundleIndex = 0u;
4512       for (auto *V : Candidates) {
4513         auto *GEP = cast<GetElementPtrInst>(V);
4514         auto *GEPIdx = GEP->idx_begin()->get();
4515         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
4516         Bundle[BundleIndex++] = GEPIdx;
4517       }
4518 
4519       // Try and vectorize the indices. We are currently only interested in
4520       // gather-like cases of the form:
4521       //
4522       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
4523       //
4524       // where the loads of "a", the loads of "b", and the subtractions can be
4525       // performed in parallel. It's likely that detecting this pattern in a
4526       // bottom-up phase will be simpler and less costly than building a
4527       // full-blown top-down phase beginning at the consecutive loads.
4528       Changed |= tryToVectorizeList(Bundle, R);
4529     }
4530   }
4531   return Changed;
4532 }
4533 
4534 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
4535   bool Changed = false;
4536   // Attempt to sort and vectorize each of the store-groups.
4537   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
4538        ++it) {
4539     if (it->second.size() < 2)
4540       continue;
4541 
4542     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
4543           << it->second.size() << ".\n");
4544 
4545     // Process the stores in chunks of 16.
4546     // TODO: The limit of 16 inhibits greater vectorization factors.
4547     //       For example, AVX2 supports v32i8. Increasing this limit, however,
4548     //       may cause a significant compile-time increase.
4549     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
4550       unsigned Len = std::min<unsigned>(CE - CI, 16);
4551       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
4552                                  -SLPCostThreshold, R);
4553     }
4554   }
4555   return Changed;
4556 }
4557 
4558 } // end anonymous namespace
4559 
4560 char SLPVectorizer::ID = 0;
4561 static const char lv_name[] = "SLP Vectorizer";
4562 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
4563 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4564 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4565 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4566 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
4567 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4568 INITIALIZE_PASS_DEPENDENCY(DemandedBits)
4569 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
4570 
4571 namespace llvm {
4572 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
4573 }
4574