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