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