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