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