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 static cl::opt<unsigned> RecursionMaxDepth(
86     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
87     cl::desc("Limit the recursion depth when building a vectorizable tree"));
88 
89 // Limit the number of alias checks. The limit is chosen so that
90 // it has no negative effect on the llvm benchmarks.
91 static const unsigned AliasedCheckLimit = 10;
92 
93 // Another limit for the alias checks: The maximum distance between load/store
94 // instructions where alias checks are done.
95 // This limit is useful for very large basic blocks.
96 static const unsigned MaxMemDepDistance = 160;
97 
98 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
99 /// regions to be handled.
100 static const int MinScheduleRegionSize = 16;
101 
102 /// \brief Predicate for the element types that the SLP vectorizer supports.
103 ///
104 /// The most important thing to filter here are types which are invalid in LLVM
105 /// vectors. We also filter target specific types which have absolutely no
106 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
107 /// avoids spending time checking the cost model and realizing that they will
108 /// be inevitably scalarized.
109 static bool isValidElementType(Type *Ty) {
110   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
111          !Ty->isPPC_FP128Ty();
112 }
113 
114 /// \returns the parent basic block if all of the instructions in \p VL
115 /// are in the same block or null otherwise.
116 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
117   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
118   if (!I0)
119     return nullptr;
120   BasicBlock *BB = I0->getParent();
121   for (int i = 1, e = VL.size(); i < e; i++) {
122     Instruction *I = dyn_cast<Instruction>(VL[i]);
123     if (!I)
124       return nullptr;
125 
126     if (BB != I->getParent())
127       return nullptr;
128   }
129   return BB;
130 }
131 
132 /// \returns True if all of the values in \p VL are constants.
133 static bool allConstant(ArrayRef<Value *> VL) {
134   for (Value *i : VL)
135     if (!isa<Constant>(i))
136       return false;
137   return true;
138 }
139 
140 /// \returns True if all of the values in \p VL are identical.
141 static bool isSplat(ArrayRef<Value *> VL) {
142   for (unsigned i = 1, e = VL.size(); i < e; ++i)
143     if (VL[i] != VL[0])
144       return false;
145   return true;
146 }
147 
148 ///\returns Opcode that can be clubbed with \p Op to create an alternate
149 /// sequence which can later be merged as a ShuffleVector instruction.
150 static unsigned getAltOpcode(unsigned Op) {
151   switch (Op) {
152   case Instruction::FAdd:
153     return Instruction::FSub;
154   case Instruction::FSub:
155     return Instruction::FAdd;
156   case Instruction::Add:
157     return Instruction::Sub;
158   case Instruction::Sub:
159     return Instruction::Add;
160   default:
161     return 0;
162   }
163 }
164 
165 ///\returns bool representing if Opcode \p Op can be part
166 /// of an alternate sequence which can later be merged as
167 /// a ShuffleVector instruction.
168 static bool canCombineAsAltInst(unsigned Op) {
169   return Op == Instruction::FAdd || Op == Instruction::FSub ||
170          Op == Instruction::Sub || Op == Instruction::Add;
171 }
172 
173 /// \returns ShuffleVector instruction if instructions in \p VL have
174 ///  alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
175 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
176 static unsigned isAltInst(ArrayRef<Value *> VL) {
177   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
178   unsigned Opcode = I0->getOpcode();
179   unsigned AltOpcode = getAltOpcode(Opcode);
180   for (int i = 1, e = VL.size(); i < e; i++) {
181     Instruction *I = dyn_cast<Instruction>(VL[i]);
182     if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
183       return 0;
184   }
185   return Instruction::ShuffleVector;
186 }
187 
188 /// \returns The opcode if all of the Instructions in \p VL have the same
189 /// opcode, or zero.
190 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
191   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
192   if (!I0)
193     return 0;
194   unsigned Opcode = I0->getOpcode();
195   for (int i = 1, e = VL.size(); i < e; i++) {
196     Instruction *I = dyn_cast<Instruction>(VL[i]);
197     if (!I || Opcode != I->getOpcode()) {
198       if (canCombineAsAltInst(Opcode) && i == 1)
199         return isAltInst(VL);
200       return 0;
201     }
202   }
203   return Opcode;
204 }
205 
206 /// Get the intersection (logical and) of all of the potential IR flags
207 /// of each scalar operation (VL) that will be converted into a vector (I).
208 /// Flag set: NSW, NUW, exact, and all of fast-math.
209 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
210   if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
211     if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
212       // Intersection is initialized to the 0th scalar,
213       // so start counting from index '1'.
214       for (int i = 1, e = VL.size(); i < e; ++i) {
215         if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
216           Intersection->andIRFlags(Scalar);
217       }
218       VecOp->copyIRFlags(Intersection);
219     }
220   }
221 }
222 
223 /// \returns The type that all of the values in \p VL have or null if there
224 /// are different types.
225 static Type* getSameType(ArrayRef<Value *> VL) {
226   Type *Ty = VL[0]->getType();
227   for (int i = 1, e = VL.size(); i < e; i++)
228     if (VL[i]->getType() != Ty)
229       return nullptr;
230 
231   return Ty;
232 }
233 
234 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
235 static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
236   assert(Opcode == Instruction::ExtractElement ||
237          Opcode == Instruction::ExtractValue);
238   if (Opcode == Instruction::ExtractElement) {
239     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
240     return CI && CI->getZExtValue() == Idx;
241   } else {
242     ExtractValueInst *EI = cast<ExtractValueInst>(E);
243     return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
244   }
245 }
246 
247 /// \returns True if in-tree use also needs extract. This refers to
248 /// possible scalar operand in vectorized instruction.
249 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
250                                     TargetLibraryInfo *TLI) {
251 
252   unsigned Opcode = UserInst->getOpcode();
253   switch (Opcode) {
254   case Instruction::Load: {
255     LoadInst *LI = cast<LoadInst>(UserInst);
256     return (LI->getPointerOperand() == Scalar);
257   }
258   case Instruction::Store: {
259     StoreInst *SI = cast<StoreInst>(UserInst);
260     return (SI->getPointerOperand() == Scalar);
261   }
262   case Instruction::Call: {
263     CallInst *CI = cast<CallInst>(UserInst);
264     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
265     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
266       return (CI->getArgOperand(1) == Scalar);
267     }
268   }
269   default:
270     return false;
271   }
272 }
273 
274 /// \returns the AA location that is being access by the instruction.
275 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
276   if (StoreInst *SI = dyn_cast<StoreInst>(I))
277     return MemoryLocation::get(SI);
278   if (LoadInst *LI = dyn_cast<LoadInst>(I))
279     return MemoryLocation::get(LI);
280   return MemoryLocation();
281 }
282 
283 /// \returns True if the instruction is not a volatile or atomic load/store.
284 static bool isSimple(Instruction *I) {
285   if (LoadInst *LI = dyn_cast<LoadInst>(I))
286     return LI->isSimple();
287   if (StoreInst *SI = dyn_cast<StoreInst>(I))
288     return SI->isSimple();
289   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
290     return !MI->isVolatile();
291   return true;
292 }
293 
294 namespace llvm {
295 namespace slpvectorizer {
296 /// Bottom Up SLP Vectorizer.
297 class BoUpSLP {
298 public:
299   typedef SmallVector<Value *, 8> ValueList;
300   typedef SmallVector<Instruction *, 16> InstrList;
301   typedef SmallPtrSet<Value *, 16> ValueSet;
302   typedef SmallVector<StoreInst *, 8> StoreList;
303 
304   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
305           TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
306           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
307           const DataLayout *DL)
308       : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
309         SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
310         DL(DL), Builder(Se->getContext()) {
311     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
312     // Use the vector register size specified by the target unless overridden
313     // by a command-line option.
314     // TODO: It would be better to limit the vectorization factor based on
315     //       data type rather than just register size. For example, x86 AVX has
316     //       256-bit registers, but it does not support integer operations
317     //       at that width (that requires AVX2).
318     if (MaxVectorRegSizeOption.getNumOccurrences())
319       MaxVecRegSize = MaxVectorRegSizeOption;
320     else
321       MaxVecRegSize = TTI->getRegisterBitWidth(true);
322 
323     MinVecRegSize = MinVectorRegSizeOption;
324   }
325 
326   /// \brief Vectorize the tree that starts with the elements in \p VL.
327   /// Returns the vectorized root.
328   Value *vectorizeTree();
329 
330   /// \returns the cost incurred by unwanted spills and fills, caused by
331   /// holding live values over call sites.
332   int getSpillCost();
333 
334   /// \returns the vectorization cost of the subtree that starts at \p VL.
335   /// A negative number means that this is profitable.
336   int getTreeCost();
337 
338   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
339   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
340   void buildTree(ArrayRef<Value *> Roots,
341                  ArrayRef<Value *> UserIgnoreLst = None);
342 
343   /// Clear the internal data structures that are created by 'buildTree'.
344   void deleteTree() {
345     VectorizableTree.clear();
346     ScalarToTreeEntry.clear();
347     MustGather.clear();
348     ExternalUses.clear();
349     NumLoadsWantToKeepOrder = 0;
350     NumLoadsWantToChangeOrder = 0;
351     for (auto &Iter : BlocksSchedules) {
352       BlockScheduling *BS = Iter.second.get();
353       BS->clear();
354     }
355     MinBWs.clear();
356   }
357 
358   /// \brief Perform LICM and CSE on the newly generated gather sequences.
359   void optimizeGatherSequence();
360 
361   /// \returns true if it is beneficial to reverse the vector order.
362   bool shouldReorder() const {
363     return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
364   }
365 
366   /// \return The vector element size in bits to use when vectorizing the
367   /// expression tree ending at \p V. If V is a store, the size is the width of
368   /// the stored value. Otherwise, the size is the width of the largest loaded
369   /// value reaching V. This method is used by the vectorizer to calculate
370   /// vectorization factors.
371   unsigned getVectorElementSize(Value *V);
372 
373   /// Compute the minimum type sizes required to represent the entries in a
374   /// vectorizable tree.
375   void computeMinimumValueSizes();
376 
377   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
378   unsigned getMaxVecRegSize() const {
379     return MaxVecRegSize;
380   }
381 
382   // \returns minimum vector register size as set by cl::opt.
383   unsigned getMinVecRegSize() const {
384     return MinVecRegSize;
385   }
386 
387   /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
388   ///
389   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
390   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
391 
392 private:
393   struct TreeEntry;
394 
395   /// \returns the cost of the vectorizable entry.
396   int getEntryCost(TreeEntry *E);
397 
398   /// This is the recursive part of buildTree.
399   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
400 
401   /// \returns True if the ExtractElement/ExtractValue instructions in VL can
402   /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
403   bool canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const;
404 
405   /// Vectorize a single entry in the tree.
406   Value *vectorizeTree(TreeEntry *E);
407 
408   /// Vectorize a single entry in the tree, starting in \p VL.
409   Value *vectorizeTree(ArrayRef<Value *> VL);
410 
411   /// \returns the pointer to the vectorized value if \p VL is already
412   /// vectorized, or NULL. They may happen in cycles.
413   Value *alreadyVectorized(ArrayRef<Value *> VL) const;
414 
415   /// \returns the scalarization cost for this type. Scalarization in this
416   /// context means the creation of vectors from a group of scalars.
417   int getGatherCost(Type *Ty);
418 
419   /// \returns the scalarization cost for this list of values. Assuming that
420   /// this subtree gets vectorized, we may need to extract the values from the
421   /// roots. This method calculates the cost of extracting the values.
422   int getGatherCost(ArrayRef<Value *> VL);
423 
424   /// \brief Set the Builder insert point to one after the last instruction in
425   /// the bundle
426   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
427 
428   /// \returns a vector from a collection of scalars in \p VL.
429   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
430 
431   /// \returns whether the VectorizableTree is fully vectorizable and will
432   /// be beneficial even the tree height is tiny.
433   bool isFullyVectorizableTinyTree();
434 
435   /// \reorder commutative operands in alt shuffle if they result in
436   ///  vectorized code.
437   void reorderAltShuffleOperands(ArrayRef<Value *> VL,
438                                  SmallVectorImpl<Value *> &Left,
439                                  SmallVectorImpl<Value *> &Right);
440   /// \reorder commutative operands to get better probability of
441   /// generating vectorized code.
442   void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
443                                       SmallVectorImpl<Value *> &Left,
444                                       SmallVectorImpl<Value *> &Right);
445   struct TreeEntry {
446     TreeEntry() : Scalars(), VectorizedValue(nullptr),
447     NeedToGather(0) {}
448 
449     /// \returns true if the scalars in VL are equal to this entry.
450     bool isSame(ArrayRef<Value *> VL) const {
451       assert(VL.size() == Scalars.size() && "Invalid size");
452       return std::equal(VL.begin(), VL.end(), Scalars.begin());
453     }
454 
455     /// A vector of scalars.
456     ValueList Scalars;
457 
458     /// The Scalars are vectorized into this value. It is initialized to Null.
459     Value *VectorizedValue;
460 
461     /// Do we need to gather this sequence ?
462     bool NeedToGather;
463   };
464 
465   /// Create a new VectorizableTree entry.
466   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
467     VectorizableTree.emplace_back();
468     int idx = VectorizableTree.size() - 1;
469     TreeEntry *Last = &VectorizableTree[idx];
470     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
471     Last->NeedToGather = !Vectorized;
472     if (Vectorized) {
473       for (int i = 0, e = VL.size(); i != e; ++i) {
474         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
475         ScalarToTreeEntry[VL[i]] = idx;
476       }
477     } else {
478       MustGather.insert(VL.begin(), VL.end());
479     }
480     return Last;
481   }
482 
483   /// -- Vectorization State --
484   /// Holds all of the tree entries.
485   std::vector<TreeEntry> VectorizableTree;
486 
487   /// Maps a specific scalar to its tree entry.
488   SmallDenseMap<Value*, int> ScalarToTreeEntry;
489 
490   /// A list of scalars that we found that we need to keep as scalars.
491   ValueSet MustGather;
492 
493   /// This POD struct describes one external user in the vectorized tree.
494   struct ExternalUser {
495     ExternalUser (Value *S, llvm::User *U, int L) :
496       Scalar(S), User(U), Lane(L){}
497     // Which scalar in our function.
498     Value *Scalar;
499     // Which user that uses the scalar.
500     llvm::User *User;
501     // Which lane does the scalar belong to.
502     int Lane;
503   };
504   typedef SmallVector<ExternalUser, 16> UserList;
505 
506   /// Checks if two instructions may access the same memory.
507   ///
508   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
509   /// is invariant in the calling loop.
510   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
511                  Instruction *Inst2) {
512 
513     // First check if the result is already in the cache.
514     AliasCacheKey key = std::make_pair(Inst1, Inst2);
515     Optional<bool> &result = AliasCache[key];
516     if (result.hasValue()) {
517       return result.getValue();
518     }
519     MemoryLocation Loc2 = getLocation(Inst2, AA);
520     bool aliased = true;
521     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
522       // Do the alias check.
523       aliased = AA->alias(Loc1, Loc2);
524     }
525     // Store the result in the cache.
526     result = aliased;
527     return aliased;
528   }
529 
530   typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
531 
532   /// Cache for alias results.
533   /// TODO: consider moving this to the AliasAnalysis itself.
534   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
535 
536   /// Removes an instruction from its block and eventually deletes it.
537   /// It's like Instruction::eraseFromParent() except that the actual deletion
538   /// is delayed until BoUpSLP is destructed.
539   /// This is required to ensure that there are no incorrect collisions in the
540   /// AliasCache, which can happen if a new instruction is allocated at the
541   /// same address as a previously deleted instruction.
542   void eraseInstruction(Instruction *I) {
543     I->removeFromParent();
544     I->dropAllReferences();
545     DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
546   }
547 
548   /// Temporary store for deleted instructions. Instructions will be deleted
549   /// eventually when the BoUpSLP is destructed.
550   SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
551 
552   /// A list of values that need to extracted out of the tree.
553   /// This list holds pairs of (Internal Scalar : External User).
554   UserList ExternalUses;
555 
556   /// Values used only by @llvm.assume calls.
557   SmallPtrSet<const Value *, 32> EphValues;
558 
559   /// Holds all of the instructions that we gathered.
560   SetVector<Instruction *> GatherSeq;
561   /// A list of blocks that we are going to CSE.
562   SetVector<BasicBlock *> CSEBlocks;
563 
564   /// Contains all scheduling relevant data for an instruction.
565   /// A ScheduleData either represents a single instruction or a member of an
566   /// instruction bundle (= a group of instructions which is combined into a
567   /// vector instruction).
568   struct ScheduleData {
569 
570     // The initial value for the dependency counters. It means that the
571     // dependencies are not calculated yet.
572     enum { InvalidDeps = -1 };
573 
574     ScheduleData()
575         : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
576           NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
577           Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
578           UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
579 
580     void init(int BlockSchedulingRegionID) {
581       FirstInBundle = this;
582       NextInBundle = nullptr;
583       NextLoadStore = nullptr;
584       IsScheduled = false;
585       SchedulingRegionID = BlockSchedulingRegionID;
586       UnscheduledDepsInBundle = UnscheduledDeps;
587       clearDependencies();
588     }
589 
590     /// Returns true if the dependency information has been calculated.
591     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
592 
593     /// Returns true for single instructions and for bundle representatives
594     /// (= the head of a bundle).
595     bool isSchedulingEntity() const { return FirstInBundle == this; }
596 
597     /// Returns true if it represents an instruction bundle and not only a
598     /// single instruction.
599     bool isPartOfBundle() const {
600       return NextInBundle != nullptr || FirstInBundle != this;
601     }
602 
603     /// Returns true if it is ready for scheduling, i.e. it has no more
604     /// unscheduled depending instructions/bundles.
605     bool isReady() const {
606       assert(isSchedulingEntity() &&
607              "can't consider non-scheduling entity for ready list");
608       return UnscheduledDepsInBundle == 0 && !IsScheduled;
609     }
610 
611     /// Modifies the number of unscheduled dependencies, also updating it for
612     /// the whole bundle.
613     int incrementUnscheduledDeps(int Incr) {
614       UnscheduledDeps += Incr;
615       return FirstInBundle->UnscheduledDepsInBundle += Incr;
616     }
617 
618     /// Sets the number of unscheduled dependencies to the number of
619     /// dependencies.
620     void resetUnscheduledDeps() {
621       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
622     }
623 
624     /// Clears all dependency information.
625     void clearDependencies() {
626       Dependencies = InvalidDeps;
627       resetUnscheduledDeps();
628       MemoryDependencies.clear();
629     }
630 
631     void dump(raw_ostream &os) const {
632       if (!isSchedulingEntity()) {
633         os << "/ " << *Inst;
634       } else if (NextInBundle) {
635         os << '[' << *Inst;
636         ScheduleData *SD = NextInBundle;
637         while (SD) {
638           os << ';' << *SD->Inst;
639           SD = SD->NextInBundle;
640         }
641         os << ']';
642       } else {
643         os << *Inst;
644       }
645     }
646 
647     Instruction *Inst;
648 
649     /// Points to the head in an instruction bundle (and always to this for
650     /// single instructions).
651     ScheduleData *FirstInBundle;
652 
653     /// Single linked list of all instructions in a bundle. Null if it is a
654     /// single instruction.
655     ScheduleData *NextInBundle;
656 
657     /// Single linked list of all memory instructions (e.g. load, store, call)
658     /// in the block - until the end of the scheduling region.
659     ScheduleData *NextLoadStore;
660 
661     /// The dependent memory instructions.
662     /// This list is derived on demand in calculateDependencies().
663     SmallVector<ScheduleData *, 4> MemoryDependencies;
664 
665     /// This ScheduleData is in the current scheduling region if this matches
666     /// the current SchedulingRegionID of BlockScheduling.
667     int SchedulingRegionID;
668 
669     /// Used for getting a "good" final ordering of instructions.
670     int SchedulingPriority;
671 
672     /// The number of dependencies. Constitutes of the number of users of the
673     /// instruction plus the number of dependent memory instructions (if any).
674     /// This value is calculated on demand.
675     /// If InvalidDeps, the number of dependencies is not calculated yet.
676     ///
677     int Dependencies;
678 
679     /// The number of dependencies minus the number of dependencies of scheduled
680     /// instructions. As soon as this is zero, the instruction/bundle gets ready
681     /// for scheduling.
682     /// Note that this is negative as long as Dependencies is not calculated.
683     int UnscheduledDeps;
684 
685     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
686     /// single instructions.
687     int UnscheduledDepsInBundle;
688 
689     /// True if this instruction is scheduled (or considered as scheduled in the
690     /// dry-run).
691     bool IsScheduled;
692   };
693 
694 #ifndef NDEBUG
695   friend inline raw_ostream &operator<<(raw_ostream &os,
696                                         const BoUpSLP::ScheduleData &SD) {
697     SD.dump(os);
698     return os;
699   }
700 #endif
701 
702   /// Contains all scheduling data for a basic block.
703   ///
704   struct BlockScheduling {
705 
706     BlockScheduling(BasicBlock *BB)
707         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
708           ScheduleStart(nullptr), ScheduleEnd(nullptr),
709           FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
710           ScheduleRegionSize(0),
711           ScheduleRegionSizeLimit(ScheduleRegionSizeBudget),
712           // Make sure that the initial SchedulingRegionID is greater than the
713           // initial SchedulingRegionID in ScheduleData (which is 0).
714           SchedulingRegionID(1) {}
715 
716     void clear() {
717       ReadyInsts.clear();
718       ScheduleStart = nullptr;
719       ScheduleEnd = nullptr;
720       FirstLoadStoreInRegion = nullptr;
721       LastLoadStoreInRegion = nullptr;
722 
723       // Reduce the maximum schedule region size by the size of the
724       // previous scheduling run.
725       ScheduleRegionSizeLimit -= ScheduleRegionSize;
726       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
727         ScheduleRegionSizeLimit = MinScheduleRegionSize;
728       ScheduleRegionSize = 0;
729 
730       // Make a new scheduling region, i.e. all existing ScheduleData is not
731       // in the new region yet.
732       ++SchedulingRegionID;
733     }
734 
735     ScheduleData *getScheduleData(Value *V) {
736       ScheduleData *SD = ScheduleDataMap[V];
737       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
738         return SD;
739       return nullptr;
740     }
741 
742     bool isInSchedulingRegion(ScheduleData *SD) {
743       return SD->SchedulingRegionID == SchedulingRegionID;
744     }
745 
746     /// Marks an instruction as scheduled and puts all dependent ready
747     /// instructions into the ready-list.
748     template <typename ReadyListType>
749     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
750       SD->IsScheduled = true;
751       DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
752 
753       ScheduleData *BundleMember = SD;
754       while (BundleMember) {
755         // Handle the def-use chain dependencies.
756         for (Use &U : BundleMember->Inst->operands()) {
757           ScheduleData *OpDef = getScheduleData(U.get());
758           if (OpDef && OpDef->hasValidDependencies() &&
759               OpDef->incrementUnscheduledDeps(-1) == 0) {
760             // There are no more unscheduled dependencies after decrementing,
761             // so we can put the dependent instruction into the ready list.
762             ScheduleData *DepBundle = OpDef->FirstInBundle;
763             assert(!DepBundle->IsScheduled &&
764                    "already scheduled bundle gets ready");
765             ReadyList.insert(DepBundle);
766             DEBUG(dbgs() << "SLP:    gets ready (def): " << *DepBundle << "\n");
767           }
768         }
769         // Handle the memory dependencies.
770         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
771           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
772             // There are no more unscheduled dependencies after decrementing,
773             // so we can put the dependent instruction into the ready list.
774             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
775             assert(!DepBundle->IsScheduled &&
776                    "already scheduled bundle gets ready");
777             ReadyList.insert(DepBundle);
778             DEBUG(dbgs() << "SLP:    gets ready (mem): " << *DepBundle << "\n");
779           }
780         }
781         BundleMember = BundleMember->NextInBundle;
782       }
783     }
784 
785     /// Put all instructions into the ReadyList which are ready for scheduling.
786     template <typename ReadyListType>
787     void initialFillReadyList(ReadyListType &ReadyList) {
788       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
789         ScheduleData *SD = getScheduleData(I);
790         if (SD->isSchedulingEntity() && SD->isReady()) {
791           ReadyList.insert(SD);
792           DEBUG(dbgs() << "SLP:    initially in ready list: " << *I << "\n");
793         }
794       }
795     }
796 
797     /// Checks if a bundle of instructions can be scheduled, i.e. has no
798     /// cyclic dependencies. This is only a dry-run, no instructions are
799     /// actually moved at this stage.
800     bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
801 
802     /// Un-bundles a group of instructions.
803     void cancelScheduling(ArrayRef<Value *> VL);
804 
805     /// Extends the scheduling region so that V is inside the region.
806     /// \returns true if the region size is within the limit.
807     bool extendSchedulingRegion(Value *V);
808 
809     /// Initialize the ScheduleData structures for new instructions in the
810     /// scheduling region.
811     void initScheduleData(Instruction *FromI, Instruction *ToI,
812                           ScheduleData *PrevLoadStore,
813                           ScheduleData *NextLoadStore);
814 
815     /// Updates the dependency information of a bundle and of all instructions/
816     /// bundles which depend on the original bundle.
817     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
818                                BoUpSLP *SLP);
819 
820     /// Sets all instruction in the scheduling region to un-scheduled.
821     void resetSchedule();
822 
823     BasicBlock *BB;
824 
825     /// Simple memory allocation for ScheduleData.
826     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
827 
828     /// The size of a ScheduleData array in ScheduleDataChunks.
829     int ChunkSize;
830 
831     /// The allocator position in the current chunk, which is the last entry
832     /// of ScheduleDataChunks.
833     int ChunkPos;
834 
835     /// Attaches ScheduleData to Instruction.
836     /// Note that the mapping survives during all vectorization iterations, i.e.
837     /// ScheduleData structures are recycled.
838     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
839 
840     struct ReadyList : SmallVector<ScheduleData *, 8> {
841       void insert(ScheduleData *SD) { push_back(SD); }
842     };
843 
844     /// The ready-list for scheduling (only used for the dry-run).
845     ReadyList ReadyInsts;
846 
847     /// The first instruction of the scheduling region.
848     Instruction *ScheduleStart;
849 
850     /// The first instruction _after_ the scheduling region.
851     Instruction *ScheduleEnd;
852 
853     /// The first memory accessing instruction in the scheduling region
854     /// (can be null).
855     ScheduleData *FirstLoadStoreInRegion;
856 
857     /// The last memory accessing instruction in the scheduling region
858     /// (can be null).
859     ScheduleData *LastLoadStoreInRegion;
860 
861     /// The current size of the scheduling region.
862     int ScheduleRegionSize;
863 
864     /// The maximum size allowed for the scheduling region.
865     int ScheduleRegionSizeLimit;
866 
867     /// The ID of the scheduling region. For a new vectorization iteration this
868     /// is incremented which "removes" all ScheduleData from the region.
869     int SchedulingRegionID;
870   };
871 
872   /// Attaches the BlockScheduling structures to basic blocks.
873   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
874 
875   /// Performs the "real" scheduling. Done before vectorization is actually
876   /// performed in a basic block.
877   void scheduleBlock(BlockScheduling *BS);
878 
879   /// List of users to ignore during scheduling and that don't need extracting.
880   ArrayRef<Value *> UserIgnoreList;
881 
882   // Number of load bundles that contain consecutive loads.
883   int NumLoadsWantToKeepOrder;
884 
885   // Number of load bundles that contain consecutive loads in reversed order.
886   int NumLoadsWantToChangeOrder;
887 
888   // Analysis and block reference.
889   Function *F;
890   ScalarEvolution *SE;
891   TargetTransformInfo *TTI;
892   TargetLibraryInfo *TLI;
893   AliasAnalysis *AA;
894   LoopInfo *LI;
895   DominatorTree *DT;
896   AssumptionCache *AC;
897   DemandedBits *DB;
898   const DataLayout *DL;
899   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
900   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
901   /// Instruction builder to construct the vectorized tree.
902   IRBuilder<> Builder;
903 
904   /// A map of scalar integer values to the smallest bit width with which they
905   /// can legally be represented.
906   MapVector<Value *, uint64_t> MinBWs;
907 };
908 
909 } // end namespace llvm
910 } // end namespace slpvectorizer
911 
912 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
913                         ArrayRef<Value *> UserIgnoreLst) {
914   deleteTree();
915   UserIgnoreList = UserIgnoreLst;
916   if (!getSameType(Roots))
917     return;
918   buildTree_rec(Roots, 0);
919 
920   // Collect the values that we need to extract from the tree.
921   for (TreeEntry &EIdx : VectorizableTree) {
922     TreeEntry *Entry = &EIdx;
923 
924     // For each lane:
925     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
926       Value *Scalar = Entry->Scalars[Lane];
927 
928       // No need to handle users of gathered values.
929       if (Entry->NeedToGather)
930         continue;
931 
932       for (User *U : Scalar->users()) {
933         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
934 
935         Instruction *UserInst = dyn_cast<Instruction>(U);
936         if (!UserInst)
937           continue;
938 
939         // Skip in-tree scalars that become vectors
940         if (ScalarToTreeEntry.count(U)) {
941           int Idx = ScalarToTreeEntry[U];
942           TreeEntry *UseEntry = &VectorizableTree[Idx];
943           Value *UseScalar = UseEntry->Scalars[0];
944           // Some in-tree scalars will remain as scalar in vectorized
945           // instructions. If that is the case, the one in Lane 0 will
946           // be used.
947           if (UseScalar != U ||
948               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
949             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
950                          << ".\n");
951             assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
952             continue;
953           }
954         }
955 
956         // Ignore users in the user ignore list.
957         if (is_contained(UserIgnoreList, UserInst))
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 (!is_contained(Scalar->users(), User))
2654       continue;
2655     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2656 
2657     int Idx = ScalarToTreeEntry[Scalar];
2658     TreeEntry *E = &VectorizableTree[Idx];
2659     assert(!E->NeedToGather && "Extracting from a gather list");
2660 
2661     Value *Vec = E->VectorizedValue;
2662     assert(Vec && "Can't find vectorizable value");
2663 
2664     Value *Lane = Builder.getInt32(ExternalUse.Lane);
2665     // Generate extracts for out-of-tree users.
2666     // Find the insertion point for the extractelement lane.
2667     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
2668       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2669         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2670           if (PH->getIncomingValue(i) == Scalar) {
2671             TerminatorInst *IncomingTerminator =
2672                 PH->getIncomingBlock(i)->getTerminator();
2673             if (isa<CatchSwitchInst>(IncomingTerminator)) {
2674               Builder.SetInsertPoint(VecI->getParent(),
2675                                      std::next(VecI->getIterator()));
2676             } else {
2677               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2678             }
2679             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2680             if (MinBWs.count(ScalarRoot))
2681               Ex = Builder.CreateSExt(Ex, Scalar->getType());
2682             CSEBlocks.insert(PH->getIncomingBlock(i));
2683             PH->setOperand(i, Ex);
2684           }
2685         }
2686       } else {
2687         Builder.SetInsertPoint(cast<Instruction>(User));
2688         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2689         if (MinBWs.count(ScalarRoot))
2690           Ex = Builder.CreateSExt(Ex, Scalar->getType());
2691         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2692         User->replaceUsesOfWith(Scalar, Ex);
2693      }
2694     } else {
2695       Builder.SetInsertPoint(&F->getEntryBlock().front());
2696       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2697       if (MinBWs.count(ScalarRoot))
2698         Ex = Builder.CreateSExt(Ex, Scalar->getType());
2699       CSEBlocks.insert(&F->getEntryBlock());
2700       User->replaceUsesOfWith(Scalar, Ex);
2701     }
2702 
2703     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2704   }
2705 
2706   // For each vectorized value:
2707   for (TreeEntry &EIdx : VectorizableTree) {
2708     TreeEntry *Entry = &EIdx;
2709 
2710     // For each lane:
2711     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2712       Value *Scalar = Entry->Scalars[Lane];
2713       // No need to handle users of gathered values.
2714       if (Entry->NeedToGather)
2715         continue;
2716 
2717       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2718 
2719       Type *Ty = Scalar->getType();
2720       if (!Ty->isVoidTy()) {
2721 #ifndef NDEBUG
2722         for (User *U : Scalar->users()) {
2723           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2724 
2725           assert((ScalarToTreeEntry.count(U) ||
2726                   // It is legal to replace users in the ignorelist by undef.
2727                   is_contained(UserIgnoreList, U)) &&
2728                  "Replacing out-of-tree value with undef");
2729         }
2730 #endif
2731         Value *Undef = UndefValue::get(Ty);
2732         Scalar->replaceAllUsesWith(Undef);
2733       }
2734       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2735       eraseInstruction(cast<Instruction>(Scalar));
2736     }
2737   }
2738 
2739   Builder.ClearInsertionPoint();
2740 
2741   return VectorizableTree[0].VectorizedValue;
2742 }
2743 
2744 void BoUpSLP::optimizeGatherSequence() {
2745   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2746         << " gather sequences instructions.\n");
2747   // LICM InsertElementInst sequences.
2748   for (Instruction *it : GatherSeq) {
2749     InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
2750 
2751     if (!Insert)
2752       continue;
2753 
2754     // Check if this block is inside a loop.
2755     Loop *L = LI->getLoopFor(Insert->getParent());
2756     if (!L)
2757       continue;
2758 
2759     // Check if it has a preheader.
2760     BasicBlock *PreHeader = L->getLoopPreheader();
2761     if (!PreHeader)
2762       continue;
2763 
2764     // If the vector or the element that we insert into it are
2765     // instructions that are defined in this basic block then we can't
2766     // hoist this instruction.
2767     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2768     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2769     if (CurrVec && L->contains(CurrVec))
2770       continue;
2771     if (NewElem && L->contains(NewElem))
2772       continue;
2773 
2774     // We can hoist this instruction. Move it to the pre-header.
2775     Insert->moveBefore(PreHeader->getTerminator());
2776   }
2777 
2778   // Make a list of all reachable blocks in our CSE queue.
2779   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2780   CSEWorkList.reserve(CSEBlocks.size());
2781   for (BasicBlock *BB : CSEBlocks)
2782     if (DomTreeNode *N = DT->getNode(BB)) {
2783       assert(DT->isReachableFromEntry(N));
2784       CSEWorkList.push_back(N);
2785     }
2786 
2787   // Sort blocks by domination. This ensures we visit a block after all blocks
2788   // dominating it are visited.
2789   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2790                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2791     return DT->properlyDominates(A, B);
2792   });
2793 
2794   // Perform O(N^2) search over the gather sequences and merge identical
2795   // instructions. TODO: We can further optimize this scan if we split the
2796   // instructions into different buckets based on the insert lane.
2797   SmallVector<Instruction *, 16> Visited;
2798   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2799     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2800            "Worklist not sorted properly!");
2801     BasicBlock *BB = (*I)->getBlock();
2802     // For all instructions in blocks containing gather sequences:
2803     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2804       Instruction *In = &*it++;
2805       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2806         continue;
2807 
2808       // Check if we can replace this instruction with any of the
2809       // visited instructions.
2810       for (Instruction *v : Visited) {
2811         if (In->isIdenticalTo(v) &&
2812             DT->dominates(v->getParent(), In->getParent())) {
2813           In->replaceAllUsesWith(v);
2814           eraseInstruction(In);
2815           In = nullptr;
2816           break;
2817         }
2818       }
2819       if (In) {
2820         assert(!is_contained(Visited, In));
2821         Visited.push_back(In);
2822       }
2823     }
2824   }
2825   CSEBlocks.clear();
2826   GatherSeq.clear();
2827 }
2828 
2829 // Groups the instructions to a bundle (which is then a single scheduling entity)
2830 // and schedules instructions until the bundle gets ready.
2831 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2832                                                  BoUpSLP *SLP) {
2833   if (isa<PHINode>(VL[0]))
2834     return true;
2835 
2836   // Initialize the instruction bundle.
2837   Instruction *OldScheduleEnd = ScheduleEnd;
2838   ScheduleData *PrevInBundle = nullptr;
2839   ScheduleData *Bundle = nullptr;
2840   bool ReSchedule = false;
2841   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2842 
2843   // Make sure that the scheduling region contains all
2844   // instructions of the bundle.
2845   for (Value *V : VL) {
2846     if (!extendSchedulingRegion(V))
2847       return false;
2848   }
2849 
2850   for (Value *V : VL) {
2851     ScheduleData *BundleMember = getScheduleData(V);
2852     assert(BundleMember &&
2853            "no ScheduleData for bundle member (maybe not in same basic block)");
2854     if (BundleMember->IsScheduled) {
2855       // A bundle member was scheduled as single instruction before and now
2856       // needs to be scheduled as part of the bundle. We just get rid of the
2857       // existing schedule.
2858       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2859                    << " was already scheduled\n");
2860       ReSchedule = true;
2861     }
2862     assert(BundleMember->isSchedulingEntity() &&
2863            "bundle member already part of other bundle");
2864     if (PrevInBundle) {
2865       PrevInBundle->NextInBundle = BundleMember;
2866     } else {
2867       Bundle = BundleMember;
2868     }
2869     BundleMember->UnscheduledDepsInBundle = 0;
2870     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2871 
2872     // Group the instructions to a bundle.
2873     BundleMember->FirstInBundle = Bundle;
2874     PrevInBundle = BundleMember;
2875   }
2876   if (ScheduleEnd != OldScheduleEnd) {
2877     // The scheduling region got new instructions at the lower end (or it is a
2878     // new region for the first bundle). This makes it necessary to
2879     // recalculate all dependencies.
2880     // It is seldom that this needs to be done a second time after adding the
2881     // initial bundle to the region.
2882     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2883       ScheduleData *SD = getScheduleData(I);
2884       SD->clearDependencies();
2885     }
2886     ReSchedule = true;
2887   }
2888   if (ReSchedule) {
2889     resetSchedule();
2890     initialFillReadyList(ReadyInsts);
2891   }
2892 
2893   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2894                << BB->getName() << "\n");
2895 
2896   calculateDependencies(Bundle, true, SLP);
2897 
2898   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2899   // means that there are no cyclic dependencies and we can schedule it.
2900   // Note that's important that we don't "schedule" the bundle yet (see
2901   // cancelScheduling).
2902   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2903 
2904     ScheduleData *pickedSD = ReadyInsts.back();
2905     ReadyInsts.pop_back();
2906 
2907     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2908       schedule(pickedSD, ReadyInsts);
2909     }
2910   }
2911   if (!Bundle->isReady()) {
2912     cancelScheduling(VL);
2913     return false;
2914   }
2915   return true;
2916 }
2917 
2918 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2919   if (isa<PHINode>(VL[0]))
2920     return;
2921 
2922   ScheduleData *Bundle = getScheduleData(VL[0]);
2923   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2924   assert(!Bundle->IsScheduled &&
2925          "Can't cancel bundle which is already scheduled");
2926   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2927          "tried to unbundle something which is not a bundle");
2928 
2929   // Un-bundle: make single instructions out of the bundle.
2930   ScheduleData *BundleMember = Bundle;
2931   while (BundleMember) {
2932     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2933     BundleMember->FirstInBundle = BundleMember;
2934     ScheduleData *Next = BundleMember->NextInBundle;
2935     BundleMember->NextInBundle = nullptr;
2936     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2937     if (BundleMember->UnscheduledDepsInBundle == 0) {
2938       ReadyInsts.insert(BundleMember);
2939     }
2940     BundleMember = Next;
2941   }
2942 }
2943 
2944 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2945   if (getScheduleData(V))
2946     return true;
2947   Instruction *I = dyn_cast<Instruction>(V);
2948   assert(I && "bundle member must be an instruction");
2949   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2950   if (!ScheduleStart) {
2951     // It's the first instruction in the new region.
2952     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2953     ScheduleStart = I;
2954     ScheduleEnd = I->getNextNode();
2955     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2956     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2957     return true;
2958   }
2959   // Search up and down at the same time, because we don't know if the new
2960   // instruction is above or below the existing scheduling region.
2961   BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
2962   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2963   BasicBlock::iterator DownIter(ScheduleEnd);
2964   BasicBlock::iterator LowerEnd = BB->end();
2965   for (;;) {
2966     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
2967       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
2968       return false;
2969     }
2970 
2971     if (UpIter != UpperEnd) {
2972       if (&*UpIter == I) {
2973         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2974         ScheduleStart = I;
2975         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2976         return true;
2977       }
2978       UpIter++;
2979     }
2980     if (DownIter != LowerEnd) {
2981       if (&*DownIter == I) {
2982         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2983                          nullptr);
2984         ScheduleEnd = I->getNextNode();
2985         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2986         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
2987         return true;
2988       }
2989       DownIter++;
2990     }
2991     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2992            "instruction not found in block");
2993   }
2994   return true;
2995 }
2996 
2997 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2998                                                 Instruction *ToI,
2999                                                 ScheduleData *PrevLoadStore,
3000                                                 ScheduleData *NextLoadStore) {
3001   ScheduleData *CurrentLoadStore = PrevLoadStore;
3002   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3003     ScheduleData *SD = ScheduleDataMap[I];
3004     if (!SD) {
3005       // Allocate a new ScheduleData for the instruction.
3006       if (ChunkPos >= ChunkSize) {
3007         ScheduleDataChunks.push_back(
3008             llvm::make_unique<ScheduleData[]>(ChunkSize));
3009         ChunkPos = 0;
3010       }
3011       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3012       ScheduleDataMap[I] = SD;
3013       SD->Inst = I;
3014     }
3015     assert(!isInSchedulingRegion(SD) &&
3016            "new ScheduleData already in scheduling region");
3017     SD->init(SchedulingRegionID);
3018 
3019     if (I->mayReadOrWriteMemory()) {
3020       // Update the linked list of memory accessing instructions.
3021       if (CurrentLoadStore) {
3022         CurrentLoadStore->NextLoadStore = SD;
3023       } else {
3024         FirstLoadStoreInRegion = SD;
3025       }
3026       CurrentLoadStore = SD;
3027     }
3028   }
3029   if (NextLoadStore) {
3030     if (CurrentLoadStore)
3031       CurrentLoadStore->NextLoadStore = NextLoadStore;
3032   } else {
3033     LastLoadStoreInRegion = CurrentLoadStore;
3034   }
3035 }
3036 
3037 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3038                                                      bool InsertInReadyList,
3039                                                      BoUpSLP *SLP) {
3040   assert(SD->isSchedulingEntity());
3041 
3042   SmallVector<ScheduleData *, 10> WorkList;
3043   WorkList.push_back(SD);
3044 
3045   while (!WorkList.empty()) {
3046     ScheduleData *SD = WorkList.back();
3047     WorkList.pop_back();
3048 
3049     ScheduleData *BundleMember = SD;
3050     while (BundleMember) {
3051       assert(isInSchedulingRegion(BundleMember));
3052       if (!BundleMember->hasValidDependencies()) {
3053 
3054         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
3055         BundleMember->Dependencies = 0;
3056         BundleMember->resetUnscheduledDeps();
3057 
3058         // Handle def-use chain dependencies.
3059         for (User *U : BundleMember->Inst->users()) {
3060           if (isa<Instruction>(U)) {
3061             ScheduleData *UseSD = getScheduleData(U);
3062             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3063               BundleMember->Dependencies++;
3064               ScheduleData *DestBundle = UseSD->FirstInBundle;
3065               if (!DestBundle->IsScheduled) {
3066                 BundleMember->incrementUnscheduledDeps(1);
3067               }
3068               if (!DestBundle->hasValidDependencies()) {
3069                 WorkList.push_back(DestBundle);
3070               }
3071             }
3072           } else {
3073             // I'm not sure if this can ever happen. But we need to be safe.
3074             // This lets the instruction/bundle never be scheduled and
3075             // eventually disable vectorization.
3076             BundleMember->Dependencies++;
3077             BundleMember->incrementUnscheduledDeps(1);
3078           }
3079         }
3080 
3081         // Handle the memory dependencies.
3082         ScheduleData *DepDest = BundleMember->NextLoadStore;
3083         if (DepDest) {
3084           Instruction *SrcInst = BundleMember->Inst;
3085           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3086           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3087           unsigned numAliased = 0;
3088           unsigned DistToSrc = 1;
3089 
3090           while (DepDest) {
3091             assert(isInSchedulingRegion(DepDest));
3092 
3093             // We have two limits to reduce the complexity:
3094             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3095             //    SLP->isAliased (which is the expensive part in this loop).
3096             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3097             //    the whole loop (even if the loop is fast, it's quadratic).
3098             //    It's important for the loop break condition (see below) to
3099             //    check this limit even between two read-only instructions.
3100             if (DistToSrc >= MaxMemDepDistance ||
3101                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3102                      (numAliased >= AliasedCheckLimit ||
3103                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3104 
3105               // We increment the counter only if the locations are aliased
3106               // (instead of counting all alias checks). This gives a better
3107               // balance between reduced runtime and accurate dependencies.
3108               numAliased++;
3109 
3110               DepDest->MemoryDependencies.push_back(BundleMember);
3111               BundleMember->Dependencies++;
3112               ScheduleData *DestBundle = DepDest->FirstInBundle;
3113               if (!DestBundle->IsScheduled) {
3114                 BundleMember->incrementUnscheduledDeps(1);
3115               }
3116               if (!DestBundle->hasValidDependencies()) {
3117                 WorkList.push_back(DestBundle);
3118               }
3119             }
3120             DepDest = DepDest->NextLoadStore;
3121 
3122             // Example, explaining the loop break condition: Let's assume our
3123             // starting instruction is i0 and MaxMemDepDistance = 3.
3124             //
3125             //                      +--------v--v--v
3126             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3127             //             +--------^--^--^
3128             //
3129             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3130             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3131             // Previously we already added dependencies from i3 to i6,i7,i8
3132             // (because of MaxMemDepDistance). As we added a dependency from
3133             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3134             // and we can abort this loop at i6.
3135             if (DistToSrc >= 2 * MaxMemDepDistance)
3136                 break;
3137             DistToSrc++;
3138           }
3139         }
3140       }
3141       BundleMember = BundleMember->NextInBundle;
3142     }
3143     if (InsertInReadyList && SD->isReady()) {
3144       ReadyInsts.push_back(SD);
3145       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3146     }
3147   }
3148 }
3149 
3150 void BoUpSLP::BlockScheduling::resetSchedule() {
3151   assert(ScheduleStart &&
3152          "tried to reset schedule on block which has not been scheduled");
3153   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3154     ScheduleData *SD = getScheduleData(I);
3155     assert(isInSchedulingRegion(SD));
3156     SD->IsScheduled = false;
3157     SD->resetUnscheduledDeps();
3158   }
3159   ReadyInsts.clear();
3160 }
3161 
3162 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3163 
3164   if (!BS->ScheduleStart)
3165     return;
3166 
3167   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3168 
3169   BS->resetSchedule();
3170 
3171   // For the real scheduling we use a more sophisticated ready-list: it is
3172   // sorted by the original instruction location. This lets the final schedule
3173   // be as  close as possible to the original instruction order.
3174   struct ScheduleDataCompare {
3175     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
3176       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3177     }
3178   };
3179   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3180 
3181   // Ensure that all dependency data is updated and fill the ready-list with
3182   // initial instructions.
3183   int Idx = 0;
3184   int NumToSchedule = 0;
3185   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3186        I = I->getNextNode()) {
3187     ScheduleData *SD = BS->getScheduleData(I);
3188     assert(
3189         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
3190         "scheduler and vectorizer have different opinion on what is a bundle");
3191     SD->FirstInBundle->SchedulingPriority = Idx++;
3192     if (SD->isSchedulingEntity()) {
3193       BS->calculateDependencies(SD, false, this);
3194       NumToSchedule++;
3195     }
3196   }
3197   BS->initialFillReadyList(ReadyInsts);
3198 
3199   Instruction *LastScheduledInst = BS->ScheduleEnd;
3200 
3201   // Do the "real" scheduling.
3202   while (!ReadyInsts.empty()) {
3203     ScheduleData *picked = *ReadyInsts.begin();
3204     ReadyInsts.erase(ReadyInsts.begin());
3205 
3206     // Move the scheduled instruction(s) to their dedicated places, if not
3207     // there yet.
3208     ScheduleData *BundleMember = picked;
3209     while (BundleMember) {
3210       Instruction *pickedInst = BundleMember->Inst;
3211       if (LastScheduledInst->getNextNode() != pickedInst) {
3212         BS->BB->getInstList().remove(pickedInst);
3213         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3214                                      pickedInst);
3215       }
3216       LastScheduledInst = pickedInst;
3217       BundleMember = BundleMember->NextInBundle;
3218     }
3219 
3220     BS->schedule(picked, ReadyInsts);
3221     NumToSchedule--;
3222   }
3223   assert(NumToSchedule == 0 && "could not schedule all instructions");
3224 
3225   // Avoid duplicate scheduling of the block.
3226   BS->ScheduleStart = nullptr;
3227 }
3228 
3229 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3230   // If V is a store, just return the width of the stored value without
3231   // traversing the expression tree. This is the common case.
3232   if (auto *Store = dyn_cast<StoreInst>(V))
3233     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3234 
3235   // If V is not a store, we can traverse the expression tree to find loads
3236   // that feed it. The type of the loaded value may indicate a more suitable
3237   // width than V's type. We want to base the vector element size on the width
3238   // of memory operations where possible.
3239   SmallVector<Instruction *, 16> Worklist;
3240   SmallPtrSet<Instruction *, 16> Visited;
3241   if (auto *I = dyn_cast<Instruction>(V))
3242     Worklist.push_back(I);
3243 
3244   // Traverse the expression tree in bottom-up order looking for loads. If we
3245   // encounter an instruciton we don't yet handle, we give up.
3246   auto MaxWidth = 0u;
3247   auto FoundUnknownInst = false;
3248   while (!Worklist.empty() && !FoundUnknownInst) {
3249     auto *I = Worklist.pop_back_val();
3250     Visited.insert(I);
3251 
3252     // We should only be looking at scalar instructions here. If the current
3253     // instruction has a vector type, give up.
3254     auto *Ty = I->getType();
3255     if (isa<VectorType>(Ty))
3256       FoundUnknownInst = true;
3257 
3258     // If the current instruction is a load, update MaxWidth to reflect the
3259     // width of the loaded value.
3260     else if (isa<LoadInst>(I))
3261       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3262 
3263     // Otherwise, we need to visit the operands of the instruction. We only
3264     // handle the interesting cases from buildTree here. If an operand is an
3265     // instruction we haven't yet visited, we add it to the worklist.
3266     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3267              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3268       for (Use &U : I->operands())
3269         if (auto *J = dyn_cast<Instruction>(U.get()))
3270           if (!Visited.count(J))
3271             Worklist.push_back(J);
3272     }
3273 
3274     // If we don't yet handle the instruction, give up.
3275     else
3276       FoundUnknownInst = true;
3277   }
3278 
3279   // If we didn't encounter a memory access in the expression tree, or if we
3280   // gave up for some reason, just return the width of V.
3281   if (!MaxWidth || FoundUnknownInst)
3282     return DL->getTypeSizeInBits(V->getType());
3283 
3284   // Otherwise, return the maximum width we found.
3285   return MaxWidth;
3286 }
3287 
3288 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3289 // smaller type with a truncation. We collect the values that will be demoted
3290 // in ToDemote and additional roots that require investigating in Roots.
3291 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3292                                   SmallVectorImpl<Value *> &ToDemote,
3293                                   SmallVectorImpl<Value *> &Roots) {
3294 
3295   // We can always demote constants.
3296   if (isa<Constant>(V)) {
3297     ToDemote.push_back(V);
3298     return true;
3299   }
3300 
3301   // If the value is not an instruction in the expression with only one use, it
3302   // cannot be demoted.
3303   auto *I = dyn_cast<Instruction>(V);
3304   if (!I || !I->hasOneUse() || !Expr.count(I))
3305     return false;
3306 
3307   switch (I->getOpcode()) {
3308 
3309   // We can always demote truncations and extensions. Since truncations can
3310   // seed additional demotion, we save the truncated value.
3311   case Instruction::Trunc:
3312     Roots.push_back(I->getOperand(0));
3313   case Instruction::ZExt:
3314   case Instruction::SExt:
3315     break;
3316 
3317   // We can demote certain binary operations if we can demote both of their
3318   // operands.
3319   case Instruction::Add:
3320   case Instruction::Sub:
3321   case Instruction::Mul:
3322   case Instruction::And:
3323   case Instruction::Or:
3324   case Instruction::Xor:
3325     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3326         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3327       return false;
3328     break;
3329 
3330   // We can demote selects if we can demote their true and false values.
3331   case Instruction::Select: {
3332     SelectInst *SI = cast<SelectInst>(I);
3333     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3334         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3335       return false;
3336     break;
3337   }
3338 
3339   // We can demote phis if we can demote all their incoming operands. Note that
3340   // we don't need to worry about cycles since we ensure single use above.
3341   case Instruction::PHI: {
3342     PHINode *PN = cast<PHINode>(I);
3343     for (Value *IncValue : PN->incoming_values())
3344       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3345         return false;
3346     break;
3347   }
3348 
3349   // Otherwise, conservatively give up.
3350   default:
3351     return false;
3352   }
3353 
3354   // Record the value that we can demote.
3355   ToDemote.push_back(V);
3356   return true;
3357 }
3358 
3359 void BoUpSLP::computeMinimumValueSizes() {
3360   // If there are no external uses, the expression tree must be rooted by a
3361   // store. We can't demote in-memory values, so there is nothing to do here.
3362   if (ExternalUses.empty())
3363     return;
3364 
3365   // We only attempt to truncate integer expressions.
3366   auto &TreeRoot = VectorizableTree[0].Scalars;
3367   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3368   if (!TreeRootIT)
3369     return;
3370 
3371   // If the expression is not rooted by a store, these roots should have
3372   // external uses. We will rely on InstCombine to rewrite the expression in
3373   // the narrower type. However, InstCombine only rewrites single-use values.
3374   // This means that if a tree entry other than a root is used externally, it
3375   // must have multiple uses and InstCombine will not rewrite it. The code
3376   // below ensures that only the roots are used externally.
3377   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3378   for (auto &EU : ExternalUses)
3379     if (!Expr.erase(EU.Scalar))
3380       return;
3381   if (!Expr.empty())
3382     return;
3383 
3384   // Collect the scalar values of the vectorizable expression. We will use this
3385   // context to determine which values can be demoted. If we see a truncation,
3386   // we mark it as seeding another demotion.
3387   for (auto &Entry : VectorizableTree)
3388     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3389 
3390   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3391   // have a single external user that is not in the vectorizable tree.
3392   for (auto *Root : TreeRoot)
3393     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3394       return;
3395 
3396   // Conservatively determine if we can actually truncate the roots of the
3397   // expression. Collect the values that can be demoted in ToDemote and
3398   // additional roots that require investigating in Roots.
3399   SmallVector<Value *, 32> ToDemote;
3400   SmallVector<Value *, 4> Roots;
3401   for (auto *Root : TreeRoot)
3402     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
3403       return;
3404 
3405   // The maximum bit width required to represent all the values that can be
3406   // demoted without loss of precision. It would be safe to truncate the roots
3407   // of the expression to this width.
3408   auto MaxBitWidth = 8u;
3409 
3410   // We first check if all the bits of the roots are demanded. If they're not,
3411   // we can truncate the roots to this narrower type.
3412   for (auto *Root : TreeRoot) {
3413     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
3414     MaxBitWidth = std::max<unsigned>(
3415         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
3416   }
3417 
3418   // If all the bits of the roots are demanded, we can try a little harder to
3419   // compute a narrower type. This can happen, for example, if the roots are
3420   // getelementptr indices. InstCombine promotes these indices to the pointer
3421   // width. Thus, all their bits are technically demanded even though the
3422   // address computation might be vectorized in a smaller type.
3423   //
3424   // We start by looking at each entry that can be demoted. We compute the
3425   // maximum bit width required to store the scalar by using ValueTracking to
3426   // compute the number of high-order bits we can truncate.
3427   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
3428     MaxBitWidth = 8u;
3429     for (auto *Scalar : ToDemote) {
3430       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
3431       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
3432       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3433     }
3434   }
3435 
3436   // Round MaxBitWidth up to the next power-of-two.
3437   if (!isPowerOf2_64(MaxBitWidth))
3438     MaxBitWidth = NextPowerOf2(MaxBitWidth);
3439 
3440   // If the maximum bit width we compute is less than the with of the roots'
3441   // type, we can proceed with the narrowing. Otherwise, do nothing.
3442   if (MaxBitWidth >= TreeRootIT->getBitWidth())
3443     return;
3444 
3445   // If we can truncate the root, we must collect additional values that might
3446   // be demoted as a result. That is, those seeded by truncations we will
3447   // modify.
3448   while (!Roots.empty())
3449     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
3450 
3451   // Finally, map the values we can demote to the maximum bit with we computed.
3452   for (auto *Scalar : ToDemote)
3453     MinBWs[Scalar] = MaxBitWidth;
3454 }
3455 
3456 namespace {
3457 /// The SLPVectorizer Pass.
3458 struct SLPVectorizer : public FunctionPass {
3459   SLPVectorizerPass Impl;
3460 
3461   /// Pass identification, replacement for typeid
3462   static char ID;
3463 
3464   explicit SLPVectorizer() : FunctionPass(ID) {
3465     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3466   }
3467 
3468 
3469   bool doInitialization(Module &M) override {
3470     return false;
3471   }
3472 
3473   bool runOnFunction(Function &F) override {
3474     if (skipFunction(F))
3475       return false;
3476 
3477     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3478     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3479     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3480     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
3481     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3482     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3483     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3484     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3485     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3486 
3487     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3488   }
3489 
3490   void getAnalysisUsage(AnalysisUsage &AU) const override {
3491     FunctionPass::getAnalysisUsage(AU);
3492     AU.addRequired<AssumptionCacheTracker>();
3493     AU.addRequired<ScalarEvolutionWrapperPass>();
3494     AU.addRequired<AAResultsWrapperPass>();
3495     AU.addRequired<TargetTransformInfoWrapperPass>();
3496     AU.addRequired<LoopInfoWrapperPass>();
3497     AU.addRequired<DominatorTreeWrapperPass>();
3498     AU.addRequired<DemandedBitsWrapperPass>();
3499     AU.addPreserved<LoopInfoWrapperPass>();
3500     AU.addPreserved<DominatorTreeWrapperPass>();
3501     AU.addPreserved<AAResultsWrapperPass>();
3502     AU.addPreserved<GlobalsAAWrapperPass>();
3503     AU.setPreservesCFG();
3504   }
3505 };
3506 } // end anonymous namespace
3507 
3508 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
3509   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
3510   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
3511   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
3512   auto *AA = &AM.getResult<AAManager>(F);
3513   auto *LI = &AM.getResult<LoopAnalysis>(F);
3514   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
3515   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
3516   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
3517 
3518   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
3519   if (!Changed)
3520     return PreservedAnalyses::all();
3521   PreservedAnalyses PA;
3522   PA.preserve<LoopAnalysis>();
3523   PA.preserve<DominatorTreeAnalysis>();
3524   PA.preserve<AAManager>();
3525   PA.preserve<GlobalsAA>();
3526   return PA;
3527 }
3528 
3529 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
3530                                 TargetTransformInfo *TTI_,
3531                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
3532                                 LoopInfo *LI_, DominatorTree *DT_,
3533                                 AssumptionCache *AC_, DemandedBits *DB_) {
3534   SE = SE_;
3535   TTI = TTI_;
3536   TLI = TLI_;
3537   AA = AA_;
3538   LI = LI_;
3539   DT = DT_;
3540   AC = AC_;
3541   DB = DB_;
3542   DL = &F.getParent()->getDataLayout();
3543 
3544   Stores.clear();
3545   GEPs.clear();
3546   bool Changed = false;
3547 
3548   // If the target claims to have no vector registers don't attempt
3549   // vectorization.
3550   if (!TTI->getNumberOfRegisters(true))
3551     return false;
3552 
3553   // Don't vectorize when the attribute NoImplicitFloat is used.
3554   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3555     return false;
3556 
3557   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3558 
3559   // Use the bottom up slp vectorizer to construct chains that start with
3560   // store instructions.
3561   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
3562 
3563   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3564   // delete instructions.
3565 
3566   // Scan the blocks in the function in post order.
3567   for (auto BB : post_order(&F.getEntryBlock())) {
3568     collectSeedInstructions(BB);
3569 
3570     // Vectorize trees that end at stores.
3571     if (!Stores.empty()) {
3572       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
3573                    << " underlying objects.\n");
3574       Changed |= vectorizeStoreChains(R);
3575     }
3576 
3577     // Vectorize trees that end at reductions.
3578     Changed |= vectorizeChainsInBlock(BB, R);
3579 
3580     // Vectorize the index computations of getelementptr instructions. This
3581     // is primarily intended to catch gather-like idioms ending at
3582     // non-consecutive loads.
3583     if (!GEPs.empty()) {
3584       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
3585                    << " underlying objects.\n");
3586       Changed |= vectorizeGEPIndices(BB, R);
3587     }
3588   }
3589 
3590   if (Changed) {
3591     R.optimizeGatherSequence();
3592     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3593     DEBUG(verifyFunction(F));
3594   }
3595   return Changed;
3596 }
3597 
3598 /// \brief Check that the Values in the slice in VL array are still existent in
3599 /// the WeakVH array.
3600 /// Vectorization of part of the VL array may cause later values in the VL array
3601 /// to become invalid. We track when this has happened in the WeakVH array.
3602 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
3603                                unsigned SliceBegin, unsigned SliceSize) {
3604   VL = VL.slice(SliceBegin, SliceSize);
3605   VH = VH.slice(SliceBegin, SliceSize);
3606   return !std::equal(VL.begin(), VL.end(), VH.begin());
3607 }
3608 
3609 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain,
3610                                             int CostThreshold, BoUpSLP &R,
3611                                             unsigned VecRegSize) {
3612   unsigned ChainLen = Chain.size();
3613   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3614         << "\n");
3615   unsigned Sz = R.getVectorElementSize(Chain[0]);
3616   unsigned VF = VecRegSize / Sz;
3617 
3618   if (!isPowerOf2_32(Sz) || VF < 2)
3619     return false;
3620 
3621   // Keep track of values that were deleted by vectorizing in the loop below.
3622   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3623 
3624   bool Changed = false;
3625   // Look for profitable vectorizable trees at all offsets, starting at zero.
3626   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3627     if (i + VF > e)
3628       break;
3629 
3630     // Check that a previous iteration of this loop did not delete the Value.
3631     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3632       continue;
3633 
3634     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3635           << "\n");
3636     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3637 
3638     R.buildTree(Operands);
3639     R.computeMinimumValueSizes();
3640 
3641     int Cost = R.getTreeCost();
3642 
3643     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3644     if (Cost < CostThreshold) {
3645       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3646       R.vectorizeTree();
3647 
3648       // Move to the next bundle.
3649       i += VF - 1;
3650       Changed = true;
3651     }
3652   }
3653 
3654   return Changed;
3655 }
3656 
3657 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
3658                                         int costThreshold, BoUpSLP &R) {
3659   SetVector<StoreInst *> Heads, Tails;
3660   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
3661 
3662   // We may run into multiple chains that merge into a single chain. We mark the
3663   // stores that we vectorized so that we don't visit the same store twice.
3664   BoUpSLP::ValueSet VectorizedStores;
3665   bool Changed = false;
3666 
3667   // Do a quadratic search on all of the given stores and find
3668   // all of the pairs of stores that follow each other.
3669   SmallVector<unsigned, 16> IndexQueue;
3670   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3671     IndexQueue.clear();
3672     // If a store has multiple consecutive store candidates, search Stores
3673     // array according to the sequence: from i+1 to e, then from i-1 to 0.
3674     // This is because usually pairing with immediate succeeding or preceding
3675     // candidate create the best chance to find slp vectorization opportunity.
3676     unsigned j = 0;
3677     for (j = i + 1; j < e; ++j)
3678       IndexQueue.push_back(j);
3679     for (j = i; j > 0; --j)
3680       IndexQueue.push_back(j - 1);
3681 
3682     for (auto &k : IndexQueue) {
3683       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
3684         Tails.insert(Stores[k]);
3685         Heads.insert(Stores[i]);
3686         ConsecutiveChain[Stores[i]] = Stores[k];
3687         break;
3688       }
3689     }
3690   }
3691 
3692   // For stores that start but don't end a link in the chain:
3693   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
3694        it != e; ++it) {
3695     if (Tails.count(*it))
3696       continue;
3697 
3698     // We found a store instr that starts a chain. Now follow the chain and try
3699     // to vectorize it.
3700     BoUpSLP::ValueList Operands;
3701     StoreInst *I = *it;
3702     // Collect the chain into a list.
3703     while (Tails.count(I) || Heads.count(I)) {
3704       if (VectorizedStores.count(I))
3705         break;
3706       Operands.push_back(I);
3707       // Move to the next value in the chain.
3708       I = ConsecutiveChain[I];
3709     }
3710 
3711     // FIXME: Is division-by-2 the correct step? Should we assert that the
3712     // register size is a power-of-2?
3713     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize(); Size /= 2) {
3714       if (vectorizeStoreChain(Operands, costThreshold, R, Size)) {
3715         // Mark the vectorized stores so that we don't vectorize them again.
3716         VectorizedStores.insert(Operands.begin(), Operands.end());
3717         Changed = true;
3718         break;
3719       }
3720     }
3721   }
3722 
3723   return Changed;
3724 }
3725 
3726 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
3727 
3728   // Initialize the collections. We will make a single pass over the block.
3729   Stores.clear();
3730   GEPs.clear();
3731 
3732   // Visit the store and getelementptr instructions in BB and organize them in
3733   // Stores and GEPs according to the underlying objects of their pointer
3734   // operands.
3735   for (Instruction &I : *BB) {
3736 
3737     // Ignore store instructions that are volatile or have a pointer operand
3738     // that doesn't point to a scalar type.
3739     if (auto *SI = dyn_cast<StoreInst>(&I)) {
3740       if (!SI->isSimple())
3741         continue;
3742       if (!isValidElementType(SI->getValueOperand()->getType()))
3743         continue;
3744       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
3745     }
3746 
3747     // Ignore getelementptr instructions that have more than one index, a
3748     // constant index, or a pointer operand that doesn't point to a scalar
3749     // type.
3750     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3751       auto Idx = GEP->idx_begin()->get();
3752       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
3753         continue;
3754       if (!isValidElementType(Idx->getType()))
3755         continue;
3756       if (GEP->getType()->isVectorTy())
3757         continue;
3758       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
3759     }
3760   }
3761 }
3762 
3763 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3764   if (!A || !B)
3765     return false;
3766   Value *VL[] = { A, B };
3767   return tryToVectorizeList(VL, R, None, true);
3768 }
3769 
3770 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3771                                            ArrayRef<Value *> BuildVector,
3772                                            bool allowReorder) {
3773   if (VL.size() < 2)
3774     return false;
3775 
3776   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3777 
3778   // Check that all of the parts are scalar instructions of the same type.
3779   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3780   if (!I0)
3781     return false;
3782 
3783   unsigned Opcode0 = I0->getOpcode();
3784 
3785   // FIXME: Register size should be a parameter to this function, so we can
3786   // try different vectorization factors.
3787   unsigned Sz = R.getVectorElementSize(I0);
3788   unsigned VF = R.getMinVecRegSize() / Sz;
3789 
3790   for (Value *V : VL) {
3791     Type *Ty = V->getType();
3792     if (!isValidElementType(Ty))
3793       return false;
3794     Instruction *Inst = dyn_cast<Instruction>(V);
3795     if (!Inst || Inst->getOpcode() != Opcode0)
3796       return false;
3797   }
3798 
3799   bool Changed = false;
3800 
3801   // Keep track of values that were deleted by vectorizing in the loop below.
3802   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3803 
3804   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3805     unsigned OpsWidth = 0;
3806 
3807     if (i + VF > e)
3808       OpsWidth = e - i;
3809     else
3810       OpsWidth = VF;
3811 
3812     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3813       break;
3814 
3815     // Check that a previous iteration of this loop did not delete the Value.
3816     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3817       continue;
3818 
3819     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3820                  << "\n");
3821     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3822 
3823     ArrayRef<Value *> BuildVectorSlice;
3824     if (!BuildVector.empty())
3825       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3826 
3827     R.buildTree(Ops, BuildVectorSlice);
3828     // TODO: check if we can allow reordering for more cases.
3829     if (allowReorder && R.shouldReorder()) {
3830       // Conceptually, there is nothing actually preventing us from trying to
3831       // reorder a larger list. In fact, we do exactly this when vectorizing
3832       // reductions. However, at this point, we only expect to get here from
3833       // tryToVectorizePair().
3834       assert(Ops.size() == 2);
3835       assert(BuildVectorSlice.empty());
3836       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3837       R.buildTree(ReorderedOps, None);
3838     }
3839     R.computeMinimumValueSizes();
3840     int Cost = R.getTreeCost();
3841 
3842     if (Cost < -SLPCostThreshold) {
3843       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3844       Value *VectorizedRoot = R.vectorizeTree();
3845 
3846       // Reconstruct the build vector by extracting the vectorized root. This
3847       // way we handle the case where some elements of the vector are undefined.
3848       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3849       if (!BuildVectorSlice.empty()) {
3850         // The insert point is the last build vector instruction. The vectorized
3851         // root will precede it. This guarantees that we get an instruction. The
3852         // vectorized tree could have been constant folded.
3853         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3854         unsigned VecIdx = 0;
3855         for (auto &V : BuildVectorSlice) {
3856           IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
3857                                       ++BasicBlock::iterator(InsertAfter));
3858           Instruction *I = cast<Instruction>(V);
3859           assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
3860           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3861               VectorizedRoot, Builder.getInt32(VecIdx++)));
3862           I->setOperand(1, Extract);
3863           I->removeFromParent();
3864           I->insertAfter(Extract);
3865           InsertAfter = I;
3866         }
3867       }
3868       // Move to the next bundle.
3869       i += VF - 1;
3870       Changed = true;
3871     }
3872   }
3873 
3874   return Changed;
3875 }
3876 
3877 bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3878   if (!V)
3879     return false;
3880 
3881   // Try to vectorize V.
3882   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3883     return true;
3884 
3885   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3886   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3887   // Try to skip B.
3888   if (B && B->hasOneUse()) {
3889     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3890     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3891     if (tryToVectorizePair(A, B0, R)) {
3892       return true;
3893     }
3894     if (tryToVectorizePair(A, B1, R)) {
3895       return true;
3896     }
3897   }
3898 
3899   // Try to skip A.
3900   if (A && A->hasOneUse()) {
3901     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3902     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3903     if (tryToVectorizePair(A0, B, R)) {
3904       return true;
3905     }
3906     if (tryToVectorizePair(A1, B, R)) {
3907       return true;
3908     }
3909   }
3910   return 0;
3911 }
3912 
3913 /// \brief Generate a shuffle mask to be used in a reduction tree.
3914 ///
3915 /// \param VecLen The length of the vector to be reduced.
3916 /// \param NumEltsToRdx The number of elements that should be reduced in the
3917 ///        vector.
3918 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3919 ///        reduction. A pairwise reduction will generate a mask of
3920 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
3921 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3922 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3923 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3924                                    bool IsPairwise, bool IsLeft,
3925                                    IRBuilder<> &Builder) {
3926   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3927 
3928   SmallVector<Constant *, 32> ShuffleMask(
3929       VecLen, UndefValue::get(Builder.getInt32Ty()));
3930 
3931   if (IsPairwise)
3932     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3933     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3934       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3935   else
3936     // Move the upper half of the vector to the lower half.
3937     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3938       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3939 
3940   return ConstantVector::get(ShuffleMask);
3941 }
3942 
3943 namespace {
3944 /// Model horizontal reductions.
3945 ///
3946 /// A horizontal reduction is a tree of reduction operations (currently add and
3947 /// fadd) that has operations that can be put into a vector as its leaf.
3948 /// For example, this tree:
3949 ///
3950 /// mul mul mul mul
3951 ///  \  /    \  /
3952 ///   +       +
3953 ///    \     /
3954 ///       +
3955 /// This tree has "mul" as its reduced values and "+" as its reduction
3956 /// operations. A reduction might be feeding into a store or a binary operation
3957 /// feeding a phi.
3958 ///    ...
3959 ///    \  /
3960 ///     +
3961 ///     |
3962 ///  phi +=
3963 ///
3964 ///  Or:
3965 ///    ...
3966 ///    \  /
3967 ///     +
3968 ///     |
3969 ///   *p =
3970 ///
3971 class HorizontalReduction {
3972   SmallVector<Value *, 16> ReductionOps;
3973   SmallVector<Value *, 32> ReducedVals;
3974 
3975   BinaryOperator *ReductionRoot;
3976   PHINode *ReductionPHI;
3977 
3978   /// The opcode of the reduction.
3979   unsigned ReductionOpcode;
3980   /// The opcode of the values we perform a reduction on.
3981   unsigned ReducedValueOpcode;
3982   /// Should we model this reduction as a pairwise reduction tree or a tree that
3983   /// splits the vector in halves and adds those halves.
3984   bool IsPairwiseReduction;
3985 
3986 public:
3987   /// The width of one full horizontal reduction operation.
3988   unsigned ReduxWidth;
3989 
3990   /// Minimal width of available vector registers. It's used to determine
3991   /// ReduxWidth.
3992   unsigned MinVecRegSize;
3993 
3994   HorizontalReduction(unsigned MinVecRegSize)
3995       : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3996         ReducedValueOpcode(0), IsPairwiseReduction(false), ReduxWidth(0),
3997         MinVecRegSize(MinVecRegSize) {}
3998 
3999   /// \brief Try to find a reduction tree.
4000   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
4001     assert((!Phi || is_contained(Phi->operands(), B)) &&
4002            "Thi phi needs to use the binary operator");
4003 
4004     // We could have a initial reductions that is not an add.
4005     //  r *= v1 + v2 + v3 + v4
4006     // In such a case start looking for a tree rooted in the first '+'.
4007     if (Phi) {
4008       if (B->getOperand(0) == Phi) {
4009         Phi = nullptr;
4010         B = dyn_cast<BinaryOperator>(B->getOperand(1));
4011       } else if (B->getOperand(1) == Phi) {
4012         Phi = nullptr;
4013         B = dyn_cast<BinaryOperator>(B->getOperand(0));
4014       }
4015     }
4016 
4017     if (!B)
4018       return false;
4019 
4020     Type *Ty = B->getType();
4021     if (!isValidElementType(Ty))
4022       return false;
4023 
4024     const DataLayout &DL = B->getModule()->getDataLayout();
4025     ReductionOpcode = B->getOpcode();
4026     ReducedValueOpcode = 0;
4027     // FIXME: Register size should be a parameter to this function, so we can
4028     // try different vectorization factors.
4029     ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
4030     ReductionRoot = B;
4031     ReductionPHI = Phi;
4032 
4033     if (ReduxWidth < 4)
4034       return false;
4035 
4036     // We currently only support adds.
4037     if (ReductionOpcode != Instruction::Add &&
4038         ReductionOpcode != Instruction::FAdd)
4039       return false;
4040 
4041     // Post order traverse the reduction tree starting at B. We only handle true
4042     // trees containing only binary operators or selects.
4043     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
4044     Stack.push_back(std::make_pair(B, 0));
4045     while (!Stack.empty()) {
4046       Instruction *TreeN = Stack.back().first;
4047       unsigned EdgeToVist = Stack.back().second++;
4048       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
4049 
4050       // Only handle trees in the current basic block.
4051       if (TreeN->getParent() != B->getParent())
4052         return false;
4053 
4054       // Each tree node needs to have one user except for the ultimate
4055       // reduction.
4056       if (!TreeN->hasOneUse() && TreeN != B)
4057         return false;
4058 
4059       // Postorder vist.
4060       if (EdgeToVist == 2 || IsReducedValue) {
4061         if (IsReducedValue) {
4062           // Make sure that the opcodes of the operations that we are going to
4063           // reduce match.
4064           if (!ReducedValueOpcode)
4065             ReducedValueOpcode = TreeN->getOpcode();
4066           else if (ReducedValueOpcode != TreeN->getOpcode())
4067             return false;
4068           ReducedVals.push_back(TreeN);
4069         } else {
4070           // We need to be able to reassociate the adds.
4071           if (!TreeN->isAssociative())
4072             return false;
4073           ReductionOps.push_back(TreeN);
4074         }
4075         // Retract.
4076         Stack.pop_back();
4077         continue;
4078       }
4079 
4080       // Visit left or right.
4081       Value *NextV = TreeN->getOperand(EdgeToVist);
4082       // We currently only allow BinaryOperator's and SelectInst's as reduction
4083       // values in our tree.
4084       if (isa<BinaryOperator>(NextV) || isa<SelectInst>(NextV))
4085         Stack.push_back(std::make_pair(cast<Instruction>(NextV), 0));
4086       else if (NextV != Phi)
4087         return false;
4088     }
4089     return true;
4090   }
4091 
4092   /// \brief Attempt to vectorize the tree found by
4093   /// matchAssociativeReduction.
4094   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
4095     if (ReducedVals.empty())
4096       return false;
4097 
4098     unsigned NumReducedVals = ReducedVals.size();
4099     if (NumReducedVals < ReduxWidth)
4100       return false;
4101 
4102     Value *VectorizedTree = nullptr;
4103     IRBuilder<> Builder(ReductionRoot);
4104     FastMathFlags Unsafe;
4105     Unsafe.setUnsafeAlgebra();
4106     Builder.setFastMathFlags(Unsafe);
4107     unsigned i = 0;
4108 
4109     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
4110       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
4111       V.buildTree(VL, ReductionOps);
4112       if (V.shouldReorder()) {
4113         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
4114         V.buildTree(Reversed, ReductionOps);
4115       }
4116       V.computeMinimumValueSizes();
4117 
4118       // Estimate cost.
4119       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
4120       if (Cost >= -SLPCostThreshold)
4121         break;
4122 
4123       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
4124                    << ". (HorRdx)\n");
4125 
4126       // Vectorize a tree.
4127       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4128       Value *VectorizedRoot = V.vectorizeTree();
4129 
4130       // Emit a reduction.
4131       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
4132       if (VectorizedTree) {
4133         Builder.SetCurrentDebugLocation(Loc);
4134         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4135                                      ReducedSubTree, "bin.rdx");
4136       } else
4137         VectorizedTree = ReducedSubTree;
4138     }
4139 
4140     if (VectorizedTree) {
4141       // Finish the reduction.
4142       for (; i < NumReducedVals; ++i) {
4143         Builder.SetCurrentDebugLocation(
4144           cast<Instruction>(ReducedVals[i])->getDebugLoc());
4145         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
4146                                      ReducedVals[i]);
4147       }
4148       // Update users.
4149       if (ReductionPHI) {
4150         assert(ReductionRoot && "Need a reduction operation");
4151         ReductionRoot->setOperand(0, VectorizedTree);
4152         ReductionRoot->setOperand(1, ReductionPHI);
4153       } else
4154         ReductionRoot->replaceAllUsesWith(VectorizedTree);
4155     }
4156     return VectorizedTree != nullptr;
4157   }
4158 
4159   unsigned numReductionValues() const {
4160     return ReducedVals.size();
4161   }
4162 
4163 private:
4164   /// \brief Calculate the cost of a reduction.
4165   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
4166     Type *ScalarTy = FirstReducedVal->getType();
4167     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
4168 
4169     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
4170     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
4171 
4172     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4173     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4174 
4175     int ScalarReduxCost =
4176         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
4177 
4178     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4179                  << " for reduction that starts with " << *FirstReducedVal
4180                  << " (It is a "
4181                  << (IsPairwiseReduction ? "pairwise" : "splitting")
4182                  << " reduction)\n");
4183 
4184     return VecReduxCost - ScalarReduxCost;
4185   }
4186 
4187   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
4188                             Value *R, const Twine &Name = "") {
4189     if (Opcode == Instruction::FAdd)
4190       return Builder.CreateFAdd(L, R, Name);
4191     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
4192   }
4193 
4194   /// \brief Emit a horizontal reduction of the vectorized value.
4195   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
4196     assert(VectorizedValue && "Need to have a vectorized tree node");
4197     assert(isPowerOf2_32(ReduxWidth) &&
4198            "We only handle power-of-two reductions for now");
4199 
4200     Value *TmpVec = VectorizedValue;
4201     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4202       if (IsPairwiseReduction) {
4203         Value *LeftMask =
4204           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
4205         Value *RightMask =
4206           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
4207 
4208         Value *LeftShuf = Builder.CreateShuffleVector(
4209           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
4210         Value *RightShuf = Builder.CreateShuffleVector(
4211           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
4212           "rdx.shuf.r");
4213         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
4214                              "bin.rdx");
4215       } else {
4216         Value *UpperHalf =
4217           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
4218         Value *Shuf = Builder.CreateShuffleVector(
4219           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
4220         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
4221       }
4222     }
4223 
4224     // The result is in the first element of the vector.
4225     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4226   }
4227 };
4228 } // end anonymous namespace
4229 
4230 /// \brief Recognize construction of vectors like
4231 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
4232 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
4233 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
4234 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
4235 ///
4236 /// Returns true if it matches
4237 ///
4238 static bool findBuildVector(InsertElementInst *FirstInsertElem,
4239                             SmallVectorImpl<Value *> &BuildVector,
4240                             SmallVectorImpl<Value *> &BuildVectorOpds) {
4241   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
4242     return false;
4243 
4244   InsertElementInst *IE = FirstInsertElem;
4245   while (true) {
4246     BuildVector.push_back(IE);
4247     BuildVectorOpds.push_back(IE->getOperand(1));
4248 
4249     if (IE->use_empty())
4250       return false;
4251 
4252     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
4253     if (!NextUse)
4254       return true;
4255 
4256     // If this isn't the final use, make sure the next insertelement is the only
4257     // use. It's OK if the final constructed vector is used multiple times
4258     if (!IE->hasOneUse())
4259       return false;
4260 
4261     IE = NextUse;
4262   }
4263 
4264   return false;
4265 }
4266 
4267 /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
4268 ///
4269 /// \return true if it matches.
4270 static bool findBuildAggregate(InsertValueInst *IV,
4271                                SmallVectorImpl<Value *> &BuildVector,
4272                                SmallVectorImpl<Value *> &BuildVectorOpds) {
4273   if (!IV->hasOneUse())
4274     return false;
4275   Value *V = IV->getAggregateOperand();
4276   if (!isa<UndefValue>(V)) {
4277     InsertValueInst *I = dyn_cast<InsertValueInst>(V);
4278     if (!I || !findBuildAggregate(I, BuildVector, BuildVectorOpds))
4279       return false;
4280   }
4281   BuildVector.push_back(IV);
4282   BuildVectorOpds.push_back(IV->getInsertedValueOperand());
4283   return true;
4284 }
4285 
4286 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
4287   return V->getType() < V2->getType();
4288 }
4289 
4290 /// \brief Try and get a reduction value from a phi node.
4291 ///
4292 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
4293 /// if they come from either \p ParentBB or a containing loop latch.
4294 ///
4295 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
4296 /// if not possible.
4297 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
4298                                 BasicBlock *ParentBB, LoopInfo *LI) {
4299   // There are situations where the reduction value is not dominated by the
4300   // reduction phi. Vectorizing such cases has been reported to cause
4301   // miscompiles. See PR25787.
4302   auto DominatedReduxValue = [&](Value *R) {
4303     return (
4304         dyn_cast<Instruction>(R) &&
4305         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
4306   };
4307 
4308   Value *Rdx = nullptr;
4309 
4310   // Return the incoming value if it comes from the same BB as the phi node.
4311   if (P->getIncomingBlock(0) == ParentBB) {
4312     Rdx = P->getIncomingValue(0);
4313   } else if (P->getIncomingBlock(1) == ParentBB) {
4314     Rdx = P->getIncomingValue(1);
4315   }
4316 
4317   if (Rdx && DominatedReduxValue(Rdx))
4318     return Rdx;
4319 
4320   // Otherwise, check whether we have a loop latch to look at.
4321   Loop *BBL = LI->getLoopFor(ParentBB);
4322   if (!BBL)
4323     return nullptr;
4324   BasicBlock *BBLatch = BBL->getLoopLatch();
4325   if (!BBLatch)
4326     return nullptr;
4327 
4328   // There is a loop latch, return the incoming value if it comes from
4329   // that. This reduction pattern occassionaly turns up.
4330   if (P->getIncomingBlock(0) == BBLatch) {
4331     Rdx = P->getIncomingValue(0);
4332   } else if (P->getIncomingBlock(1) == BBLatch) {
4333     Rdx = P->getIncomingValue(1);
4334   }
4335 
4336   if (Rdx && DominatedReduxValue(Rdx))
4337     return Rdx;
4338 
4339   return nullptr;
4340 }
4341 
4342 /// \brief Attempt to reduce a horizontal reduction.
4343 /// If it is legal to match a horizontal reduction feeding
4344 /// the phi node P with reduction operators BI, then check if it
4345 /// can be done.
4346 /// \returns true if a horizontal reduction was matched and reduced.
4347 /// \returns false if a horizontal reduction was not matched.
4348 static bool canMatchHorizontalReduction(PHINode *P, BinaryOperator *BI,
4349                                         BoUpSLP &R, TargetTransformInfo *TTI,
4350                                         unsigned MinRegSize) {
4351   if (!ShouldVectorizeHor)
4352     return false;
4353 
4354   HorizontalReduction HorRdx(MinRegSize);
4355   if (!HorRdx.matchAssociativeReduction(P, BI))
4356     return false;
4357 
4358   // If there is a sufficient number of reduction values, reduce
4359   // to a nearby power-of-2. Can safely generate oversized
4360   // vectors and rely on the backend to split them to legal sizes.
4361   HorRdx.ReduxWidth =
4362     std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
4363 
4364   return HorRdx.tryToReduce(R, TTI);
4365 }
4366 
4367 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
4368   bool Changed = false;
4369   SmallVector<Value *, 4> Incoming;
4370   SmallSet<Value *, 16> VisitedInstrs;
4371 
4372   bool HaveVectorizedPhiNodes = true;
4373   while (HaveVectorizedPhiNodes) {
4374     HaveVectorizedPhiNodes = false;
4375 
4376     // Collect the incoming values from the PHIs.
4377     Incoming.clear();
4378     for (Instruction &I : *BB) {
4379       PHINode *P = dyn_cast<PHINode>(&I);
4380       if (!P)
4381         break;
4382 
4383       if (!VisitedInstrs.count(P))
4384         Incoming.push_back(P);
4385     }
4386 
4387     // Sort by type.
4388     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
4389 
4390     // Try to vectorize elements base on their type.
4391     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
4392                                            E = Incoming.end();
4393          IncIt != E;) {
4394 
4395       // Look for the next elements with the same type.
4396       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
4397       while (SameTypeIt != E &&
4398              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4399         VisitedInstrs.insert(*SameTypeIt);
4400         ++SameTypeIt;
4401       }
4402 
4403       // Try to vectorize them.
4404       unsigned NumElts = (SameTypeIt - IncIt);
4405       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
4406       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
4407         // Success start over because instructions might have been changed.
4408         HaveVectorizedPhiNodes = true;
4409         Changed = true;
4410         break;
4411       }
4412 
4413       // Start over at the next instruction of a different type (or the end).
4414       IncIt = SameTypeIt;
4415     }
4416   }
4417 
4418   VisitedInstrs.clear();
4419 
4420   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
4421     // We may go through BB multiple times so skip the one we have checked.
4422     if (!VisitedInstrs.insert(&*it).second)
4423       continue;
4424 
4425     if (isa<DbgInfoIntrinsic>(it))
4426       continue;
4427 
4428     // Try to vectorize reductions that use PHINodes.
4429     if (PHINode *P = dyn_cast<PHINode>(it)) {
4430       // Check that the PHI is a reduction PHI.
4431       if (P->getNumIncomingValues() != 2)
4432         return Changed;
4433 
4434       Value *Rdx = getReductionValue(DT, P, BB, LI);
4435 
4436       // Check if this is a Binary Operator.
4437       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
4438       if (!BI)
4439         continue;
4440 
4441       // Try to match and vectorize a horizontal reduction.
4442       if (canMatchHorizontalReduction(P, BI, R, TTI, R.getMinVecRegSize())) {
4443         Changed = true;
4444         it = BB->begin();
4445         e = BB->end();
4446         continue;
4447       }
4448 
4449      Value *Inst = BI->getOperand(0);
4450       if (Inst == P)
4451         Inst = BI->getOperand(1);
4452 
4453       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4454         // We would like to start over since some instructions are deleted
4455         // and the iterator may become invalid value.
4456         Changed = true;
4457         it = BB->begin();
4458         e = BB->end();
4459         continue;
4460       }
4461 
4462       continue;
4463     }
4464 
4465     if (ShouldStartVectorizeHorAtStore)
4466       if (StoreInst *SI = dyn_cast<StoreInst>(it))
4467         if (BinaryOperator *BinOp =
4468                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
4469           if (canMatchHorizontalReduction(nullptr, BinOp, R, TTI,
4470                                           R.getMinVecRegSize()) ||
4471               tryToVectorize(BinOp, R)) {
4472             Changed = true;
4473             it = BB->begin();
4474             e = BB->end();
4475             continue;
4476           }
4477         }
4478 
4479     // Try to vectorize horizontal reductions feeding into a return.
4480     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
4481       if (RI->getNumOperands() != 0)
4482         if (BinaryOperator *BinOp =
4483                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
4484           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
4485           if (tryToVectorizePair(BinOp->getOperand(0),
4486                                  BinOp->getOperand(1), R)) {
4487             Changed = true;
4488             it = BB->begin();
4489             e = BB->end();
4490             continue;
4491           }
4492         }
4493 
4494     // Try to vectorize trees that start at compare instructions.
4495     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
4496       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
4497         Changed = true;
4498         // We would like to start over since some instructions are deleted
4499         // and the iterator may become invalid value.
4500         it = BB->begin();
4501         e = BB->end();
4502         continue;
4503       }
4504 
4505       for (int i = 0; i < 2; ++i) {
4506         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
4507           if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
4508             Changed = true;
4509             // We would like to start over since some instructions are deleted
4510             // and the iterator may become invalid value.
4511             it = BB->begin();
4512             e = BB->end();
4513             break;
4514           }
4515         }
4516       }
4517       continue;
4518     }
4519 
4520     // Try to vectorize trees that start at insertelement instructions.
4521     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
4522       SmallVector<Value *, 16> BuildVector;
4523       SmallVector<Value *, 16> BuildVectorOpds;
4524       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
4525         continue;
4526 
4527       // Vectorize starting with the build vector operands ignoring the
4528       // BuildVector instructions for the purpose of scheduling and user
4529       // extraction.
4530       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
4531         Changed = true;
4532         it = BB->begin();
4533         e = BB->end();
4534       }
4535 
4536       continue;
4537     }
4538 
4539     // Try to vectorize trees that start at insertvalue instructions feeding into
4540     // a store.
4541     if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
4542       if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
4543         const DataLayout &DL = BB->getModule()->getDataLayout();
4544         if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
4545           SmallVector<Value *, 16> BuildVector;
4546           SmallVector<Value *, 16> BuildVectorOpds;
4547           if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
4548             continue;
4549 
4550           DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
4551           if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
4552             Changed = true;
4553             it = BB->begin();
4554             e = BB->end();
4555           }
4556           continue;
4557         }
4558       }
4559     }
4560   }
4561 
4562   return Changed;
4563 }
4564 
4565 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
4566   auto Changed = false;
4567   for (auto &Entry : GEPs) {
4568 
4569     // If the getelementptr list has fewer than two elements, there's nothing
4570     // to do.
4571     if (Entry.second.size() < 2)
4572       continue;
4573 
4574     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
4575                  << Entry.second.size() << ".\n");
4576 
4577     // We process the getelementptr list in chunks of 16 (like we do for
4578     // stores) to minimize compile-time.
4579     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
4580       auto Len = std::min<unsigned>(BE - BI, 16);
4581       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
4582 
4583       // Initialize a set a candidate getelementptrs. Note that we use a
4584       // SetVector here to preserve program order. If the index computations
4585       // are vectorizable and begin with loads, we want to minimize the chance
4586       // of having to reorder them later.
4587       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
4588 
4589       // Some of the candidates may have already been vectorized after we
4590       // initially collected them. If so, the WeakVHs will have nullified the
4591       // values, so remove them from the set of candidates.
4592       Candidates.remove(nullptr);
4593 
4594       // Remove from the set of candidates all pairs of getelementptrs with
4595       // constant differences. Such getelementptrs are likely not good
4596       // candidates for vectorization in a bottom-up phase since one can be
4597       // computed from the other. We also ensure all candidate getelementptr
4598       // indices are unique.
4599       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
4600         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
4601         if (!Candidates.count(GEPI))
4602           continue;
4603         auto *SCEVI = SE->getSCEV(GEPList[I]);
4604         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
4605           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
4606           auto *SCEVJ = SE->getSCEV(GEPList[J]);
4607           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
4608             Candidates.remove(GEPList[I]);
4609             Candidates.remove(GEPList[J]);
4610           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
4611             Candidates.remove(GEPList[J]);
4612           }
4613         }
4614       }
4615 
4616       // We break out of the above computation as soon as we know there are
4617       // fewer than two candidates remaining.
4618       if (Candidates.size() < 2)
4619         continue;
4620 
4621       // Add the single, non-constant index of each candidate to the bundle. We
4622       // ensured the indices met these constraints when we originally collected
4623       // the getelementptrs.
4624       SmallVector<Value *, 16> Bundle(Candidates.size());
4625       auto BundleIndex = 0u;
4626       for (auto *V : Candidates) {
4627         auto *GEP = cast<GetElementPtrInst>(V);
4628         auto *GEPIdx = GEP->idx_begin()->get();
4629         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
4630         Bundle[BundleIndex++] = GEPIdx;
4631       }
4632 
4633       // Try and vectorize the indices. We are currently only interested in
4634       // gather-like cases of the form:
4635       //
4636       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
4637       //
4638       // where the loads of "a", the loads of "b", and the subtractions can be
4639       // performed in parallel. It's likely that detecting this pattern in a
4640       // bottom-up phase will be simpler and less costly than building a
4641       // full-blown top-down phase beginning at the consecutive loads.
4642       Changed |= tryToVectorizeList(Bundle, R);
4643     }
4644   }
4645   return Changed;
4646 }
4647 
4648 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
4649   bool Changed = false;
4650   // Attempt to sort and vectorize each of the store-groups.
4651   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
4652        ++it) {
4653     if (it->second.size() < 2)
4654       continue;
4655 
4656     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
4657           << it->second.size() << ".\n");
4658 
4659     // Process the stores in chunks of 16.
4660     // TODO: The limit of 16 inhibits greater vectorization factors.
4661     //       For example, AVX2 supports v32i8. Increasing this limit, however,
4662     //       may cause a significant compile-time increase.
4663     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
4664       unsigned Len = std::min<unsigned>(CE - CI, 16);
4665       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
4666                                  -SLPCostThreshold, R);
4667     }
4668   }
4669   return Changed;
4670 }
4671 
4672 char SLPVectorizer::ID = 0;
4673 static const char lv_name[] = "SLP Vectorizer";
4674 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
4675 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4676 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4677 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4678 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
4679 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4680 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
4681 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
4682 
4683 namespace llvm {
4684 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
4685 }
4686