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