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