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