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