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/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.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/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
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/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (hasVectorIntrinsicScalarOpd(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Gets reordering data for the given tree entry. If the entry is vectorized
933   /// - just return ReorderIndices, otherwise check if the scalars can be
934   /// reordered and return the most optimal order.
935   /// \param TopToBottom If true, include the order of vectorized stores and
936   /// insertelement nodes, otherwise skip them.
937   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
938 
939   /// Reorders the current graph to the most profitable order starting from the
940   /// root node to the leaf nodes. The best order is chosen only from the nodes
941   /// of the same size (vectorization factor). Smaller nodes are considered
942   /// parts of subgraph with smaller VF and they are reordered independently. We
943   /// can make it because we still need to extend smaller nodes to the wider VF
944   /// and we can merge reordering shuffles with the widening shuffles.
945   void reorderTopToBottom();
946 
947   /// Reorders the current graph to the most profitable order starting from
948   /// leaves to the root. It allows to rotate small subgraphs and reduce the
949   /// number of reshuffles if the leaf nodes use the same order. In this case we
950   /// can merge the orders and just shuffle user node instead of shuffling its
951   /// operands. Plus, even the leaf nodes have different orders, it allows to
952   /// sink reordering in the graph closer to the root node and merge it later
953   /// during analysis.
954   void reorderBottomToTop(bool IgnoreReorder = false);
955 
956   /// \return The vector element size in bits to use when vectorizing the
957   /// expression tree ending at \p V. If V is a store, the size is the width of
958   /// the stored value. Otherwise, the size is the width of the largest loaded
959   /// value reaching V. This method is used by the vectorizer to calculate
960   /// vectorization factors.
961   unsigned getVectorElementSize(Value *V);
962 
963   /// Compute the minimum type sizes required to represent the entries in a
964   /// vectorizable tree.
965   void computeMinimumValueSizes();
966 
967   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
968   unsigned getMaxVecRegSize() const {
969     return MaxVecRegSize;
970   }
971 
972   // \returns minimum vector register size as set by cl::opt.
973   unsigned getMinVecRegSize() const {
974     return MinVecRegSize;
975   }
976 
977   unsigned getMinVF(unsigned Sz) const {
978     return std::max(2U, getMinVecRegSize() / Sz);
979   }
980 
981   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
982     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
983       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
984     return MaxVF ? MaxVF : UINT_MAX;
985   }
986 
987   /// Check if homogeneous aggregate is isomorphic to some VectorType.
988   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
989   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
990   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
991   ///
992   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
993   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
994 
995   /// \returns True if the VectorizableTree is both tiny and not fully
996   /// vectorizable. We do not vectorize such trees.
997   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
998 
999   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1007 
1008   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1009   /// can be load combined in the backend. Load combining may not be allowed in
1010   /// the IR optimizer, so we do not want to alter the pattern. For example,
1011   /// partially transforming a scalar bswap() pattern into vector code is
1012   /// effectively impossible for the backend to undo.
1013   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1014   ///       may not be necessary.
1015   bool isLoadCombineCandidate() const;
1016 
1017   OptimizationRemarkEmitter *getORE() { return ORE; }
1018 
1019   /// This structure holds any data we need about the edges being traversed
1020   /// during buildTree_rec(). We keep track of:
1021   /// (i) the user TreeEntry index, and
1022   /// (ii) the index of the edge.
1023   struct EdgeInfo {
1024     EdgeInfo() = default;
1025     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1026         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1027     /// The user TreeEntry.
1028     TreeEntry *UserTE = nullptr;
1029     /// The operand index of the use.
1030     unsigned EdgeIdx = UINT_MAX;
1031 #ifndef NDEBUG
1032     friend inline raw_ostream &operator<<(raw_ostream &OS,
1033                                           const BoUpSLP::EdgeInfo &EI) {
1034       EI.dump(OS);
1035       return OS;
1036     }
1037     /// Debug print.
1038     void dump(raw_ostream &OS) const {
1039       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1040          << " EdgeIdx:" << EdgeIdx << "}";
1041     }
1042     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1043 #endif
1044   };
1045 
1046   /// A helper class used for scoring candidates for two consecutive lanes.
1047   class LookAheadHeuristics {
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051     int NumLanes; // Total number of lanes (aka vectorization factor).
1052     int MaxLevel; // The maximum recursion depth for accumulating score.
1053 
1054   public:
1055     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1056                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1057         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1058 
1059     // The hard-coded scores listed here are not very important, though it shall
1060     // be higher for better matches to improve the resulting cost. When
1061     // computing the scores of matching one sub-tree with another, we are
1062     // basically counting the number of values that are matching. So even if all
1063     // scores are set to 1, we would still get a decent matching result.
1064     // However, sometimes we have to break ties. For example we may have to
1065     // choose between matching loads vs matching opcodes. This is what these
1066     // scores are helping us with: they provide the order of preference. Also,
1067     // this is important if the scalar is externally used or used in another
1068     // tree entry node in the different lane.
1069 
1070     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1071     static const int ScoreConsecutiveLoads = 4;
1072     /// The same load multiple times. This should have a better score than
1073     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1074     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1075     /// a vector load and 1.0 for a broadcast.
1076     static const int ScoreSplatLoads = 3;
1077     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1078     static const int ScoreReversedLoads = 3;
1079     /// ExtractElementInst from same vector and consecutive indexes.
1080     static const int ScoreConsecutiveExtracts = 4;
1081     /// ExtractElementInst from same vector and reversed indices.
1082     static const int ScoreReversedExtracts = 3;
1083     /// Constants.
1084     static const int ScoreConstants = 2;
1085     /// Instructions with the same opcode.
1086     static const int ScoreSameOpcode = 2;
1087     /// Instructions with alt opcodes (e.g, add + sub).
1088     static const int ScoreAltOpcodes = 1;
1089     /// Identical instructions (a.k.a. splat or broadcast).
1090     static const int ScoreSplat = 1;
1091     /// Matching with an undef is preferable to failing.
1092     static const int ScoreUndef = 1;
1093     /// Score for failing to find a decent match.
1094     static const int ScoreFail = 0;
1095     /// Score if all users are vectorized.
1096     static const int ScoreAllUserVectorized = 1;
1097 
1098     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1099     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1100     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1101     /// MainAltOps.
1102     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1103                         ArrayRef<Value *> MainAltOps) const {
1104       if (V1 == V2) {
1105         if (isa<LoadInst>(V1)) {
1106           // Retruns true if the users of V1 and V2 won't need to be extracted.
1107           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1108             // Bail out if we have too many uses to save compilation time.
1109             static constexpr unsigned Limit = 8;
1110             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1111               return false;
1112 
1113             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1114               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1115                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1116               });
1117             };
1118             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1119           };
1120           // A broadcast of a load can be cheaper on some targets.
1121           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1122                                           ElementCount::getFixed(NumLanes)) &&
1123               ((int)V1->getNumUses() == NumLanes ||
1124                AllUsersAreInternal(V1, V2)))
1125             return LookAheadHeuristics::ScoreSplatLoads;
1126         }
1127         return LookAheadHeuristics::ScoreSplat;
1128       }
1129 
1130       auto *LI1 = dyn_cast<LoadInst>(V1);
1131       auto *LI2 = dyn_cast<LoadInst>(V2);
1132       if (LI1 && LI2) {
1133         if (LI1->getParent() != LI2->getParent())
1134           return LookAheadHeuristics::ScoreFail;
1135 
1136         Optional<int> Dist = getPointersDiff(
1137             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1138             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1139         if (!Dist || *Dist == 0)
1140           return LookAheadHeuristics::ScoreFail;
1141         // The distance is too large - still may be profitable to use masked
1142         // loads/gathers.
1143         if (std::abs(*Dist) > NumLanes / 2)
1144           return LookAheadHeuristics::ScoreAltOpcodes;
1145         // This still will detect consecutive loads, but we might have "holes"
1146         // in some cases. It is ok for non-power-2 vectorization and may produce
1147         // better results. It should not affect current vectorization.
1148         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1149                            : LookAheadHeuristics::ScoreReversedLoads;
1150       }
1151 
1152       auto *C1 = dyn_cast<Constant>(V1);
1153       auto *C2 = dyn_cast<Constant>(V2);
1154       if (C1 && C2)
1155         return LookAheadHeuristics::ScoreConstants;
1156 
1157       // Extracts from consecutive indexes of the same vector better score as
1158       // the extracts could be optimized away.
1159       Value *EV1;
1160       ConstantInt *Ex1Idx;
1161       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1162         // Undefs are always profitable for extractelements.
1163         if (isa<UndefValue>(V2))
1164           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1165         Value *EV2 = nullptr;
1166         ConstantInt *Ex2Idx = nullptr;
1167         if (match(V2,
1168                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1169                                                          m_Undef())))) {
1170           // Undefs are always profitable for extractelements.
1171           if (!Ex2Idx)
1172             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1173           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1174             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1175           if (EV2 == EV1) {
1176             int Idx1 = Ex1Idx->getZExtValue();
1177             int Idx2 = Ex2Idx->getZExtValue();
1178             int Dist = Idx2 - Idx1;
1179             // The distance is too large - still may be profitable to use
1180             // shuffles.
1181             if (std::abs(Dist) == 0)
1182               return LookAheadHeuristics::ScoreSplat;
1183             if (std::abs(Dist) > NumLanes / 2)
1184               return LookAheadHeuristics::ScoreSameOpcode;
1185             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1186                               : LookAheadHeuristics::ScoreReversedExtracts;
1187           }
1188           return LookAheadHeuristics::ScoreAltOpcodes;
1189         }
1190         return LookAheadHeuristics::ScoreFail;
1191       }
1192 
1193       auto *I1 = dyn_cast<Instruction>(V1);
1194       auto *I2 = dyn_cast<Instruction>(V2);
1195       if (I1 && I2) {
1196         if (I1->getParent() != I2->getParent())
1197           return LookAheadHeuristics::ScoreFail;
1198         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1199         Ops.push_back(I1);
1200         Ops.push_back(I2);
1201         InstructionsState S = getSameOpcode(Ops);
1202         // Note: Only consider instructions with <= 2 operands to avoid
1203         // complexity explosion.
1204         if (S.getOpcode() &&
1205             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1206              !S.isAltShuffle()) &&
1207             all_of(Ops, [&S](Value *V) {
1208               return cast<Instruction>(V)->getNumOperands() ==
1209                      S.MainOp->getNumOperands();
1210             }))
1211           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1212                                   : LookAheadHeuristics::ScoreSameOpcode;
1213       }
1214 
1215       if (isa<UndefValue>(V2))
1216         return LookAheadHeuristics::ScoreUndef;
1217 
1218       return LookAheadHeuristics::ScoreFail;
1219     }
1220 
1221     /// Go through the operands of \p LHS and \p RHS recursively until
1222     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1223     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1224     /// of \p U1 and \p U2), except at the beginning of the recursion where
1225     /// these are set to nullptr.
1226     ///
1227     /// For example:
1228     /// \verbatim
1229     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1230     ///     \ /         \ /         \ /        \ /
1231     ///      +           +           +          +
1232     ///     G1          G2          G3         G4
1233     /// \endverbatim
1234     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1235     /// each level recursively, accumulating the score. It starts from matching
1236     /// the additions at level 0, then moves on to the loads (level 1). The
1237     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1238     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1239     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1240     /// Please note that the order of the operands does not matter, as we
1241     /// evaluate the score of all profitable combinations of operands. In
1242     /// other words the score of G1 and G4 is the same as G1 and G2. This
1243     /// heuristic is based on ideas described in:
1244     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1245     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1246     ///   Luís F. W. Góes
1247     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1248                            Instruction *U2, int CurrLevel,
1249                            ArrayRef<Value *> MainAltOps) const {
1250 
1251       // Get the shallow score of V1 and V2.
1252       int ShallowScoreAtThisLevel =
1253           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1254 
1255       // If reached MaxLevel,
1256       //  or if V1 and V2 are not instructions,
1257       //  or if they are SPLAT,
1258       //  or if they are not consecutive,
1259       //  or if profitable to vectorize loads or extractelements, early return
1260       //  the current cost.
1261       auto *I1 = dyn_cast<Instruction>(LHS);
1262       auto *I2 = dyn_cast<Instruction>(RHS);
1263       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1264           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1265           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1266             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1267             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1268            ShallowScoreAtThisLevel))
1269         return ShallowScoreAtThisLevel;
1270       assert(I1 && I2 && "Should have early exited.");
1271 
1272       // Contains the I2 operand indexes that got matched with I1 operands.
1273       SmallSet<unsigned, 4> Op2Used;
1274 
1275       // Recursion towards the operands of I1 and I2. We are trying all possible
1276       // operand pairs, and keeping track of the best score.
1277       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1278            OpIdx1 != NumOperands1; ++OpIdx1) {
1279         // Try to pair op1I with the best operand of I2.
1280         int MaxTmpScore = 0;
1281         unsigned MaxOpIdx2 = 0;
1282         bool FoundBest = false;
1283         // If I2 is commutative try all combinations.
1284         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1285         unsigned ToIdx = isCommutative(I2)
1286                              ? I2->getNumOperands()
1287                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1288         assert(FromIdx <= ToIdx && "Bad index");
1289         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1290           // Skip operands already paired with OpIdx1.
1291           if (Op2Used.count(OpIdx2))
1292             continue;
1293           // Recursively calculate the cost at each level
1294           int TmpScore =
1295               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1296                                  I1, I2, CurrLevel + 1, None);
1297           // Look for the best score.
1298           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1299               TmpScore > MaxTmpScore) {
1300             MaxTmpScore = TmpScore;
1301             MaxOpIdx2 = OpIdx2;
1302             FoundBest = true;
1303           }
1304         }
1305         if (FoundBest) {
1306           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1307           Op2Used.insert(MaxOpIdx2);
1308           ShallowScoreAtThisLevel += MaxTmpScore;
1309         }
1310       }
1311       return ShallowScoreAtThisLevel;
1312     }
1313   };
1314   /// A helper data structure to hold the operands of a vector of instructions.
1315   /// This supports a fixed vector length for all operand vectors.
1316   class VLOperands {
1317     /// For each operand we need (i) the value, and (ii) the opcode that it
1318     /// would be attached to if the expression was in a left-linearized form.
1319     /// This is required to avoid illegal operand reordering.
1320     /// For example:
1321     /// \verbatim
1322     ///                         0 Op1
1323     ///                         |/
1324     /// Op1 Op2   Linearized    + Op2
1325     ///   \ /     ---------->   |/
1326     ///    -                    -
1327     ///
1328     /// Op1 - Op2            (0 + Op1) - Op2
1329     /// \endverbatim
1330     ///
1331     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1332     ///
1333     /// Another way to think of this is to track all the operations across the
1334     /// path from the operand all the way to the root of the tree and to
1335     /// calculate the operation that corresponds to this path. For example, the
1336     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1337     /// corresponding operation is a '-' (which matches the one in the
1338     /// linearized tree, as shown above).
1339     ///
1340     /// For lack of a better term, we refer to this operation as Accumulated
1341     /// Path Operation (APO).
1342     struct OperandData {
1343       OperandData() = default;
1344       OperandData(Value *V, bool APO, bool IsUsed)
1345           : V(V), APO(APO), IsUsed(IsUsed) {}
1346       /// The operand value.
1347       Value *V = nullptr;
1348       /// TreeEntries only allow a single opcode, or an alternate sequence of
1349       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1350       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1351       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1352       /// (e.g., Add/Mul)
1353       bool APO = false;
1354       /// Helper data for the reordering function.
1355       bool IsUsed = false;
1356     };
1357 
1358     /// During operand reordering, we are trying to select the operand at lane
1359     /// that matches best with the operand at the neighboring lane. Our
1360     /// selection is based on the type of value we are looking for. For example,
1361     /// if the neighboring lane has a load, we need to look for a load that is
1362     /// accessing a consecutive address. These strategies are summarized in the
1363     /// 'ReorderingMode' enumerator.
1364     enum class ReorderingMode {
1365       Load,     ///< Matching loads to consecutive memory addresses
1366       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1367       Constant, ///< Matching constants
1368       Splat,    ///< Matching the same instruction multiple times (broadcast)
1369       Failed,   ///< We failed to create a vectorizable group
1370     };
1371 
1372     using OperandDataVec = SmallVector<OperandData, 2>;
1373 
1374     /// A vector of operand vectors.
1375     SmallVector<OperandDataVec, 4> OpsVec;
1376 
1377     const DataLayout &DL;
1378     ScalarEvolution &SE;
1379     const BoUpSLP &R;
1380 
1381     /// \returns the operand data at \p OpIdx and \p Lane.
1382     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1383       return OpsVec[OpIdx][Lane];
1384     }
1385 
1386     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1387     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1388       return OpsVec[OpIdx][Lane];
1389     }
1390 
1391     /// Clears the used flag for all entries.
1392     void clearUsed() {
1393       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1394            OpIdx != NumOperands; ++OpIdx)
1395         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1396              ++Lane)
1397           OpsVec[OpIdx][Lane].IsUsed = false;
1398     }
1399 
1400     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1401     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1402       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1403     }
1404 
1405     /// \param Lane lane of the operands under analysis.
1406     /// \param OpIdx operand index in \p Lane lane we're looking the best
1407     /// candidate for.
1408     /// \param Idx operand index of the current candidate value.
1409     /// \returns The additional score due to possible broadcasting of the
1410     /// elements in the lane. It is more profitable to have power-of-2 unique
1411     /// elements in the lane, it will be vectorized with higher probability
1412     /// after removing duplicates. Currently the SLP vectorizer supports only
1413     /// vectorization of the power-of-2 number of unique scalars.
1414     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1415       Value *IdxLaneV = getData(Idx, Lane).V;
1416       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1417         return 0;
1418       SmallPtrSet<Value *, 4> Uniques;
1419       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1420         if (Ln == Lane)
1421           continue;
1422         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1423         if (!isa<Instruction>(OpIdxLnV))
1424           return 0;
1425         Uniques.insert(OpIdxLnV);
1426       }
1427       int UniquesCount = Uniques.size();
1428       int UniquesCntWithIdxLaneV =
1429           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1430       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1431       int UniquesCntWithOpIdxLaneV =
1432           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1434         return 0;
1435       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1436               UniquesCntWithOpIdxLaneV) -
1437              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1438     }
1439 
1440     /// \param Lane lane of the operands under analysis.
1441     /// \param OpIdx operand index in \p Lane lane we're looking the best
1442     /// candidate for.
1443     /// \param Idx operand index of the current candidate value.
1444     /// \returns The additional score for the scalar which users are all
1445     /// vectorized.
1446     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1447       Value *IdxLaneV = getData(Idx, Lane).V;
1448       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1449       // Do not care about number of uses for vector-like instructions
1450       // (extractelement/extractvalue with constant indices), they are extracts
1451       // themselves and already externally used. Vectorization of such
1452       // instructions does not add extra extractelement instruction, just may
1453       // remove it.
1454       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1455           isVectorLikeInstWithConstOps(OpIdxLaneV))
1456         return LookAheadHeuristics::ScoreAllUserVectorized;
1457       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1458       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1459         return 0;
1460       return R.areAllUsersVectorized(IdxLaneI, None)
1461                  ? LookAheadHeuristics::ScoreAllUserVectorized
1462                  : 0;
1463     }
1464 
1465     /// Score scaling factor for fully compatible instructions but with
1466     /// different number of external uses. Allows better selection of the
1467     /// instructions with less external uses.
1468     static const int ScoreScaleFactor = 10;
1469 
1470     /// \Returns the look-ahead score, which tells us how much the sub-trees
1471     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1472     /// score. This helps break ties in an informed way when we cannot decide on
1473     /// the order of the operands by just considering the immediate
1474     /// predecessors.
1475     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1476                           int Lane, unsigned OpIdx, unsigned Idx,
1477                           bool &IsUsed) {
1478       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1479                                     LookAheadMaxDepth);
1480       // Keep track of the instruction stack as we recurse into the operands
1481       // during the look-ahead score exploration.
1482       int Score =
1483           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1484                                        /*CurrLevel=*/1, MainAltOps);
1485       if (Score) {
1486         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1487         if (Score <= -SplatScore) {
1488           // Set the minimum score for splat-like sequence to avoid setting
1489           // failed state.
1490           Score = 1;
1491         } else {
1492           Score += SplatScore;
1493           // Scale score to see the difference between different operands
1494           // and similar operands but all vectorized/not all vectorized
1495           // uses. It does not affect actual selection of the best
1496           // compatible operand in general, just allows to select the
1497           // operand with all vectorized uses.
1498           Score *= ScoreScaleFactor;
1499           Score += getExternalUseScore(Lane, OpIdx, Idx);
1500           IsUsed = true;
1501         }
1502       }
1503       return Score;
1504     }
1505 
1506     /// Best defined scores per lanes between the passes. Used to choose the
1507     /// best operand (with the highest score) between the passes.
1508     /// The key - {Operand Index, Lane}.
1509     /// The value - the best score between the passes for the lane and the
1510     /// operand.
1511     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1512         BestScoresPerLanes;
1513 
1514     // Search all operands in Ops[*][Lane] for the one that matches best
1515     // Ops[OpIdx][LastLane] and return its opreand index.
1516     // If no good match can be found, return None.
1517     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1518                                       ArrayRef<ReorderingMode> ReorderingModes,
1519                                       ArrayRef<Value *> MainAltOps) {
1520       unsigned NumOperands = getNumOperands();
1521 
1522       // The operand of the previous lane at OpIdx.
1523       Value *OpLastLane = getData(OpIdx, LastLane).V;
1524 
1525       // Our strategy mode for OpIdx.
1526       ReorderingMode RMode = ReorderingModes[OpIdx];
1527       if (RMode == ReorderingMode::Failed)
1528         return None;
1529 
1530       // The linearized opcode of the operand at OpIdx, Lane.
1531       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1532 
1533       // The best operand index and its score.
1534       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1535       // are using the score to differentiate between the two.
1536       struct BestOpData {
1537         Optional<unsigned> Idx = None;
1538         unsigned Score = 0;
1539       } BestOp;
1540       BestOp.Score =
1541           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1542               .first->second;
1543 
1544       // Track if the operand must be marked as used. If the operand is set to
1545       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1546       // want to reestimate the operands again on the following iterations).
1547       bool IsUsed =
1548           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1549       // Iterate through all unused operands and look for the best.
1550       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1551         // Get the operand at Idx and Lane.
1552         OperandData &OpData = getData(Idx, Lane);
1553         Value *Op = OpData.V;
1554         bool OpAPO = OpData.APO;
1555 
1556         // Skip already selected operands.
1557         if (OpData.IsUsed)
1558           continue;
1559 
1560         // Skip if we are trying to move the operand to a position with a
1561         // different opcode in the linearized tree form. This would break the
1562         // semantics.
1563         if (OpAPO != OpIdxAPO)
1564           continue;
1565 
1566         // Look for an operand that matches the current mode.
1567         switch (RMode) {
1568         case ReorderingMode::Load:
1569         case ReorderingMode::Constant:
1570         case ReorderingMode::Opcode: {
1571           bool LeftToRight = Lane > LastLane;
1572           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1573           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1574           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1575                                         OpIdx, Idx, IsUsed);
1576           if (Score > static_cast<int>(BestOp.Score)) {
1577             BestOp.Idx = Idx;
1578             BestOp.Score = Score;
1579             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1580           }
1581           break;
1582         }
1583         case ReorderingMode::Splat:
1584           if (Op == OpLastLane)
1585             BestOp.Idx = Idx;
1586           break;
1587         case ReorderingMode::Failed:
1588           llvm_unreachable("Not expected Failed reordering mode.");
1589         }
1590       }
1591 
1592       if (BestOp.Idx) {
1593         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1594         return BestOp.Idx;
1595       }
1596       // If we could not find a good match return None.
1597       return None;
1598     }
1599 
1600     /// Helper for reorderOperandVecs.
1601     /// \returns the lane that we should start reordering from. This is the one
1602     /// which has the least number of operands that can freely move about or
1603     /// less profitable because it already has the most optimal set of operands.
1604     unsigned getBestLaneToStartReordering() const {
1605       unsigned Min = UINT_MAX;
1606       unsigned SameOpNumber = 0;
1607       // std::pair<unsigned, unsigned> is used to implement a simple voting
1608       // algorithm and choose the lane with the least number of operands that
1609       // can freely move about or less profitable because it already has the
1610       // most optimal set of operands. The first unsigned is a counter for
1611       // voting, the second unsigned is the counter of lanes with instructions
1612       // with same/alternate opcodes and same parent basic block.
1613       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1614       // Try to be closer to the original results, if we have multiple lanes
1615       // with same cost. If 2 lanes have the same cost, use the one with the
1616       // lowest index.
1617       for (int I = getNumLanes(); I > 0; --I) {
1618         unsigned Lane = I - 1;
1619         OperandsOrderData NumFreeOpsHash =
1620             getMaxNumOperandsThatCanBeReordered(Lane);
1621         // Compare the number of operands that can move and choose the one with
1622         // the least number.
1623         if (NumFreeOpsHash.NumOfAPOs < Min) {
1624           Min = NumFreeOpsHash.NumOfAPOs;
1625           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1626           HashMap.clear();
1627           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1628         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1629                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1630           // Select the most optimal lane in terms of number of operands that
1631           // should be moved around.
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1634         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1635                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1636           auto It = HashMap.find(NumFreeOpsHash.Hash);
1637           if (It == HashMap.end())
1638             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1639           else
1640             ++It->second.first;
1641         }
1642       }
1643       // Select the lane with the minimum counter.
1644       unsigned BestLane = 0;
1645       unsigned CntMin = UINT_MAX;
1646       for (const auto &Data : reverse(HashMap)) {
1647         if (Data.second.first < CntMin) {
1648           CntMin = Data.second.first;
1649           BestLane = Data.second.second;
1650         }
1651       }
1652       return BestLane;
1653     }
1654 
1655     /// Data structure that helps to reorder operands.
1656     struct OperandsOrderData {
1657       /// The best number of operands with the same APOs, which can be
1658       /// reordered.
1659       unsigned NumOfAPOs = UINT_MAX;
1660       /// Number of operands with the same/alternate instruction opcode and
1661       /// parent.
1662       unsigned NumOpsWithSameOpcodeParent = 0;
1663       /// Hash for the actual operands ordering.
1664       /// Used to count operands, actually their position id and opcode
1665       /// value. It is used in the voting mechanism to find the lane with the
1666       /// least number of operands that can freely move about or less profitable
1667       /// because it already has the most optimal set of operands. Can be
1668       /// replaced with SmallVector<unsigned> instead but hash code is faster
1669       /// and requires less memory.
1670       unsigned Hash = 0;
1671     };
1672     /// \returns the maximum number of operands that are allowed to be reordered
1673     /// for \p Lane and the number of compatible instructions(with the same
1674     /// parent/opcode). This is used as a heuristic for selecting the first lane
1675     /// to start operand reordering.
1676     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1677       unsigned CntTrue = 0;
1678       unsigned NumOperands = getNumOperands();
1679       // Operands with the same APO can be reordered. We therefore need to count
1680       // how many of them we have for each APO, like this: Cnt[APO] = x.
1681       // Since we only have two APOs, namely true and false, we can avoid using
1682       // a map. Instead we can simply count the number of operands that
1683       // correspond to one of them (in this case the 'true' APO), and calculate
1684       // the other by subtracting it from the total number of operands.
1685       // Operands with the same instruction opcode and parent are more
1686       // profitable since we don't need to move them in many cases, with a high
1687       // probability such lane already can be vectorized effectively.
1688       bool AllUndefs = true;
1689       unsigned NumOpsWithSameOpcodeParent = 0;
1690       Instruction *OpcodeI = nullptr;
1691       BasicBlock *Parent = nullptr;
1692       unsigned Hash = 0;
1693       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1694         const OperandData &OpData = getData(OpIdx, Lane);
1695         if (OpData.APO)
1696           ++CntTrue;
1697         // Use Boyer-Moore majority voting for finding the majority opcode and
1698         // the number of times it occurs.
1699         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1700           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1701               I->getParent() != Parent) {
1702             if (NumOpsWithSameOpcodeParent == 0) {
1703               NumOpsWithSameOpcodeParent = 1;
1704               OpcodeI = I;
1705               Parent = I->getParent();
1706             } else {
1707               --NumOpsWithSameOpcodeParent;
1708             }
1709           } else {
1710             ++NumOpsWithSameOpcodeParent;
1711           }
1712         }
1713         Hash = hash_combine(
1714             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1715         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1716       }
1717       if (AllUndefs)
1718         return {};
1719       OperandsOrderData Data;
1720       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1721       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1722       Data.Hash = Hash;
1723       return Data;
1724     }
1725 
1726     /// Go through the instructions in VL and append their operands.
1727     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1728       assert(!VL.empty() && "Bad VL");
1729       assert((empty() || VL.size() == getNumLanes()) &&
1730              "Expected same number of lanes");
1731       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1732       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1733       OpsVec.resize(NumOperands);
1734       unsigned NumLanes = VL.size();
1735       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1736         OpsVec[OpIdx].resize(NumLanes);
1737         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1738           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1739           // Our tree has just 3 nodes: the root and two operands.
1740           // It is therefore trivial to get the APO. We only need to check the
1741           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1742           // RHS operand. The LHS operand of both add and sub is never attached
1743           // to an inversese operation in the linearized form, therefore its APO
1744           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1745 
1746           // Since operand reordering is performed on groups of commutative
1747           // operations or alternating sequences (e.g., +, -), we can safely
1748           // tell the inverse operations by checking commutativity.
1749           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1750           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1751           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1752                                  APO, false};
1753         }
1754       }
1755     }
1756 
1757     /// \returns the number of operands.
1758     unsigned getNumOperands() const { return OpsVec.size(); }
1759 
1760     /// \returns the number of lanes.
1761     unsigned getNumLanes() const { return OpsVec[0].size(); }
1762 
1763     /// \returns the operand value at \p OpIdx and \p Lane.
1764     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1765       return getData(OpIdx, Lane).V;
1766     }
1767 
1768     /// \returns true if the data structure is empty.
1769     bool empty() const { return OpsVec.empty(); }
1770 
1771     /// Clears the data.
1772     void clear() { OpsVec.clear(); }
1773 
1774     /// \Returns true if there are enough operands identical to \p Op to fill
1775     /// the whole vector.
1776     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1777     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1778       bool OpAPO = getData(OpIdx, Lane).APO;
1779       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1780         if (Ln == Lane)
1781           continue;
1782         // This is set to true if we found a candidate for broadcast at Lane.
1783         bool FoundCandidate = false;
1784         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1785           OperandData &Data = getData(OpI, Ln);
1786           if (Data.APO != OpAPO || Data.IsUsed)
1787             continue;
1788           if (Data.V == Op) {
1789             FoundCandidate = true;
1790             Data.IsUsed = true;
1791             break;
1792           }
1793         }
1794         if (!FoundCandidate)
1795           return false;
1796       }
1797       return true;
1798     }
1799 
1800   public:
1801     /// Initialize with all the operands of the instruction vector \p RootVL.
1802     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1803                ScalarEvolution &SE, const BoUpSLP &R)
1804         : DL(DL), SE(SE), R(R) {
1805       // Append all the operands of RootVL.
1806       appendOperandsOfVL(RootVL);
1807     }
1808 
1809     /// \Returns a value vector with the operands across all lanes for the
1810     /// opearnd at \p OpIdx.
1811     ValueList getVL(unsigned OpIdx) const {
1812       ValueList OpVL(OpsVec[OpIdx].size());
1813       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1814              "Expected same num of lanes across all operands");
1815       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1816         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1817       return OpVL;
1818     }
1819 
1820     // Performs operand reordering for 2 or more operands.
1821     // The original operands are in OrigOps[OpIdx][Lane].
1822     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1823     void reorder() {
1824       unsigned NumOperands = getNumOperands();
1825       unsigned NumLanes = getNumLanes();
1826       // Each operand has its own mode. We are using this mode to help us select
1827       // the instructions for each lane, so that they match best with the ones
1828       // we have selected so far.
1829       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1830 
1831       // This is a greedy single-pass algorithm. We are going over each lane
1832       // once and deciding on the best order right away with no back-tracking.
1833       // However, in order to increase its effectiveness, we start with the lane
1834       // that has operands that can move the least. For example, given the
1835       // following lanes:
1836       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1837       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1838       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1839       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1840       // we will start at Lane 1, since the operands of the subtraction cannot
1841       // be reordered. Then we will visit the rest of the lanes in a circular
1842       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1843 
1844       // Find the first lane that we will start our search from.
1845       unsigned FirstLane = getBestLaneToStartReordering();
1846 
1847       // Initialize the modes.
1848       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1849         Value *OpLane0 = getValue(OpIdx, FirstLane);
1850         // Keep track if we have instructions with all the same opcode on one
1851         // side.
1852         if (isa<LoadInst>(OpLane0))
1853           ReorderingModes[OpIdx] = ReorderingMode::Load;
1854         else if (isa<Instruction>(OpLane0)) {
1855           // Check if OpLane0 should be broadcast.
1856           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1857             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1858           else
1859             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1860         }
1861         else if (isa<Constant>(OpLane0))
1862           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1863         else if (isa<Argument>(OpLane0))
1864           // Our best hope is a Splat. It may save some cost in some cases.
1865           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1866         else
1867           // NOTE: This should be unreachable.
1868           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1869       }
1870 
1871       // Check that we don't have same operands. No need to reorder if operands
1872       // are just perfect diamond or shuffled diamond match. Do not do it only
1873       // for possible broadcasts or non-power of 2 number of scalars (just for
1874       // now).
1875       auto &&SkipReordering = [this]() {
1876         SmallPtrSet<Value *, 4> UniqueValues;
1877         ArrayRef<OperandData> Op0 = OpsVec.front();
1878         for (const OperandData &Data : Op0)
1879           UniqueValues.insert(Data.V);
1880         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1881           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1882                 return !UniqueValues.contains(Data.V);
1883               }))
1884             return false;
1885         }
1886         // TODO: Check if we can remove a check for non-power-2 number of
1887         // scalars after full support of non-power-2 vectorization.
1888         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1889       };
1890 
1891       // If the initial strategy fails for any of the operand indexes, then we
1892       // perform reordering again in a second pass. This helps avoid assigning
1893       // high priority to the failed strategy, and should improve reordering for
1894       // the non-failed operand indexes.
1895       for (int Pass = 0; Pass != 2; ++Pass) {
1896         // Check if no need to reorder operands since they're are perfect or
1897         // shuffled diamond match.
1898         // Need to to do it to avoid extra external use cost counting for
1899         // shuffled matches, which may cause regressions.
1900         if (SkipReordering())
1901           break;
1902         // Skip the second pass if the first pass did not fail.
1903         bool StrategyFailed = false;
1904         // Mark all operand data as free to use.
1905         clearUsed();
1906         // We keep the original operand order for the FirstLane, so reorder the
1907         // rest of the lanes. We are visiting the nodes in a circular fashion,
1908         // using FirstLane as the center point and increasing the radius
1909         // distance.
1910         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1911         for (unsigned I = 0; I < NumOperands; ++I)
1912           MainAltOps[I].push_back(getData(I, FirstLane).V);
1913 
1914         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1915           // Visit the lane on the right and then the lane on the left.
1916           for (int Direction : {+1, -1}) {
1917             int Lane = FirstLane + Direction * Distance;
1918             if (Lane < 0 || Lane >= (int)NumLanes)
1919               continue;
1920             int LastLane = Lane - Direction;
1921             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1922                    "Out of bounds");
1923             // Look for a good match for each operand.
1924             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1925               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1926               Optional<unsigned> BestIdx = getBestOperand(
1927                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1928               // By not selecting a value, we allow the operands that follow to
1929               // select a better matching value. We will get a non-null value in
1930               // the next run of getBestOperand().
1931               if (BestIdx) {
1932                 // Swap the current operand with the one returned by
1933                 // getBestOperand().
1934                 swap(OpIdx, BestIdx.getValue(), Lane);
1935               } else {
1936                 // We failed to find a best operand, set mode to 'Failed'.
1937                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1938                 // Enable the second pass.
1939                 StrategyFailed = true;
1940               }
1941               // Try to get the alternate opcode and follow it during analysis.
1942               if (MainAltOps[OpIdx].size() != 2) {
1943                 OperandData &AltOp = getData(OpIdx, Lane);
1944                 InstructionsState OpS =
1945                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1946                 if (OpS.getOpcode() && OpS.isAltShuffle())
1947                   MainAltOps[OpIdx].push_back(AltOp.V);
1948               }
1949             }
1950           }
1951         }
1952         // Skip second pass if the strategy did not fail.
1953         if (!StrategyFailed)
1954           break;
1955       }
1956     }
1957 
1958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1959     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1960       switch (RMode) {
1961       case ReorderingMode::Load:
1962         return "Load";
1963       case ReorderingMode::Opcode:
1964         return "Opcode";
1965       case ReorderingMode::Constant:
1966         return "Constant";
1967       case ReorderingMode::Splat:
1968         return "Splat";
1969       case ReorderingMode::Failed:
1970         return "Failed";
1971       }
1972       llvm_unreachable("Unimplemented Reordering Type");
1973     }
1974 
1975     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1976                                                    raw_ostream &OS) {
1977       return OS << getModeStr(RMode);
1978     }
1979 
1980     /// Debug print.
1981     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1982       printMode(RMode, dbgs());
1983     }
1984 
1985     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1986       return printMode(RMode, OS);
1987     }
1988 
1989     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1990       const unsigned Indent = 2;
1991       unsigned Cnt = 0;
1992       for (const OperandDataVec &OpDataVec : OpsVec) {
1993         OS << "Operand " << Cnt++ << "\n";
1994         for (const OperandData &OpData : OpDataVec) {
1995           OS.indent(Indent) << "{";
1996           if (Value *V = OpData.V)
1997             OS << *V;
1998           else
1999             OS << "null";
2000           OS << ", APO:" << OpData.APO << "}\n";
2001         }
2002         OS << "\n";
2003       }
2004       return OS;
2005     }
2006 
2007     /// Debug print.
2008     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2009 #endif
2010   };
2011 
2012   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2013   /// for a pair which have highest score deemed to have best chance to form
2014   /// root of profitable tree to vectorize. Return None if no candidate scored
2015   /// above the LookAheadHeuristics::ScoreFail.
2016   Optional<int>
2017   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2018     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2019                                   RootLookAheadMaxDepth);
2020     int BestScore = LookAheadHeuristics::ScoreFail;
2021     Optional<int> Index = None;
2022     for (int I : seq<int>(0, Candidates.size())) {
2023       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2024                                                Candidates[I].second,
2025                                                /*U1=*/nullptr, /*U2=*/nullptr,
2026                                                /*Level=*/1, None);
2027       if (Score > BestScore) {
2028         BestScore = Score;
2029         Index = I;
2030       }
2031     }
2032     return Index;
2033   }
2034 
2035   /// Checks if the instruction is marked for deletion.
2036   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2037 
2038   /// Removes an instruction from its block and eventually deletes it.
2039   /// It's like Instruction::eraseFromParent() except that the actual deletion
2040   /// is delayed until BoUpSLP is destructed.
2041   void eraseInstruction(Instruction *I) {
2042     DeletedInstructions.insert(I);
2043   }
2044 
2045   ~BoUpSLP();
2046 
2047 private:
2048   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2049   /// reordering (i.e. the operands can be reordered because they have only one
2050   /// user and reordarable).
2051   /// \param ReorderableGathers List of all gather nodes that require reordering
2052   /// (e.g., gather of extractlements or partially vectorizable loads).
2053   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2054   /// reordering, subset of \p NonVectorized.
2055   bool
2056   canReorderOperands(TreeEntry *UserTE,
2057                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2058                      ArrayRef<TreeEntry *> ReorderableGathers,
2059                      SmallVectorImpl<TreeEntry *> &GatherOps);
2060 
2061   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2062   /// if any. If it is not vectorized (gather node), returns nullptr.
2063   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2064     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2065     TreeEntry *TE = nullptr;
2066     const auto *It = find_if(VL, [this, &TE](Value *V) {
2067       TE = getTreeEntry(V);
2068       return TE;
2069     });
2070     if (It != VL.end() && TE->isSame(VL))
2071       return TE;
2072     return nullptr;
2073   }
2074 
2075   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2076   /// if any. If it is not vectorized (gather node), returns nullptr.
2077   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2078                                         unsigned OpIdx) const {
2079     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2080         const_cast<TreeEntry *>(UserTE), OpIdx);
2081   }
2082 
2083   /// Checks if all users of \p I are the part of the vectorization tree.
2084   bool areAllUsersVectorized(Instruction *I,
2085                              ArrayRef<Value *> VectorizedVals) const;
2086 
2087   /// \returns the cost of the vectorizable entry.
2088   InstructionCost getEntryCost(const TreeEntry *E,
2089                                ArrayRef<Value *> VectorizedVals);
2090 
2091   /// This is the recursive part of buildTree.
2092   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2093                      const EdgeInfo &EI);
2094 
2095   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2096   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2097   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2098   /// returns false, setting \p CurrentOrder to either an empty vector or a
2099   /// non-identity permutation that allows to reuse extract instructions.
2100   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2101                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2102 
2103   /// Vectorize a single entry in the tree.
2104   Value *vectorizeTree(TreeEntry *E);
2105 
2106   /// Vectorize a single entry in the tree, starting in \p VL.
2107   Value *vectorizeTree(ArrayRef<Value *> VL);
2108 
2109   /// Create a new vector from a list of scalar values.  Produces a sequence
2110   /// which exploits values reused across lanes, and arranges the inserts
2111   /// for ease of later optimization.
2112   Value *createBuildVector(ArrayRef<Value *> VL);
2113 
2114   /// \returns the scalarization cost for this type. Scalarization in this
2115   /// context means the creation of vectors from a group of scalars. If \p
2116   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2117   /// vector elements.
2118   InstructionCost getGatherCost(FixedVectorType *Ty,
2119                                 const APInt &ShuffledIndices,
2120                                 bool NeedToShuffle) const;
2121 
2122   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2123   /// tree entries.
2124   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2125   /// previous tree entries. \p Mask is filled with the shuffle mask.
2126   Optional<TargetTransformInfo::ShuffleKind>
2127   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2128                         SmallVectorImpl<const TreeEntry *> &Entries);
2129 
2130   /// \returns the scalarization cost for this list of values. Assuming that
2131   /// this subtree gets vectorized, we may need to extract the values from the
2132   /// roots. This method calculates the cost of extracting the values.
2133   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2134 
2135   /// Set the Builder insert point to one after the last instruction in
2136   /// the bundle
2137   void setInsertPointAfterBundle(const TreeEntry *E);
2138 
2139   /// \returns a vector from a collection of scalars in \p VL.
2140   Value *gather(ArrayRef<Value *> VL);
2141 
2142   /// \returns whether the VectorizableTree is fully vectorizable and will
2143   /// be beneficial even the tree height is tiny.
2144   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2145 
2146   /// Reorder commutative or alt operands to get better probability of
2147   /// generating vectorized code.
2148   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2149                                              SmallVectorImpl<Value *> &Left,
2150                                              SmallVectorImpl<Value *> &Right,
2151                                              const DataLayout &DL,
2152                                              ScalarEvolution &SE,
2153                                              const BoUpSLP &R);
2154   struct TreeEntry {
2155     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2156     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2157 
2158     /// \returns true if the scalars in VL are equal to this entry.
2159     bool isSame(ArrayRef<Value *> VL) const {
2160       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2161         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2162           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2163         return VL.size() == Mask.size() &&
2164                std::equal(VL.begin(), VL.end(), Mask.begin(),
2165                           [Scalars](Value *V, int Idx) {
2166                             return (isa<UndefValue>(V) &&
2167                                     Idx == UndefMaskElem) ||
2168                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2169                           });
2170       };
2171       if (!ReorderIndices.empty()) {
2172         // TODO: implement matching if the nodes are just reordered, still can
2173         // treat the vector as the same if the list of scalars matches VL
2174         // directly, without reordering.
2175         SmallVector<int> Mask;
2176         inversePermutation(ReorderIndices, Mask);
2177         if (VL.size() == Scalars.size())
2178           return IsSame(Scalars, Mask);
2179         if (VL.size() == ReuseShuffleIndices.size()) {
2180           ::addMask(Mask, ReuseShuffleIndices);
2181           return IsSame(Scalars, Mask);
2182         }
2183         return false;
2184       }
2185       return IsSame(Scalars, ReuseShuffleIndices);
2186     }
2187 
2188     /// \returns true if current entry has same operands as \p TE.
2189     bool hasEqualOperands(const TreeEntry &TE) const {
2190       if (TE.getNumOperands() != getNumOperands())
2191         return false;
2192       SmallBitVector Used(getNumOperands());
2193       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2194         unsigned PrevCount = Used.count();
2195         for (unsigned K = 0; K < E; ++K) {
2196           if (Used.test(K))
2197             continue;
2198           if (getOperand(K) == TE.getOperand(I)) {
2199             Used.set(K);
2200             break;
2201           }
2202         }
2203         // Check if we actually found the matching operand.
2204         if (PrevCount == Used.count())
2205           return false;
2206       }
2207       return true;
2208     }
2209 
2210     /// \return Final vectorization factor for the node. Defined by the total
2211     /// number of vectorized scalars, including those, used several times in the
2212     /// entry and counted in the \a ReuseShuffleIndices, if any.
2213     unsigned getVectorFactor() const {
2214       if (!ReuseShuffleIndices.empty())
2215         return ReuseShuffleIndices.size();
2216       return Scalars.size();
2217     };
2218 
2219     /// A vector of scalars.
2220     ValueList Scalars;
2221 
2222     /// The Scalars are vectorized into this value. It is initialized to Null.
2223     Value *VectorizedValue = nullptr;
2224 
2225     /// Do we need to gather this sequence or vectorize it
2226     /// (either with vector instruction or with scatter/gather
2227     /// intrinsics for store/load)?
2228     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2229     EntryState State;
2230 
2231     /// Does this sequence require some shuffling?
2232     SmallVector<int, 4> ReuseShuffleIndices;
2233 
2234     /// Does this entry require reordering?
2235     SmallVector<unsigned, 4> ReorderIndices;
2236 
2237     /// Points back to the VectorizableTree.
2238     ///
2239     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2240     /// to be a pointer and needs to be able to initialize the child iterator.
2241     /// Thus we need a reference back to the container to translate the indices
2242     /// to entries.
2243     VecTreeTy &Container;
2244 
2245     /// The TreeEntry index containing the user of this entry.  We can actually
2246     /// have multiple users so the data structure is not truly a tree.
2247     SmallVector<EdgeInfo, 1> UserTreeIndices;
2248 
2249     /// The index of this treeEntry in VectorizableTree.
2250     int Idx = -1;
2251 
2252   private:
2253     /// The operands of each instruction in each lane Operands[op_index][lane].
2254     /// Note: This helps avoid the replication of the code that performs the
2255     /// reordering of operands during buildTree_rec() and vectorizeTree().
2256     SmallVector<ValueList, 2> Operands;
2257 
2258     /// The main/alternate instruction.
2259     Instruction *MainOp = nullptr;
2260     Instruction *AltOp = nullptr;
2261 
2262   public:
2263     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2264     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2265       if (Operands.size() < OpIdx + 1)
2266         Operands.resize(OpIdx + 1);
2267       assert(Operands[OpIdx].empty() && "Already resized?");
2268       assert(OpVL.size() <= Scalars.size() &&
2269              "Number of operands is greater than the number of scalars.");
2270       Operands[OpIdx].resize(OpVL.size());
2271       copy(OpVL, Operands[OpIdx].begin());
2272     }
2273 
2274     /// Set the operands of this bundle in their original order.
2275     void setOperandsInOrder() {
2276       assert(Operands.empty() && "Already initialized?");
2277       auto *I0 = cast<Instruction>(Scalars[0]);
2278       Operands.resize(I0->getNumOperands());
2279       unsigned NumLanes = Scalars.size();
2280       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2281            OpIdx != NumOperands; ++OpIdx) {
2282         Operands[OpIdx].resize(NumLanes);
2283         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2284           auto *I = cast<Instruction>(Scalars[Lane]);
2285           assert(I->getNumOperands() == NumOperands &&
2286                  "Expected same number of operands");
2287           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2288         }
2289       }
2290     }
2291 
2292     /// Reorders operands of the node to the given mask \p Mask.
2293     void reorderOperands(ArrayRef<int> Mask) {
2294       for (ValueList &Operand : Operands)
2295         reorderScalars(Operand, Mask);
2296     }
2297 
2298     /// \returns the \p OpIdx operand of this TreeEntry.
2299     ValueList &getOperand(unsigned OpIdx) {
2300       assert(OpIdx < Operands.size() && "Off bounds");
2301       return Operands[OpIdx];
2302     }
2303 
2304     /// \returns the \p OpIdx operand of this TreeEntry.
2305     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2306       assert(OpIdx < Operands.size() && "Off bounds");
2307       return Operands[OpIdx];
2308     }
2309 
2310     /// \returns the number of operands.
2311     unsigned getNumOperands() const { return Operands.size(); }
2312 
2313     /// \return the single \p OpIdx operand.
2314     Value *getSingleOperand(unsigned OpIdx) const {
2315       assert(OpIdx < Operands.size() && "Off bounds");
2316       assert(!Operands[OpIdx].empty() && "No operand available");
2317       return Operands[OpIdx][0];
2318     }
2319 
2320     /// Some of the instructions in the list have alternate opcodes.
2321     bool isAltShuffle() const { return MainOp != AltOp; }
2322 
2323     bool isOpcodeOrAlt(Instruction *I) const {
2324       unsigned CheckedOpcode = I->getOpcode();
2325       return (getOpcode() == CheckedOpcode ||
2326               getAltOpcode() == CheckedOpcode);
2327     }
2328 
2329     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2330     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2331     /// \p OpValue.
2332     Value *isOneOf(Value *Op) const {
2333       auto *I = dyn_cast<Instruction>(Op);
2334       if (I && isOpcodeOrAlt(I))
2335         return Op;
2336       return MainOp;
2337     }
2338 
2339     void setOperations(const InstructionsState &S) {
2340       MainOp = S.MainOp;
2341       AltOp = S.AltOp;
2342     }
2343 
2344     Instruction *getMainOp() const {
2345       return MainOp;
2346     }
2347 
2348     Instruction *getAltOp() const {
2349       return AltOp;
2350     }
2351 
2352     /// The main/alternate opcodes for the list of instructions.
2353     unsigned getOpcode() const {
2354       return MainOp ? MainOp->getOpcode() : 0;
2355     }
2356 
2357     unsigned getAltOpcode() const {
2358       return AltOp ? AltOp->getOpcode() : 0;
2359     }
2360 
2361     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2362     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2363     int findLaneForValue(Value *V) const {
2364       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2365       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2366       if (!ReorderIndices.empty())
2367         FoundLane = ReorderIndices[FoundLane];
2368       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2369       if (!ReuseShuffleIndices.empty()) {
2370         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2371                                   find(ReuseShuffleIndices, FoundLane));
2372       }
2373       return FoundLane;
2374     }
2375 
2376 #ifndef NDEBUG
2377     /// Debug printer.
2378     LLVM_DUMP_METHOD void dump() const {
2379       dbgs() << Idx << ".\n";
2380       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2381         dbgs() << "Operand " << OpI << ":\n";
2382         for (const Value *V : Operands[OpI])
2383           dbgs().indent(2) << *V << "\n";
2384       }
2385       dbgs() << "Scalars: \n";
2386       for (Value *V : Scalars)
2387         dbgs().indent(2) << *V << "\n";
2388       dbgs() << "State: ";
2389       switch (State) {
2390       case Vectorize:
2391         dbgs() << "Vectorize\n";
2392         break;
2393       case ScatterVectorize:
2394         dbgs() << "ScatterVectorize\n";
2395         break;
2396       case NeedToGather:
2397         dbgs() << "NeedToGather\n";
2398         break;
2399       }
2400       dbgs() << "MainOp: ";
2401       if (MainOp)
2402         dbgs() << *MainOp << "\n";
2403       else
2404         dbgs() << "NULL\n";
2405       dbgs() << "AltOp: ";
2406       if (AltOp)
2407         dbgs() << *AltOp << "\n";
2408       else
2409         dbgs() << "NULL\n";
2410       dbgs() << "VectorizedValue: ";
2411       if (VectorizedValue)
2412         dbgs() << *VectorizedValue << "\n";
2413       else
2414         dbgs() << "NULL\n";
2415       dbgs() << "ReuseShuffleIndices: ";
2416       if (ReuseShuffleIndices.empty())
2417         dbgs() << "Empty";
2418       else
2419         for (int ReuseIdx : ReuseShuffleIndices)
2420           dbgs() << ReuseIdx << ", ";
2421       dbgs() << "\n";
2422       dbgs() << "ReorderIndices: ";
2423       for (unsigned ReorderIdx : ReorderIndices)
2424         dbgs() << ReorderIdx << ", ";
2425       dbgs() << "\n";
2426       dbgs() << "UserTreeIndices: ";
2427       for (const auto &EInfo : UserTreeIndices)
2428         dbgs() << EInfo << ", ";
2429       dbgs() << "\n";
2430     }
2431 #endif
2432   };
2433 
2434 #ifndef NDEBUG
2435   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2436                      InstructionCost VecCost,
2437                      InstructionCost ScalarCost) const {
2438     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2439     dbgs() << "SLP: Costs:\n";
2440     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2441     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2442     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2443     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2444                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2445   }
2446 #endif
2447 
2448   /// Create a new VectorizableTree entry.
2449   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2450                           const InstructionsState &S,
2451                           const EdgeInfo &UserTreeIdx,
2452                           ArrayRef<int> ReuseShuffleIndices = None,
2453                           ArrayRef<unsigned> ReorderIndices = None) {
2454     TreeEntry::EntryState EntryState =
2455         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2456     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2457                         ReuseShuffleIndices, ReorderIndices);
2458   }
2459 
2460   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2461                           TreeEntry::EntryState EntryState,
2462                           Optional<ScheduleData *> Bundle,
2463                           const InstructionsState &S,
2464                           const EdgeInfo &UserTreeIdx,
2465                           ArrayRef<int> ReuseShuffleIndices = None,
2466                           ArrayRef<unsigned> ReorderIndices = None) {
2467     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2468             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2469            "Need to vectorize gather entry?");
2470     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2471     TreeEntry *Last = VectorizableTree.back().get();
2472     Last->Idx = VectorizableTree.size() - 1;
2473     Last->State = EntryState;
2474     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2475                                      ReuseShuffleIndices.end());
2476     if (ReorderIndices.empty()) {
2477       Last->Scalars.assign(VL.begin(), VL.end());
2478       Last->setOperations(S);
2479     } else {
2480       // Reorder scalars and build final mask.
2481       Last->Scalars.assign(VL.size(), nullptr);
2482       transform(ReorderIndices, Last->Scalars.begin(),
2483                 [VL](unsigned Idx) -> Value * {
2484                   if (Idx >= VL.size())
2485                     return UndefValue::get(VL.front()->getType());
2486                   return VL[Idx];
2487                 });
2488       InstructionsState S = getSameOpcode(Last->Scalars);
2489       Last->setOperations(S);
2490       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2491     }
2492     if (Last->State != TreeEntry::NeedToGather) {
2493       for (Value *V : VL) {
2494         assert(!getTreeEntry(V) && "Scalar already in tree!");
2495         ScalarToTreeEntry[V] = Last;
2496       }
2497       // Update the scheduler bundle to point to this TreeEntry.
2498       ScheduleData *BundleMember = Bundle.getValue();
2499       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2500               isVectorLikeInstWithConstOps(S.MainOp) ||
2501               doesNotNeedToSchedule(VL)) &&
2502              "Bundle and VL out of sync");
2503       if (BundleMember) {
2504         for (Value *V : VL) {
2505           if (doesNotNeedToBeScheduled(V))
2506             continue;
2507           assert(BundleMember && "Unexpected end of bundle.");
2508           BundleMember->TE = Last;
2509           BundleMember = BundleMember->NextInBundle;
2510         }
2511       }
2512       assert(!BundleMember && "Bundle and VL out of sync");
2513     } else {
2514       MustGather.insert(VL.begin(), VL.end());
2515     }
2516 
2517     if (UserTreeIdx.UserTE)
2518       Last->UserTreeIndices.push_back(UserTreeIdx);
2519 
2520     return Last;
2521   }
2522 
2523   /// -- Vectorization State --
2524   /// Holds all of the tree entries.
2525   TreeEntry::VecTreeTy VectorizableTree;
2526 
2527 #ifndef NDEBUG
2528   /// Debug printer.
2529   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2530     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2531       VectorizableTree[Id]->dump();
2532       dbgs() << "\n";
2533     }
2534   }
2535 #endif
2536 
2537   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2538 
2539   const TreeEntry *getTreeEntry(Value *V) const {
2540     return ScalarToTreeEntry.lookup(V);
2541   }
2542 
2543   /// Maps a specific scalar to its tree entry.
2544   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2545 
2546   /// Maps a value to the proposed vectorizable size.
2547   SmallDenseMap<Value *, unsigned> InstrElementSize;
2548 
2549   /// A list of scalars that we found that we need to keep as scalars.
2550   ValueSet MustGather;
2551 
2552   /// This POD struct describes one external user in the vectorized tree.
2553   struct ExternalUser {
2554     ExternalUser(Value *S, llvm::User *U, int L)
2555         : Scalar(S), User(U), Lane(L) {}
2556 
2557     // Which scalar in our function.
2558     Value *Scalar;
2559 
2560     // Which user that uses the scalar.
2561     llvm::User *User;
2562 
2563     // Which lane does the scalar belong to.
2564     int Lane;
2565   };
2566   using UserList = SmallVector<ExternalUser, 16>;
2567 
2568   /// Checks if two instructions may access the same memory.
2569   ///
2570   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2571   /// is invariant in the calling loop.
2572   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2573                  Instruction *Inst2) {
2574     // First check if the result is already in the cache.
2575     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2576     Optional<bool> &result = AliasCache[key];
2577     if (result.hasValue()) {
2578       return result.getValue();
2579     }
2580     bool aliased = true;
2581     if (Loc1.Ptr && isSimple(Inst1))
2582       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2583     // Store the result in the cache.
2584     result = aliased;
2585     return aliased;
2586   }
2587 
2588   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2589 
2590   /// Cache for alias results.
2591   /// TODO: consider moving this to the AliasAnalysis itself.
2592   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2593 
2594   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2595   // globally through SLP because we don't perform any action which
2596   // invalidates capture results.
2597   BatchAAResults BatchAA;
2598 
2599   /// Temporary store for deleted instructions. Instructions will be deleted
2600   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2601   /// ensure that there are no incorrect collisions in the AliasCache, which
2602   /// can happen if a new instruction is allocated at the same address as a
2603   /// previously deleted instruction.
2604   DenseSet<Instruction *> DeletedInstructions;
2605 
2606   /// A list of values that need to extracted out of the tree.
2607   /// This list holds pairs of (Internal Scalar : External User). External User
2608   /// can be nullptr, it means that this Internal Scalar will be used later,
2609   /// after vectorization.
2610   UserList ExternalUses;
2611 
2612   /// Values used only by @llvm.assume calls.
2613   SmallPtrSet<const Value *, 32> EphValues;
2614 
2615   /// Holds all of the instructions that we gathered.
2616   SetVector<Instruction *> GatherShuffleSeq;
2617 
2618   /// A list of blocks that we are going to CSE.
2619   SetVector<BasicBlock *> CSEBlocks;
2620 
2621   /// Contains all scheduling relevant data for an instruction.
2622   /// A ScheduleData either represents a single instruction or a member of an
2623   /// instruction bundle (= a group of instructions which is combined into a
2624   /// vector instruction).
2625   struct ScheduleData {
2626     // The initial value for the dependency counters. It means that the
2627     // dependencies are not calculated yet.
2628     enum { InvalidDeps = -1 };
2629 
2630     ScheduleData() = default;
2631 
2632     void init(int BlockSchedulingRegionID, Value *OpVal) {
2633       FirstInBundle = this;
2634       NextInBundle = nullptr;
2635       NextLoadStore = nullptr;
2636       IsScheduled = false;
2637       SchedulingRegionID = BlockSchedulingRegionID;
2638       clearDependencies();
2639       OpValue = OpVal;
2640       TE = nullptr;
2641     }
2642 
2643     /// Verify basic self consistency properties
2644     void verify() {
2645       if (hasValidDependencies()) {
2646         assert(UnscheduledDeps <= Dependencies && "invariant");
2647       } else {
2648         assert(UnscheduledDeps == Dependencies && "invariant");
2649       }
2650 
2651       if (IsScheduled) {
2652         assert(isSchedulingEntity() &&
2653                 "unexpected scheduled state");
2654         for (const ScheduleData *BundleMember = this; BundleMember;
2655              BundleMember = BundleMember->NextInBundle) {
2656           assert(BundleMember->hasValidDependencies() &&
2657                  BundleMember->UnscheduledDeps == 0 &&
2658                  "unexpected scheduled state");
2659           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2660                  "only bundle is marked scheduled");
2661         }
2662       }
2663 
2664       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2665              "all bundle members must be in same basic block");
2666     }
2667 
2668     /// Returns true if the dependency information has been calculated.
2669     /// Note that depenendency validity can vary between instructions within
2670     /// a single bundle.
2671     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2672 
2673     /// Returns true for single instructions and for bundle representatives
2674     /// (= the head of a bundle).
2675     bool isSchedulingEntity() const { return FirstInBundle == this; }
2676 
2677     /// Returns true if it represents an instruction bundle and not only a
2678     /// single instruction.
2679     bool isPartOfBundle() const {
2680       return NextInBundle != nullptr || FirstInBundle != this || TE;
2681     }
2682 
2683     /// Returns true if it is ready for scheduling, i.e. it has no more
2684     /// unscheduled depending instructions/bundles.
2685     bool isReady() const {
2686       assert(isSchedulingEntity() &&
2687              "can't consider non-scheduling entity for ready list");
2688       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2689     }
2690 
2691     /// Modifies the number of unscheduled dependencies for this instruction,
2692     /// and returns the number of remaining dependencies for the containing
2693     /// bundle.
2694     int incrementUnscheduledDeps(int Incr) {
2695       assert(hasValidDependencies() &&
2696              "increment of unscheduled deps would be meaningless");
2697       UnscheduledDeps += Incr;
2698       return FirstInBundle->unscheduledDepsInBundle();
2699     }
2700 
2701     /// Sets the number of unscheduled dependencies to the number of
2702     /// dependencies.
2703     void resetUnscheduledDeps() {
2704       UnscheduledDeps = Dependencies;
2705     }
2706 
2707     /// Clears all dependency information.
2708     void clearDependencies() {
2709       Dependencies = InvalidDeps;
2710       resetUnscheduledDeps();
2711       MemoryDependencies.clear();
2712       ControlDependencies.clear();
2713     }
2714 
2715     int unscheduledDepsInBundle() const {
2716       assert(isSchedulingEntity() && "only meaningful on the bundle");
2717       int Sum = 0;
2718       for (const ScheduleData *BundleMember = this; BundleMember;
2719            BundleMember = BundleMember->NextInBundle) {
2720         if (BundleMember->UnscheduledDeps == InvalidDeps)
2721           return InvalidDeps;
2722         Sum += BundleMember->UnscheduledDeps;
2723       }
2724       return Sum;
2725     }
2726 
2727     void dump(raw_ostream &os) const {
2728       if (!isSchedulingEntity()) {
2729         os << "/ " << *Inst;
2730       } else if (NextInBundle) {
2731         os << '[' << *Inst;
2732         ScheduleData *SD = NextInBundle;
2733         while (SD) {
2734           os << ';' << *SD->Inst;
2735           SD = SD->NextInBundle;
2736         }
2737         os << ']';
2738       } else {
2739         os << *Inst;
2740       }
2741     }
2742 
2743     Instruction *Inst = nullptr;
2744 
2745     /// Opcode of the current instruction in the schedule data.
2746     Value *OpValue = nullptr;
2747 
2748     /// The TreeEntry that this instruction corresponds to.
2749     TreeEntry *TE = nullptr;
2750 
2751     /// Points to the head in an instruction bundle (and always to this for
2752     /// single instructions).
2753     ScheduleData *FirstInBundle = nullptr;
2754 
2755     /// Single linked list of all instructions in a bundle. Null if it is a
2756     /// single instruction.
2757     ScheduleData *NextInBundle = nullptr;
2758 
2759     /// Single linked list of all memory instructions (e.g. load, store, call)
2760     /// in the block - until the end of the scheduling region.
2761     ScheduleData *NextLoadStore = nullptr;
2762 
2763     /// The dependent memory instructions.
2764     /// This list is derived on demand in calculateDependencies().
2765     SmallVector<ScheduleData *, 4> MemoryDependencies;
2766 
2767     /// List of instructions which this instruction could be control dependent
2768     /// on.  Allowing such nodes to be scheduled below this one could introduce
2769     /// a runtime fault which didn't exist in the original program.
2770     /// ex: this is a load or udiv following a readonly call which inf loops
2771     SmallVector<ScheduleData *, 4> ControlDependencies;
2772 
2773     /// This ScheduleData is in the current scheduling region if this matches
2774     /// the current SchedulingRegionID of BlockScheduling.
2775     int SchedulingRegionID = 0;
2776 
2777     /// Used for getting a "good" final ordering of instructions.
2778     int SchedulingPriority = 0;
2779 
2780     /// The number of dependencies. Constitutes of the number of users of the
2781     /// instruction plus the number of dependent memory instructions (if any).
2782     /// This value is calculated on demand.
2783     /// If InvalidDeps, the number of dependencies is not calculated yet.
2784     int Dependencies = InvalidDeps;
2785 
2786     /// The number of dependencies minus the number of dependencies of scheduled
2787     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2788     /// for scheduling.
2789     /// Note that this is negative as long as Dependencies is not calculated.
2790     int UnscheduledDeps = InvalidDeps;
2791 
2792     /// True if this instruction is scheduled (or considered as scheduled in the
2793     /// dry-run).
2794     bool IsScheduled = false;
2795   };
2796 
2797 #ifndef NDEBUG
2798   friend inline raw_ostream &operator<<(raw_ostream &os,
2799                                         const BoUpSLP::ScheduleData &SD) {
2800     SD.dump(os);
2801     return os;
2802   }
2803 #endif
2804 
2805   friend struct GraphTraits<BoUpSLP *>;
2806   friend struct DOTGraphTraits<BoUpSLP *>;
2807 
2808   /// Contains all scheduling data for a basic block.
2809   /// It does not schedules instructions, which are not memory read/write
2810   /// instructions and their operands are either constants, or arguments, or
2811   /// phis, or instructions from others blocks, or their users are phis or from
2812   /// the other blocks. The resulting vector instructions can be placed at the
2813   /// beginning of the basic block without scheduling (if operands does not need
2814   /// to be scheduled) or at the end of the block (if users are outside of the
2815   /// block). It allows to save some compile time and memory used by the
2816   /// compiler.
2817   /// ScheduleData is assigned for each instruction in between the boundaries of
2818   /// the tree entry, even for those, which are not part of the graph. It is
2819   /// required to correctly follow the dependencies between the instructions and
2820   /// their correct scheduling. The ScheduleData is not allocated for the
2821   /// instructions, which do not require scheduling, like phis, nodes with
2822   /// extractelements/insertelements only or nodes with instructions, with
2823   /// uses/operands outside of the block.
2824   struct BlockScheduling {
2825     BlockScheduling(BasicBlock *BB)
2826         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2827 
2828     void clear() {
2829       ReadyInsts.clear();
2830       ScheduleStart = nullptr;
2831       ScheduleEnd = nullptr;
2832       FirstLoadStoreInRegion = nullptr;
2833       LastLoadStoreInRegion = nullptr;
2834       RegionHasStackSave = false;
2835 
2836       // Reduce the maximum schedule region size by the size of the
2837       // previous scheduling run.
2838       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2839       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2840         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2841       ScheduleRegionSize = 0;
2842 
2843       // Make a new scheduling region, i.e. all existing ScheduleData is not
2844       // in the new region yet.
2845       ++SchedulingRegionID;
2846     }
2847 
2848     ScheduleData *getScheduleData(Instruction *I) {
2849       if (BB != I->getParent())
2850         // Avoid lookup if can't possibly be in map.
2851         return nullptr;
2852       ScheduleData *SD = ScheduleDataMap.lookup(I);
2853       if (SD && isInSchedulingRegion(SD))
2854         return SD;
2855       return nullptr;
2856     }
2857 
2858     ScheduleData *getScheduleData(Value *V) {
2859       if (auto *I = dyn_cast<Instruction>(V))
2860         return getScheduleData(I);
2861       return nullptr;
2862     }
2863 
2864     ScheduleData *getScheduleData(Value *V, Value *Key) {
2865       if (V == Key)
2866         return getScheduleData(V);
2867       auto I = ExtraScheduleDataMap.find(V);
2868       if (I != ExtraScheduleDataMap.end()) {
2869         ScheduleData *SD = I->second.lookup(Key);
2870         if (SD && isInSchedulingRegion(SD))
2871           return SD;
2872       }
2873       return nullptr;
2874     }
2875 
2876     bool isInSchedulingRegion(ScheduleData *SD) const {
2877       return SD->SchedulingRegionID == SchedulingRegionID;
2878     }
2879 
2880     /// Marks an instruction as scheduled and puts all dependent ready
2881     /// instructions into the ready-list.
2882     template <typename ReadyListType>
2883     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2884       SD->IsScheduled = true;
2885       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2886 
2887       for (ScheduleData *BundleMember = SD; BundleMember;
2888            BundleMember = BundleMember->NextInBundle) {
2889         if (BundleMember->Inst != BundleMember->OpValue)
2890           continue;
2891 
2892         // Handle the def-use chain dependencies.
2893 
2894         // Decrement the unscheduled counter and insert to ready list if ready.
2895         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2896           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2897             if (OpDef && OpDef->hasValidDependencies() &&
2898                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2899               // There are no more unscheduled dependencies after
2900               // decrementing, so we can put the dependent instruction
2901               // into the ready list.
2902               ScheduleData *DepBundle = OpDef->FirstInBundle;
2903               assert(!DepBundle->IsScheduled &&
2904                      "already scheduled bundle gets ready");
2905               ReadyList.insert(DepBundle);
2906               LLVM_DEBUG(dbgs()
2907                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2908             }
2909           });
2910         };
2911 
2912         // If BundleMember is a vector bundle, its operands may have been
2913         // reordered during buildTree(). We therefore need to get its operands
2914         // through the TreeEntry.
2915         if (TreeEntry *TE = BundleMember->TE) {
2916           // Need to search for the lane since the tree entry can be reordered.
2917           int Lane = std::distance(TE->Scalars.begin(),
2918                                    find(TE->Scalars, BundleMember->Inst));
2919           assert(Lane >= 0 && "Lane not set");
2920 
2921           // Since vectorization tree is being built recursively this assertion
2922           // ensures that the tree entry has all operands set before reaching
2923           // this code. Couple of exceptions known at the moment are extracts
2924           // where their second (immediate) operand is not added. Since
2925           // immediates do not affect scheduler behavior this is considered
2926           // okay.
2927           auto *In = BundleMember->Inst;
2928           assert(In &&
2929                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2930                   In->getNumOperands() == TE->getNumOperands()) &&
2931                  "Missed TreeEntry operands?");
2932           (void)In; // fake use to avoid build failure when assertions disabled
2933 
2934           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2935                OpIdx != NumOperands; ++OpIdx)
2936             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2937               DecrUnsched(I);
2938         } else {
2939           // If BundleMember is a stand-alone instruction, no operand reordering
2940           // has taken place, so we directly access its operands.
2941           for (Use &U : BundleMember->Inst->operands())
2942             if (auto *I = dyn_cast<Instruction>(U.get()))
2943               DecrUnsched(I);
2944         }
2945         // Handle the memory dependencies.
2946         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2947           if (MemoryDepSD->hasValidDependencies() &&
2948               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2949             // There are no more unscheduled dependencies after decrementing,
2950             // so we can put the dependent instruction into the ready list.
2951             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2952             assert(!DepBundle->IsScheduled &&
2953                    "already scheduled bundle gets ready");
2954             ReadyList.insert(DepBundle);
2955             LLVM_DEBUG(dbgs()
2956                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2957           }
2958         }
2959         // Handle the control dependencies.
2960         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2961           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2962             // There are no more unscheduled dependencies after decrementing,
2963             // so we can put the dependent instruction into the ready list.
2964             ScheduleData *DepBundle = DepSD->FirstInBundle;
2965             assert(!DepBundle->IsScheduled &&
2966                    "already scheduled bundle gets ready");
2967             ReadyList.insert(DepBundle);
2968             LLVM_DEBUG(dbgs()
2969                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2970           }
2971         }
2972 
2973       }
2974     }
2975 
2976     /// Verify basic self consistency properties of the data structure.
2977     void verify() {
2978       if (!ScheduleStart)
2979         return;
2980 
2981       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2982              ScheduleStart->comesBefore(ScheduleEnd) &&
2983              "Not a valid scheduling region?");
2984 
2985       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2986         auto *SD = getScheduleData(I);
2987         if (!SD)
2988           continue;
2989         assert(isInSchedulingRegion(SD) &&
2990                "primary schedule data not in window?");
2991         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2992                "entire bundle in window!");
2993         (void)SD;
2994         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2995       }
2996 
2997       for (auto *SD : ReadyInsts) {
2998         assert(SD->isSchedulingEntity() && SD->isReady() &&
2999                "item in ready list not ready?");
3000         (void)SD;
3001       }
3002     }
3003 
3004     void doForAllOpcodes(Value *V,
3005                          function_ref<void(ScheduleData *SD)> Action) {
3006       if (ScheduleData *SD = getScheduleData(V))
3007         Action(SD);
3008       auto I = ExtraScheduleDataMap.find(V);
3009       if (I != ExtraScheduleDataMap.end())
3010         for (auto &P : I->second)
3011           if (isInSchedulingRegion(P.second))
3012             Action(P.second);
3013     }
3014 
3015     /// Put all instructions into the ReadyList which are ready for scheduling.
3016     template <typename ReadyListType>
3017     void initialFillReadyList(ReadyListType &ReadyList) {
3018       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3019         doForAllOpcodes(I, [&](ScheduleData *SD) {
3020           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3021               SD->isReady()) {
3022             ReadyList.insert(SD);
3023             LLVM_DEBUG(dbgs()
3024                        << "SLP:    initially in ready list: " << *SD << "\n");
3025           }
3026         });
3027       }
3028     }
3029 
3030     /// Build a bundle from the ScheduleData nodes corresponding to the
3031     /// scalar instruction for each lane.
3032     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3033 
3034     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3035     /// cyclic dependencies. This is only a dry-run, no instructions are
3036     /// actually moved at this stage.
3037     /// \returns the scheduling bundle. The returned Optional value is non-None
3038     /// if \p VL is allowed to be scheduled.
3039     Optional<ScheduleData *>
3040     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3041                       const InstructionsState &S);
3042 
3043     /// Un-bundles a group of instructions.
3044     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3045 
3046     /// Allocates schedule data chunk.
3047     ScheduleData *allocateScheduleDataChunks();
3048 
3049     /// Extends the scheduling region so that V is inside the region.
3050     /// \returns true if the region size is within the limit.
3051     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3052 
3053     /// Initialize the ScheduleData structures for new instructions in the
3054     /// scheduling region.
3055     void initScheduleData(Instruction *FromI, Instruction *ToI,
3056                           ScheduleData *PrevLoadStore,
3057                           ScheduleData *NextLoadStore);
3058 
3059     /// Updates the dependency information of a bundle and of all instructions/
3060     /// bundles which depend on the original bundle.
3061     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3062                                BoUpSLP *SLP);
3063 
3064     /// Sets all instruction in the scheduling region to un-scheduled.
3065     void resetSchedule();
3066 
3067     BasicBlock *BB;
3068 
3069     /// Simple memory allocation for ScheduleData.
3070     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3071 
3072     /// The size of a ScheduleData array in ScheduleDataChunks.
3073     int ChunkSize;
3074 
3075     /// The allocator position in the current chunk, which is the last entry
3076     /// of ScheduleDataChunks.
3077     int ChunkPos;
3078 
3079     /// Attaches ScheduleData to Instruction.
3080     /// Note that the mapping survives during all vectorization iterations, i.e.
3081     /// ScheduleData structures are recycled.
3082     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3083 
3084     /// Attaches ScheduleData to Instruction with the leading key.
3085     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3086         ExtraScheduleDataMap;
3087 
3088     /// The ready-list for scheduling (only used for the dry-run).
3089     SetVector<ScheduleData *> ReadyInsts;
3090 
3091     /// The first instruction of the scheduling region.
3092     Instruction *ScheduleStart = nullptr;
3093 
3094     /// The first instruction _after_ the scheduling region.
3095     Instruction *ScheduleEnd = nullptr;
3096 
3097     /// The first memory accessing instruction in the scheduling region
3098     /// (can be null).
3099     ScheduleData *FirstLoadStoreInRegion = nullptr;
3100 
3101     /// The last memory accessing instruction in the scheduling region
3102     /// (can be null).
3103     ScheduleData *LastLoadStoreInRegion = nullptr;
3104 
3105     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3106     /// region?  Used to optimize the dependence calculation for the
3107     /// common case where there isn't.
3108     bool RegionHasStackSave = false;
3109 
3110     /// The current size of the scheduling region.
3111     int ScheduleRegionSize = 0;
3112 
3113     /// The maximum size allowed for the scheduling region.
3114     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3115 
3116     /// The ID of the scheduling region. For a new vectorization iteration this
3117     /// is incremented which "removes" all ScheduleData from the region.
3118     /// Make sure that the initial SchedulingRegionID is greater than the
3119     /// initial SchedulingRegionID in ScheduleData (which is 0).
3120     int SchedulingRegionID = 1;
3121   };
3122 
3123   /// Attaches the BlockScheduling structures to basic blocks.
3124   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3125 
3126   /// Performs the "real" scheduling. Done before vectorization is actually
3127   /// performed in a basic block.
3128   void scheduleBlock(BlockScheduling *BS);
3129 
3130   /// List of users to ignore during scheduling and that don't need extracting.
3131   ArrayRef<Value *> UserIgnoreList;
3132 
3133   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3134   /// sorted SmallVectors of unsigned.
3135   struct OrdersTypeDenseMapInfo {
3136     static OrdersType getEmptyKey() {
3137       OrdersType V;
3138       V.push_back(~1U);
3139       return V;
3140     }
3141 
3142     static OrdersType getTombstoneKey() {
3143       OrdersType V;
3144       V.push_back(~2U);
3145       return V;
3146     }
3147 
3148     static unsigned getHashValue(const OrdersType &V) {
3149       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3150     }
3151 
3152     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3153       return LHS == RHS;
3154     }
3155   };
3156 
3157   // Analysis and block reference.
3158   Function *F;
3159   ScalarEvolution *SE;
3160   TargetTransformInfo *TTI;
3161   TargetLibraryInfo *TLI;
3162   LoopInfo *LI;
3163   DominatorTree *DT;
3164   AssumptionCache *AC;
3165   DemandedBits *DB;
3166   const DataLayout *DL;
3167   OptimizationRemarkEmitter *ORE;
3168 
3169   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3170   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3171 
3172   /// Instruction builder to construct the vectorized tree.
3173   IRBuilder<> Builder;
3174 
3175   /// A map of scalar integer values to the smallest bit width with which they
3176   /// can legally be represented. The values map to (width, signed) pairs,
3177   /// where "width" indicates the minimum bit width and "signed" is True if the
3178   /// value must be signed-extended, rather than zero-extended, back to its
3179   /// original width.
3180   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3181 };
3182 
3183 } // end namespace slpvectorizer
3184 
3185 template <> struct GraphTraits<BoUpSLP *> {
3186   using TreeEntry = BoUpSLP::TreeEntry;
3187 
3188   /// NodeRef has to be a pointer per the GraphWriter.
3189   using NodeRef = TreeEntry *;
3190 
3191   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3192 
3193   /// Add the VectorizableTree to the index iterator to be able to return
3194   /// TreeEntry pointers.
3195   struct ChildIteratorType
3196       : public iterator_adaptor_base<
3197             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3198     ContainerTy &VectorizableTree;
3199 
3200     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3201                       ContainerTy &VT)
3202         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3203 
3204     NodeRef operator*() { return I->UserTE; }
3205   };
3206 
3207   static NodeRef getEntryNode(BoUpSLP &R) {
3208     return R.VectorizableTree[0].get();
3209   }
3210 
3211   static ChildIteratorType child_begin(NodeRef N) {
3212     return {N->UserTreeIndices.begin(), N->Container};
3213   }
3214 
3215   static ChildIteratorType child_end(NodeRef N) {
3216     return {N->UserTreeIndices.end(), N->Container};
3217   }
3218 
3219   /// For the node iterator we just need to turn the TreeEntry iterator into a
3220   /// TreeEntry* iterator so that it dereferences to NodeRef.
3221   class nodes_iterator {
3222     using ItTy = ContainerTy::iterator;
3223     ItTy It;
3224 
3225   public:
3226     nodes_iterator(const ItTy &It2) : It(It2) {}
3227     NodeRef operator*() { return It->get(); }
3228     nodes_iterator operator++() {
3229       ++It;
3230       return *this;
3231     }
3232     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3233   };
3234 
3235   static nodes_iterator nodes_begin(BoUpSLP *R) {
3236     return nodes_iterator(R->VectorizableTree.begin());
3237   }
3238 
3239   static nodes_iterator nodes_end(BoUpSLP *R) {
3240     return nodes_iterator(R->VectorizableTree.end());
3241   }
3242 
3243   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3244 };
3245 
3246 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3247   using TreeEntry = BoUpSLP::TreeEntry;
3248 
3249   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3250 
3251   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3252     std::string Str;
3253     raw_string_ostream OS(Str);
3254     if (isSplat(Entry->Scalars))
3255       OS << "<splat> ";
3256     for (auto V : Entry->Scalars) {
3257       OS << *V;
3258       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3259             return EU.Scalar == V;
3260           }))
3261         OS << " <extract>";
3262       OS << "\n";
3263     }
3264     return Str;
3265   }
3266 
3267   static std::string getNodeAttributes(const TreeEntry *Entry,
3268                                        const BoUpSLP *) {
3269     if (Entry->State == TreeEntry::NeedToGather)
3270       return "color=red";
3271     return "";
3272   }
3273 };
3274 
3275 } // end namespace llvm
3276 
3277 BoUpSLP::~BoUpSLP() {
3278   SmallVector<WeakTrackingVH> DeadInsts;
3279   for (auto *I : DeletedInstructions) {
3280     for (Use &U : I->operands()) {
3281       auto *Op = dyn_cast<Instruction>(U.get());
3282       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3283           wouldInstructionBeTriviallyDead(Op, TLI))
3284         DeadInsts.emplace_back(Op);
3285     }
3286     I->dropAllReferences();
3287   }
3288   for (auto *I : DeletedInstructions) {
3289     assert(I->use_empty() &&
3290            "trying to erase instruction with users.");
3291     I->eraseFromParent();
3292   }
3293 
3294   // Cleanup any dead scalar code feeding the vectorized instructions
3295   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3296 
3297 #ifdef EXPENSIVE_CHECKS
3298   // If we could guarantee that this call is not extremely slow, we could
3299   // remove the ifdef limitation (see PR47712).
3300   assert(!verifyFunction(*F, &dbgs()));
3301 #endif
3302 }
3303 
3304 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3305 /// contains original mask for the scalars reused in the node. Procedure
3306 /// transform this mask in accordance with the given \p Mask.
3307 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3308   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3309          "Expected non-empty mask.");
3310   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3311   Prev.swap(Reuses);
3312   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3313     if (Mask[I] != UndefMaskElem)
3314       Reuses[Mask[I]] = Prev[I];
3315 }
3316 
3317 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3318 /// the original order of the scalars. Procedure transforms the provided order
3319 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3320 /// identity order, \p Order is cleared.
3321 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3322   assert(!Mask.empty() && "Expected non-empty mask.");
3323   SmallVector<int> MaskOrder;
3324   if (Order.empty()) {
3325     MaskOrder.resize(Mask.size());
3326     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3327   } else {
3328     inversePermutation(Order, MaskOrder);
3329   }
3330   reorderReuses(MaskOrder, Mask);
3331   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3332     Order.clear();
3333     return;
3334   }
3335   Order.assign(Mask.size(), Mask.size());
3336   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3337     if (MaskOrder[I] != UndefMaskElem)
3338       Order[MaskOrder[I]] = I;
3339   fixupOrderingIndices(Order);
3340 }
3341 
3342 Optional<BoUpSLP::OrdersType>
3343 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3344   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3345   unsigned NumScalars = TE.Scalars.size();
3346   OrdersType CurrentOrder(NumScalars, NumScalars);
3347   SmallVector<int> Positions;
3348   SmallBitVector UsedPositions(NumScalars);
3349   const TreeEntry *STE = nullptr;
3350   // Try to find all gathered scalars that are gets vectorized in other
3351   // vectorize node. Here we can have only one single tree vector node to
3352   // correctly identify order of the gathered scalars.
3353   for (unsigned I = 0; I < NumScalars; ++I) {
3354     Value *V = TE.Scalars[I];
3355     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3356       continue;
3357     if (const auto *LocalSTE = getTreeEntry(V)) {
3358       if (!STE)
3359         STE = LocalSTE;
3360       else if (STE != LocalSTE)
3361         // Take the order only from the single vector node.
3362         return None;
3363       unsigned Lane =
3364           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3365       if (Lane >= NumScalars)
3366         return None;
3367       if (CurrentOrder[Lane] != NumScalars) {
3368         if (Lane != I)
3369           continue;
3370         UsedPositions.reset(CurrentOrder[Lane]);
3371       }
3372       // The partial identity (where only some elements of the gather node are
3373       // in the identity order) is good.
3374       CurrentOrder[Lane] = I;
3375       UsedPositions.set(I);
3376     }
3377   }
3378   // Need to keep the order if we have a vector entry and at least 2 scalars or
3379   // the vectorized entry has just 2 scalars.
3380   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3381     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3382       for (unsigned I = 0; I < NumScalars; ++I)
3383         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3384           return false;
3385       return true;
3386     };
3387     if (IsIdentityOrder(CurrentOrder)) {
3388       CurrentOrder.clear();
3389       return CurrentOrder;
3390     }
3391     auto *It = CurrentOrder.begin();
3392     for (unsigned I = 0; I < NumScalars;) {
3393       if (UsedPositions.test(I)) {
3394         ++I;
3395         continue;
3396       }
3397       if (*It == NumScalars) {
3398         *It = I;
3399         ++I;
3400       }
3401       ++It;
3402     }
3403     return CurrentOrder;
3404   }
3405   return None;
3406 }
3407 
3408 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3409                                                          bool TopToBottom) {
3410   // No need to reorder if need to shuffle reuses, still need to shuffle the
3411   // node.
3412   if (!TE.ReuseShuffleIndices.empty())
3413     return None;
3414   if (TE.State == TreeEntry::Vectorize &&
3415       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3416        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3417       !TE.isAltShuffle())
3418     return TE.ReorderIndices;
3419   if (TE.State == TreeEntry::NeedToGather) {
3420     // TODO: add analysis of other gather nodes with extractelement
3421     // instructions and other values/instructions, not only undefs.
3422     if (((TE.getOpcode() == Instruction::ExtractElement &&
3423           !TE.isAltShuffle()) ||
3424          (all_of(TE.Scalars,
3425                  [](Value *V) {
3426                    return isa<UndefValue, ExtractElementInst>(V);
3427                  }) &&
3428           any_of(TE.Scalars,
3429                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3430         all_of(TE.Scalars,
3431                [](Value *V) {
3432                  auto *EE = dyn_cast<ExtractElementInst>(V);
3433                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3434                }) &&
3435         allSameType(TE.Scalars)) {
3436       // Check that gather of extractelements can be represented as
3437       // just a shuffle of a single vector.
3438       OrdersType CurrentOrder;
3439       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3440       if (Reuse || !CurrentOrder.empty()) {
3441         if (!CurrentOrder.empty())
3442           fixupOrderingIndices(CurrentOrder);
3443         return CurrentOrder;
3444       }
3445     }
3446     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3447       return CurrentOrder;
3448   }
3449   return None;
3450 }
3451 
3452 void BoUpSLP::reorderTopToBottom() {
3453   // Maps VF to the graph nodes.
3454   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3455   // ExtractElement gather nodes which can be vectorized and need to handle
3456   // their ordering.
3457   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3458   // Find all reorderable nodes with the given VF.
3459   // Currently the are vectorized stores,loads,extracts + some gathering of
3460   // extracts.
3461   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3462                                  const std::unique_ptr<TreeEntry> &TE) {
3463     if (Optional<OrdersType> CurrentOrder =
3464             getReorderingData(*TE, /*TopToBottom=*/true)) {
3465       // Do not include ordering for nodes used in the alt opcode vectorization,
3466       // better to reorder them during bottom-to-top stage. If follow the order
3467       // here, it causes reordering of the whole graph though actually it is
3468       // profitable just to reorder the subgraph that starts from the alternate
3469       // opcode vectorization node. Such nodes already end-up with the shuffle
3470       // instruction and it is just enough to change this shuffle rather than
3471       // rotate the scalars for the whole graph.
3472       unsigned Cnt = 0;
3473       const TreeEntry *UserTE = TE.get();
3474       while (UserTE && Cnt < RecursionMaxDepth) {
3475         if (UserTE->UserTreeIndices.size() != 1)
3476           break;
3477         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3478               return EI.UserTE->State == TreeEntry::Vectorize &&
3479                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3480             }))
3481           return;
3482         if (UserTE->UserTreeIndices.empty())
3483           UserTE = nullptr;
3484         else
3485           UserTE = UserTE->UserTreeIndices.back().UserTE;
3486         ++Cnt;
3487       }
3488       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3489       if (TE->State != TreeEntry::Vectorize)
3490         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3491     }
3492   });
3493 
3494   // Reorder the graph nodes according to their vectorization factor.
3495   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3496        VF /= 2) {
3497     auto It = VFToOrderedEntries.find(VF);
3498     if (It == VFToOrderedEntries.end())
3499       continue;
3500     // Try to find the most profitable order. We just are looking for the most
3501     // used order and reorder scalar elements in the nodes according to this
3502     // mostly used order.
3503     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3504     // All operands are reordered and used only in this node - propagate the
3505     // most used order to the user node.
3506     MapVector<OrdersType, unsigned,
3507               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3508         OrdersUses;
3509     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3510     for (const TreeEntry *OpTE : OrderedEntries) {
3511       // No need to reorder this nodes, still need to extend and to use shuffle,
3512       // just need to merge reordering shuffle and the reuse shuffle.
3513       if (!OpTE->ReuseShuffleIndices.empty())
3514         continue;
3515       // Count number of orders uses.
3516       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3517         if (OpTE->State == TreeEntry::NeedToGather)
3518           return GathersToOrders.find(OpTE)->second;
3519         return OpTE->ReorderIndices;
3520       }();
3521       // Stores actually store the mask, not the order, need to invert.
3522       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3523           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3524         SmallVector<int> Mask;
3525         inversePermutation(Order, Mask);
3526         unsigned E = Order.size();
3527         OrdersType CurrentOrder(E, E);
3528         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3529           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3530         });
3531         fixupOrderingIndices(CurrentOrder);
3532         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3533       } else {
3534         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3535       }
3536     }
3537     // Set order of the user node.
3538     if (OrdersUses.empty())
3539       continue;
3540     // Choose the most used order.
3541     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3542     unsigned Cnt = OrdersUses.front().second;
3543     for (const auto &Pair : drop_begin(OrdersUses)) {
3544       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3545         BestOrder = Pair.first;
3546         Cnt = Pair.second;
3547       }
3548     }
3549     // Set order of the user node.
3550     if (BestOrder.empty())
3551       continue;
3552     SmallVector<int> Mask;
3553     inversePermutation(BestOrder, Mask);
3554     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3555     unsigned E = BestOrder.size();
3556     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3557       return I < E ? static_cast<int>(I) : UndefMaskElem;
3558     });
3559     // Do an actual reordering, if profitable.
3560     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3561       // Just do the reordering for the nodes with the given VF.
3562       if (TE->Scalars.size() != VF) {
3563         if (TE->ReuseShuffleIndices.size() == VF) {
3564           // Need to reorder the reuses masks of the operands with smaller VF to
3565           // be able to find the match between the graph nodes and scalar
3566           // operands of the given node during vectorization/cost estimation.
3567           assert(all_of(TE->UserTreeIndices,
3568                         [VF, &TE](const EdgeInfo &EI) {
3569                           return EI.UserTE->Scalars.size() == VF ||
3570                                  EI.UserTE->Scalars.size() ==
3571                                      TE->Scalars.size();
3572                         }) &&
3573                  "All users must be of VF size.");
3574           // Update ordering of the operands with the smaller VF than the given
3575           // one.
3576           reorderReuses(TE->ReuseShuffleIndices, Mask);
3577         }
3578         continue;
3579       }
3580       if (TE->State == TreeEntry::Vectorize &&
3581           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3582               InsertElementInst>(TE->getMainOp()) &&
3583           !TE->isAltShuffle()) {
3584         // Build correct orders for extract{element,value}, loads and
3585         // stores.
3586         reorderOrder(TE->ReorderIndices, Mask);
3587         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3588           TE->reorderOperands(Mask);
3589       } else {
3590         // Reorder the node and its operands.
3591         TE->reorderOperands(Mask);
3592         assert(TE->ReorderIndices.empty() &&
3593                "Expected empty reorder sequence.");
3594         reorderScalars(TE->Scalars, Mask);
3595       }
3596       if (!TE->ReuseShuffleIndices.empty()) {
3597         // Apply reversed order to keep the original ordering of the reused
3598         // elements to avoid extra reorder indices shuffling.
3599         OrdersType CurrentOrder;
3600         reorderOrder(CurrentOrder, MaskOrder);
3601         SmallVector<int> NewReuses;
3602         inversePermutation(CurrentOrder, NewReuses);
3603         addMask(NewReuses, TE->ReuseShuffleIndices);
3604         TE->ReuseShuffleIndices.swap(NewReuses);
3605       }
3606     }
3607   }
3608 }
3609 
3610 bool BoUpSLP::canReorderOperands(
3611     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3612     ArrayRef<TreeEntry *> ReorderableGathers,
3613     SmallVectorImpl<TreeEntry *> &GatherOps) {
3614   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3615     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3616           return OpData.first == I &&
3617                  OpData.second->State == TreeEntry::Vectorize;
3618         }))
3619       continue;
3620     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3621       // Do not reorder if operand node is used by many user nodes.
3622       if (any_of(TE->UserTreeIndices,
3623                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3624         return false;
3625       // Add the node to the list of the ordered nodes with the identity
3626       // order.
3627       Edges.emplace_back(I, TE);
3628       continue;
3629     }
3630     ArrayRef<Value *> VL = UserTE->getOperand(I);
3631     TreeEntry *Gather = nullptr;
3632     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3633           assert(TE->State != TreeEntry::Vectorize &&
3634                  "Only non-vectorized nodes are expected.");
3635           if (TE->isSame(VL)) {
3636             Gather = TE;
3637             return true;
3638           }
3639           return false;
3640         }) > 1)
3641       return false;
3642     if (Gather)
3643       GatherOps.push_back(Gather);
3644   }
3645   return true;
3646 }
3647 
3648 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3649   SetVector<TreeEntry *> OrderedEntries;
3650   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3651   // Find all reorderable leaf nodes with the given VF.
3652   // Currently the are vectorized loads,extracts without alternate operands +
3653   // some gathering of extracts.
3654   SmallVector<TreeEntry *> NonVectorized;
3655   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3656                               &NonVectorized](
3657                                  const std::unique_ptr<TreeEntry> &TE) {
3658     if (TE->State != TreeEntry::Vectorize)
3659       NonVectorized.push_back(TE.get());
3660     if (Optional<OrdersType> CurrentOrder =
3661             getReorderingData(*TE, /*TopToBottom=*/false)) {
3662       OrderedEntries.insert(TE.get());
3663       if (TE->State != TreeEntry::Vectorize)
3664         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3665     }
3666   });
3667 
3668   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3669   // I.e., if the node has operands, that are reordered, try to make at least
3670   // one operand order in the natural order and reorder others + reorder the
3671   // user node itself.
3672   SmallPtrSet<const TreeEntry *, 4> Visited;
3673   while (!OrderedEntries.empty()) {
3674     // 1. Filter out only reordered nodes.
3675     // 2. If the entry has multiple uses - skip it and jump to the next node.
3676     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3677     SmallVector<TreeEntry *> Filtered;
3678     for (TreeEntry *TE : OrderedEntries) {
3679       if (!(TE->State == TreeEntry::Vectorize ||
3680             (TE->State == TreeEntry::NeedToGather &&
3681              GathersToOrders.count(TE))) ||
3682           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3683           !all_of(drop_begin(TE->UserTreeIndices),
3684                   [TE](const EdgeInfo &EI) {
3685                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3686                   }) ||
3687           !Visited.insert(TE).second) {
3688         Filtered.push_back(TE);
3689         continue;
3690       }
3691       // Build a map between user nodes and their operands order to speedup
3692       // search. The graph currently does not provide this dependency directly.
3693       for (EdgeInfo &EI : TE->UserTreeIndices) {
3694         TreeEntry *UserTE = EI.UserTE;
3695         auto It = Users.find(UserTE);
3696         if (It == Users.end())
3697           It = Users.insert({UserTE, {}}).first;
3698         It->second.emplace_back(EI.EdgeIdx, TE);
3699       }
3700     }
3701     // Erase filtered entries.
3702     for_each(Filtered,
3703              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3704     for (auto &Data : Users) {
3705       // Check that operands are used only in the User node.
3706       SmallVector<TreeEntry *> GatherOps;
3707       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3708                               GatherOps)) {
3709         for_each(Data.second,
3710                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3711                    OrderedEntries.remove(Op.second);
3712                  });
3713         continue;
3714       }
3715       // All operands are reordered and used only in this node - propagate the
3716       // most used order to the user node.
3717       MapVector<OrdersType, unsigned,
3718                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3719           OrdersUses;
3720       // Do the analysis for each tree entry only once, otherwise the order of
3721       // the same node my be considered several times, though might be not
3722       // profitable.
3723       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3724       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3725       for (const auto &Op : Data.second) {
3726         TreeEntry *OpTE = Op.second;
3727         if (!VisitedOps.insert(OpTE).second)
3728           continue;
3729         if (!OpTE->ReuseShuffleIndices.empty() ||
3730             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3731           continue;
3732         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3733           if (OpTE->State == TreeEntry::NeedToGather)
3734             return GathersToOrders.find(OpTE)->second;
3735           return OpTE->ReorderIndices;
3736         }();
3737         unsigned NumOps = count_if(
3738             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3739               return P.second == OpTE;
3740             });
3741         // Stores actually store the mask, not the order, need to invert.
3742         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3743             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3744           SmallVector<int> Mask;
3745           inversePermutation(Order, Mask);
3746           unsigned E = Order.size();
3747           OrdersType CurrentOrder(E, E);
3748           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3749             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3750           });
3751           fixupOrderingIndices(CurrentOrder);
3752           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3753               NumOps;
3754         } else {
3755           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3756         }
3757         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3758         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3759                                             const TreeEntry *TE) {
3760           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3761               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3762               (IgnoreReorder && TE->Idx == 0))
3763             return true;
3764           if (TE->State == TreeEntry::NeedToGather) {
3765             auto It = GathersToOrders.find(TE);
3766             if (It != GathersToOrders.end())
3767               return !It->second.empty();
3768             return true;
3769           }
3770           return false;
3771         };
3772         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3773           TreeEntry *UserTE = EI.UserTE;
3774           if (!VisitedUsers.insert(UserTE).second)
3775             continue;
3776           // May reorder user node if it requires reordering, has reused
3777           // scalars, is an alternate op vectorize node or its op nodes require
3778           // reordering.
3779           if (AllowsReordering(UserTE))
3780             continue;
3781           // Check if users allow reordering.
3782           // Currently look up just 1 level of operands to avoid increase of
3783           // the compile time.
3784           // Profitable to reorder if definitely more operands allow
3785           // reordering rather than those with natural order.
3786           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3787           if (static_cast<unsigned>(count_if(
3788                   Ops, [UserTE, &AllowsReordering](
3789                            const std::pair<unsigned, TreeEntry *> &Op) {
3790                     return AllowsReordering(Op.second) &&
3791                            all_of(Op.second->UserTreeIndices,
3792                                   [UserTE](const EdgeInfo &EI) {
3793                                     return EI.UserTE == UserTE;
3794                                   });
3795                   })) <= Ops.size() / 2)
3796             ++Res.first->second;
3797         }
3798       }
3799       // If no orders - skip current nodes and jump to the next one, if any.
3800       if (OrdersUses.empty()) {
3801         for_each(Data.second,
3802                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3803                    OrderedEntries.remove(Op.second);
3804                  });
3805         continue;
3806       }
3807       // Choose the best order.
3808       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3809       unsigned Cnt = OrdersUses.front().second;
3810       for (const auto &Pair : drop_begin(OrdersUses)) {
3811         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3812           BestOrder = Pair.first;
3813           Cnt = Pair.second;
3814         }
3815       }
3816       // Set order of the user node (reordering of operands and user nodes).
3817       if (BestOrder.empty()) {
3818         for_each(Data.second,
3819                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3820                    OrderedEntries.remove(Op.second);
3821                  });
3822         continue;
3823       }
3824       // Erase operands from OrderedEntries list and adjust their orders.
3825       VisitedOps.clear();
3826       SmallVector<int> Mask;
3827       inversePermutation(BestOrder, Mask);
3828       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3829       unsigned E = BestOrder.size();
3830       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3831         return I < E ? static_cast<int>(I) : UndefMaskElem;
3832       });
3833       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3834         TreeEntry *TE = Op.second;
3835         OrderedEntries.remove(TE);
3836         if (!VisitedOps.insert(TE).second)
3837           continue;
3838         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3839           // Just reorder reuses indices.
3840           reorderReuses(TE->ReuseShuffleIndices, Mask);
3841           continue;
3842         }
3843         // Gathers are processed separately.
3844         if (TE->State != TreeEntry::Vectorize)
3845           continue;
3846         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3847                 TE->ReorderIndices.empty()) &&
3848                "Non-matching sizes of user/operand entries.");
3849         reorderOrder(TE->ReorderIndices, Mask);
3850       }
3851       // For gathers just need to reorder its scalars.
3852       for (TreeEntry *Gather : GatherOps) {
3853         assert(Gather->ReorderIndices.empty() &&
3854                "Unexpected reordering of gathers.");
3855         if (!Gather->ReuseShuffleIndices.empty()) {
3856           // Just reorder reuses indices.
3857           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3858           continue;
3859         }
3860         reorderScalars(Gather->Scalars, Mask);
3861         OrderedEntries.remove(Gather);
3862       }
3863       // Reorder operands of the user node and set the ordering for the user
3864       // node itself.
3865       if (Data.first->State != TreeEntry::Vectorize ||
3866           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3867               Data.first->getMainOp()) ||
3868           Data.first->isAltShuffle())
3869         Data.first->reorderOperands(Mask);
3870       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3871           Data.first->isAltShuffle()) {
3872         reorderScalars(Data.first->Scalars, Mask);
3873         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3874         if (Data.first->ReuseShuffleIndices.empty() &&
3875             !Data.first->ReorderIndices.empty() &&
3876             !Data.first->isAltShuffle()) {
3877           // Insert user node to the list to try to sink reordering deeper in
3878           // the graph.
3879           OrderedEntries.insert(Data.first);
3880         }
3881       } else {
3882         reorderOrder(Data.first->ReorderIndices, Mask);
3883       }
3884     }
3885   }
3886   // If the reordering is unnecessary, just remove the reorder.
3887   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3888       VectorizableTree.front()->ReuseShuffleIndices.empty())
3889     VectorizableTree.front()->ReorderIndices.clear();
3890 }
3891 
3892 void BoUpSLP::buildExternalUses(
3893     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3894   // Collect the values that we need to extract from the tree.
3895   for (auto &TEPtr : VectorizableTree) {
3896     TreeEntry *Entry = TEPtr.get();
3897 
3898     // No need to handle users of gathered values.
3899     if (Entry->State == TreeEntry::NeedToGather)
3900       continue;
3901 
3902     // For each lane:
3903     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3904       Value *Scalar = Entry->Scalars[Lane];
3905       int FoundLane = Entry->findLaneForValue(Scalar);
3906 
3907       // Check if the scalar is externally used as an extra arg.
3908       auto ExtI = ExternallyUsedValues.find(Scalar);
3909       if (ExtI != ExternallyUsedValues.end()) {
3910         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3911                           << Lane << " from " << *Scalar << ".\n");
3912         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3913       }
3914       for (User *U : Scalar->users()) {
3915         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3916 
3917         Instruction *UserInst = dyn_cast<Instruction>(U);
3918         if (!UserInst)
3919           continue;
3920 
3921         if (isDeleted(UserInst))
3922           continue;
3923 
3924         // Skip in-tree scalars that become vectors
3925         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3926           Value *UseScalar = UseEntry->Scalars[0];
3927           // Some in-tree scalars will remain as scalar in vectorized
3928           // instructions. If that is the case, the one in Lane 0 will
3929           // be used.
3930           if (UseScalar != U ||
3931               UseEntry->State == TreeEntry::ScatterVectorize ||
3932               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3933             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3934                               << ".\n");
3935             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3936             continue;
3937           }
3938         }
3939 
3940         // Ignore users in the user ignore list.
3941         if (is_contained(UserIgnoreList, UserInst))
3942           continue;
3943 
3944         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3945                           << Lane << " from " << *Scalar << ".\n");
3946         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3947       }
3948     }
3949   }
3950 }
3951 
3952 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3953                         ArrayRef<Value *> UserIgnoreLst) {
3954   deleteTree();
3955   UserIgnoreList = UserIgnoreLst;
3956   if (!allSameType(Roots))
3957     return;
3958   buildTree_rec(Roots, 0, EdgeInfo());
3959 }
3960 
3961 namespace {
3962 /// Tracks the state we can represent the loads in the given sequence.
3963 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3964 } // anonymous namespace
3965 
3966 /// Checks if the given array of loads can be represented as a vectorized,
3967 /// scatter or just simple gather.
3968 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3969                                     const TargetTransformInfo &TTI,
3970                                     const DataLayout &DL, ScalarEvolution &SE,
3971                                     SmallVectorImpl<unsigned> &Order,
3972                                     SmallVectorImpl<Value *> &PointerOps) {
3973   // Check that a vectorized load would load the same memory as a scalar
3974   // load. For example, we don't want to vectorize loads that are smaller
3975   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3976   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3977   // from such a struct, we read/write packed bits disagreeing with the
3978   // unvectorized version.
3979   Type *ScalarTy = VL0->getType();
3980 
3981   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3982     return LoadsState::Gather;
3983 
3984   // Make sure all loads in the bundle are simple - we can't vectorize
3985   // atomic or volatile loads.
3986   PointerOps.clear();
3987   PointerOps.resize(VL.size());
3988   auto *POIter = PointerOps.begin();
3989   for (Value *V : VL) {
3990     auto *L = cast<LoadInst>(V);
3991     if (!L->isSimple())
3992       return LoadsState::Gather;
3993     *POIter = L->getPointerOperand();
3994     ++POIter;
3995   }
3996 
3997   Order.clear();
3998   // Check the order of pointer operands.
3999   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4000     Value *Ptr0;
4001     Value *PtrN;
4002     if (Order.empty()) {
4003       Ptr0 = PointerOps.front();
4004       PtrN = PointerOps.back();
4005     } else {
4006       Ptr0 = PointerOps[Order.front()];
4007       PtrN = PointerOps[Order.back()];
4008     }
4009     Optional<int> Diff =
4010         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4011     // Check that the sorted loads are consecutive.
4012     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4013       return LoadsState::Vectorize;
4014     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4015     for (Value *V : VL)
4016       CommonAlignment =
4017           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4018     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4019                                 CommonAlignment))
4020       return LoadsState::ScatterVectorize;
4021   }
4022 
4023   return LoadsState::Gather;
4024 }
4025 
4026 /// \return true if the specified list of values has only one instruction that
4027 /// requires scheduling, false otherwise.
4028 #ifndef NDEBUG
4029 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4030   Value *NeedsScheduling = nullptr;
4031   for (Value *V : VL) {
4032     if (doesNotNeedToBeScheduled(V))
4033       continue;
4034     if (!NeedsScheduling) {
4035       NeedsScheduling = V;
4036       continue;
4037     }
4038     return false;
4039   }
4040   return NeedsScheduling;
4041 }
4042 #endif
4043 
4044 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4045                             const EdgeInfo &UserTreeIdx) {
4046   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4047 
4048   SmallVector<int> ReuseShuffleIndicies;
4049   SmallVector<Value *> UniqueValues;
4050   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4051                                 &UserTreeIdx,
4052                                 this](const InstructionsState &S) {
4053     // Check that every instruction appears once in this bundle.
4054     DenseMap<Value *, unsigned> UniquePositions;
4055     for (Value *V : VL) {
4056       if (isConstant(V)) {
4057         ReuseShuffleIndicies.emplace_back(
4058             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4059         UniqueValues.emplace_back(V);
4060         continue;
4061       }
4062       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4063       ReuseShuffleIndicies.emplace_back(Res.first->second);
4064       if (Res.second)
4065         UniqueValues.emplace_back(V);
4066     }
4067     size_t NumUniqueScalarValues = UniqueValues.size();
4068     if (NumUniqueScalarValues == VL.size()) {
4069       ReuseShuffleIndicies.clear();
4070     } else {
4071       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4072       if (NumUniqueScalarValues <= 1 ||
4073           (UniquePositions.size() == 1 && all_of(UniqueValues,
4074                                                  [](Value *V) {
4075                                                    return isa<UndefValue>(V) ||
4076                                                           !isConstant(V);
4077                                                  })) ||
4078           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4079         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4080         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4081         return false;
4082       }
4083       VL = UniqueValues;
4084     }
4085     return true;
4086   };
4087 
4088   InstructionsState S = getSameOpcode(VL);
4089   if (Depth == RecursionMaxDepth) {
4090     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4091     if (TryToFindDuplicates(S))
4092       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4093                    ReuseShuffleIndicies);
4094     return;
4095   }
4096 
4097   // Don't handle scalable vectors
4098   if (S.getOpcode() == Instruction::ExtractElement &&
4099       isa<ScalableVectorType>(
4100           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4101     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4102     if (TryToFindDuplicates(S))
4103       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4104                    ReuseShuffleIndicies);
4105     return;
4106   }
4107 
4108   // Don't handle vectors.
4109   if (S.OpValue->getType()->isVectorTy() &&
4110       !isa<InsertElementInst>(S.OpValue)) {
4111     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4112     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4113     return;
4114   }
4115 
4116   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4117     if (SI->getValueOperand()->getType()->isVectorTy()) {
4118       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4119       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4120       return;
4121     }
4122 
4123   // If all of the operands are identical or constant we have a simple solution.
4124   // If we deal with insert/extract instructions, they all must have constant
4125   // indices, otherwise we should gather them, not try to vectorize.
4126   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4127       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4128        !all_of(VL, isVectorLikeInstWithConstOps))) {
4129     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4130     if (TryToFindDuplicates(S))
4131       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4132                    ReuseShuffleIndicies);
4133     return;
4134   }
4135 
4136   // We now know that this is a vector of instructions of the same type from
4137   // the same block.
4138 
4139   // Don't vectorize ephemeral values.
4140   for (Value *V : VL) {
4141     if (EphValues.count(V)) {
4142       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4143                         << ") is ephemeral.\n");
4144       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4145       return;
4146     }
4147   }
4148 
4149   // Check if this is a duplicate of another entry.
4150   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4151     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4152     if (!E->isSame(VL)) {
4153       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4154       if (TryToFindDuplicates(S))
4155         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4156                      ReuseShuffleIndicies);
4157       return;
4158     }
4159     // Record the reuse of the tree node.  FIXME, currently this is only used to
4160     // properly draw the graph rather than for the actual vectorization.
4161     E->UserTreeIndices.push_back(UserTreeIdx);
4162     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4163                       << ".\n");
4164     return;
4165   }
4166 
4167   // Check that none of the instructions in the bundle are already in the tree.
4168   for (Value *V : VL) {
4169     auto *I = dyn_cast<Instruction>(V);
4170     if (!I)
4171       continue;
4172     if (getTreeEntry(I)) {
4173       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4174                         << ") is already in tree.\n");
4175       if (TryToFindDuplicates(S))
4176         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4177                      ReuseShuffleIndicies);
4178       return;
4179     }
4180   }
4181 
4182   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4183   for (Value *V : VL) {
4184     if (is_contained(UserIgnoreList, V)) {
4185       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4186       if (TryToFindDuplicates(S))
4187         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4188                      ReuseShuffleIndicies);
4189       return;
4190     }
4191   }
4192 
4193   // Check that all of the users of the scalars that we want to vectorize are
4194   // schedulable.
4195   auto *VL0 = cast<Instruction>(S.OpValue);
4196   BasicBlock *BB = VL0->getParent();
4197 
4198   if (!DT->isReachableFromEntry(BB)) {
4199     // Don't go into unreachable blocks. They may contain instructions with
4200     // dependency cycles which confuse the final scheduling.
4201     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4202     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4203     return;
4204   }
4205 
4206   // Check that every instruction appears once in this bundle.
4207   if (!TryToFindDuplicates(S))
4208     return;
4209 
4210   auto &BSRef = BlocksSchedules[BB];
4211   if (!BSRef)
4212     BSRef = std::make_unique<BlockScheduling>(BB);
4213 
4214   BlockScheduling &BS = *BSRef;
4215 
4216   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4217 #ifdef EXPENSIVE_CHECKS
4218   // Make sure we didn't break any internal invariants
4219   BS.verify();
4220 #endif
4221   if (!Bundle) {
4222     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4223     assert((!BS.getScheduleData(VL0) ||
4224             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4225            "tryScheduleBundle should cancelScheduling on failure");
4226     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4227                  ReuseShuffleIndicies);
4228     return;
4229   }
4230   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4231 
4232   unsigned ShuffleOrOp = S.isAltShuffle() ?
4233                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4234   switch (ShuffleOrOp) {
4235     case Instruction::PHI: {
4236       auto *PH = cast<PHINode>(VL0);
4237 
4238       // Check for terminator values (e.g. invoke).
4239       for (Value *V : VL)
4240         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4241           Instruction *Term = dyn_cast<Instruction>(Incoming);
4242           if (Term && Term->isTerminator()) {
4243             LLVM_DEBUG(dbgs()
4244                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4245             BS.cancelScheduling(VL, VL0);
4246             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4247                          ReuseShuffleIndicies);
4248             return;
4249           }
4250         }
4251 
4252       TreeEntry *TE =
4253           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4254       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4255 
4256       // Keeps the reordered operands to avoid code duplication.
4257       SmallVector<ValueList, 2> OperandsVec;
4258       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4259         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4260           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4261           TE->setOperand(I, Operands);
4262           OperandsVec.push_back(Operands);
4263           continue;
4264         }
4265         ValueList Operands;
4266         // Prepare the operand vector.
4267         for (Value *V : VL)
4268           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4269               PH->getIncomingBlock(I)));
4270         TE->setOperand(I, Operands);
4271         OperandsVec.push_back(Operands);
4272       }
4273       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4274         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4275       return;
4276     }
4277     case Instruction::ExtractValue:
4278     case Instruction::ExtractElement: {
4279       OrdersType CurrentOrder;
4280       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4281       if (Reuse) {
4282         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4283         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4284                      ReuseShuffleIndicies);
4285         // This is a special case, as it does not gather, but at the same time
4286         // we are not extending buildTree_rec() towards the operands.
4287         ValueList Op0;
4288         Op0.assign(VL.size(), VL0->getOperand(0));
4289         VectorizableTree.back()->setOperand(0, Op0);
4290         return;
4291       }
4292       if (!CurrentOrder.empty()) {
4293         LLVM_DEBUG({
4294           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4295                     "with order";
4296           for (unsigned Idx : CurrentOrder)
4297             dbgs() << " " << Idx;
4298           dbgs() << "\n";
4299         });
4300         fixupOrderingIndices(CurrentOrder);
4301         // Insert new order with initial value 0, if it does not exist,
4302         // otherwise return the iterator to the existing one.
4303         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4304                      ReuseShuffleIndicies, CurrentOrder);
4305         // This is a special case, as it does not gather, but at the same time
4306         // we are not extending buildTree_rec() towards the operands.
4307         ValueList Op0;
4308         Op0.assign(VL.size(), VL0->getOperand(0));
4309         VectorizableTree.back()->setOperand(0, Op0);
4310         return;
4311       }
4312       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4313       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4314                    ReuseShuffleIndicies);
4315       BS.cancelScheduling(VL, VL0);
4316       return;
4317     }
4318     case Instruction::InsertElement: {
4319       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4320 
4321       // Check that we have a buildvector and not a shuffle of 2 or more
4322       // different vectors.
4323       ValueSet SourceVectors;
4324       for (Value *V : VL) {
4325         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4326         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4327       }
4328 
4329       if (count_if(VL, [&SourceVectors](Value *V) {
4330             return !SourceVectors.contains(V);
4331           }) >= 2) {
4332         // Found 2nd source vector - cancel.
4333         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4334                              "different source vectors.\n");
4335         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4336         BS.cancelScheduling(VL, VL0);
4337         return;
4338       }
4339 
4340       auto OrdCompare = [](const std::pair<int, int> &P1,
4341                            const std::pair<int, int> &P2) {
4342         return P1.first > P2.first;
4343       };
4344       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4345                     decltype(OrdCompare)>
4346           Indices(OrdCompare);
4347       for (int I = 0, E = VL.size(); I < E; ++I) {
4348         unsigned Idx = *getInsertIndex(VL[I]);
4349         Indices.emplace(Idx, I);
4350       }
4351       OrdersType CurrentOrder(VL.size(), VL.size());
4352       bool IsIdentity = true;
4353       for (int I = 0, E = VL.size(); I < E; ++I) {
4354         CurrentOrder[Indices.top().second] = I;
4355         IsIdentity &= Indices.top().second == I;
4356         Indices.pop();
4357       }
4358       if (IsIdentity)
4359         CurrentOrder.clear();
4360       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4361                                    None, CurrentOrder);
4362       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4363 
4364       constexpr int NumOps = 2;
4365       ValueList VectorOperands[NumOps];
4366       for (int I = 0; I < NumOps; ++I) {
4367         for (Value *V : VL)
4368           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4369 
4370         TE->setOperand(I, VectorOperands[I]);
4371       }
4372       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4373       return;
4374     }
4375     case Instruction::Load: {
4376       // Check that a vectorized load would load the same memory as a scalar
4377       // load. For example, we don't want to vectorize loads that are smaller
4378       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4379       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4380       // from such a struct, we read/write packed bits disagreeing with the
4381       // unvectorized version.
4382       SmallVector<Value *> PointerOps;
4383       OrdersType CurrentOrder;
4384       TreeEntry *TE = nullptr;
4385       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4386                                 PointerOps)) {
4387       case LoadsState::Vectorize:
4388         if (CurrentOrder.empty()) {
4389           // Original loads are consecutive and does not require reordering.
4390           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4391                             ReuseShuffleIndicies);
4392           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4393         } else {
4394           fixupOrderingIndices(CurrentOrder);
4395           // Need to reorder.
4396           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                             ReuseShuffleIndicies, CurrentOrder);
4398           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4399         }
4400         TE->setOperandsInOrder();
4401         break;
4402       case LoadsState::ScatterVectorize:
4403         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4404         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4405                           UserTreeIdx, ReuseShuffleIndicies);
4406         TE->setOperandsInOrder();
4407         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4408         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4409         break;
4410       case LoadsState::Gather:
4411         BS.cancelScheduling(VL, VL0);
4412         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4413                      ReuseShuffleIndicies);
4414 #ifndef NDEBUG
4415         Type *ScalarTy = VL0->getType();
4416         if (DL->getTypeSizeInBits(ScalarTy) !=
4417             DL->getTypeAllocSizeInBits(ScalarTy))
4418           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4419         else if (any_of(VL, [](Value *V) {
4420                    return !cast<LoadInst>(V)->isSimple();
4421                  }))
4422           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4423         else
4424           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4425 #endif // NDEBUG
4426         break;
4427       }
4428       return;
4429     }
4430     case Instruction::ZExt:
4431     case Instruction::SExt:
4432     case Instruction::FPToUI:
4433     case Instruction::FPToSI:
4434     case Instruction::FPExt:
4435     case Instruction::PtrToInt:
4436     case Instruction::IntToPtr:
4437     case Instruction::SIToFP:
4438     case Instruction::UIToFP:
4439     case Instruction::Trunc:
4440     case Instruction::FPTrunc:
4441     case Instruction::BitCast: {
4442       Type *SrcTy = VL0->getOperand(0)->getType();
4443       for (Value *V : VL) {
4444         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4445         if (Ty != SrcTy || !isValidElementType(Ty)) {
4446           BS.cancelScheduling(VL, VL0);
4447           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4448                        ReuseShuffleIndicies);
4449           LLVM_DEBUG(dbgs()
4450                      << "SLP: Gathering casts with different src types.\n");
4451           return;
4452         }
4453       }
4454       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4455                                    ReuseShuffleIndicies);
4456       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4457 
4458       TE->setOperandsInOrder();
4459       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4460         ValueList Operands;
4461         // Prepare the operand vector.
4462         for (Value *V : VL)
4463           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4464 
4465         buildTree_rec(Operands, Depth + 1, {TE, i});
4466       }
4467       return;
4468     }
4469     case Instruction::ICmp:
4470     case Instruction::FCmp: {
4471       // Check that all of the compares have the same predicate.
4472       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4473       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4474       Type *ComparedTy = VL0->getOperand(0)->getType();
4475       for (Value *V : VL) {
4476         CmpInst *Cmp = cast<CmpInst>(V);
4477         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4478             Cmp->getOperand(0)->getType() != ComparedTy) {
4479           BS.cancelScheduling(VL, VL0);
4480           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4481                        ReuseShuffleIndicies);
4482           LLVM_DEBUG(dbgs()
4483                      << "SLP: Gathering cmp with different predicate.\n");
4484           return;
4485         }
4486       }
4487 
4488       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4489                                    ReuseShuffleIndicies);
4490       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4491 
4492       ValueList Left, Right;
4493       if (cast<CmpInst>(VL0)->isCommutative()) {
4494         // Commutative predicate - collect + sort operands of the instructions
4495         // so that each side is more likely to have the same opcode.
4496         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4497         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4498       } else {
4499         // Collect operands - commute if it uses the swapped predicate.
4500         for (Value *V : VL) {
4501           auto *Cmp = cast<CmpInst>(V);
4502           Value *LHS = Cmp->getOperand(0);
4503           Value *RHS = Cmp->getOperand(1);
4504           if (Cmp->getPredicate() != P0)
4505             std::swap(LHS, RHS);
4506           Left.push_back(LHS);
4507           Right.push_back(RHS);
4508         }
4509       }
4510       TE->setOperand(0, Left);
4511       TE->setOperand(1, Right);
4512       buildTree_rec(Left, Depth + 1, {TE, 0});
4513       buildTree_rec(Right, Depth + 1, {TE, 1});
4514       return;
4515     }
4516     case Instruction::Select:
4517     case Instruction::FNeg:
4518     case Instruction::Add:
4519     case Instruction::FAdd:
4520     case Instruction::Sub:
4521     case Instruction::FSub:
4522     case Instruction::Mul:
4523     case Instruction::FMul:
4524     case Instruction::UDiv:
4525     case Instruction::SDiv:
4526     case Instruction::FDiv:
4527     case Instruction::URem:
4528     case Instruction::SRem:
4529     case Instruction::FRem:
4530     case Instruction::Shl:
4531     case Instruction::LShr:
4532     case Instruction::AShr:
4533     case Instruction::And:
4534     case Instruction::Or:
4535     case Instruction::Xor: {
4536       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4537                                    ReuseShuffleIndicies);
4538       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4539 
4540       // Sort operands of the instructions so that each side is more likely to
4541       // have the same opcode.
4542       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4543         ValueList Left, Right;
4544         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4545         TE->setOperand(0, Left);
4546         TE->setOperand(1, Right);
4547         buildTree_rec(Left, Depth + 1, {TE, 0});
4548         buildTree_rec(Right, Depth + 1, {TE, 1});
4549         return;
4550       }
4551 
4552       TE->setOperandsInOrder();
4553       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4554         ValueList Operands;
4555         // Prepare the operand vector.
4556         for (Value *V : VL)
4557           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4558 
4559         buildTree_rec(Operands, Depth + 1, {TE, i});
4560       }
4561       return;
4562     }
4563     case Instruction::GetElementPtr: {
4564       // We don't combine GEPs with complicated (nested) indexing.
4565       for (Value *V : VL) {
4566         if (cast<Instruction>(V)->getNumOperands() != 2) {
4567           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4568           BS.cancelScheduling(VL, VL0);
4569           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4570                        ReuseShuffleIndicies);
4571           return;
4572         }
4573       }
4574 
4575       // We can't combine several GEPs into one vector if they operate on
4576       // different types.
4577       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4578       for (Value *V : VL) {
4579         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4580         if (Ty0 != CurTy) {
4581           LLVM_DEBUG(dbgs()
4582                      << "SLP: not-vectorizable GEP (different types).\n");
4583           BS.cancelScheduling(VL, VL0);
4584           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4585                        ReuseShuffleIndicies);
4586           return;
4587         }
4588       }
4589 
4590       // We don't combine GEPs with non-constant indexes.
4591       Type *Ty1 = VL0->getOperand(1)->getType();
4592       for (Value *V : VL) {
4593         auto Op = cast<Instruction>(V)->getOperand(1);
4594         if (!isa<ConstantInt>(Op) ||
4595             (Op->getType() != Ty1 &&
4596              Op->getType()->getScalarSizeInBits() >
4597                  DL->getIndexSizeInBits(
4598                      V->getType()->getPointerAddressSpace()))) {
4599           LLVM_DEBUG(dbgs()
4600                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4601           BS.cancelScheduling(VL, VL0);
4602           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4603                        ReuseShuffleIndicies);
4604           return;
4605         }
4606       }
4607 
4608       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4609                                    ReuseShuffleIndicies);
4610       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4611       SmallVector<ValueList, 2> Operands(2);
4612       // Prepare the operand vector for pointer operands.
4613       for (Value *V : VL)
4614         Operands.front().push_back(
4615             cast<GetElementPtrInst>(V)->getPointerOperand());
4616       TE->setOperand(0, Operands.front());
4617       // Need to cast all indices to the same type before vectorization to
4618       // avoid crash.
4619       // Required to be able to find correct matches between different gather
4620       // nodes and reuse the vectorized values rather than trying to gather them
4621       // again.
4622       int IndexIdx = 1;
4623       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4624       Type *Ty = all_of(VL,
4625                         [VL0Ty, IndexIdx](Value *V) {
4626                           return VL0Ty == cast<GetElementPtrInst>(V)
4627                                               ->getOperand(IndexIdx)
4628                                               ->getType();
4629                         })
4630                      ? VL0Ty
4631                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4632                                             ->getPointerOperandType()
4633                                             ->getScalarType());
4634       // Prepare the operand vector.
4635       for (Value *V : VL) {
4636         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4637         auto *CI = cast<ConstantInt>(Op);
4638         Operands.back().push_back(ConstantExpr::getIntegerCast(
4639             CI, Ty, CI->getValue().isSignBitSet()));
4640       }
4641       TE->setOperand(IndexIdx, Operands.back());
4642 
4643       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4644         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4645       return;
4646     }
4647     case Instruction::Store: {
4648       // Check if the stores are consecutive or if we need to swizzle them.
4649       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4650       // Avoid types that are padded when being allocated as scalars, while
4651       // being packed together in a vector (such as i1).
4652       if (DL->getTypeSizeInBits(ScalarTy) !=
4653           DL->getTypeAllocSizeInBits(ScalarTy)) {
4654         BS.cancelScheduling(VL, VL0);
4655         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4656                      ReuseShuffleIndicies);
4657         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4658         return;
4659       }
4660       // Make sure all stores in the bundle are simple - we can't vectorize
4661       // atomic or volatile stores.
4662       SmallVector<Value *, 4> PointerOps(VL.size());
4663       ValueList Operands(VL.size());
4664       auto POIter = PointerOps.begin();
4665       auto OIter = Operands.begin();
4666       for (Value *V : VL) {
4667         auto *SI = cast<StoreInst>(V);
4668         if (!SI->isSimple()) {
4669           BS.cancelScheduling(VL, VL0);
4670           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4671                        ReuseShuffleIndicies);
4672           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4673           return;
4674         }
4675         *POIter = SI->getPointerOperand();
4676         *OIter = SI->getValueOperand();
4677         ++POIter;
4678         ++OIter;
4679       }
4680 
4681       OrdersType CurrentOrder;
4682       // Check the order of pointer operands.
4683       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4684         Value *Ptr0;
4685         Value *PtrN;
4686         if (CurrentOrder.empty()) {
4687           Ptr0 = PointerOps.front();
4688           PtrN = PointerOps.back();
4689         } else {
4690           Ptr0 = PointerOps[CurrentOrder.front()];
4691           PtrN = PointerOps[CurrentOrder.back()];
4692         }
4693         Optional<int> Dist =
4694             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4695         // Check that the sorted pointer operands are consecutive.
4696         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4697           if (CurrentOrder.empty()) {
4698             // Original stores are consecutive and does not require reordering.
4699             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4700                                          UserTreeIdx, ReuseShuffleIndicies);
4701             TE->setOperandsInOrder();
4702             buildTree_rec(Operands, Depth + 1, {TE, 0});
4703             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4704           } else {
4705             fixupOrderingIndices(CurrentOrder);
4706             TreeEntry *TE =
4707                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4708                              ReuseShuffleIndicies, CurrentOrder);
4709             TE->setOperandsInOrder();
4710             buildTree_rec(Operands, Depth + 1, {TE, 0});
4711             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4712           }
4713           return;
4714         }
4715       }
4716 
4717       BS.cancelScheduling(VL, VL0);
4718       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4719                    ReuseShuffleIndicies);
4720       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4721       return;
4722     }
4723     case Instruction::Call: {
4724       // Check if the calls are all to the same vectorizable intrinsic or
4725       // library function.
4726       CallInst *CI = cast<CallInst>(VL0);
4727       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4728 
4729       VFShape Shape = VFShape::get(
4730           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4731           false /*HasGlobalPred*/);
4732       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4733 
4734       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4735         BS.cancelScheduling(VL, VL0);
4736         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4737                      ReuseShuffleIndicies);
4738         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4739         return;
4740       }
4741       Function *F = CI->getCalledFunction();
4742       unsigned NumArgs = CI->arg_size();
4743       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4744       for (unsigned j = 0; j != NumArgs; ++j)
4745         if (hasVectorIntrinsicScalarOpd(ID, j))
4746           ScalarArgs[j] = CI->getArgOperand(j);
4747       for (Value *V : VL) {
4748         CallInst *CI2 = dyn_cast<CallInst>(V);
4749         if (!CI2 || CI2->getCalledFunction() != F ||
4750             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4751             (VecFunc &&
4752              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4753             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4754           BS.cancelScheduling(VL, VL0);
4755           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4756                        ReuseShuffleIndicies);
4757           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4758                             << "\n");
4759           return;
4760         }
4761         // Some intrinsics have scalar arguments and should be same in order for
4762         // them to be vectorized.
4763         for (unsigned j = 0; j != NumArgs; ++j) {
4764           if (hasVectorIntrinsicScalarOpd(ID, j)) {
4765             Value *A1J = CI2->getArgOperand(j);
4766             if (ScalarArgs[j] != A1J) {
4767               BS.cancelScheduling(VL, VL0);
4768               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4769                            ReuseShuffleIndicies);
4770               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4771                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4772                                 << "\n");
4773               return;
4774             }
4775           }
4776         }
4777         // Verify that the bundle operands are identical between the two calls.
4778         if (CI->hasOperandBundles() &&
4779             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4780                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4781                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4782           BS.cancelScheduling(VL, VL0);
4783           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4784                        ReuseShuffleIndicies);
4785           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4786                             << *CI << "!=" << *V << '\n');
4787           return;
4788         }
4789       }
4790 
4791       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4792                                    ReuseShuffleIndicies);
4793       TE->setOperandsInOrder();
4794       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4795         // For scalar operands no need to to create an entry since no need to
4796         // vectorize it.
4797         if (hasVectorIntrinsicScalarOpd(ID, i))
4798           continue;
4799         ValueList Operands;
4800         // Prepare the operand vector.
4801         for (Value *V : VL) {
4802           auto *CI2 = cast<CallInst>(V);
4803           Operands.push_back(CI2->getArgOperand(i));
4804         }
4805         buildTree_rec(Operands, Depth + 1, {TE, i});
4806       }
4807       return;
4808     }
4809     case Instruction::ShuffleVector: {
4810       // If this is not an alternate sequence of opcode like add-sub
4811       // then do not vectorize this instruction.
4812       if (!S.isAltShuffle()) {
4813         BS.cancelScheduling(VL, VL0);
4814         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4815                      ReuseShuffleIndicies);
4816         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4817         return;
4818       }
4819       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4820                                    ReuseShuffleIndicies);
4821       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4822 
4823       // Reorder operands if reordering would enable vectorization.
4824       auto *CI = dyn_cast<CmpInst>(VL0);
4825       if (isa<BinaryOperator>(VL0) || CI) {
4826         ValueList Left, Right;
4827         if (!CI || all_of(VL, [](Value *V) {
4828               return cast<CmpInst>(V)->isCommutative();
4829             })) {
4830           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4831         } else {
4832           CmpInst::Predicate P0 = CI->getPredicate();
4833           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4834           assert(P0 != AltP0 &&
4835                  "Expected different main/alternate predicates.");
4836           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4837           Value *BaseOp0 = VL0->getOperand(0);
4838           Value *BaseOp1 = VL0->getOperand(1);
4839           // Collect operands - commute if it uses the swapped predicate or
4840           // alternate operation.
4841           for (Value *V : VL) {
4842             auto *Cmp = cast<CmpInst>(V);
4843             Value *LHS = Cmp->getOperand(0);
4844             Value *RHS = Cmp->getOperand(1);
4845             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4846             if (P0 == AltP0Swapped) {
4847               if (CI != Cmp && S.AltOp != Cmp &&
4848                   ((P0 == CurrentPred &&
4849                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4850                    (AltP0 == CurrentPred &&
4851                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4852                 std::swap(LHS, RHS);
4853             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4854               std::swap(LHS, RHS);
4855             }
4856             Left.push_back(LHS);
4857             Right.push_back(RHS);
4858           }
4859         }
4860         TE->setOperand(0, Left);
4861         TE->setOperand(1, Right);
4862         buildTree_rec(Left, Depth + 1, {TE, 0});
4863         buildTree_rec(Right, Depth + 1, {TE, 1});
4864         return;
4865       }
4866 
4867       TE->setOperandsInOrder();
4868       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4869         ValueList Operands;
4870         // Prepare the operand vector.
4871         for (Value *V : VL)
4872           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4873 
4874         buildTree_rec(Operands, Depth + 1, {TE, i});
4875       }
4876       return;
4877     }
4878     default:
4879       BS.cancelScheduling(VL, VL0);
4880       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4881                    ReuseShuffleIndicies);
4882       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4883       return;
4884   }
4885 }
4886 
4887 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4888   unsigned N = 1;
4889   Type *EltTy = T;
4890 
4891   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4892          isa<VectorType>(EltTy)) {
4893     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4894       // Check that struct is homogeneous.
4895       for (const auto *Ty : ST->elements())
4896         if (Ty != *ST->element_begin())
4897           return 0;
4898       N *= ST->getNumElements();
4899       EltTy = *ST->element_begin();
4900     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4901       N *= AT->getNumElements();
4902       EltTy = AT->getElementType();
4903     } else {
4904       auto *VT = cast<FixedVectorType>(EltTy);
4905       N *= VT->getNumElements();
4906       EltTy = VT->getElementType();
4907     }
4908   }
4909 
4910   if (!isValidElementType(EltTy))
4911     return 0;
4912   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4913   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4914     return 0;
4915   return N;
4916 }
4917 
4918 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4919                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4920   const auto *It = find_if(VL, [](Value *V) {
4921     return isa<ExtractElementInst, ExtractValueInst>(V);
4922   });
4923   assert(It != VL.end() && "Expected at least one extract instruction.");
4924   auto *E0 = cast<Instruction>(*It);
4925   assert(all_of(VL,
4926                 [](Value *V) {
4927                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4928                       V);
4929                 }) &&
4930          "Invalid opcode");
4931   // Check if all of the extracts come from the same vector and from the
4932   // correct offset.
4933   Value *Vec = E0->getOperand(0);
4934 
4935   CurrentOrder.clear();
4936 
4937   // We have to extract from a vector/aggregate with the same number of elements.
4938   unsigned NElts;
4939   if (E0->getOpcode() == Instruction::ExtractValue) {
4940     const DataLayout &DL = E0->getModule()->getDataLayout();
4941     NElts = canMapToVector(Vec->getType(), DL);
4942     if (!NElts)
4943       return false;
4944     // Check if load can be rewritten as load of vector.
4945     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4946     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4947       return false;
4948   } else {
4949     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4950   }
4951 
4952   if (NElts != VL.size())
4953     return false;
4954 
4955   // Check that all of the indices extract from the correct offset.
4956   bool ShouldKeepOrder = true;
4957   unsigned E = VL.size();
4958   // Assign to all items the initial value E + 1 so we can check if the extract
4959   // instruction index was used already.
4960   // Also, later we can check that all the indices are used and we have a
4961   // consecutive access in the extract instructions, by checking that no
4962   // element of CurrentOrder still has value E + 1.
4963   CurrentOrder.assign(E, E);
4964   unsigned I = 0;
4965   for (; I < E; ++I) {
4966     auto *Inst = dyn_cast<Instruction>(VL[I]);
4967     if (!Inst)
4968       continue;
4969     if (Inst->getOperand(0) != Vec)
4970       break;
4971     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4972       if (isa<UndefValue>(EE->getIndexOperand()))
4973         continue;
4974     Optional<unsigned> Idx = getExtractIndex(Inst);
4975     if (!Idx)
4976       break;
4977     const unsigned ExtIdx = *Idx;
4978     if (ExtIdx != I) {
4979       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4980         break;
4981       ShouldKeepOrder = false;
4982       CurrentOrder[ExtIdx] = I;
4983     } else {
4984       if (CurrentOrder[I] != E)
4985         break;
4986       CurrentOrder[I] = I;
4987     }
4988   }
4989   if (I < E) {
4990     CurrentOrder.clear();
4991     return false;
4992   }
4993   if (ShouldKeepOrder)
4994     CurrentOrder.clear();
4995 
4996   return ShouldKeepOrder;
4997 }
4998 
4999 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5000                                     ArrayRef<Value *> VectorizedVals) const {
5001   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5002          all_of(I->users(), [this](User *U) {
5003            return ScalarToTreeEntry.count(U) > 0 ||
5004                   isVectorLikeInstWithConstOps(U) ||
5005                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5006          });
5007 }
5008 
5009 static std::pair<InstructionCost, InstructionCost>
5010 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5011                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5012   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5013 
5014   // Calculate the cost of the scalar and vector calls.
5015   SmallVector<Type *, 4> VecTys;
5016   for (Use &Arg : CI->args())
5017     VecTys.push_back(
5018         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5019   FastMathFlags FMF;
5020   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5021     FMF = FPCI->getFastMathFlags();
5022   SmallVector<const Value *> Arguments(CI->args());
5023   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5024                                     dyn_cast<IntrinsicInst>(CI));
5025   auto IntrinsicCost =
5026     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5027 
5028   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5029                                      VecTy->getNumElements())),
5030                             false /*HasGlobalPred*/);
5031   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5032   auto LibCost = IntrinsicCost;
5033   if (!CI->isNoBuiltin() && VecFunc) {
5034     // Calculate the cost of the vector library call.
5035     // If the corresponding vector call is cheaper, return its cost.
5036     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5037                                     TTI::TCK_RecipThroughput);
5038   }
5039   return {IntrinsicCost, LibCost};
5040 }
5041 
5042 /// Compute the cost of creating a vector of type \p VecTy containing the
5043 /// extracted values from \p VL.
5044 static InstructionCost
5045 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5046                    TargetTransformInfo::ShuffleKind ShuffleKind,
5047                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5048   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5049 
5050   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5051       VecTy->getNumElements() < NumOfParts)
5052     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5053 
5054   bool AllConsecutive = true;
5055   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5056   unsigned Idx = -1;
5057   InstructionCost Cost = 0;
5058 
5059   // Process extracts in blocks of EltsPerVector to check if the source vector
5060   // operand can be re-used directly. If not, add the cost of creating a shuffle
5061   // to extract the values into a vector register.
5062   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5063   for (auto *V : VL) {
5064     ++Idx;
5065 
5066     // Need to exclude undefs from analysis.
5067     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5068       continue;
5069 
5070     // Reached the start of a new vector registers.
5071     if (Idx % EltsPerVector == 0) {
5072       RegMask.assign(EltsPerVector, UndefMaskElem);
5073       AllConsecutive = true;
5074       continue;
5075     }
5076 
5077     // Check all extracts for a vector register on the target directly
5078     // extract values in order.
5079     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5080     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5081       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5082       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5083                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5084       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5085     }
5086 
5087     if (AllConsecutive)
5088       continue;
5089 
5090     // Skip all indices, except for the last index per vector block.
5091     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5092       continue;
5093 
5094     // If we have a series of extracts which are not consecutive and hence
5095     // cannot re-use the source vector register directly, compute the shuffle
5096     // cost to extract the a vector with EltsPerVector elements.
5097     Cost += TTI.getShuffleCost(
5098         TargetTransformInfo::SK_PermuteSingleSrc,
5099         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5100   }
5101   return Cost;
5102 }
5103 
5104 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5105 /// operations operands.
5106 static void
5107 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5108                       ArrayRef<int> ReusesIndices,
5109                       const function_ref<bool(Instruction *)> IsAltOp,
5110                       SmallVectorImpl<int> &Mask,
5111                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5112                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5113   unsigned Sz = VL.size();
5114   Mask.assign(Sz, UndefMaskElem);
5115   SmallVector<int> OrderMask;
5116   if (!ReorderIndices.empty())
5117     inversePermutation(ReorderIndices, OrderMask);
5118   for (unsigned I = 0; I < Sz; ++I) {
5119     unsigned Idx = I;
5120     if (!ReorderIndices.empty())
5121       Idx = OrderMask[I];
5122     auto *OpInst = cast<Instruction>(VL[Idx]);
5123     if (IsAltOp(OpInst)) {
5124       Mask[I] = Sz + Idx;
5125       if (AltScalars)
5126         AltScalars->push_back(OpInst);
5127     } else {
5128       Mask[I] = Idx;
5129       if (OpScalars)
5130         OpScalars->push_back(OpInst);
5131     }
5132   }
5133   if (!ReusesIndices.empty()) {
5134     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5135     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5136       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5137     });
5138     Mask.swap(NewMask);
5139   }
5140 }
5141 
5142 /// Checks if the specified instruction \p I is an alternate operation for the
5143 /// given \p MainOp and \p AltOp instructions.
5144 static bool isAlternateInstruction(const Instruction *I,
5145                                    const Instruction *MainOp,
5146                                    const Instruction *AltOp) {
5147   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5148     auto *AltCI0 = cast<CmpInst>(AltOp);
5149     auto *CI = cast<CmpInst>(I);
5150     CmpInst::Predicate P0 = CI0->getPredicate();
5151     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5152     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5153     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5154     CmpInst::Predicate CurrentPred = CI->getPredicate();
5155     if (P0 == AltP0Swapped)
5156       return I == AltCI0 ||
5157              (I != MainOp &&
5158               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5159                                    CI->getOperand(0), CI->getOperand(1)));
5160     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5161   }
5162   return I->getOpcode() == AltOp->getOpcode();
5163 }
5164 
5165 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5166                                       ArrayRef<Value *> VectorizedVals) {
5167   ArrayRef<Value*> VL = E->Scalars;
5168 
5169   Type *ScalarTy = VL[0]->getType();
5170   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5171     ScalarTy = SI->getValueOperand()->getType();
5172   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5173     ScalarTy = CI->getOperand(0)->getType();
5174   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5175     ScalarTy = IE->getOperand(1)->getType();
5176   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5177   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5178 
5179   // If we have computed a smaller type for the expression, update VecTy so
5180   // that the costs will be accurate.
5181   if (MinBWs.count(VL[0]))
5182     VecTy = FixedVectorType::get(
5183         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5184   unsigned EntryVF = E->getVectorFactor();
5185   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5186 
5187   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5188   // FIXME: it tries to fix a problem with MSVC buildbots.
5189   TargetTransformInfo &TTIRef = *TTI;
5190   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5191                                VectorizedVals, E](InstructionCost &Cost) {
5192     DenseMap<Value *, int> ExtractVectorsTys;
5193     SmallPtrSet<Value *, 4> CheckedExtracts;
5194     for (auto *V : VL) {
5195       if (isa<UndefValue>(V))
5196         continue;
5197       // If all users of instruction are going to be vectorized and this
5198       // instruction itself is not going to be vectorized, consider this
5199       // instruction as dead and remove its cost from the final cost of the
5200       // vectorized tree.
5201       // Also, avoid adjusting the cost for extractelements with multiple uses
5202       // in different graph entries.
5203       const TreeEntry *VE = getTreeEntry(V);
5204       if (!CheckedExtracts.insert(V).second ||
5205           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5206           (VE && VE != E))
5207         continue;
5208       auto *EE = cast<ExtractElementInst>(V);
5209       Optional<unsigned> EEIdx = getExtractIndex(EE);
5210       if (!EEIdx)
5211         continue;
5212       unsigned Idx = *EEIdx;
5213       if (TTIRef.getNumberOfParts(VecTy) !=
5214           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5215         auto It =
5216             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5217         It->getSecond() = std::min<int>(It->second, Idx);
5218       }
5219       // Take credit for instruction that will become dead.
5220       if (EE->hasOneUse()) {
5221         Instruction *Ext = EE->user_back();
5222         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5223             all_of(Ext->users(),
5224                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5225           // Use getExtractWithExtendCost() to calculate the cost of
5226           // extractelement/ext pair.
5227           Cost -=
5228               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5229                                               EE->getVectorOperandType(), Idx);
5230           // Add back the cost of s|zext which is subtracted separately.
5231           Cost += TTIRef.getCastInstrCost(
5232               Ext->getOpcode(), Ext->getType(), EE->getType(),
5233               TTI::getCastContextHint(Ext), CostKind, Ext);
5234           continue;
5235         }
5236       }
5237       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5238                                         EE->getVectorOperandType(), Idx);
5239     }
5240     // Add a cost for subvector extracts/inserts if required.
5241     for (const auto &Data : ExtractVectorsTys) {
5242       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5243       unsigned NumElts = VecTy->getNumElements();
5244       if (Data.second % NumElts == 0)
5245         continue;
5246       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5247         unsigned Idx = (Data.second / NumElts) * NumElts;
5248         unsigned EENumElts = EEVTy->getNumElements();
5249         if (Idx + NumElts <= EENumElts) {
5250           Cost +=
5251               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5252                                     EEVTy, None, Idx, VecTy);
5253         } else {
5254           // Need to round up the subvector type vectorization factor to avoid a
5255           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5256           // <= EENumElts.
5257           auto *SubVT =
5258               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5259           Cost +=
5260               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5261                                     EEVTy, None, Idx, SubVT);
5262         }
5263       } else {
5264         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5265                                       VecTy, None, 0, EEVTy);
5266       }
5267     }
5268   };
5269   if (E->State == TreeEntry::NeedToGather) {
5270     if (allConstant(VL))
5271       return 0;
5272     if (isa<InsertElementInst>(VL[0]))
5273       return InstructionCost::getInvalid();
5274     SmallVector<int> Mask;
5275     SmallVector<const TreeEntry *> Entries;
5276     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5277         isGatherShuffledEntry(E, Mask, Entries);
5278     if (Shuffle.hasValue()) {
5279       InstructionCost GatherCost = 0;
5280       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5281         // Perfect match in the graph, will reuse the previously vectorized
5282         // node. Cost is 0.
5283         LLVM_DEBUG(
5284             dbgs()
5285             << "SLP: perfect diamond match for gather bundle that starts with "
5286             << *VL.front() << ".\n");
5287         if (NeedToShuffleReuses)
5288           GatherCost =
5289               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5290                                   FinalVecTy, E->ReuseShuffleIndices);
5291       } else {
5292         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5293                           << " entries for bundle that starts with "
5294                           << *VL.front() << ".\n");
5295         // Detected that instead of gather we can emit a shuffle of single/two
5296         // previously vectorized nodes. Add the cost of the permutation rather
5297         // than gather.
5298         ::addMask(Mask, E->ReuseShuffleIndices);
5299         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5300       }
5301       return GatherCost;
5302     }
5303     if ((E->getOpcode() == Instruction::ExtractElement ||
5304          all_of(E->Scalars,
5305                 [](Value *V) {
5306                   return isa<ExtractElementInst, UndefValue>(V);
5307                 })) &&
5308         allSameType(VL)) {
5309       // Check that gather of extractelements can be represented as just a
5310       // shuffle of a single/two vectors the scalars are extracted from.
5311       SmallVector<int> Mask;
5312       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5313           isFixedVectorShuffle(VL, Mask);
5314       if (ShuffleKind.hasValue()) {
5315         // Found the bunch of extractelement instructions that must be gathered
5316         // into a vector and can be represented as a permutation elements in a
5317         // single input vector or of 2 input vectors.
5318         InstructionCost Cost =
5319             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5320         AdjustExtractsCost(Cost);
5321         if (NeedToShuffleReuses)
5322           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5323                                       FinalVecTy, E->ReuseShuffleIndices);
5324         return Cost;
5325       }
5326     }
5327     if (isSplat(VL)) {
5328       // Found the broadcasting of the single scalar, calculate the cost as the
5329       // broadcast.
5330       assert(VecTy == FinalVecTy &&
5331              "No reused scalars expected for broadcast.");
5332       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5333                                  /*Mask=*/None, /*Index=*/0,
5334                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5335     }
5336     InstructionCost ReuseShuffleCost = 0;
5337     if (NeedToShuffleReuses)
5338       ReuseShuffleCost = TTI->getShuffleCost(
5339           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5340     // Improve gather cost for gather of loads, if we can group some of the
5341     // loads into vector loads.
5342     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5343         !E->isAltShuffle()) {
5344       BoUpSLP::ValueSet VectorizedLoads;
5345       unsigned StartIdx = 0;
5346       unsigned VF = VL.size() / 2;
5347       unsigned VectorizedCnt = 0;
5348       unsigned ScatterVectorizeCnt = 0;
5349       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5350       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5351         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5352              Cnt += VF) {
5353           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5354           if (!VectorizedLoads.count(Slice.front()) &&
5355               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5356             SmallVector<Value *> PointerOps;
5357             OrdersType CurrentOrder;
5358             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5359                                               *SE, CurrentOrder, PointerOps);
5360             switch (LS) {
5361             case LoadsState::Vectorize:
5362             case LoadsState::ScatterVectorize:
5363               // Mark the vectorized loads so that we don't vectorize them
5364               // again.
5365               if (LS == LoadsState::Vectorize)
5366                 ++VectorizedCnt;
5367               else
5368                 ++ScatterVectorizeCnt;
5369               VectorizedLoads.insert(Slice.begin(), Slice.end());
5370               // If we vectorized initial block, no need to try to vectorize it
5371               // again.
5372               if (Cnt == StartIdx)
5373                 StartIdx += VF;
5374               break;
5375             case LoadsState::Gather:
5376               break;
5377             }
5378           }
5379         }
5380         // Check if the whole array was vectorized already - exit.
5381         if (StartIdx >= VL.size())
5382           break;
5383         // Found vectorizable parts - exit.
5384         if (!VectorizedLoads.empty())
5385           break;
5386       }
5387       if (!VectorizedLoads.empty()) {
5388         InstructionCost GatherCost = 0;
5389         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5390         bool NeedInsertSubvectorAnalysis =
5391             !NumParts || (VL.size() / VF) > NumParts;
5392         // Get the cost for gathered loads.
5393         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5394           if (VectorizedLoads.contains(VL[I]))
5395             continue;
5396           GatherCost += getGatherCost(VL.slice(I, VF));
5397         }
5398         // The cost for vectorized loads.
5399         InstructionCost ScalarsCost = 0;
5400         for (Value *V : VectorizedLoads) {
5401           auto *LI = cast<LoadInst>(V);
5402           ScalarsCost += TTI->getMemoryOpCost(
5403               Instruction::Load, LI->getType(), LI->getAlign(),
5404               LI->getPointerAddressSpace(), CostKind, LI);
5405         }
5406         auto *LI = cast<LoadInst>(E->getMainOp());
5407         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5408         Align Alignment = LI->getAlign();
5409         GatherCost +=
5410             VectorizedCnt *
5411             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5412                                  LI->getPointerAddressSpace(), CostKind, LI);
5413         GatherCost += ScatterVectorizeCnt *
5414                       TTI->getGatherScatterOpCost(
5415                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5416                           /*VariableMask=*/false, Alignment, CostKind, LI);
5417         if (NeedInsertSubvectorAnalysis) {
5418           // Add the cost for the subvectors insert.
5419           for (int I = VF, E = VL.size(); I < E; I += VF)
5420             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5421                                               None, I, LoadTy);
5422         }
5423         return ReuseShuffleCost + GatherCost - ScalarsCost;
5424       }
5425     }
5426     return ReuseShuffleCost + getGatherCost(VL);
5427   }
5428   InstructionCost CommonCost = 0;
5429   SmallVector<int> Mask;
5430   if (!E->ReorderIndices.empty()) {
5431     SmallVector<int> NewMask;
5432     if (E->getOpcode() == Instruction::Store) {
5433       // For stores the order is actually a mask.
5434       NewMask.resize(E->ReorderIndices.size());
5435       copy(E->ReorderIndices, NewMask.begin());
5436     } else {
5437       inversePermutation(E->ReorderIndices, NewMask);
5438     }
5439     ::addMask(Mask, NewMask);
5440   }
5441   if (NeedToShuffleReuses)
5442     ::addMask(Mask, E->ReuseShuffleIndices);
5443   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5444     CommonCost =
5445         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5446   assert((E->State == TreeEntry::Vectorize ||
5447           E->State == TreeEntry::ScatterVectorize) &&
5448          "Unhandled state");
5449   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5450   Instruction *VL0 = E->getMainOp();
5451   unsigned ShuffleOrOp =
5452       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5453   switch (ShuffleOrOp) {
5454     case Instruction::PHI:
5455       return 0;
5456 
5457     case Instruction::ExtractValue:
5458     case Instruction::ExtractElement: {
5459       // The common cost of removal ExtractElement/ExtractValue instructions +
5460       // the cost of shuffles, if required to resuffle the original vector.
5461       if (NeedToShuffleReuses) {
5462         unsigned Idx = 0;
5463         for (unsigned I : E->ReuseShuffleIndices) {
5464           if (ShuffleOrOp == Instruction::ExtractElement) {
5465             auto *EE = cast<ExtractElementInst>(VL[I]);
5466             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5467                                                   EE->getVectorOperandType(),
5468                                                   *getExtractIndex(EE));
5469           } else {
5470             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5471                                                   VecTy, Idx);
5472             ++Idx;
5473           }
5474         }
5475         Idx = EntryVF;
5476         for (Value *V : VL) {
5477           if (ShuffleOrOp == Instruction::ExtractElement) {
5478             auto *EE = cast<ExtractElementInst>(V);
5479             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5480                                                   EE->getVectorOperandType(),
5481                                                   *getExtractIndex(EE));
5482           } else {
5483             --Idx;
5484             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5485                                                   VecTy, Idx);
5486           }
5487         }
5488       }
5489       if (ShuffleOrOp == Instruction::ExtractValue) {
5490         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5491           auto *EI = cast<Instruction>(VL[I]);
5492           // Take credit for instruction that will become dead.
5493           if (EI->hasOneUse()) {
5494             Instruction *Ext = EI->user_back();
5495             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5496                 all_of(Ext->users(),
5497                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5498               // Use getExtractWithExtendCost() to calculate the cost of
5499               // extractelement/ext pair.
5500               CommonCost -= TTI->getExtractWithExtendCost(
5501                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5502               // Add back the cost of s|zext which is subtracted separately.
5503               CommonCost += TTI->getCastInstrCost(
5504                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5505                   TTI::getCastContextHint(Ext), CostKind, Ext);
5506               continue;
5507             }
5508           }
5509           CommonCost -=
5510               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5511         }
5512       } else {
5513         AdjustExtractsCost(CommonCost);
5514       }
5515       return CommonCost;
5516     }
5517     case Instruction::InsertElement: {
5518       assert(E->ReuseShuffleIndices.empty() &&
5519              "Unique insertelements only are expected.");
5520       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5521 
5522       unsigned const NumElts = SrcVecTy->getNumElements();
5523       unsigned const NumScalars = VL.size();
5524       APInt DemandedElts = APInt::getZero(NumElts);
5525       // TODO: Add support for Instruction::InsertValue.
5526       SmallVector<int> Mask;
5527       if (!E->ReorderIndices.empty()) {
5528         inversePermutation(E->ReorderIndices, Mask);
5529         Mask.append(NumElts - NumScalars, UndefMaskElem);
5530       } else {
5531         Mask.assign(NumElts, UndefMaskElem);
5532         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5533       }
5534       unsigned Offset = *getInsertIndex(VL0);
5535       bool IsIdentity = true;
5536       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5537       Mask.swap(PrevMask);
5538       for (unsigned I = 0; I < NumScalars; ++I) {
5539         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5540         DemandedElts.setBit(InsertIdx);
5541         IsIdentity &= InsertIdx - Offset == I;
5542         Mask[InsertIdx - Offset] = I;
5543       }
5544       assert(Offset < NumElts && "Failed to find vector index offset");
5545 
5546       InstructionCost Cost = 0;
5547       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5548                                             /*Insert*/ true, /*Extract*/ false);
5549 
5550       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5551         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5552         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5553         Cost += TTI->getShuffleCost(
5554             TargetTransformInfo::SK_PermuteSingleSrc,
5555             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5556       } else if (!IsIdentity) {
5557         auto *FirstInsert =
5558             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5559               return !is_contained(E->Scalars,
5560                                    cast<Instruction>(V)->getOperand(0));
5561             }));
5562         if (isUndefVector(FirstInsert->getOperand(0))) {
5563           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5564         } else {
5565           SmallVector<int> InsertMask(NumElts);
5566           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5567           for (unsigned I = 0; I < NumElts; I++) {
5568             if (Mask[I] != UndefMaskElem)
5569               InsertMask[Offset + I] = NumElts + I;
5570           }
5571           Cost +=
5572               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5573         }
5574       }
5575 
5576       return Cost;
5577     }
5578     case Instruction::ZExt:
5579     case Instruction::SExt:
5580     case Instruction::FPToUI:
5581     case Instruction::FPToSI:
5582     case Instruction::FPExt:
5583     case Instruction::PtrToInt:
5584     case Instruction::IntToPtr:
5585     case Instruction::SIToFP:
5586     case Instruction::UIToFP:
5587     case Instruction::Trunc:
5588     case Instruction::FPTrunc:
5589     case Instruction::BitCast: {
5590       Type *SrcTy = VL0->getOperand(0)->getType();
5591       InstructionCost ScalarEltCost =
5592           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5593                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5594       if (NeedToShuffleReuses) {
5595         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5596       }
5597 
5598       // Calculate the cost of this instruction.
5599       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5600 
5601       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5602       InstructionCost VecCost = 0;
5603       // Check if the values are candidates to demote.
5604       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5605         VecCost = CommonCost + TTI->getCastInstrCost(
5606                                    E->getOpcode(), VecTy, SrcVecTy,
5607                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5608       }
5609       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5610       return VecCost - ScalarCost;
5611     }
5612     case Instruction::FCmp:
5613     case Instruction::ICmp:
5614     case Instruction::Select: {
5615       // Calculate the cost of this instruction.
5616       InstructionCost ScalarEltCost =
5617           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5618                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5619       if (NeedToShuffleReuses) {
5620         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5621       }
5622       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5623       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5624 
5625       // Check if all entries in VL are either compares or selects with compares
5626       // as condition that have the same predicates.
5627       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5628       bool First = true;
5629       for (auto *V : VL) {
5630         CmpInst::Predicate CurrentPred;
5631         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5632         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5633              !match(V, MatchCmp)) ||
5634             (!First && VecPred != CurrentPred)) {
5635           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5636           break;
5637         }
5638         First = false;
5639         VecPred = CurrentPred;
5640       }
5641 
5642       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5643           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5644       // Check if it is possible and profitable to use min/max for selects in
5645       // VL.
5646       //
5647       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5648       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5649         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5650                                           {VecTy, VecTy});
5651         InstructionCost IntrinsicCost =
5652             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5653         // If the selects are the only uses of the compares, they will be dead
5654         // and we can adjust the cost by removing their cost.
5655         if (IntrinsicAndUse.second)
5656           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5657                                                    MaskTy, VecPred, CostKind);
5658         VecCost = std::min(VecCost, IntrinsicCost);
5659       }
5660       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5661       return CommonCost + VecCost - ScalarCost;
5662     }
5663     case Instruction::FNeg:
5664     case Instruction::Add:
5665     case Instruction::FAdd:
5666     case Instruction::Sub:
5667     case Instruction::FSub:
5668     case Instruction::Mul:
5669     case Instruction::FMul:
5670     case Instruction::UDiv:
5671     case Instruction::SDiv:
5672     case Instruction::FDiv:
5673     case Instruction::URem:
5674     case Instruction::SRem:
5675     case Instruction::FRem:
5676     case Instruction::Shl:
5677     case Instruction::LShr:
5678     case Instruction::AShr:
5679     case Instruction::And:
5680     case Instruction::Or:
5681     case Instruction::Xor: {
5682       // Certain instructions can be cheaper to vectorize if they have a
5683       // constant second vector operand.
5684       TargetTransformInfo::OperandValueKind Op1VK =
5685           TargetTransformInfo::OK_AnyValue;
5686       TargetTransformInfo::OperandValueKind Op2VK =
5687           TargetTransformInfo::OK_UniformConstantValue;
5688       TargetTransformInfo::OperandValueProperties Op1VP =
5689           TargetTransformInfo::OP_None;
5690       TargetTransformInfo::OperandValueProperties Op2VP =
5691           TargetTransformInfo::OP_PowerOf2;
5692 
5693       // If all operands are exactly the same ConstantInt then set the
5694       // operand kind to OK_UniformConstantValue.
5695       // If instead not all operands are constants, then set the operand kind
5696       // to OK_AnyValue. If all operands are constants but not the same,
5697       // then set the operand kind to OK_NonUniformConstantValue.
5698       ConstantInt *CInt0 = nullptr;
5699       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5700         const Instruction *I = cast<Instruction>(VL[i]);
5701         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5702         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5703         if (!CInt) {
5704           Op2VK = TargetTransformInfo::OK_AnyValue;
5705           Op2VP = TargetTransformInfo::OP_None;
5706           break;
5707         }
5708         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5709             !CInt->getValue().isPowerOf2())
5710           Op2VP = TargetTransformInfo::OP_None;
5711         if (i == 0) {
5712           CInt0 = CInt;
5713           continue;
5714         }
5715         if (CInt0 != CInt)
5716           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5717       }
5718 
5719       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5720       InstructionCost ScalarEltCost =
5721           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5722                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5723       if (NeedToShuffleReuses) {
5724         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5725       }
5726       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5727       InstructionCost VecCost =
5728           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5729                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5730       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5731       return CommonCost + VecCost - ScalarCost;
5732     }
5733     case Instruction::GetElementPtr: {
5734       TargetTransformInfo::OperandValueKind Op1VK =
5735           TargetTransformInfo::OK_AnyValue;
5736       TargetTransformInfo::OperandValueKind Op2VK =
5737           TargetTransformInfo::OK_UniformConstantValue;
5738 
5739       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5740           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5741       if (NeedToShuffleReuses) {
5742         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5743       }
5744       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5745       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5746           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5747       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5748       return CommonCost + VecCost - ScalarCost;
5749     }
5750     case Instruction::Load: {
5751       // Cost of wide load - cost of scalar loads.
5752       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5753       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5754           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5755       if (NeedToShuffleReuses) {
5756         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5757       }
5758       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5759       InstructionCost VecLdCost;
5760       if (E->State == TreeEntry::Vectorize) {
5761         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5762                                          CostKind, VL0);
5763       } else {
5764         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5765         Align CommonAlignment = Alignment;
5766         for (Value *V : VL)
5767           CommonAlignment =
5768               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5769         VecLdCost = TTI->getGatherScatterOpCost(
5770             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5771             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5772       }
5773       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5774       return CommonCost + VecLdCost - ScalarLdCost;
5775     }
5776     case Instruction::Store: {
5777       // We know that we can merge the stores. Calculate the cost.
5778       bool IsReorder = !E->ReorderIndices.empty();
5779       auto *SI =
5780           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5781       Align Alignment = SI->getAlign();
5782       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5783           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5784       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5785       InstructionCost VecStCost = TTI->getMemoryOpCost(
5786           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5787       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5788       return CommonCost + VecStCost - ScalarStCost;
5789     }
5790     case Instruction::Call: {
5791       CallInst *CI = cast<CallInst>(VL0);
5792       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5793 
5794       // Calculate the cost of the scalar and vector calls.
5795       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5796       InstructionCost ScalarEltCost =
5797           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5798       if (NeedToShuffleReuses) {
5799         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5800       }
5801       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5802 
5803       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5804       InstructionCost VecCallCost =
5805           std::min(VecCallCosts.first, VecCallCosts.second);
5806 
5807       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5808                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5809                         << " for " << *CI << "\n");
5810 
5811       return CommonCost + VecCallCost - ScalarCallCost;
5812     }
5813     case Instruction::ShuffleVector: {
5814       assert(E->isAltShuffle() &&
5815              ((Instruction::isBinaryOp(E->getOpcode()) &&
5816                Instruction::isBinaryOp(E->getAltOpcode())) ||
5817               (Instruction::isCast(E->getOpcode()) &&
5818                Instruction::isCast(E->getAltOpcode())) ||
5819               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5820              "Invalid Shuffle Vector Operand");
5821       InstructionCost ScalarCost = 0;
5822       if (NeedToShuffleReuses) {
5823         for (unsigned Idx : E->ReuseShuffleIndices) {
5824           Instruction *I = cast<Instruction>(VL[Idx]);
5825           CommonCost -= TTI->getInstructionCost(I, CostKind);
5826         }
5827         for (Value *V : VL) {
5828           Instruction *I = cast<Instruction>(V);
5829           CommonCost += TTI->getInstructionCost(I, CostKind);
5830         }
5831       }
5832       for (Value *V : VL) {
5833         Instruction *I = cast<Instruction>(V);
5834         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5835         ScalarCost += TTI->getInstructionCost(I, CostKind);
5836       }
5837       // VecCost is equal to sum of the cost of creating 2 vectors
5838       // and the cost of creating shuffle.
5839       InstructionCost VecCost = 0;
5840       // Try to find the previous shuffle node with the same operands and same
5841       // main/alternate ops.
5842       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5843         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5844           if (TE.get() == E)
5845             break;
5846           if (TE->isAltShuffle() &&
5847               ((TE->getOpcode() == E->getOpcode() &&
5848                 TE->getAltOpcode() == E->getAltOpcode()) ||
5849                (TE->getOpcode() == E->getAltOpcode() &&
5850                 TE->getAltOpcode() == E->getOpcode())) &&
5851               TE->hasEqualOperands(*E))
5852             return true;
5853         }
5854         return false;
5855       };
5856       if (TryFindNodeWithEqualOperands()) {
5857         LLVM_DEBUG({
5858           dbgs() << "SLP: diamond match for alternate node found.\n";
5859           E->dump();
5860         });
5861         // No need to add new vector costs here since we're going to reuse
5862         // same main/alternate vector ops, just do different shuffling.
5863       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5864         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5865         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5866                                                CostKind);
5867       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5868         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5869                                           Builder.getInt1Ty(),
5870                                           CI0->getPredicate(), CostKind, VL0);
5871         VecCost += TTI->getCmpSelInstrCost(
5872             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5873             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5874             E->getAltOp());
5875       } else {
5876         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5877         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5878         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5879         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5880         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5881                                         TTI::CastContextHint::None, CostKind);
5882         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5883                                          TTI::CastContextHint::None, CostKind);
5884       }
5885 
5886       if (E->ReuseShuffleIndices.empty()) {
5887         CommonCost =
5888             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
5889       } else {
5890         SmallVector<int> Mask;
5891         buildShuffleEntryMask(
5892             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5893             [E](Instruction *I) {
5894               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5895               return I->getOpcode() == E->getAltOpcode();
5896             },
5897             Mask);
5898         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
5899                                          FinalVecTy, Mask);
5900       }
5901       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5902       return CommonCost + VecCost - ScalarCost;
5903     }
5904     default:
5905       llvm_unreachable("Unknown instruction");
5906   }
5907 }
5908 
5909 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5910   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5911                     << VectorizableTree.size() << " is fully vectorizable .\n");
5912 
5913   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5914     SmallVector<int> Mask;
5915     return TE->State == TreeEntry::NeedToGather &&
5916            !any_of(TE->Scalars,
5917                    [this](Value *V) { return EphValues.contains(V); }) &&
5918            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5919             TE->Scalars.size() < Limit ||
5920             ((TE->getOpcode() == Instruction::ExtractElement ||
5921               all_of(TE->Scalars,
5922                      [](Value *V) {
5923                        return isa<ExtractElementInst, UndefValue>(V);
5924                      })) &&
5925              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5926             (TE->State == TreeEntry::NeedToGather &&
5927              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5928   };
5929 
5930   // We only handle trees of heights 1 and 2.
5931   if (VectorizableTree.size() == 1 &&
5932       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5933        (ForReduction &&
5934         AreVectorizableGathers(VectorizableTree[0].get(),
5935                                VectorizableTree[0]->Scalars.size()) &&
5936         VectorizableTree[0]->getVectorFactor() > 2)))
5937     return true;
5938 
5939   if (VectorizableTree.size() != 2)
5940     return false;
5941 
5942   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5943   // with the second gather nodes if they have less scalar operands rather than
5944   // the initial tree element (may be profitable to shuffle the second gather)
5945   // or they are extractelements, which form shuffle.
5946   SmallVector<int> Mask;
5947   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5948       AreVectorizableGathers(VectorizableTree[1].get(),
5949                              VectorizableTree[0]->Scalars.size()))
5950     return true;
5951 
5952   // Gathering cost would be too much for tiny trees.
5953   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5954       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5955        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5956     return false;
5957 
5958   return true;
5959 }
5960 
5961 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5962                                        TargetTransformInfo *TTI,
5963                                        bool MustMatchOrInst) {
5964   // Look past the root to find a source value. Arbitrarily follow the
5965   // path through operand 0 of any 'or'. Also, peek through optional
5966   // shift-left-by-multiple-of-8-bits.
5967   Value *ZextLoad = Root;
5968   const APInt *ShAmtC;
5969   bool FoundOr = false;
5970   while (!isa<ConstantExpr>(ZextLoad) &&
5971          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5972           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5973            ShAmtC->urem(8) == 0))) {
5974     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5975     ZextLoad = BinOp->getOperand(0);
5976     if (BinOp->getOpcode() == Instruction::Or)
5977       FoundOr = true;
5978   }
5979   // Check if the input is an extended load of the required or/shift expression.
5980   Value *Load;
5981   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5982       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5983     return false;
5984 
5985   // Require that the total load bit width is a legal integer type.
5986   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5987   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5988   Type *SrcTy = Load->getType();
5989   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5990   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5991     return false;
5992 
5993   // Everything matched - assume that we can fold the whole sequence using
5994   // load combining.
5995   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5996              << *(cast<Instruction>(Root)) << "\n");
5997 
5998   return true;
5999 }
6000 
6001 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6002   if (RdxKind != RecurKind::Or)
6003     return false;
6004 
6005   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6006   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6007   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6008                                     /* MatchOr */ false);
6009 }
6010 
6011 bool BoUpSLP::isLoadCombineCandidate() const {
6012   // Peek through a final sequence of stores and check if all operations are
6013   // likely to be load-combined.
6014   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6015   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6016     Value *X;
6017     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6018         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6019       return false;
6020   }
6021   return true;
6022 }
6023 
6024 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6025   // No need to vectorize inserts of gathered values.
6026   if (VectorizableTree.size() == 2 &&
6027       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6028       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6029     return true;
6030 
6031   // We can vectorize the tree if its size is greater than or equal to the
6032   // minimum size specified by the MinTreeSize command line option.
6033   if (VectorizableTree.size() >= MinTreeSize)
6034     return false;
6035 
6036   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6037   // can vectorize it if we can prove it fully vectorizable.
6038   if (isFullyVectorizableTinyTree(ForReduction))
6039     return false;
6040 
6041   assert(VectorizableTree.empty()
6042              ? ExternalUses.empty()
6043              : true && "We shouldn't have any external users");
6044 
6045   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6046   // vectorizable.
6047   return true;
6048 }
6049 
6050 InstructionCost BoUpSLP::getSpillCost() const {
6051   // Walk from the bottom of the tree to the top, tracking which values are
6052   // live. When we see a call instruction that is not part of our tree,
6053   // query TTI to see if there is a cost to keeping values live over it
6054   // (for example, if spills and fills are required).
6055   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6056   InstructionCost Cost = 0;
6057 
6058   SmallPtrSet<Instruction*, 4> LiveValues;
6059   Instruction *PrevInst = nullptr;
6060 
6061   // The entries in VectorizableTree are not necessarily ordered by their
6062   // position in basic blocks. Collect them and order them by dominance so later
6063   // instructions are guaranteed to be visited first. For instructions in
6064   // different basic blocks, we only scan to the beginning of the block, so
6065   // their order does not matter, as long as all instructions in a basic block
6066   // are grouped together. Using dominance ensures a deterministic order.
6067   SmallVector<Instruction *, 16> OrderedScalars;
6068   for (const auto &TEPtr : VectorizableTree) {
6069     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6070     if (!Inst)
6071       continue;
6072     OrderedScalars.push_back(Inst);
6073   }
6074   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6075     auto *NodeA = DT->getNode(A->getParent());
6076     auto *NodeB = DT->getNode(B->getParent());
6077     assert(NodeA && "Should only process reachable instructions");
6078     assert(NodeB && "Should only process reachable instructions");
6079     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6080            "Different nodes should have different DFS numbers");
6081     if (NodeA != NodeB)
6082       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6083     return B->comesBefore(A);
6084   });
6085 
6086   for (Instruction *Inst : OrderedScalars) {
6087     if (!PrevInst) {
6088       PrevInst = Inst;
6089       continue;
6090     }
6091 
6092     // Update LiveValues.
6093     LiveValues.erase(PrevInst);
6094     for (auto &J : PrevInst->operands()) {
6095       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6096         LiveValues.insert(cast<Instruction>(&*J));
6097     }
6098 
6099     LLVM_DEBUG({
6100       dbgs() << "SLP: #LV: " << LiveValues.size();
6101       for (auto *X : LiveValues)
6102         dbgs() << " " << X->getName();
6103       dbgs() << ", Looking at ";
6104       Inst->dump();
6105     });
6106 
6107     // Now find the sequence of instructions between PrevInst and Inst.
6108     unsigned NumCalls = 0;
6109     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6110                                  PrevInstIt =
6111                                      PrevInst->getIterator().getReverse();
6112     while (InstIt != PrevInstIt) {
6113       if (PrevInstIt == PrevInst->getParent()->rend()) {
6114         PrevInstIt = Inst->getParent()->rbegin();
6115         continue;
6116       }
6117 
6118       // Debug information does not impact spill cost.
6119       if ((isa<CallInst>(&*PrevInstIt) &&
6120            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6121           &*PrevInstIt != PrevInst)
6122         NumCalls++;
6123 
6124       ++PrevInstIt;
6125     }
6126 
6127     if (NumCalls) {
6128       SmallVector<Type*, 4> V;
6129       for (auto *II : LiveValues) {
6130         auto *ScalarTy = II->getType();
6131         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6132           ScalarTy = VectorTy->getElementType();
6133         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6134       }
6135       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6136     }
6137 
6138     PrevInst = Inst;
6139   }
6140 
6141   return Cost;
6142 }
6143 
6144 /// Check if two insertelement instructions are from the same buildvector.
6145 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6146                                             InsertElementInst *V) {
6147   // Instructions must be from the same basic blocks.
6148   if (VU->getParent() != V->getParent())
6149     return false;
6150   // Checks if 2 insertelements are from the same buildvector.
6151   if (VU->getType() != V->getType())
6152     return false;
6153   // Multiple used inserts are separate nodes.
6154   if (!VU->hasOneUse() && !V->hasOneUse())
6155     return false;
6156   auto *IE1 = VU;
6157   auto *IE2 = V;
6158   // Go through the vector operand of insertelement instructions trying to find
6159   // either VU as the original vector for IE2 or V as the original vector for
6160   // IE1.
6161   do {
6162     if (IE2 == VU || IE1 == V)
6163       return true;
6164     if (IE1) {
6165       if (IE1 != VU && !IE1->hasOneUse())
6166         IE1 = nullptr;
6167       else
6168         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6169     }
6170     if (IE2) {
6171       if (IE2 != V && !IE2->hasOneUse())
6172         IE2 = nullptr;
6173       else
6174         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6175     }
6176   } while (IE1 || IE2);
6177   return false;
6178 }
6179 
6180 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6181   InstructionCost Cost = 0;
6182   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6183                     << VectorizableTree.size() << ".\n");
6184 
6185   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6186 
6187   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6188     TreeEntry &TE = *VectorizableTree[I];
6189 
6190     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6191     Cost += C;
6192     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6193                       << " for bundle that starts with " << *TE.Scalars[0]
6194                       << ".\n"
6195                       << "SLP: Current total cost = " << Cost << "\n");
6196   }
6197 
6198   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6199   InstructionCost ExtractCost = 0;
6200   SmallVector<unsigned> VF;
6201   SmallVector<SmallVector<int>> ShuffleMask;
6202   SmallVector<Value *> FirstUsers;
6203   SmallVector<APInt> DemandedElts;
6204   for (ExternalUser &EU : ExternalUses) {
6205     // We only add extract cost once for the same scalar.
6206     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6207         !ExtractCostCalculated.insert(EU.Scalar).second)
6208       continue;
6209 
6210     // Uses by ephemeral values are free (because the ephemeral value will be
6211     // removed prior to code generation, and so the extraction will be
6212     // removed as well).
6213     if (EphValues.count(EU.User))
6214       continue;
6215 
6216     // No extract cost for vector "scalar"
6217     if (isa<FixedVectorType>(EU.Scalar->getType()))
6218       continue;
6219 
6220     // Already counted the cost for external uses when tried to adjust the cost
6221     // for extractelements, no need to add it again.
6222     if (isa<ExtractElementInst>(EU.Scalar))
6223       continue;
6224 
6225     // If found user is an insertelement, do not calculate extract cost but try
6226     // to detect it as a final shuffled/identity match.
6227     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6228       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6229         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6230         if (InsertIdx) {
6231           auto *It = find_if(FirstUsers, [VU](Value *V) {
6232             return areTwoInsertFromSameBuildVector(VU,
6233                                                    cast<InsertElementInst>(V));
6234           });
6235           int VecId = -1;
6236           if (It == FirstUsers.end()) {
6237             VF.push_back(FTy->getNumElements());
6238             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6239             // Find the insertvector, vectorized in tree, if any.
6240             Value *Base = VU;
6241             while (isa<InsertElementInst>(Base)) {
6242               // Build the mask for the vectorized insertelement instructions.
6243               if (const TreeEntry *E = getTreeEntry(Base)) {
6244                 VU = cast<InsertElementInst>(Base);
6245                 do {
6246                   int Idx = E->findLaneForValue(Base);
6247                   ShuffleMask.back()[Idx] = Idx;
6248                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6249                 } while (E == getTreeEntry(Base));
6250                 break;
6251               }
6252               Base = cast<InsertElementInst>(Base)->getOperand(0);
6253             }
6254             FirstUsers.push_back(VU);
6255             DemandedElts.push_back(APInt::getZero(VF.back()));
6256             VecId = FirstUsers.size() - 1;
6257           } else {
6258             VecId = std::distance(FirstUsers.begin(), It);
6259           }
6260           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6261           DemandedElts[VecId].setBit(*InsertIdx);
6262           continue;
6263         }
6264       }
6265     }
6266 
6267     // If we plan to rewrite the tree in a smaller type, we will need to sign
6268     // extend the extracted value back to the original type. Here, we account
6269     // for the extract and the added cost of the sign extend if needed.
6270     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6271     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6272     if (MinBWs.count(ScalarRoot)) {
6273       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6274       auto Extend =
6275           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6276       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6277       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6278                                                    VecTy, EU.Lane);
6279     } else {
6280       ExtractCost +=
6281           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6282     }
6283   }
6284 
6285   InstructionCost SpillCost = getSpillCost();
6286   Cost += SpillCost + ExtractCost;
6287   if (FirstUsers.size() == 1) {
6288     int Limit = ShuffleMask.front().size() * 2;
6289     if (!all_of(ShuffleMask.front(),
6290                 [Limit](int Idx) { return Idx < Limit; }) ||
6291         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6292       InstructionCost C = TTI->getShuffleCost(
6293           TTI::SK_PermuteSingleSrc,
6294           cast<FixedVectorType>(FirstUsers.front()->getType()),
6295           ShuffleMask.front());
6296       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6297                         << " for final shuffle of insertelement external users "
6298                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6299                         << "SLP: Current total cost = " << Cost << "\n");
6300       Cost += C;
6301     }
6302     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6303         cast<FixedVectorType>(FirstUsers.front()->getType()),
6304         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6305     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6306                       << " for insertelements gather.\n"
6307                       << "SLP: Current total cost = " << Cost << "\n");
6308     Cost -= InsertCost;
6309   } else if (FirstUsers.size() >= 2) {
6310     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6311     // Combined masks of the first 2 vectors.
6312     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6313     copy(ShuffleMask.front(), CombinedMask.begin());
6314     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6315     auto *VecTy = FixedVectorType::get(
6316         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6317         MaxVF);
6318     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6319       if (ShuffleMask[1][I] != UndefMaskElem) {
6320         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6321         CombinedDemandedElts.setBit(I);
6322       }
6323     }
6324     InstructionCost C =
6325         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6326     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6327                       << " for final shuffle of vector node and external "
6328                          "insertelement users "
6329                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6330                       << "SLP: Current total cost = " << Cost << "\n");
6331     Cost += C;
6332     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6333         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6334     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6335                       << " for insertelements gather.\n"
6336                       << "SLP: Current total cost = " << Cost << "\n");
6337     Cost -= InsertCost;
6338     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6339       if (ShuffleMask[I].empty())
6340         continue;
6341       // Other elements - permutation of 2 vectors (the initial one and the
6342       // next Ith incoming vector).
6343       unsigned VF = ShuffleMask[I].size();
6344       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6345         int Mask = ShuffleMask[I][Idx];
6346         if (Mask != UndefMaskElem)
6347           CombinedMask[Idx] = MaxVF + Mask;
6348         else if (CombinedMask[Idx] != UndefMaskElem)
6349           CombinedMask[Idx] = Idx;
6350       }
6351       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6352         if (CombinedMask[Idx] != UndefMaskElem)
6353           CombinedMask[Idx] = Idx;
6354       InstructionCost C =
6355           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6356       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6357                         << " for final shuffle of vector node and external "
6358                            "insertelement users "
6359                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6360                         << "SLP: Current total cost = " << Cost << "\n");
6361       Cost += C;
6362       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6363           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6364           /*Insert*/ true, /*Extract*/ false);
6365       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6366                         << " for insertelements gather.\n"
6367                         << "SLP: Current total cost = " << Cost << "\n");
6368       Cost -= InsertCost;
6369     }
6370   }
6371 
6372 #ifndef NDEBUG
6373   SmallString<256> Str;
6374   {
6375     raw_svector_ostream OS(Str);
6376     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6377        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6378        << "SLP: Total Cost = " << Cost << ".\n";
6379   }
6380   LLVM_DEBUG(dbgs() << Str);
6381   if (ViewSLPTree)
6382     ViewGraph(this, "SLP" + F->getName(), false, Str);
6383 #endif
6384 
6385   return Cost;
6386 }
6387 
6388 Optional<TargetTransformInfo::ShuffleKind>
6389 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6390                                SmallVectorImpl<const TreeEntry *> &Entries) {
6391   // TODO: currently checking only for Scalars in the tree entry, need to count
6392   // reused elements too for better cost estimation.
6393   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6394   Entries.clear();
6395   // Build a lists of values to tree entries.
6396   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6397   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6398     if (EntryPtr.get() == TE)
6399       break;
6400     if (EntryPtr->State != TreeEntry::NeedToGather)
6401       continue;
6402     for (Value *V : EntryPtr->Scalars)
6403       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6404   }
6405   // Find all tree entries used by the gathered values. If no common entries
6406   // found - not a shuffle.
6407   // Here we build a set of tree nodes for each gathered value and trying to
6408   // find the intersection between these sets. If we have at least one common
6409   // tree node for each gathered value - we have just a permutation of the
6410   // single vector. If we have 2 different sets, we're in situation where we
6411   // have a permutation of 2 input vectors.
6412   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6413   DenseMap<Value *, int> UsedValuesEntry;
6414   for (Value *V : TE->Scalars) {
6415     if (isa<UndefValue>(V))
6416       continue;
6417     // Build a list of tree entries where V is used.
6418     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6419     auto It = ValueToTEs.find(V);
6420     if (It != ValueToTEs.end())
6421       VToTEs = It->second;
6422     if (const TreeEntry *VTE = getTreeEntry(V))
6423       VToTEs.insert(VTE);
6424     if (VToTEs.empty())
6425       return None;
6426     if (UsedTEs.empty()) {
6427       // The first iteration, just insert the list of nodes to vector.
6428       UsedTEs.push_back(VToTEs);
6429     } else {
6430       // Need to check if there are any previously used tree nodes which use V.
6431       // If there are no such nodes, consider that we have another one input
6432       // vector.
6433       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6434       unsigned Idx = 0;
6435       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6436         // Do we have a non-empty intersection of previously listed tree entries
6437         // and tree entries using current V?
6438         set_intersect(VToTEs, Set);
6439         if (!VToTEs.empty()) {
6440           // Yes, write the new subset and continue analysis for the next
6441           // scalar.
6442           Set.swap(VToTEs);
6443           break;
6444         }
6445         VToTEs = SavedVToTEs;
6446         ++Idx;
6447       }
6448       // No non-empty intersection found - need to add a second set of possible
6449       // source vectors.
6450       if (Idx == UsedTEs.size()) {
6451         // If the number of input vectors is greater than 2 - not a permutation,
6452         // fallback to the regular gather.
6453         if (UsedTEs.size() == 2)
6454           return None;
6455         UsedTEs.push_back(SavedVToTEs);
6456         Idx = UsedTEs.size() - 1;
6457       }
6458       UsedValuesEntry.try_emplace(V, Idx);
6459     }
6460   }
6461 
6462   unsigned VF = 0;
6463   if (UsedTEs.size() == 1) {
6464     // Try to find the perfect match in another gather node at first.
6465     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6466       return EntryPtr->isSame(TE->Scalars);
6467     });
6468     if (It != UsedTEs.front().end()) {
6469       Entries.push_back(*It);
6470       std::iota(Mask.begin(), Mask.end(), 0);
6471       return TargetTransformInfo::SK_PermuteSingleSrc;
6472     }
6473     // No perfect match, just shuffle, so choose the first tree node.
6474     Entries.push_back(*UsedTEs.front().begin());
6475   } else {
6476     // Try to find nodes with the same vector factor.
6477     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6478     DenseMap<int, const TreeEntry *> VFToTE;
6479     for (const TreeEntry *TE : UsedTEs.front())
6480       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6481     for (const TreeEntry *TE : UsedTEs.back()) {
6482       auto It = VFToTE.find(TE->getVectorFactor());
6483       if (It != VFToTE.end()) {
6484         VF = It->first;
6485         Entries.push_back(It->second);
6486         Entries.push_back(TE);
6487         break;
6488       }
6489     }
6490     // No 2 source vectors with the same vector factor - give up and do regular
6491     // gather.
6492     if (Entries.empty())
6493       return None;
6494   }
6495 
6496   // Build a shuffle mask for better cost estimation and vector emission.
6497   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6498     Value *V = TE->Scalars[I];
6499     if (isa<UndefValue>(V))
6500       continue;
6501     unsigned Idx = UsedValuesEntry.lookup(V);
6502     const TreeEntry *VTE = Entries[Idx];
6503     int FoundLane = VTE->findLaneForValue(V);
6504     Mask[I] = Idx * VF + FoundLane;
6505     // Extra check required by isSingleSourceMaskImpl function (called by
6506     // ShuffleVectorInst::isSingleSourceMask).
6507     if (Mask[I] >= 2 * E)
6508       return None;
6509   }
6510   switch (Entries.size()) {
6511   case 1:
6512     return TargetTransformInfo::SK_PermuteSingleSrc;
6513   case 2:
6514     return TargetTransformInfo::SK_PermuteTwoSrc;
6515   default:
6516     break;
6517   }
6518   return None;
6519 }
6520 
6521 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6522                                        const APInt &ShuffledIndices,
6523                                        bool NeedToShuffle) const {
6524   InstructionCost Cost =
6525       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6526                                     /*Extract*/ false);
6527   if (NeedToShuffle)
6528     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6529   return Cost;
6530 }
6531 
6532 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6533   // Find the type of the operands in VL.
6534   Type *ScalarTy = VL[0]->getType();
6535   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6536     ScalarTy = SI->getValueOperand()->getType();
6537   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6538   bool DuplicateNonConst = false;
6539   // Find the cost of inserting/extracting values from the vector.
6540   // Check if the same elements are inserted several times and count them as
6541   // shuffle candidates.
6542   APInt ShuffledElements = APInt::getZero(VL.size());
6543   DenseSet<Value *> UniqueElements;
6544   // Iterate in reverse order to consider insert elements with the high cost.
6545   for (unsigned I = VL.size(); I > 0; --I) {
6546     unsigned Idx = I - 1;
6547     // No need to shuffle duplicates for constants.
6548     if (isConstant(VL[Idx])) {
6549       ShuffledElements.setBit(Idx);
6550       continue;
6551     }
6552     if (!UniqueElements.insert(VL[Idx]).second) {
6553       DuplicateNonConst = true;
6554       ShuffledElements.setBit(Idx);
6555     }
6556   }
6557   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6558 }
6559 
6560 // Perform operand reordering on the instructions in VL and return the reordered
6561 // operands in Left and Right.
6562 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6563                                              SmallVectorImpl<Value *> &Left,
6564                                              SmallVectorImpl<Value *> &Right,
6565                                              const DataLayout &DL,
6566                                              ScalarEvolution &SE,
6567                                              const BoUpSLP &R) {
6568   if (VL.empty())
6569     return;
6570   VLOperands Ops(VL, DL, SE, R);
6571   // Reorder the operands in place.
6572   Ops.reorder();
6573   Left = Ops.getVL(0);
6574   Right = Ops.getVL(1);
6575 }
6576 
6577 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6578   // Get the basic block this bundle is in. All instructions in the bundle
6579   // should be in this block.
6580   auto *Front = E->getMainOp();
6581   auto *BB = Front->getParent();
6582   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6583     auto *I = cast<Instruction>(V);
6584     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6585   }));
6586 
6587   auto &&FindLastInst = [E, Front]() {
6588     Instruction *LastInst = Front;
6589     for (Value *V : E->Scalars) {
6590       auto *I = dyn_cast<Instruction>(V);
6591       if (!I)
6592         continue;
6593       if (LastInst->comesBefore(I))
6594         LastInst = I;
6595     }
6596     return LastInst;
6597   };
6598 
6599   auto &&FindFirstInst = [E, Front]() {
6600     Instruction *FirstInst = Front;
6601     for (Value *V : E->Scalars) {
6602       auto *I = dyn_cast<Instruction>(V);
6603       if (!I)
6604         continue;
6605       if (I->comesBefore(FirstInst))
6606         FirstInst = I;
6607     }
6608     return FirstInst;
6609   };
6610 
6611   // Set the insert point to the beginning of the basic block if the entry
6612   // should not be scheduled.
6613   if (E->State != TreeEntry::NeedToGather &&
6614       doesNotNeedToSchedule(E->Scalars)) {
6615     BasicBlock::iterator InsertPt;
6616     if (all_of(E->Scalars, isUsedOutsideBlock))
6617       InsertPt = FindLastInst()->getIterator();
6618     else
6619       InsertPt = FindFirstInst()->getIterator();
6620     Builder.SetInsertPoint(BB, InsertPt);
6621     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6622     return;
6623   }
6624 
6625   // The last instruction in the bundle in program order.
6626   Instruction *LastInst = nullptr;
6627 
6628   // Find the last instruction. The common case should be that BB has been
6629   // scheduled, and the last instruction is VL.back(). So we start with
6630   // VL.back() and iterate over schedule data until we reach the end of the
6631   // bundle. The end of the bundle is marked by null ScheduleData.
6632   if (BlocksSchedules.count(BB)) {
6633     Value *V = E->isOneOf(E->Scalars.back());
6634     if (doesNotNeedToBeScheduled(V))
6635       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6636     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6637     if (Bundle && Bundle->isPartOfBundle())
6638       for (; Bundle; Bundle = Bundle->NextInBundle)
6639         if (Bundle->OpValue == Bundle->Inst)
6640           LastInst = Bundle->Inst;
6641   }
6642 
6643   // LastInst can still be null at this point if there's either not an entry
6644   // for BB in BlocksSchedules or there's no ScheduleData available for
6645   // VL.back(). This can be the case if buildTree_rec aborts for various
6646   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6647   // size is reached, etc.). ScheduleData is initialized in the scheduling
6648   // "dry-run".
6649   //
6650   // If this happens, we can still find the last instruction by brute force. We
6651   // iterate forwards from Front (inclusive) until we either see all
6652   // instructions in the bundle or reach the end of the block. If Front is the
6653   // last instruction in program order, LastInst will be set to Front, and we
6654   // will visit all the remaining instructions in the block.
6655   //
6656   // One of the reasons we exit early from buildTree_rec is to place an upper
6657   // bound on compile-time. Thus, taking an additional compile-time hit here is
6658   // not ideal. However, this should be exceedingly rare since it requires that
6659   // we both exit early from buildTree_rec and that the bundle be out-of-order
6660   // (causing us to iterate all the way to the end of the block).
6661   if (!LastInst)
6662     LastInst = FindLastInst();
6663   assert(LastInst && "Failed to find last instruction in bundle");
6664 
6665   // Set the insertion point after the last instruction in the bundle. Set the
6666   // debug location to Front.
6667   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6668   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6669 }
6670 
6671 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6672   // List of instructions/lanes from current block and/or the blocks which are
6673   // part of the current loop. These instructions will be inserted at the end to
6674   // make it possible to optimize loops and hoist invariant instructions out of
6675   // the loops body with better chances for success.
6676   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6677   SmallSet<int, 4> PostponedIndices;
6678   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6679   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6680     SmallPtrSet<BasicBlock *, 4> Visited;
6681     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6682       InsertBB = InsertBB->getSinglePredecessor();
6683     return InsertBB && InsertBB == InstBB;
6684   };
6685   for (int I = 0, E = VL.size(); I < E; ++I) {
6686     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6687       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6688            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6689           PostponedIndices.insert(I).second)
6690         PostponedInsts.emplace_back(Inst, I);
6691   }
6692 
6693   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6694     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6695     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6696     if (!InsElt)
6697       return Vec;
6698     GatherShuffleSeq.insert(InsElt);
6699     CSEBlocks.insert(InsElt->getParent());
6700     // Add to our 'need-to-extract' list.
6701     if (TreeEntry *Entry = getTreeEntry(V)) {
6702       // Find which lane we need to extract.
6703       unsigned FoundLane = Entry->findLaneForValue(V);
6704       ExternalUses.emplace_back(V, InsElt, FoundLane);
6705     }
6706     return Vec;
6707   };
6708   Value *Val0 =
6709       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6710   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6711   Value *Vec = PoisonValue::get(VecTy);
6712   SmallVector<int> NonConsts;
6713   // Insert constant values at first.
6714   for (int I = 0, E = VL.size(); I < E; ++I) {
6715     if (PostponedIndices.contains(I))
6716       continue;
6717     if (!isConstant(VL[I])) {
6718       NonConsts.push_back(I);
6719       continue;
6720     }
6721     Vec = CreateInsertElement(Vec, VL[I], I);
6722   }
6723   // Insert non-constant values.
6724   for (int I : NonConsts)
6725     Vec = CreateInsertElement(Vec, VL[I], I);
6726   // Append instructions, which are/may be part of the loop, in the end to make
6727   // it possible to hoist non-loop-based instructions.
6728   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6729     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6730 
6731   return Vec;
6732 }
6733 
6734 namespace {
6735 /// Merges shuffle masks and emits final shuffle instruction, if required.
6736 class ShuffleInstructionBuilder {
6737   IRBuilderBase &Builder;
6738   const unsigned VF = 0;
6739   bool IsFinalized = false;
6740   SmallVector<int, 4> Mask;
6741   /// Holds all of the instructions that we gathered.
6742   SetVector<Instruction *> &GatherShuffleSeq;
6743   /// A list of blocks that we are going to CSE.
6744   SetVector<BasicBlock *> &CSEBlocks;
6745 
6746 public:
6747   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6748                             SetVector<Instruction *> &GatherShuffleSeq,
6749                             SetVector<BasicBlock *> &CSEBlocks)
6750       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6751         CSEBlocks(CSEBlocks) {}
6752 
6753   /// Adds a mask, inverting it before applying.
6754   void addInversedMask(ArrayRef<unsigned> SubMask) {
6755     if (SubMask.empty())
6756       return;
6757     SmallVector<int, 4> NewMask;
6758     inversePermutation(SubMask, NewMask);
6759     addMask(NewMask);
6760   }
6761 
6762   /// Functions adds masks, merging them into  single one.
6763   void addMask(ArrayRef<unsigned> SubMask) {
6764     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6765     addMask(NewMask);
6766   }
6767 
6768   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6769 
6770   Value *finalize(Value *V) {
6771     IsFinalized = true;
6772     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6773     if (VF == ValueVF && Mask.empty())
6774       return V;
6775     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6776     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6777     addMask(NormalizedMask);
6778 
6779     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6780       return V;
6781     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6782     if (auto *I = dyn_cast<Instruction>(Vec)) {
6783       GatherShuffleSeq.insert(I);
6784       CSEBlocks.insert(I->getParent());
6785     }
6786     return Vec;
6787   }
6788 
6789   ~ShuffleInstructionBuilder() {
6790     assert((IsFinalized || Mask.empty()) &&
6791            "Shuffle construction must be finalized.");
6792   }
6793 };
6794 } // namespace
6795 
6796 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6797   const unsigned VF = VL.size();
6798   InstructionsState S = getSameOpcode(VL);
6799   if (S.getOpcode()) {
6800     if (TreeEntry *E = getTreeEntry(S.OpValue))
6801       if (E->isSame(VL)) {
6802         Value *V = vectorizeTree(E);
6803         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6804           if (!E->ReuseShuffleIndices.empty()) {
6805             // Reshuffle to get only unique values.
6806             // If some of the scalars are duplicated in the vectorization tree
6807             // entry, we do not vectorize them but instead generate a mask for
6808             // the reuses. But if there are several users of the same entry,
6809             // they may have different vectorization factors. This is especially
6810             // important for PHI nodes. In this case, we need to adapt the
6811             // resulting instruction for the user vectorization factor and have
6812             // to reshuffle it again to take only unique elements of the vector.
6813             // Without this code the function incorrectly returns reduced vector
6814             // instruction with the same elements, not with the unique ones.
6815 
6816             // block:
6817             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6818             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6819             // ... (use %2)
6820             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6821             // br %block
6822             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6823             SmallSet<int, 4> UsedIdxs;
6824             int Pos = 0;
6825             int Sz = VL.size();
6826             for (int Idx : E->ReuseShuffleIndices) {
6827               if (Idx != Sz && Idx != UndefMaskElem &&
6828                   UsedIdxs.insert(Idx).second)
6829                 UniqueIdxs[Idx] = Pos;
6830               ++Pos;
6831             }
6832             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6833                                             "less than original vector size.");
6834             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6835             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6836           } else {
6837             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6838                    "Expected vectorization factor less "
6839                    "than original vector size.");
6840             SmallVector<int> UniformMask(VF, 0);
6841             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6842             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6843           }
6844           if (auto *I = dyn_cast<Instruction>(V)) {
6845             GatherShuffleSeq.insert(I);
6846             CSEBlocks.insert(I->getParent());
6847           }
6848         }
6849         return V;
6850       }
6851   }
6852 
6853   // Can't vectorize this, so simply build a new vector with each lane
6854   // corresponding to the requested value.
6855   return createBuildVector(VL);
6856 }
6857 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6858   unsigned VF = VL.size();
6859   // Exploit possible reuse of values across lanes.
6860   SmallVector<int> ReuseShuffleIndicies;
6861   SmallVector<Value *> UniqueValues;
6862   if (VL.size() > 2) {
6863     DenseMap<Value *, unsigned> UniquePositions;
6864     unsigned NumValues =
6865         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6866                                     return !isa<UndefValue>(V);
6867                                   }).base());
6868     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6869     int UniqueVals = 0;
6870     for (Value *V : VL.drop_back(VL.size() - VF)) {
6871       if (isa<UndefValue>(V)) {
6872         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6873         continue;
6874       }
6875       if (isConstant(V)) {
6876         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6877         UniqueValues.emplace_back(V);
6878         continue;
6879       }
6880       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6881       ReuseShuffleIndicies.emplace_back(Res.first->second);
6882       if (Res.second) {
6883         UniqueValues.emplace_back(V);
6884         ++UniqueVals;
6885       }
6886     }
6887     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6888       // Emit pure splat vector.
6889       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6890                                   UndefMaskElem);
6891     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6892       ReuseShuffleIndicies.clear();
6893       UniqueValues.clear();
6894       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6895     }
6896     UniqueValues.append(VF - UniqueValues.size(),
6897                         PoisonValue::get(VL[0]->getType()));
6898     VL = UniqueValues;
6899   }
6900 
6901   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6902                                            CSEBlocks);
6903   Value *Vec = gather(VL);
6904   if (!ReuseShuffleIndicies.empty()) {
6905     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6906     Vec = ShuffleBuilder.finalize(Vec);
6907   }
6908   return Vec;
6909 }
6910 
6911 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6912   IRBuilder<>::InsertPointGuard Guard(Builder);
6913 
6914   if (E->VectorizedValue) {
6915     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6916     return E->VectorizedValue;
6917   }
6918 
6919   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6920   unsigned VF = E->getVectorFactor();
6921   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6922                                            CSEBlocks);
6923   if (E->State == TreeEntry::NeedToGather) {
6924     if (E->getMainOp())
6925       setInsertPointAfterBundle(E);
6926     Value *Vec;
6927     SmallVector<int> Mask;
6928     SmallVector<const TreeEntry *> Entries;
6929     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6930         isGatherShuffledEntry(E, Mask, Entries);
6931     if (Shuffle.hasValue()) {
6932       assert((Entries.size() == 1 || Entries.size() == 2) &&
6933              "Expected shuffle of 1 or 2 entries.");
6934       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6935                                         Entries.back()->VectorizedValue, Mask);
6936       if (auto *I = dyn_cast<Instruction>(Vec)) {
6937         GatherShuffleSeq.insert(I);
6938         CSEBlocks.insert(I->getParent());
6939       }
6940     } else {
6941       Vec = gather(E->Scalars);
6942     }
6943     if (NeedToShuffleReuses) {
6944       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6945       Vec = ShuffleBuilder.finalize(Vec);
6946     }
6947     E->VectorizedValue = Vec;
6948     return Vec;
6949   }
6950 
6951   assert((E->State == TreeEntry::Vectorize ||
6952           E->State == TreeEntry::ScatterVectorize) &&
6953          "Unhandled state");
6954   unsigned ShuffleOrOp =
6955       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6956   Instruction *VL0 = E->getMainOp();
6957   Type *ScalarTy = VL0->getType();
6958   if (auto *Store = dyn_cast<StoreInst>(VL0))
6959     ScalarTy = Store->getValueOperand()->getType();
6960   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6961     ScalarTy = IE->getOperand(1)->getType();
6962   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6963   switch (ShuffleOrOp) {
6964     case Instruction::PHI: {
6965       assert(
6966           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6967           "PHI reordering is free.");
6968       auto *PH = cast<PHINode>(VL0);
6969       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6970       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6971       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6972       Value *V = NewPhi;
6973 
6974       // Adjust insertion point once all PHI's have been generated.
6975       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6976       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6977 
6978       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6979       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6980       V = ShuffleBuilder.finalize(V);
6981 
6982       E->VectorizedValue = V;
6983 
6984       // PHINodes may have multiple entries from the same block. We want to
6985       // visit every block once.
6986       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6987 
6988       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6989         ValueList Operands;
6990         BasicBlock *IBB = PH->getIncomingBlock(i);
6991 
6992         if (!VisitedBBs.insert(IBB).second) {
6993           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6994           continue;
6995         }
6996 
6997         Builder.SetInsertPoint(IBB->getTerminator());
6998         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6999         Value *Vec = vectorizeTree(E->getOperand(i));
7000         NewPhi->addIncoming(Vec, IBB);
7001       }
7002 
7003       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7004              "Invalid number of incoming values");
7005       return V;
7006     }
7007 
7008     case Instruction::ExtractElement: {
7009       Value *V = E->getSingleOperand(0);
7010       Builder.SetInsertPoint(VL0);
7011       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7012       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7013       V = ShuffleBuilder.finalize(V);
7014       E->VectorizedValue = V;
7015       return V;
7016     }
7017     case Instruction::ExtractValue: {
7018       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7019       Builder.SetInsertPoint(LI);
7020       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7021       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7022       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7023       Value *NewV = propagateMetadata(V, E->Scalars);
7024       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7025       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7026       NewV = ShuffleBuilder.finalize(NewV);
7027       E->VectorizedValue = NewV;
7028       return NewV;
7029     }
7030     case Instruction::InsertElement: {
7031       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7032       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7033       Value *V = vectorizeTree(E->getOperand(1));
7034 
7035       // Create InsertVector shuffle if necessary
7036       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7037         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7038       }));
7039       const unsigned NumElts =
7040           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7041       const unsigned NumScalars = E->Scalars.size();
7042 
7043       unsigned Offset = *getInsertIndex(VL0);
7044       assert(Offset < NumElts && "Failed to find vector index offset");
7045 
7046       // Create shuffle to resize vector
7047       SmallVector<int> Mask;
7048       if (!E->ReorderIndices.empty()) {
7049         inversePermutation(E->ReorderIndices, Mask);
7050         Mask.append(NumElts - NumScalars, UndefMaskElem);
7051       } else {
7052         Mask.assign(NumElts, UndefMaskElem);
7053         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7054       }
7055       // Create InsertVector shuffle if necessary
7056       bool IsIdentity = true;
7057       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7058       Mask.swap(PrevMask);
7059       for (unsigned I = 0; I < NumScalars; ++I) {
7060         Value *Scalar = E->Scalars[PrevMask[I]];
7061         unsigned InsertIdx = *getInsertIndex(Scalar);
7062         IsIdentity &= InsertIdx - Offset == I;
7063         Mask[InsertIdx - Offset] = I;
7064       }
7065       if (!IsIdentity || NumElts != NumScalars) {
7066         V = Builder.CreateShuffleVector(V, Mask);
7067         if (auto *I = dyn_cast<Instruction>(V)) {
7068           GatherShuffleSeq.insert(I);
7069           CSEBlocks.insert(I->getParent());
7070         }
7071       }
7072 
7073       if ((!IsIdentity || Offset != 0 ||
7074            !isUndefVector(FirstInsert->getOperand(0))) &&
7075           NumElts != NumScalars) {
7076         SmallVector<int> InsertMask(NumElts);
7077         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7078         for (unsigned I = 0; I < NumElts; I++) {
7079           if (Mask[I] != UndefMaskElem)
7080             InsertMask[Offset + I] = NumElts + I;
7081         }
7082 
7083         V = Builder.CreateShuffleVector(
7084             FirstInsert->getOperand(0), V, InsertMask,
7085             cast<Instruction>(E->Scalars.back())->getName());
7086         if (auto *I = dyn_cast<Instruction>(V)) {
7087           GatherShuffleSeq.insert(I);
7088           CSEBlocks.insert(I->getParent());
7089         }
7090       }
7091 
7092       ++NumVectorInstructions;
7093       E->VectorizedValue = V;
7094       return V;
7095     }
7096     case Instruction::ZExt:
7097     case Instruction::SExt:
7098     case Instruction::FPToUI:
7099     case Instruction::FPToSI:
7100     case Instruction::FPExt:
7101     case Instruction::PtrToInt:
7102     case Instruction::IntToPtr:
7103     case Instruction::SIToFP:
7104     case Instruction::UIToFP:
7105     case Instruction::Trunc:
7106     case Instruction::FPTrunc:
7107     case Instruction::BitCast: {
7108       setInsertPointAfterBundle(E);
7109 
7110       Value *InVec = vectorizeTree(E->getOperand(0));
7111 
7112       if (E->VectorizedValue) {
7113         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7114         return E->VectorizedValue;
7115       }
7116 
7117       auto *CI = cast<CastInst>(VL0);
7118       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7119       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7120       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7121       V = ShuffleBuilder.finalize(V);
7122 
7123       E->VectorizedValue = V;
7124       ++NumVectorInstructions;
7125       return V;
7126     }
7127     case Instruction::FCmp:
7128     case Instruction::ICmp: {
7129       setInsertPointAfterBundle(E);
7130 
7131       Value *L = vectorizeTree(E->getOperand(0));
7132       Value *R = vectorizeTree(E->getOperand(1));
7133 
7134       if (E->VectorizedValue) {
7135         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7136         return E->VectorizedValue;
7137       }
7138 
7139       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7140       Value *V = Builder.CreateCmp(P0, L, R);
7141       propagateIRFlags(V, E->Scalars, VL0);
7142       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7143       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7144       V = ShuffleBuilder.finalize(V);
7145 
7146       E->VectorizedValue = V;
7147       ++NumVectorInstructions;
7148       return V;
7149     }
7150     case Instruction::Select: {
7151       setInsertPointAfterBundle(E);
7152 
7153       Value *Cond = vectorizeTree(E->getOperand(0));
7154       Value *True = vectorizeTree(E->getOperand(1));
7155       Value *False = vectorizeTree(E->getOperand(2));
7156 
7157       if (E->VectorizedValue) {
7158         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7159         return E->VectorizedValue;
7160       }
7161 
7162       Value *V = Builder.CreateSelect(Cond, True, False);
7163       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7164       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7165       V = ShuffleBuilder.finalize(V);
7166 
7167       E->VectorizedValue = V;
7168       ++NumVectorInstructions;
7169       return V;
7170     }
7171     case Instruction::FNeg: {
7172       setInsertPointAfterBundle(E);
7173 
7174       Value *Op = vectorizeTree(E->getOperand(0));
7175 
7176       if (E->VectorizedValue) {
7177         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7178         return E->VectorizedValue;
7179       }
7180 
7181       Value *V = Builder.CreateUnOp(
7182           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7183       propagateIRFlags(V, E->Scalars, VL0);
7184       if (auto *I = dyn_cast<Instruction>(V))
7185         V = propagateMetadata(I, E->Scalars);
7186 
7187       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7188       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7189       V = ShuffleBuilder.finalize(V);
7190 
7191       E->VectorizedValue = V;
7192       ++NumVectorInstructions;
7193 
7194       return V;
7195     }
7196     case Instruction::Add:
7197     case Instruction::FAdd:
7198     case Instruction::Sub:
7199     case Instruction::FSub:
7200     case Instruction::Mul:
7201     case Instruction::FMul:
7202     case Instruction::UDiv:
7203     case Instruction::SDiv:
7204     case Instruction::FDiv:
7205     case Instruction::URem:
7206     case Instruction::SRem:
7207     case Instruction::FRem:
7208     case Instruction::Shl:
7209     case Instruction::LShr:
7210     case Instruction::AShr:
7211     case Instruction::And:
7212     case Instruction::Or:
7213     case Instruction::Xor: {
7214       setInsertPointAfterBundle(E);
7215 
7216       Value *LHS = vectorizeTree(E->getOperand(0));
7217       Value *RHS = vectorizeTree(E->getOperand(1));
7218 
7219       if (E->VectorizedValue) {
7220         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7221         return E->VectorizedValue;
7222       }
7223 
7224       Value *V = Builder.CreateBinOp(
7225           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7226           RHS);
7227       propagateIRFlags(V, E->Scalars, VL0);
7228       if (auto *I = dyn_cast<Instruction>(V))
7229         V = propagateMetadata(I, E->Scalars);
7230 
7231       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7232       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7233       V = ShuffleBuilder.finalize(V);
7234 
7235       E->VectorizedValue = V;
7236       ++NumVectorInstructions;
7237 
7238       return V;
7239     }
7240     case Instruction::Load: {
7241       // Loads are inserted at the head of the tree because we don't want to
7242       // sink them all the way down past store instructions.
7243       setInsertPointAfterBundle(E);
7244 
7245       LoadInst *LI = cast<LoadInst>(VL0);
7246       Instruction *NewLI;
7247       unsigned AS = LI->getPointerAddressSpace();
7248       Value *PO = LI->getPointerOperand();
7249       if (E->State == TreeEntry::Vectorize) {
7250         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7251         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7252 
7253         // The pointer operand uses an in-tree scalar so we add the new BitCast
7254         // or LoadInst to ExternalUses list to make sure that an extract will
7255         // be generated in the future.
7256         if (TreeEntry *Entry = getTreeEntry(PO)) {
7257           // Find which lane we need to extract.
7258           unsigned FoundLane = Entry->findLaneForValue(PO);
7259           ExternalUses.emplace_back(
7260               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7261         }
7262       } else {
7263         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7264         Value *VecPtr = vectorizeTree(E->getOperand(0));
7265         // Use the minimum alignment of the gathered loads.
7266         Align CommonAlignment = LI->getAlign();
7267         for (Value *V : E->Scalars)
7268           CommonAlignment =
7269               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7270         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7271       }
7272       Value *V = propagateMetadata(NewLI, E->Scalars);
7273 
7274       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7275       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7276       V = ShuffleBuilder.finalize(V);
7277       E->VectorizedValue = V;
7278       ++NumVectorInstructions;
7279       return V;
7280     }
7281     case Instruction::Store: {
7282       auto *SI = cast<StoreInst>(VL0);
7283       unsigned AS = SI->getPointerAddressSpace();
7284 
7285       setInsertPointAfterBundle(E);
7286 
7287       Value *VecValue = vectorizeTree(E->getOperand(0));
7288       ShuffleBuilder.addMask(E->ReorderIndices);
7289       VecValue = ShuffleBuilder.finalize(VecValue);
7290 
7291       Value *ScalarPtr = SI->getPointerOperand();
7292       Value *VecPtr = Builder.CreateBitCast(
7293           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7294       StoreInst *ST =
7295           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7296 
7297       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7298       // StoreInst to ExternalUses to make sure that an extract will be
7299       // generated in the future.
7300       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7301         // Find which lane we need to extract.
7302         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7303         ExternalUses.push_back(ExternalUser(
7304             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7305             FoundLane));
7306       }
7307 
7308       Value *V = propagateMetadata(ST, E->Scalars);
7309 
7310       E->VectorizedValue = V;
7311       ++NumVectorInstructions;
7312       return V;
7313     }
7314     case Instruction::GetElementPtr: {
7315       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7316       setInsertPointAfterBundle(E);
7317 
7318       Value *Op0 = vectorizeTree(E->getOperand(0));
7319 
7320       SmallVector<Value *> OpVecs;
7321       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7322         Value *OpVec = vectorizeTree(E->getOperand(J));
7323         OpVecs.push_back(OpVec);
7324       }
7325 
7326       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7327       if (Instruction *I = dyn_cast<Instruction>(V))
7328         V = propagateMetadata(I, E->Scalars);
7329 
7330       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7331       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7332       V = ShuffleBuilder.finalize(V);
7333 
7334       E->VectorizedValue = V;
7335       ++NumVectorInstructions;
7336 
7337       return V;
7338     }
7339     case Instruction::Call: {
7340       CallInst *CI = cast<CallInst>(VL0);
7341       setInsertPointAfterBundle(E);
7342 
7343       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7344       if (Function *FI = CI->getCalledFunction())
7345         IID = FI->getIntrinsicID();
7346 
7347       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7348 
7349       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7350       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7351                           VecCallCosts.first <= VecCallCosts.second;
7352 
7353       Value *ScalarArg = nullptr;
7354       std::vector<Value *> OpVecs;
7355       SmallVector<Type *, 2> TysForDecl =
7356           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7357       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7358         ValueList OpVL;
7359         // Some intrinsics have scalar arguments. This argument should not be
7360         // vectorized.
7361         if (UseIntrinsic && hasVectorIntrinsicScalarOpd(IID, j)) {
7362           CallInst *CEI = cast<CallInst>(VL0);
7363           ScalarArg = CEI->getArgOperand(j);
7364           OpVecs.push_back(CEI->getArgOperand(j));
7365           if (hasVectorIntrinsicOverloadedScalarOpd(IID, j))
7366             TysForDecl.push_back(ScalarArg->getType());
7367           continue;
7368         }
7369 
7370         Value *OpVec = vectorizeTree(E->getOperand(j));
7371         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7372         OpVecs.push_back(OpVec);
7373       }
7374 
7375       Function *CF;
7376       if (!UseIntrinsic) {
7377         VFShape Shape =
7378             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7379                                   VecTy->getNumElements())),
7380                          false /*HasGlobalPred*/);
7381         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7382       } else {
7383         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7384       }
7385 
7386       SmallVector<OperandBundleDef, 1> OpBundles;
7387       CI->getOperandBundlesAsDefs(OpBundles);
7388       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7389 
7390       // The scalar argument uses an in-tree scalar so we add the new vectorized
7391       // call to ExternalUses list to make sure that an extract will be
7392       // generated in the future.
7393       if (ScalarArg) {
7394         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7395           // Find which lane we need to extract.
7396           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7397           ExternalUses.push_back(
7398               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7399         }
7400       }
7401 
7402       propagateIRFlags(V, E->Scalars, VL0);
7403       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7404       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7405       V = ShuffleBuilder.finalize(V);
7406 
7407       E->VectorizedValue = V;
7408       ++NumVectorInstructions;
7409       return V;
7410     }
7411     case Instruction::ShuffleVector: {
7412       assert(E->isAltShuffle() &&
7413              ((Instruction::isBinaryOp(E->getOpcode()) &&
7414                Instruction::isBinaryOp(E->getAltOpcode())) ||
7415               (Instruction::isCast(E->getOpcode()) &&
7416                Instruction::isCast(E->getAltOpcode())) ||
7417               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7418              "Invalid Shuffle Vector Operand");
7419 
7420       Value *LHS = nullptr, *RHS = nullptr;
7421       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7422         setInsertPointAfterBundle(E);
7423         LHS = vectorizeTree(E->getOperand(0));
7424         RHS = vectorizeTree(E->getOperand(1));
7425       } else {
7426         setInsertPointAfterBundle(E);
7427         LHS = vectorizeTree(E->getOperand(0));
7428       }
7429 
7430       if (E->VectorizedValue) {
7431         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7432         return E->VectorizedValue;
7433       }
7434 
7435       Value *V0, *V1;
7436       if (Instruction::isBinaryOp(E->getOpcode())) {
7437         V0 = Builder.CreateBinOp(
7438             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7439         V1 = Builder.CreateBinOp(
7440             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7441       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7442         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7443         auto *AltCI = cast<CmpInst>(E->getAltOp());
7444         CmpInst::Predicate AltPred = AltCI->getPredicate();
7445         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7446       } else {
7447         V0 = Builder.CreateCast(
7448             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7449         V1 = Builder.CreateCast(
7450             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7451       }
7452       // Add V0 and V1 to later analysis to try to find and remove matching
7453       // instruction, if any.
7454       for (Value *V : {V0, V1}) {
7455         if (auto *I = dyn_cast<Instruction>(V)) {
7456           GatherShuffleSeq.insert(I);
7457           CSEBlocks.insert(I->getParent());
7458         }
7459       }
7460 
7461       // Create shuffle to take alternate operations from the vector.
7462       // Also, gather up main and alt scalar ops to propagate IR flags to
7463       // each vector operation.
7464       ValueList OpScalars, AltScalars;
7465       SmallVector<int> Mask;
7466       buildShuffleEntryMask(
7467           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7468           [E](Instruction *I) {
7469             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7470             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7471           },
7472           Mask, &OpScalars, &AltScalars);
7473 
7474       propagateIRFlags(V0, OpScalars);
7475       propagateIRFlags(V1, AltScalars);
7476 
7477       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7478       if (auto *I = dyn_cast<Instruction>(V)) {
7479         V = propagateMetadata(I, E->Scalars);
7480         GatherShuffleSeq.insert(I);
7481         CSEBlocks.insert(I->getParent());
7482       }
7483       V = ShuffleBuilder.finalize(V);
7484 
7485       E->VectorizedValue = V;
7486       ++NumVectorInstructions;
7487 
7488       return V;
7489     }
7490     default:
7491     llvm_unreachable("unknown inst");
7492   }
7493   return nullptr;
7494 }
7495 
7496 Value *BoUpSLP::vectorizeTree() {
7497   ExtraValueToDebugLocsMap ExternallyUsedValues;
7498   return vectorizeTree(ExternallyUsedValues);
7499 }
7500 
7501 Value *
7502 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7503   // All blocks must be scheduled before any instructions are inserted.
7504   for (auto &BSIter : BlocksSchedules) {
7505     scheduleBlock(BSIter.second.get());
7506   }
7507 
7508   Builder.SetInsertPoint(&F->getEntryBlock().front());
7509   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7510 
7511   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7512   // vectorized root. InstCombine will then rewrite the entire expression. We
7513   // sign extend the extracted values below.
7514   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7515   if (MinBWs.count(ScalarRoot)) {
7516     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7517       // If current instr is a phi and not the last phi, insert it after the
7518       // last phi node.
7519       if (isa<PHINode>(I))
7520         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7521       else
7522         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7523     }
7524     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7525     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7526     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7527     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7528     VectorizableTree[0]->VectorizedValue = Trunc;
7529   }
7530 
7531   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7532                     << " values .\n");
7533 
7534   // Extract all of the elements with the external uses.
7535   for (const auto &ExternalUse : ExternalUses) {
7536     Value *Scalar = ExternalUse.Scalar;
7537     llvm::User *User = ExternalUse.User;
7538 
7539     // Skip users that we already RAUW. This happens when one instruction
7540     // has multiple uses of the same value.
7541     if (User && !is_contained(Scalar->users(), User))
7542       continue;
7543     TreeEntry *E = getTreeEntry(Scalar);
7544     assert(E && "Invalid scalar");
7545     assert(E->State != TreeEntry::NeedToGather &&
7546            "Extracting from a gather list");
7547 
7548     Value *Vec = E->VectorizedValue;
7549     assert(Vec && "Can't find vectorizable value");
7550 
7551     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7552     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7553       if (Scalar->getType() != Vec->getType()) {
7554         Value *Ex;
7555         // "Reuse" the existing extract to improve final codegen.
7556         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7557           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7558                                             ES->getOperand(1));
7559         } else {
7560           Ex = Builder.CreateExtractElement(Vec, Lane);
7561         }
7562         // If necessary, sign-extend or zero-extend ScalarRoot
7563         // to the larger type.
7564         if (!MinBWs.count(ScalarRoot))
7565           return Ex;
7566         if (MinBWs[ScalarRoot].second)
7567           return Builder.CreateSExt(Ex, Scalar->getType());
7568         return Builder.CreateZExt(Ex, Scalar->getType());
7569       }
7570       assert(isa<FixedVectorType>(Scalar->getType()) &&
7571              isa<InsertElementInst>(Scalar) &&
7572              "In-tree scalar of vector type is not insertelement?");
7573       return Vec;
7574     };
7575     // If User == nullptr, the Scalar is used as extra arg. Generate
7576     // ExtractElement instruction and update the record for this scalar in
7577     // ExternallyUsedValues.
7578     if (!User) {
7579       assert(ExternallyUsedValues.count(Scalar) &&
7580              "Scalar with nullptr as an external user must be registered in "
7581              "ExternallyUsedValues map");
7582       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7583         Builder.SetInsertPoint(VecI->getParent(),
7584                                std::next(VecI->getIterator()));
7585       } else {
7586         Builder.SetInsertPoint(&F->getEntryBlock().front());
7587       }
7588       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7589       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7590       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7591       auto It = ExternallyUsedValues.find(Scalar);
7592       assert(It != ExternallyUsedValues.end() &&
7593              "Externally used scalar is not found in ExternallyUsedValues");
7594       NewInstLocs.append(It->second);
7595       ExternallyUsedValues.erase(Scalar);
7596       // Required to update internally referenced instructions.
7597       Scalar->replaceAllUsesWith(NewInst);
7598       continue;
7599     }
7600 
7601     // Generate extracts for out-of-tree users.
7602     // Find the insertion point for the extractelement lane.
7603     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7604       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7605         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7606           if (PH->getIncomingValue(i) == Scalar) {
7607             Instruction *IncomingTerminator =
7608                 PH->getIncomingBlock(i)->getTerminator();
7609             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7610               Builder.SetInsertPoint(VecI->getParent(),
7611                                      std::next(VecI->getIterator()));
7612             } else {
7613               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7614             }
7615             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7616             CSEBlocks.insert(PH->getIncomingBlock(i));
7617             PH->setOperand(i, NewInst);
7618           }
7619         }
7620       } else {
7621         Builder.SetInsertPoint(cast<Instruction>(User));
7622         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7623         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7624         User->replaceUsesOfWith(Scalar, NewInst);
7625       }
7626     } else {
7627       Builder.SetInsertPoint(&F->getEntryBlock().front());
7628       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7629       CSEBlocks.insert(&F->getEntryBlock());
7630       User->replaceUsesOfWith(Scalar, NewInst);
7631     }
7632 
7633     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7634   }
7635 
7636   // For each vectorized value:
7637   for (auto &TEPtr : VectorizableTree) {
7638     TreeEntry *Entry = TEPtr.get();
7639 
7640     // No need to handle users of gathered values.
7641     if (Entry->State == TreeEntry::NeedToGather)
7642       continue;
7643 
7644     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7645 
7646     // For each lane:
7647     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7648       Value *Scalar = Entry->Scalars[Lane];
7649 
7650 #ifndef NDEBUG
7651       Type *Ty = Scalar->getType();
7652       if (!Ty->isVoidTy()) {
7653         for (User *U : Scalar->users()) {
7654           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7655 
7656           // It is legal to delete users in the ignorelist.
7657           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7658                   (isa_and_nonnull<Instruction>(U) &&
7659                    isDeleted(cast<Instruction>(U)))) &&
7660                  "Deleting out-of-tree value");
7661         }
7662       }
7663 #endif
7664       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7665       eraseInstruction(cast<Instruction>(Scalar));
7666     }
7667   }
7668 
7669   Builder.ClearInsertionPoint();
7670   InstrElementSize.clear();
7671 
7672   return VectorizableTree[0]->VectorizedValue;
7673 }
7674 
7675 void BoUpSLP::optimizeGatherSequence() {
7676   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7677                     << " gather sequences instructions.\n");
7678   // LICM InsertElementInst sequences.
7679   for (Instruction *I : GatherShuffleSeq) {
7680     if (isDeleted(I))
7681       continue;
7682 
7683     // Check if this block is inside a loop.
7684     Loop *L = LI->getLoopFor(I->getParent());
7685     if (!L)
7686       continue;
7687 
7688     // Check if it has a preheader.
7689     BasicBlock *PreHeader = L->getLoopPreheader();
7690     if (!PreHeader)
7691       continue;
7692 
7693     // If the vector or the element that we insert into it are
7694     // instructions that are defined in this basic block then we can't
7695     // hoist this instruction.
7696     if (any_of(I->operands(), [L](Value *V) {
7697           auto *OpI = dyn_cast<Instruction>(V);
7698           return OpI && L->contains(OpI);
7699         }))
7700       continue;
7701 
7702     // We can hoist this instruction. Move it to the pre-header.
7703     I->moveBefore(PreHeader->getTerminator());
7704   }
7705 
7706   // Make a list of all reachable blocks in our CSE queue.
7707   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7708   CSEWorkList.reserve(CSEBlocks.size());
7709   for (BasicBlock *BB : CSEBlocks)
7710     if (DomTreeNode *N = DT->getNode(BB)) {
7711       assert(DT->isReachableFromEntry(N));
7712       CSEWorkList.push_back(N);
7713     }
7714 
7715   // Sort blocks by domination. This ensures we visit a block after all blocks
7716   // dominating it are visited.
7717   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7718     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7719            "Different nodes should have different DFS numbers");
7720     return A->getDFSNumIn() < B->getDFSNumIn();
7721   });
7722 
7723   // Less defined shuffles can be replaced by the more defined copies.
7724   // Between two shuffles one is less defined if it has the same vector operands
7725   // and its mask indeces are the same as in the first one or undefs. E.g.
7726   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7727   // poison, <0, 0, 0, 0>.
7728   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7729                                            SmallVectorImpl<int> &NewMask) {
7730     if (I1->getType() != I2->getType())
7731       return false;
7732     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7733     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7734     if (!SI1 || !SI2)
7735       return I1->isIdenticalTo(I2);
7736     if (SI1->isIdenticalTo(SI2))
7737       return true;
7738     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7739       if (SI1->getOperand(I) != SI2->getOperand(I))
7740         return false;
7741     // Check if the second instruction is more defined than the first one.
7742     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7743     ArrayRef<int> SM1 = SI1->getShuffleMask();
7744     // Count trailing undefs in the mask to check the final number of used
7745     // registers.
7746     unsigned LastUndefsCnt = 0;
7747     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7748       if (SM1[I] == UndefMaskElem)
7749         ++LastUndefsCnt;
7750       else
7751         LastUndefsCnt = 0;
7752       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7753           NewMask[I] != SM1[I])
7754         return false;
7755       if (NewMask[I] == UndefMaskElem)
7756         NewMask[I] = SM1[I];
7757     }
7758     // Check if the last undefs actually change the final number of used vector
7759     // registers.
7760     return SM1.size() - LastUndefsCnt > 1 &&
7761            TTI->getNumberOfParts(SI1->getType()) ==
7762                TTI->getNumberOfParts(
7763                    FixedVectorType::get(SI1->getType()->getElementType(),
7764                                         SM1.size() - LastUndefsCnt));
7765   };
7766   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7767   // instructions. TODO: We can further optimize this scan if we split the
7768   // instructions into different buckets based on the insert lane.
7769   SmallVector<Instruction *, 16> Visited;
7770   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7771     assert(*I &&
7772            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7773            "Worklist not sorted properly!");
7774     BasicBlock *BB = (*I)->getBlock();
7775     // For all instructions in blocks containing gather sequences:
7776     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7777       if (isDeleted(&In))
7778         continue;
7779       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7780           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7781         continue;
7782 
7783       // Check if we can replace this instruction with any of the
7784       // visited instructions.
7785       bool Replaced = false;
7786       for (Instruction *&V : Visited) {
7787         SmallVector<int> NewMask;
7788         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7789             DT->dominates(V->getParent(), In.getParent())) {
7790           In.replaceAllUsesWith(V);
7791           eraseInstruction(&In);
7792           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7793             if (!NewMask.empty())
7794               SI->setShuffleMask(NewMask);
7795           Replaced = true;
7796           break;
7797         }
7798         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7799             GatherShuffleSeq.contains(V) &&
7800             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7801             DT->dominates(In.getParent(), V->getParent())) {
7802           In.moveAfter(V);
7803           V->replaceAllUsesWith(&In);
7804           eraseInstruction(V);
7805           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7806             if (!NewMask.empty())
7807               SI->setShuffleMask(NewMask);
7808           V = &In;
7809           Replaced = true;
7810           break;
7811         }
7812       }
7813       if (!Replaced) {
7814         assert(!is_contained(Visited, &In));
7815         Visited.push_back(&In);
7816       }
7817     }
7818   }
7819   CSEBlocks.clear();
7820   GatherShuffleSeq.clear();
7821 }
7822 
7823 BoUpSLP::ScheduleData *
7824 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7825   ScheduleData *Bundle = nullptr;
7826   ScheduleData *PrevInBundle = nullptr;
7827   for (Value *V : VL) {
7828     if (doesNotNeedToBeScheduled(V))
7829       continue;
7830     ScheduleData *BundleMember = getScheduleData(V);
7831     assert(BundleMember &&
7832            "no ScheduleData for bundle member "
7833            "(maybe not in same basic block)");
7834     assert(BundleMember->isSchedulingEntity() &&
7835            "bundle member already part of other bundle");
7836     if (PrevInBundle) {
7837       PrevInBundle->NextInBundle = BundleMember;
7838     } else {
7839       Bundle = BundleMember;
7840     }
7841 
7842     // Group the instructions to a bundle.
7843     BundleMember->FirstInBundle = Bundle;
7844     PrevInBundle = BundleMember;
7845   }
7846   assert(Bundle && "Failed to find schedule bundle");
7847   return Bundle;
7848 }
7849 
7850 // Groups the instructions to a bundle (which is then a single scheduling entity)
7851 // and schedules instructions until the bundle gets ready.
7852 Optional<BoUpSLP::ScheduleData *>
7853 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7854                                             const InstructionsState &S) {
7855   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7856   // instructions.
7857   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7858       doesNotNeedToSchedule(VL))
7859     return nullptr;
7860 
7861   // Initialize the instruction bundle.
7862   Instruction *OldScheduleEnd = ScheduleEnd;
7863   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7864 
7865   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7866                                                          ScheduleData *Bundle) {
7867     // The scheduling region got new instructions at the lower end (or it is a
7868     // new region for the first bundle). This makes it necessary to
7869     // recalculate all dependencies.
7870     // It is seldom that this needs to be done a second time after adding the
7871     // initial bundle to the region.
7872     if (ScheduleEnd != OldScheduleEnd) {
7873       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7874         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7875       ReSchedule = true;
7876     }
7877     if (Bundle) {
7878       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7879                         << " in block " << BB->getName() << "\n");
7880       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7881     }
7882 
7883     if (ReSchedule) {
7884       resetSchedule();
7885       initialFillReadyList(ReadyInsts);
7886     }
7887 
7888     // Now try to schedule the new bundle or (if no bundle) just calculate
7889     // dependencies. As soon as the bundle is "ready" it means that there are no
7890     // cyclic dependencies and we can schedule it. Note that's important that we
7891     // don't "schedule" the bundle yet (see cancelScheduling).
7892     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7893            !ReadyInsts.empty()) {
7894       ScheduleData *Picked = ReadyInsts.pop_back_val();
7895       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7896              "must be ready to schedule");
7897       schedule(Picked, ReadyInsts);
7898     }
7899   };
7900 
7901   // Make sure that the scheduling region contains all
7902   // instructions of the bundle.
7903   for (Value *V : VL) {
7904     if (doesNotNeedToBeScheduled(V))
7905       continue;
7906     if (!extendSchedulingRegion(V, S)) {
7907       // If the scheduling region got new instructions at the lower end (or it
7908       // is a new region for the first bundle). This makes it necessary to
7909       // recalculate all dependencies.
7910       // Otherwise the compiler may crash trying to incorrectly calculate
7911       // dependencies and emit instruction in the wrong order at the actual
7912       // scheduling.
7913       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7914       return None;
7915     }
7916   }
7917 
7918   bool ReSchedule = false;
7919   for (Value *V : VL) {
7920     if (doesNotNeedToBeScheduled(V))
7921       continue;
7922     ScheduleData *BundleMember = getScheduleData(V);
7923     assert(BundleMember &&
7924            "no ScheduleData for bundle member (maybe not in same basic block)");
7925 
7926     // Make sure we don't leave the pieces of the bundle in the ready list when
7927     // whole bundle might not be ready.
7928     ReadyInsts.remove(BundleMember);
7929 
7930     if (!BundleMember->IsScheduled)
7931       continue;
7932     // A bundle member was scheduled as single instruction before and now
7933     // needs to be scheduled as part of the bundle. We just get rid of the
7934     // existing schedule.
7935     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7936                       << " was already scheduled\n");
7937     ReSchedule = true;
7938   }
7939 
7940   auto *Bundle = buildBundle(VL);
7941   TryScheduleBundleImpl(ReSchedule, Bundle);
7942   if (!Bundle->isReady()) {
7943     cancelScheduling(VL, S.OpValue);
7944     return None;
7945   }
7946   return Bundle;
7947 }
7948 
7949 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7950                                                 Value *OpValue) {
7951   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7952       doesNotNeedToSchedule(VL))
7953     return;
7954 
7955   if (doesNotNeedToBeScheduled(OpValue))
7956     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7957   ScheduleData *Bundle = getScheduleData(OpValue);
7958   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7959   assert(!Bundle->IsScheduled &&
7960          "Can't cancel bundle which is already scheduled");
7961   assert(Bundle->isSchedulingEntity() &&
7962          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7963          "tried to unbundle something which is not a bundle");
7964 
7965   // Remove the bundle from the ready list.
7966   if (Bundle->isReady())
7967     ReadyInsts.remove(Bundle);
7968 
7969   // Un-bundle: make single instructions out of the bundle.
7970   ScheduleData *BundleMember = Bundle;
7971   while (BundleMember) {
7972     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7973     BundleMember->FirstInBundle = BundleMember;
7974     ScheduleData *Next = BundleMember->NextInBundle;
7975     BundleMember->NextInBundle = nullptr;
7976     BundleMember->TE = nullptr;
7977     if (BundleMember->unscheduledDepsInBundle() == 0) {
7978       ReadyInsts.insert(BundleMember);
7979     }
7980     BundleMember = Next;
7981   }
7982 }
7983 
7984 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7985   // Allocate a new ScheduleData for the instruction.
7986   if (ChunkPos >= ChunkSize) {
7987     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7988     ChunkPos = 0;
7989   }
7990   return &(ScheduleDataChunks.back()[ChunkPos++]);
7991 }
7992 
7993 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7994                                                       const InstructionsState &S) {
7995   if (getScheduleData(V, isOneOf(S, V)))
7996     return true;
7997   Instruction *I = dyn_cast<Instruction>(V);
7998   assert(I && "bundle member must be an instruction");
7999   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8000          !doesNotNeedToBeScheduled(I) &&
8001          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8002          "be scheduled");
8003   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8004     ScheduleData *ISD = getScheduleData(I);
8005     if (!ISD)
8006       return false;
8007     assert(isInSchedulingRegion(ISD) &&
8008            "ScheduleData not in scheduling region");
8009     ScheduleData *SD = allocateScheduleDataChunks();
8010     SD->Inst = I;
8011     SD->init(SchedulingRegionID, S.OpValue);
8012     ExtraScheduleDataMap[I][S.OpValue] = SD;
8013     return true;
8014   };
8015   if (CheckScheduleForI(I))
8016     return true;
8017   if (!ScheduleStart) {
8018     // It's the first instruction in the new region.
8019     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8020     ScheduleStart = I;
8021     ScheduleEnd = I->getNextNode();
8022     if (isOneOf(S, I) != I)
8023       CheckScheduleForI(I);
8024     assert(ScheduleEnd && "tried to vectorize a terminator?");
8025     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8026     return true;
8027   }
8028   // Search up and down at the same time, because we don't know if the new
8029   // instruction is above or below the existing scheduling region.
8030   BasicBlock::reverse_iterator UpIter =
8031       ++ScheduleStart->getIterator().getReverse();
8032   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8033   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8034   BasicBlock::iterator LowerEnd = BB->end();
8035   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8036          &*DownIter != I) {
8037     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8038       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8039       return false;
8040     }
8041 
8042     ++UpIter;
8043     ++DownIter;
8044   }
8045   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8046     assert(I->getParent() == ScheduleStart->getParent() &&
8047            "Instruction is in wrong basic block.");
8048     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8049     ScheduleStart = I;
8050     if (isOneOf(S, I) != I)
8051       CheckScheduleForI(I);
8052     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8053                       << "\n");
8054     return true;
8055   }
8056   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8057          "Expected to reach top of the basic block or instruction down the "
8058          "lower end.");
8059   assert(I->getParent() == ScheduleEnd->getParent() &&
8060          "Instruction is in wrong basic block.");
8061   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8062                    nullptr);
8063   ScheduleEnd = I->getNextNode();
8064   if (isOneOf(S, I) != I)
8065     CheckScheduleForI(I);
8066   assert(ScheduleEnd && "tried to vectorize a terminator?");
8067   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8068   return true;
8069 }
8070 
8071 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8072                                                 Instruction *ToI,
8073                                                 ScheduleData *PrevLoadStore,
8074                                                 ScheduleData *NextLoadStore) {
8075   ScheduleData *CurrentLoadStore = PrevLoadStore;
8076   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8077     // No need to allocate data for non-schedulable instructions.
8078     if (doesNotNeedToBeScheduled(I))
8079       continue;
8080     ScheduleData *SD = ScheduleDataMap.lookup(I);
8081     if (!SD) {
8082       SD = allocateScheduleDataChunks();
8083       ScheduleDataMap[I] = SD;
8084       SD->Inst = I;
8085     }
8086     assert(!isInSchedulingRegion(SD) &&
8087            "new ScheduleData already in scheduling region");
8088     SD->init(SchedulingRegionID, I);
8089 
8090     if (I->mayReadOrWriteMemory() &&
8091         (!isa<IntrinsicInst>(I) ||
8092          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8093           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8094               Intrinsic::pseudoprobe))) {
8095       // Update the linked list of memory accessing instructions.
8096       if (CurrentLoadStore) {
8097         CurrentLoadStore->NextLoadStore = SD;
8098       } else {
8099         FirstLoadStoreInRegion = SD;
8100       }
8101       CurrentLoadStore = SD;
8102     }
8103 
8104     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8105         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8106       RegionHasStackSave = true;
8107   }
8108   if (NextLoadStore) {
8109     if (CurrentLoadStore)
8110       CurrentLoadStore->NextLoadStore = NextLoadStore;
8111   } else {
8112     LastLoadStoreInRegion = CurrentLoadStore;
8113   }
8114 }
8115 
8116 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8117                                                      bool InsertInReadyList,
8118                                                      BoUpSLP *SLP) {
8119   assert(SD->isSchedulingEntity());
8120 
8121   SmallVector<ScheduleData *, 10> WorkList;
8122   WorkList.push_back(SD);
8123 
8124   while (!WorkList.empty()) {
8125     ScheduleData *SD = WorkList.pop_back_val();
8126     for (ScheduleData *BundleMember = SD; BundleMember;
8127          BundleMember = BundleMember->NextInBundle) {
8128       assert(isInSchedulingRegion(BundleMember));
8129       if (BundleMember->hasValidDependencies())
8130         continue;
8131 
8132       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8133                  << "\n");
8134       BundleMember->Dependencies = 0;
8135       BundleMember->resetUnscheduledDeps();
8136 
8137       // Handle def-use chain dependencies.
8138       if (BundleMember->OpValue != BundleMember->Inst) {
8139         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8140           BundleMember->Dependencies++;
8141           ScheduleData *DestBundle = UseSD->FirstInBundle;
8142           if (!DestBundle->IsScheduled)
8143             BundleMember->incrementUnscheduledDeps(1);
8144           if (!DestBundle->hasValidDependencies())
8145             WorkList.push_back(DestBundle);
8146         }
8147       } else {
8148         for (User *U : BundleMember->Inst->users()) {
8149           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8150             BundleMember->Dependencies++;
8151             ScheduleData *DestBundle = UseSD->FirstInBundle;
8152             if (!DestBundle->IsScheduled)
8153               BundleMember->incrementUnscheduledDeps(1);
8154             if (!DestBundle->hasValidDependencies())
8155               WorkList.push_back(DestBundle);
8156           }
8157         }
8158       }
8159 
8160       auto makeControlDependent = [&](Instruction *I) {
8161         auto *DepDest = getScheduleData(I);
8162         assert(DepDest && "must be in schedule window");
8163         DepDest->ControlDependencies.push_back(BundleMember);
8164         BundleMember->Dependencies++;
8165         ScheduleData *DestBundle = DepDest->FirstInBundle;
8166         if (!DestBundle->IsScheduled)
8167           BundleMember->incrementUnscheduledDeps(1);
8168         if (!DestBundle->hasValidDependencies())
8169           WorkList.push_back(DestBundle);
8170       };
8171 
8172       // Any instruction which isn't safe to speculate at the begining of the
8173       // block is control dependend on any early exit or non-willreturn call
8174       // which proceeds it.
8175       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8176         for (Instruction *I = BundleMember->Inst->getNextNode();
8177              I != ScheduleEnd; I = I->getNextNode()) {
8178           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8179             continue;
8180 
8181           // Add the dependency
8182           makeControlDependent(I);
8183 
8184           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8185             // Everything past here must be control dependent on I.
8186             break;
8187         }
8188       }
8189 
8190       if (RegionHasStackSave) {
8191         // If we have an inalloc alloca instruction, it needs to be scheduled
8192         // after any preceeding stacksave.  We also need to prevent any alloca
8193         // from reordering above a preceeding stackrestore.
8194         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8195             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8196           for (Instruction *I = BundleMember->Inst->getNextNode();
8197                I != ScheduleEnd; I = I->getNextNode()) {
8198             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8199                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8200               // Any allocas past here must be control dependent on I, and I
8201               // must be memory dependend on BundleMember->Inst.
8202               break;
8203 
8204             if (!isa<AllocaInst>(I))
8205               continue;
8206 
8207             // Add the dependency
8208             makeControlDependent(I);
8209           }
8210         }
8211 
8212         // In addition to the cases handle just above, we need to prevent
8213         // allocas from moving below a stacksave.  The stackrestore case
8214         // is currently thought to be conservatism.
8215         if (isa<AllocaInst>(BundleMember->Inst)) {
8216           for (Instruction *I = BundleMember->Inst->getNextNode();
8217                I != ScheduleEnd; I = I->getNextNode()) {
8218             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8219                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8220               continue;
8221 
8222             // Add the dependency
8223             makeControlDependent(I);
8224             break;
8225           }
8226         }
8227       }
8228 
8229       // Handle the memory dependencies (if any).
8230       ScheduleData *DepDest = BundleMember->NextLoadStore;
8231       if (!DepDest)
8232         continue;
8233       Instruction *SrcInst = BundleMember->Inst;
8234       assert(SrcInst->mayReadOrWriteMemory() &&
8235              "NextLoadStore list for non memory effecting bundle?");
8236       MemoryLocation SrcLoc = getLocation(SrcInst);
8237       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8238       unsigned numAliased = 0;
8239       unsigned DistToSrc = 1;
8240 
8241       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8242         assert(isInSchedulingRegion(DepDest));
8243 
8244         // We have two limits to reduce the complexity:
8245         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8246         //    SLP->isAliased (which is the expensive part in this loop).
8247         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8248         //    the whole loop (even if the loop is fast, it's quadratic).
8249         //    It's important for the loop break condition (see below) to
8250         //    check this limit even between two read-only instructions.
8251         if (DistToSrc >= MaxMemDepDistance ||
8252             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8253              (numAliased >= AliasedCheckLimit ||
8254               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8255 
8256           // We increment the counter only if the locations are aliased
8257           // (instead of counting all alias checks). This gives a better
8258           // balance between reduced runtime and accurate dependencies.
8259           numAliased++;
8260 
8261           DepDest->MemoryDependencies.push_back(BundleMember);
8262           BundleMember->Dependencies++;
8263           ScheduleData *DestBundle = DepDest->FirstInBundle;
8264           if (!DestBundle->IsScheduled) {
8265             BundleMember->incrementUnscheduledDeps(1);
8266           }
8267           if (!DestBundle->hasValidDependencies()) {
8268             WorkList.push_back(DestBundle);
8269           }
8270         }
8271 
8272         // Example, explaining the loop break condition: Let's assume our
8273         // starting instruction is i0 and MaxMemDepDistance = 3.
8274         //
8275         //                      +--------v--v--v
8276         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8277         //             +--------^--^--^
8278         //
8279         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8280         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8281         // Previously we already added dependencies from i3 to i6,i7,i8
8282         // (because of MaxMemDepDistance). As we added a dependency from
8283         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8284         // and we can abort this loop at i6.
8285         if (DistToSrc >= 2 * MaxMemDepDistance)
8286           break;
8287         DistToSrc++;
8288       }
8289     }
8290     if (InsertInReadyList && SD->isReady()) {
8291       ReadyInsts.insert(SD);
8292       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8293                         << "\n");
8294     }
8295   }
8296 }
8297 
8298 void BoUpSLP::BlockScheduling::resetSchedule() {
8299   assert(ScheduleStart &&
8300          "tried to reset schedule on block which has not been scheduled");
8301   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8302     doForAllOpcodes(I, [&](ScheduleData *SD) {
8303       assert(isInSchedulingRegion(SD) &&
8304              "ScheduleData not in scheduling region");
8305       SD->IsScheduled = false;
8306       SD->resetUnscheduledDeps();
8307     });
8308   }
8309   ReadyInsts.clear();
8310 }
8311 
8312 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8313   if (!BS->ScheduleStart)
8314     return;
8315 
8316   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8317 
8318   // A key point - if we got here, pre-scheduling was able to find a valid
8319   // scheduling of the sub-graph of the scheduling window which consists
8320   // of all vector bundles and their transitive users.  As such, we do not
8321   // need to reschedule anything *outside of* that subgraph.
8322 
8323   BS->resetSchedule();
8324 
8325   // For the real scheduling we use a more sophisticated ready-list: it is
8326   // sorted by the original instruction location. This lets the final schedule
8327   // be as  close as possible to the original instruction order.
8328   // WARNING: If changing this order causes a correctness issue, that means
8329   // there is some missing dependence edge in the schedule data graph.
8330   struct ScheduleDataCompare {
8331     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8332       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8333     }
8334   };
8335   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8336 
8337   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8338   // and fill the ready-list with initial instructions.
8339   int Idx = 0;
8340   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8341        I = I->getNextNode()) {
8342     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8343       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8344       (void)SDTE;
8345       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8346               SD->isPartOfBundle() ==
8347                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8348              "scheduler and vectorizer bundle mismatch");
8349       SD->FirstInBundle->SchedulingPriority = Idx++;
8350 
8351       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8352         BS->calculateDependencies(SD, false, this);
8353     });
8354   }
8355   BS->initialFillReadyList(ReadyInsts);
8356 
8357   Instruction *LastScheduledInst = BS->ScheduleEnd;
8358 
8359   // Do the "real" scheduling.
8360   while (!ReadyInsts.empty()) {
8361     ScheduleData *picked = *ReadyInsts.begin();
8362     ReadyInsts.erase(ReadyInsts.begin());
8363 
8364     // Move the scheduled instruction(s) to their dedicated places, if not
8365     // there yet.
8366     for (ScheduleData *BundleMember = picked; BundleMember;
8367          BundleMember = BundleMember->NextInBundle) {
8368       Instruction *pickedInst = BundleMember->Inst;
8369       if (pickedInst->getNextNode() != LastScheduledInst)
8370         pickedInst->moveBefore(LastScheduledInst);
8371       LastScheduledInst = pickedInst;
8372     }
8373 
8374     BS->schedule(picked, ReadyInsts);
8375   }
8376 
8377   // Check that we didn't break any of our invariants.
8378 #ifdef EXPENSIVE_CHECKS
8379   BS->verify();
8380 #endif
8381 
8382 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8383   // Check that all schedulable entities got scheduled
8384   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8385     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8386       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8387         assert(SD->IsScheduled && "must be scheduled at this point");
8388       }
8389     });
8390   }
8391 #endif
8392 
8393   // Avoid duplicate scheduling of the block.
8394   BS->ScheduleStart = nullptr;
8395 }
8396 
8397 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8398   // If V is a store, just return the width of the stored value (or value
8399   // truncated just before storing) without traversing the expression tree.
8400   // This is the common case.
8401   if (auto *Store = dyn_cast<StoreInst>(V)) {
8402     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8403       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8404     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8405   }
8406 
8407   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8408     return getVectorElementSize(IEI->getOperand(1));
8409 
8410   auto E = InstrElementSize.find(V);
8411   if (E != InstrElementSize.end())
8412     return E->second;
8413 
8414   // If V is not a store, we can traverse the expression tree to find loads
8415   // that feed it. The type of the loaded value may indicate a more suitable
8416   // width than V's type. We want to base the vector element size on the width
8417   // of memory operations where possible.
8418   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8419   SmallPtrSet<Instruction *, 16> Visited;
8420   if (auto *I = dyn_cast<Instruction>(V)) {
8421     Worklist.emplace_back(I, I->getParent());
8422     Visited.insert(I);
8423   }
8424 
8425   // Traverse the expression tree in bottom-up order looking for loads. If we
8426   // encounter an instruction we don't yet handle, we give up.
8427   auto Width = 0u;
8428   while (!Worklist.empty()) {
8429     Instruction *I;
8430     BasicBlock *Parent;
8431     std::tie(I, Parent) = Worklist.pop_back_val();
8432 
8433     // We should only be looking at scalar instructions here. If the current
8434     // instruction has a vector type, skip.
8435     auto *Ty = I->getType();
8436     if (isa<VectorType>(Ty))
8437       continue;
8438 
8439     // If the current instruction is a load, update MaxWidth to reflect the
8440     // width of the loaded value.
8441     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8442         isa<ExtractValueInst>(I))
8443       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8444 
8445     // Otherwise, we need to visit the operands of the instruction. We only
8446     // handle the interesting cases from buildTree here. If an operand is an
8447     // instruction we haven't yet visited and from the same basic block as the
8448     // user or the use is a PHI node, we add it to the worklist.
8449     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8450              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8451              isa<UnaryOperator>(I)) {
8452       for (Use &U : I->operands())
8453         if (auto *J = dyn_cast<Instruction>(U.get()))
8454           if (Visited.insert(J).second &&
8455               (isa<PHINode>(I) || J->getParent() == Parent))
8456             Worklist.emplace_back(J, J->getParent());
8457     } else {
8458       break;
8459     }
8460   }
8461 
8462   // If we didn't encounter a memory access in the expression tree, or if we
8463   // gave up for some reason, just return the width of V. Otherwise, return the
8464   // maximum width we found.
8465   if (!Width) {
8466     if (auto *CI = dyn_cast<CmpInst>(V))
8467       V = CI->getOperand(0);
8468     Width = DL->getTypeSizeInBits(V->getType());
8469   }
8470 
8471   for (Instruction *I : Visited)
8472     InstrElementSize[I] = Width;
8473 
8474   return Width;
8475 }
8476 
8477 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8478 // smaller type with a truncation. We collect the values that will be demoted
8479 // in ToDemote and additional roots that require investigating in Roots.
8480 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8481                                   SmallVectorImpl<Value *> &ToDemote,
8482                                   SmallVectorImpl<Value *> &Roots) {
8483   // We can always demote constants.
8484   if (isa<Constant>(V)) {
8485     ToDemote.push_back(V);
8486     return true;
8487   }
8488 
8489   // If the value is not an instruction in the expression with only one use, it
8490   // cannot be demoted.
8491   auto *I = dyn_cast<Instruction>(V);
8492   if (!I || !I->hasOneUse() || !Expr.count(I))
8493     return false;
8494 
8495   switch (I->getOpcode()) {
8496 
8497   // We can always demote truncations and extensions. Since truncations can
8498   // seed additional demotion, we save the truncated value.
8499   case Instruction::Trunc:
8500     Roots.push_back(I->getOperand(0));
8501     break;
8502   case Instruction::ZExt:
8503   case Instruction::SExt:
8504     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8505         isa<InsertElementInst>(I->getOperand(0)))
8506       return false;
8507     break;
8508 
8509   // We can demote certain binary operations if we can demote both of their
8510   // operands.
8511   case Instruction::Add:
8512   case Instruction::Sub:
8513   case Instruction::Mul:
8514   case Instruction::And:
8515   case Instruction::Or:
8516   case Instruction::Xor:
8517     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8518         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8519       return false;
8520     break;
8521 
8522   // We can demote selects if we can demote their true and false values.
8523   case Instruction::Select: {
8524     SelectInst *SI = cast<SelectInst>(I);
8525     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8526         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8527       return false;
8528     break;
8529   }
8530 
8531   // We can demote phis if we can demote all their incoming operands. Note that
8532   // we don't need to worry about cycles since we ensure single use above.
8533   case Instruction::PHI: {
8534     PHINode *PN = cast<PHINode>(I);
8535     for (Value *IncValue : PN->incoming_values())
8536       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8537         return false;
8538     break;
8539   }
8540 
8541   // Otherwise, conservatively give up.
8542   default:
8543     return false;
8544   }
8545 
8546   // Record the value that we can demote.
8547   ToDemote.push_back(V);
8548   return true;
8549 }
8550 
8551 void BoUpSLP::computeMinimumValueSizes() {
8552   // If there are no external uses, the expression tree must be rooted by a
8553   // store. We can't demote in-memory values, so there is nothing to do here.
8554   if (ExternalUses.empty())
8555     return;
8556 
8557   // We only attempt to truncate integer expressions.
8558   auto &TreeRoot = VectorizableTree[0]->Scalars;
8559   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8560   if (!TreeRootIT)
8561     return;
8562 
8563   // If the expression is not rooted by a store, these roots should have
8564   // external uses. We will rely on InstCombine to rewrite the expression in
8565   // the narrower type. However, InstCombine only rewrites single-use values.
8566   // This means that if a tree entry other than a root is used externally, it
8567   // must have multiple uses and InstCombine will not rewrite it. The code
8568   // below ensures that only the roots are used externally.
8569   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8570   for (auto &EU : ExternalUses)
8571     if (!Expr.erase(EU.Scalar))
8572       return;
8573   if (!Expr.empty())
8574     return;
8575 
8576   // Collect the scalar values of the vectorizable expression. We will use this
8577   // context to determine which values can be demoted. If we see a truncation,
8578   // we mark it as seeding another demotion.
8579   for (auto &EntryPtr : VectorizableTree)
8580     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8581 
8582   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8583   // have a single external user that is not in the vectorizable tree.
8584   for (auto *Root : TreeRoot)
8585     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8586       return;
8587 
8588   // Conservatively determine if we can actually truncate the roots of the
8589   // expression. Collect the values that can be demoted in ToDemote and
8590   // additional roots that require investigating in Roots.
8591   SmallVector<Value *, 32> ToDemote;
8592   SmallVector<Value *, 4> Roots;
8593   for (auto *Root : TreeRoot)
8594     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8595       return;
8596 
8597   // The maximum bit width required to represent all the values that can be
8598   // demoted without loss of precision. It would be safe to truncate the roots
8599   // of the expression to this width.
8600   auto MaxBitWidth = 8u;
8601 
8602   // We first check if all the bits of the roots are demanded. If they're not,
8603   // we can truncate the roots to this narrower type.
8604   for (auto *Root : TreeRoot) {
8605     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8606     MaxBitWidth = std::max<unsigned>(
8607         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8608   }
8609 
8610   // True if the roots can be zero-extended back to their original type, rather
8611   // than sign-extended. We know that if the leading bits are not demanded, we
8612   // can safely zero-extend. So we initialize IsKnownPositive to True.
8613   bool IsKnownPositive = true;
8614 
8615   // If all the bits of the roots are demanded, we can try a little harder to
8616   // compute a narrower type. This can happen, for example, if the roots are
8617   // getelementptr indices. InstCombine promotes these indices to the pointer
8618   // width. Thus, all their bits are technically demanded even though the
8619   // address computation might be vectorized in a smaller type.
8620   //
8621   // We start by looking at each entry that can be demoted. We compute the
8622   // maximum bit width required to store the scalar by using ValueTracking to
8623   // compute the number of high-order bits we can truncate.
8624   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8625       llvm::all_of(TreeRoot, [](Value *R) {
8626         assert(R->hasOneUse() && "Root should have only one use!");
8627         return isa<GetElementPtrInst>(R->user_back());
8628       })) {
8629     MaxBitWidth = 8u;
8630 
8631     // Determine if the sign bit of all the roots is known to be zero. If not,
8632     // IsKnownPositive is set to False.
8633     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8634       KnownBits Known = computeKnownBits(R, *DL);
8635       return Known.isNonNegative();
8636     });
8637 
8638     // Determine the maximum number of bits required to store the scalar
8639     // values.
8640     for (auto *Scalar : ToDemote) {
8641       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8642       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8643       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8644     }
8645 
8646     // If we can't prove that the sign bit is zero, we must add one to the
8647     // maximum bit width to account for the unknown sign bit. This preserves
8648     // the existing sign bit so we can safely sign-extend the root back to the
8649     // original type. Otherwise, if we know the sign bit is zero, we will
8650     // zero-extend the root instead.
8651     //
8652     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8653     //        one to the maximum bit width will yield a larger-than-necessary
8654     //        type. In general, we need to add an extra bit only if we can't
8655     //        prove that the upper bit of the original type is equal to the
8656     //        upper bit of the proposed smaller type. If these two bits are the
8657     //        same (either zero or one) we know that sign-extending from the
8658     //        smaller type will result in the same value. Here, since we can't
8659     //        yet prove this, we are just making the proposed smaller type
8660     //        larger to ensure correctness.
8661     if (!IsKnownPositive)
8662       ++MaxBitWidth;
8663   }
8664 
8665   // Round MaxBitWidth up to the next power-of-two.
8666   if (!isPowerOf2_64(MaxBitWidth))
8667     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8668 
8669   // If the maximum bit width we compute is less than the with of the roots'
8670   // type, we can proceed with the narrowing. Otherwise, do nothing.
8671   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8672     return;
8673 
8674   // If we can truncate the root, we must collect additional values that might
8675   // be demoted as a result. That is, those seeded by truncations we will
8676   // modify.
8677   while (!Roots.empty())
8678     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8679 
8680   // Finally, map the values we can demote to the maximum bit with we computed.
8681   for (auto *Scalar : ToDemote)
8682     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8683 }
8684 
8685 namespace {
8686 
8687 /// The SLPVectorizer Pass.
8688 struct SLPVectorizer : public FunctionPass {
8689   SLPVectorizerPass Impl;
8690 
8691   /// Pass identification, replacement for typeid
8692   static char ID;
8693 
8694   explicit SLPVectorizer() : FunctionPass(ID) {
8695     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8696   }
8697 
8698   bool doInitialization(Module &M) override { return false; }
8699 
8700   bool runOnFunction(Function &F) override {
8701     if (skipFunction(F))
8702       return false;
8703 
8704     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8705     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8706     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8707     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8708     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8709     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8710     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8711     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8712     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8713     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8714 
8715     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8716   }
8717 
8718   void getAnalysisUsage(AnalysisUsage &AU) const override {
8719     FunctionPass::getAnalysisUsage(AU);
8720     AU.addRequired<AssumptionCacheTracker>();
8721     AU.addRequired<ScalarEvolutionWrapperPass>();
8722     AU.addRequired<AAResultsWrapperPass>();
8723     AU.addRequired<TargetTransformInfoWrapperPass>();
8724     AU.addRequired<LoopInfoWrapperPass>();
8725     AU.addRequired<DominatorTreeWrapperPass>();
8726     AU.addRequired<DemandedBitsWrapperPass>();
8727     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8728     AU.addRequired<InjectTLIMappingsLegacy>();
8729     AU.addPreserved<LoopInfoWrapperPass>();
8730     AU.addPreserved<DominatorTreeWrapperPass>();
8731     AU.addPreserved<AAResultsWrapperPass>();
8732     AU.addPreserved<GlobalsAAWrapperPass>();
8733     AU.setPreservesCFG();
8734   }
8735 };
8736 
8737 } // end anonymous namespace
8738 
8739 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8740   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8741   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8742   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8743   auto *AA = &AM.getResult<AAManager>(F);
8744   auto *LI = &AM.getResult<LoopAnalysis>(F);
8745   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8746   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8747   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8748   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8749 
8750   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8751   if (!Changed)
8752     return PreservedAnalyses::all();
8753 
8754   PreservedAnalyses PA;
8755   PA.preserveSet<CFGAnalyses>();
8756   return PA;
8757 }
8758 
8759 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8760                                 TargetTransformInfo *TTI_,
8761                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8762                                 LoopInfo *LI_, DominatorTree *DT_,
8763                                 AssumptionCache *AC_, DemandedBits *DB_,
8764                                 OptimizationRemarkEmitter *ORE_) {
8765   if (!RunSLPVectorization)
8766     return false;
8767   SE = SE_;
8768   TTI = TTI_;
8769   TLI = TLI_;
8770   AA = AA_;
8771   LI = LI_;
8772   DT = DT_;
8773   AC = AC_;
8774   DB = DB_;
8775   DL = &F.getParent()->getDataLayout();
8776 
8777   Stores.clear();
8778   GEPs.clear();
8779   bool Changed = false;
8780 
8781   // If the target claims to have no vector registers don't attempt
8782   // vectorization.
8783   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8784     LLVM_DEBUG(
8785         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8786     return false;
8787   }
8788 
8789   // Don't vectorize when the attribute NoImplicitFloat is used.
8790   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8791     return false;
8792 
8793   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8794 
8795   // Use the bottom up slp vectorizer to construct chains that start with
8796   // store instructions.
8797   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8798 
8799   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8800   // delete instructions.
8801 
8802   // Update DFS numbers now so that we can use them for ordering.
8803   DT->updateDFSNumbers();
8804 
8805   // Scan the blocks in the function in post order.
8806   for (auto BB : post_order(&F.getEntryBlock())) {
8807     collectSeedInstructions(BB);
8808 
8809     // Vectorize trees that end at stores.
8810     if (!Stores.empty()) {
8811       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8812                         << " underlying objects.\n");
8813       Changed |= vectorizeStoreChains(R);
8814     }
8815 
8816     // Vectorize trees that end at reductions.
8817     Changed |= vectorizeChainsInBlock(BB, R);
8818 
8819     // Vectorize the index computations of getelementptr instructions. This
8820     // is primarily intended to catch gather-like idioms ending at
8821     // non-consecutive loads.
8822     if (!GEPs.empty()) {
8823       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8824                         << " underlying objects.\n");
8825       Changed |= vectorizeGEPIndices(BB, R);
8826     }
8827   }
8828 
8829   if (Changed) {
8830     R.optimizeGatherSequence();
8831     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8832   }
8833   return Changed;
8834 }
8835 
8836 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8837                                             unsigned Idx) {
8838   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8839                     << "\n");
8840   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8841   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8842   unsigned VF = Chain.size();
8843 
8844   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8845     return false;
8846 
8847   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8848                     << "\n");
8849 
8850   R.buildTree(Chain);
8851   if (R.isTreeTinyAndNotFullyVectorizable())
8852     return false;
8853   if (R.isLoadCombineCandidate())
8854     return false;
8855   R.reorderTopToBottom();
8856   R.reorderBottomToTop();
8857   R.buildExternalUses();
8858 
8859   R.computeMinimumValueSizes();
8860 
8861   InstructionCost Cost = R.getTreeCost();
8862 
8863   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8864   if (Cost < -SLPCostThreshold) {
8865     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8866 
8867     using namespace ore;
8868 
8869     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8870                                         cast<StoreInst>(Chain[0]))
8871                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8872                      << " and with tree size "
8873                      << NV("TreeSize", R.getTreeSize()));
8874 
8875     R.vectorizeTree();
8876     return true;
8877   }
8878 
8879   return false;
8880 }
8881 
8882 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8883                                         BoUpSLP &R) {
8884   // We may run into multiple chains that merge into a single chain. We mark the
8885   // stores that we vectorized so that we don't visit the same store twice.
8886   BoUpSLP::ValueSet VectorizedStores;
8887   bool Changed = false;
8888 
8889   int E = Stores.size();
8890   SmallBitVector Tails(E, false);
8891   int MaxIter = MaxStoreLookup.getValue();
8892   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8893       E, std::make_pair(E, INT_MAX));
8894   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8895   int IterCnt;
8896   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8897                                   &CheckedPairs,
8898                                   &ConsecutiveChain](int K, int Idx) {
8899     if (IterCnt >= MaxIter)
8900       return true;
8901     if (CheckedPairs[Idx].test(K))
8902       return ConsecutiveChain[K].second == 1 &&
8903              ConsecutiveChain[K].first == Idx;
8904     ++IterCnt;
8905     CheckedPairs[Idx].set(K);
8906     CheckedPairs[K].set(Idx);
8907     Optional<int> Diff = getPointersDiff(
8908         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8909         Stores[Idx]->getValueOperand()->getType(),
8910         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8911     if (!Diff || *Diff == 0)
8912       return false;
8913     int Val = *Diff;
8914     if (Val < 0) {
8915       if (ConsecutiveChain[Idx].second > -Val) {
8916         Tails.set(K);
8917         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8918       }
8919       return false;
8920     }
8921     if (ConsecutiveChain[K].second <= Val)
8922       return false;
8923 
8924     Tails.set(Idx);
8925     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8926     return Val == 1;
8927   };
8928   // Do a quadratic search on all of the given stores in reverse order and find
8929   // all of the pairs of stores that follow each other.
8930   for (int Idx = E - 1; Idx >= 0; --Idx) {
8931     // If a store has multiple consecutive store candidates, search according
8932     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8933     // This is because usually pairing with immediate succeeding or preceding
8934     // candidate create the best chance to find slp vectorization opportunity.
8935     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8936     IterCnt = 0;
8937     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8938       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8939           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8940         break;
8941   }
8942 
8943   // Tracks if we tried to vectorize stores starting from the given tail
8944   // already.
8945   SmallBitVector TriedTails(E, false);
8946   // For stores that start but don't end a link in the chain:
8947   for (int Cnt = E; Cnt > 0; --Cnt) {
8948     int I = Cnt - 1;
8949     if (ConsecutiveChain[I].first == E || Tails.test(I))
8950       continue;
8951     // We found a store instr that starts a chain. Now follow the chain and try
8952     // to vectorize it.
8953     BoUpSLP::ValueList Operands;
8954     // Collect the chain into a list.
8955     while (I != E && !VectorizedStores.count(Stores[I])) {
8956       Operands.push_back(Stores[I]);
8957       Tails.set(I);
8958       if (ConsecutiveChain[I].second != 1) {
8959         // Mark the new end in the chain and go back, if required. It might be
8960         // required if the original stores come in reversed order, for example.
8961         if (ConsecutiveChain[I].first != E &&
8962             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8963             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8964           TriedTails.set(I);
8965           Tails.reset(ConsecutiveChain[I].first);
8966           if (Cnt < ConsecutiveChain[I].first + 2)
8967             Cnt = ConsecutiveChain[I].first + 2;
8968         }
8969         break;
8970       }
8971       // Move to the next value in the chain.
8972       I = ConsecutiveChain[I].first;
8973     }
8974     assert(!Operands.empty() && "Expected non-empty list of stores.");
8975 
8976     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8977     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8978     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8979 
8980     unsigned MinVF = R.getMinVF(EltSize);
8981     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8982                               MaxElts);
8983 
8984     // FIXME: Is division-by-2 the correct step? Should we assert that the
8985     // register size is a power-of-2?
8986     unsigned StartIdx = 0;
8987     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8988       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8989         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8990         if (!VectorizedStores.count(Slice.front()) &&
8991             !VectorizedStores.count(Slice.back()) &&
8992             vectorizeStoreChain(Slice, R, Cnt)) {
8993           // Mark the vectorized stores so that we don't vectorize them again.
8994           VectorizedStores.insert(Slice.begin(), Slice.end());
8995           Changed = true;
8996           // If we vectorized initial block, no need to try to vectorize it
8997           // again.
8998           if (Cnt == StartIdx)
8999             StartIdx += Size;
9000           Cnt += Size;
9001           continue;
9002         }
9003         ++Cnt;
9004       }
9005       // Check if the whole array was vectorized already - exit.
9006       if (StartIdx >= Operands.size())
9007         break;
9008     }
9009   }
9010 
9011   return Changed;
9012 }
9013 
9014 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9015   // Initialize the collections. We will make a single pass over the block.
9016   Stores.clear();
9017   GEPs.clear();
9018 
9019   // Visit the store and getelementptr instructions in BB and organize them in
9020   // Stores and GEPs according to the underlying objects of their pointer
9021   // operands.
9022   for (Instruction &I : *BB) {
9023     // Ignore store instructions that are volatile or have a pointer operand
9024     // that doesn't point to a scalar type.
9025     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9026       if (!SI->isSimple())
9027         continue;
9028       if (!isValidElementType(SI->getValueOperand()->getType()))
9029         continue;
9030       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9031     }
9032 
9033     // Ignore getelementptr instructions that have more than one index, a
9034     // constant index, or a pointer operand that doesn't point to a scalar
9035     // type.
9036     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9037       auto Idx = GEP->idx_begin()->get();
9038       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9039         continue;
9040       if (!isValidElementType(Idx->getType()))
9041         continue;
9042       if (GEP->getType()->isVectorTy())
9043         continue;
9044       GEPs[GEP->getPointerOperand()].push_back(GEP);
9045     }
9046   }
9047 }
9048 
9049 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9050   if (!A || !B)
9051     return false;
9052   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9053     return false;
9054   Value *VL[] = {A, B};
9055   return tryToVectorizeList(VL, R);
9056 }
9057 
9058 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9059                                            bool LimitForRegisterSize) {
9060   if (VL.size() < 2)
9061     return false;
9062 
9063   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9064                     << VL.size() << ".\n");
9065 
9066   // Check that all of the parts are instructions of the same type,
9067   // we permit an alternate opcode via InstructionsState.
9068   InstructionsState S = getSameOpcode(VL);
9069   if (!S.getOpcode())
9070     return false;
9071 
9072   Instruction *I0 = cast<Instruction>(S.OpValue);
9073   // Make sure invalid types (including vector type) are rejected before
9074   // determining vectorization factor for scalar instructions.
9075   for (Value *V : VL) {
9076     Type *Ty = V->getType();
9077     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9078       // NOTE: the following will give user internal llvm type name, which may
9079       // not be useful.
9080       R.getORE()->emit([&]() {
9081         std::string type_str;
9082         llvm::raw_string_ostream rso(type_str);
9083         Ty->print(rso);
9084         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9085                << "Cannot SLP vectorize list: type "
9086                << rso.str() + " is unsupported by vectorizer";
9087       });
9088       return false;
9089     }
9090   }
9091 
9092   unsigned Sz = R.getVectorElementSize(I0);
9093   unsigned MinVF = R.getMinVF(Sz);
9094   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9095   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9096   if (MaxVF < 2) {
9097     R.getORE()->emit([&]() {
9098       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9099              << "Cannot SLP vectorize list: vectorization factor "
9100              << "less than 2 is not supported";
9101     });
9102     return false;
9103   }
9104 
9105   bool Changed = false;
9106   bool CandidateFound = false;
9107   InstructionCost MinCost = SLPCostThreshold.getValue();
9108   Type *ScalarTy = VL[0]->getType();
9109   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9110     ScalarTy = IE->getOperand(1)->getType();
9111 
9112   unsigned NextInst = 0, MaxInst = VL.size();
9113   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9114     // No actual vectorization should happen, if number of parts is the same as
9115     // provided vectorization factor (i.e. the scalar type is used for vector
9116     // code during codegen).
9117     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9118     if (TTI->getNumberOfParts(VecTy) == VF)
9119       continue;
9120     for (unsigned I = NextInst; I < MaxInst; ++I) {
9121       unsigned OpsWidth = 0;
9122 
9123       if (I + VF > MaxInst)
9124         OpsWidth = MaxInst - I;
9125       else
9126         OpsWidth = VF;
9127 
9128       if (!isPowerOf2_32(OpsWidth))
9129         continue;
9130 
9131       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9132           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9133         break;
9134 
9135       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9136       // Check that a previous iteration of this loop did not delete the Value.
9137       if (llvm::any_of(Ops, [&R](Value *V) {
9138             auto *I = dyn_cast<Instruction>(V);
9139             return I && R.isDeleted(I);
9140           }))
9141         continue;
9142 
9143       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9144                         << "\n");
9145 
9146       R.buildTree(Ops);
9147       if (R.isTreeTinyAndNotFullyVectorizable())
9148         continue;
9149       R.reorderTopToBottom();
9150       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9151       R.buildExternalUses();
9152 
9153       R.computeMinimumValueSizes();
9154       InstructionCost Cost = R.getTreeCost();
9155       CandidateFound = true;
9156       MinCost = std::min(MinCost, Cost);
9157 
9158       if (Cost < -SLPCostThreshold) {
9159         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9160         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9161                                                     cast<Instruction>(Ops[0]))
9162                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9163                                  << " and with tree size "
9164                                  << ore::NV("TreeSize", R.getTreeSize()));
9165 
9166         R.vectorizeTree();
9167         // Move to the next bundle.
9168         I += VF - 1;
9169         NextInst = I + 1;
9170         Changed = true;
9171       }
9172     }
9173   }
9174 
9175   if (!Changed && CandidateFound) {
9176     R.getORE()->emit([&]() {
9177       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9178              << "List vectorization was possible but not beneficial with cost "
9179              << ore::NV("Cost", MinCost) << " >= "
9180              << ore::NV("Treshold", -SLPCostThreshold);
9181     });
9182   } else if (!Changed) {
9183     R.getORE()->emit([&]() {
9184       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9185              << "Cannot SLP vectorize list: vectorization was impossible"
9186              << " with available vectorization factors";
9187     });
9188   }
9189   return Changed;
9190 }
9191 
9192 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9193   if (!I)
9194     return false;
9195 
9196   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9197       isa<VectorType>(I->getType()))
9198     return false;
9199 
9200   Value *P = I->getParent();
9201 
9202   // Vectorize in current basic block only.
9203   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9204   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9205   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9206     return false;
9207 
9208   // First collect all possible candidates
9209   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9210   Candidates.emplace_back(Op0, Op1);
9211 
9212   auto *A = dyn_cast<BinaryOperator>(Op0);
9213   auto *B = dyn_cast<BinaryOperator>(Op1);
9214   // Try to skip B.
9215   if (A && B && B->hasOneUse()) {
9216     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9217     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9218     if (B0 && B0->getParent() == P)
9219       Candidates.emplace_back(A, B0);
9220     if (B1 && B1->getParent() == P)
9221       Candidates.emplace_back(A, B1);
9222   }
9223   // Try to skip A.
9224   if (B && A && A->hasOneUse()) {
9225     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9226     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9227     if (A0 && A0->getParent() == P)
9228       Candidates.emplace_back(A0, B);
9229     if (A1 && A1->getParent() == P)
9230       Candidates.emplace_back(A1, B);
9231   }
9232 
9233   if (Candidates.size() == 1)
9234     return tryToVectorizePair(Op0, Op1, R);
9235 
9236   // We have multiple options. Try to pick the single best.
9237   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9238   if (!BestCandidate)
9239     return false;
9240   return tryToVectorizePair(Candidates[*BestCandidate].first,
9241                             Candidates[*BestCandidate].second, R);
9242 }
9243 
9244 namespace {
9245 
9246 /// Model horizontal reductions.
9247 ///
9248 /// A horizontal reduction is a tree of reduction instructions that has values
9249 /// that can be put into a vector as its leaves. For example:
9250 ///
9251 /// mul mul mul mul
9252 ///  \  /    \  /
9253 ///   +       +
9254 ///    \     /
9255 ///       +
9256 /// This tree has "mul" as its leaf values and "+" as its reduction
9257 /// instructions. A reduction can feed into a store or a binary operation
9258 /// feeding a phi.
9259 ///    ...
9260 ///    \  /
9261 ///     +
9262 ///     |
9263 ///  phi +=
9264 ///
9265 ///  Or:
9266 ///    ...
9267 ///    \  /
9268 ///     +
9269 ///     |
9270 ///   *p =
9271 ///
9272 class HorizontalReduction {
9273   using ReductionOpsType = SmallVector<Value *, 16>;
9274   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9275   ReductionOpsListType ReductionOps;
9276   SmallVector<Value *, 32> ReducedVals;
9277   // Use map vector to make stable output.
9278   MapVector<Instruction *, Value *> ExtraArgs;
9279   WeakTrackingVH ReductionRoot;
9280   /// The type of reduction operation.
9281   RecurKind RdxKind;
9282 
9283   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9284 
9285   static bool isCmpSelMinMax(Instruction *I) {
9286     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9287            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9288   }
9289 
9290   // And/or are potentially poison-safe logical patterns like:
9291   // select x, y, false
9292   // select x, true, y
9293   static bool isBoolLogicOp(Instruction *I) {
9294     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9295            match(I, m_LogicalOr(m_Value(), m_Value()));
9296   }
9297 
9298   /// Checks if instruction is associative and can be vectorized.
9299   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9300     if (Kind == RecurKind::None)
9301       return false;
9302 
9303     // Integer ops that map to select instructions or intrinsics are fine.
9304     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9305         isBoolLogicOp(I))
9306       return true;
9307 
9308     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9309       // FP min/max are associative except for NaN and -0.0. We do not
9310       // have to rule out -0.0 here because the intrinsic semantics do not
9311       // specify a fixed result for it.
9312       return I->getFastMathFlags().noNaNs();
9313     }
9314 
9315     return I->isAssociative();
9316   }
9317 
9318   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9319     // Poison-safe 'or' takes the form: select X, true, Y
9320     // To make that work with the normal operand processing, we skip the
9321     // true value operand.
9322     // TODO: Change the code and data structures to handle this without a hack.
9323     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9324       return I->getOperand(2);
9325     return I->getOperand(Index);
9326   }
9327 
9328   /// Checks if the ParentStackElem.first should be marked as a reduction
9329   /// operation with an extra argument or as extra argument itself.
9330   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9331                     Value *ExtraArg) {
9332     if (ExtraArgs.count(ParentStackElem.first)) {
9333       ExtraArgs[ParentStackElem.first] = nullptr;
9334       // We ran into something like:
9335       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9336       // The whole ParentStackElem.first should be considered as an extra value
9337       // in this case.
9338       // Do not perform analysis of remaining operands of ParentStackElem.first
9339       // instruction, this whole instruction is an extra argument.
9340       ParentStackElem.second = INVALID_OPERAND_INDEX;
9341     } else {
9342       // We ran into something like:
9343       // ParentStackElem.first += ... + ExtraArg + ...
9344       ExtraArgs[ParentStackElem.first] = ExtraArg;
9345     }
9346   }
9347 
9348   /// Creates reduction operation with the current opcode.
9349   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9350                          Value *RHS, const Twine &Name, bool UseSelect) {
9351     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9352     switch (Kind) {
9353     case RecurKind::Or:
9354       if (UseSelect &&
9355           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9356         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9357       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9358                                  Name);
9359     case RecurKind::And:
9360       if (UseSelect &&
9361           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9362         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9363       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9364                                  Name);
9365     case RecurKind::Add:
9366     case RecurKind::Mul:
9367     case RecurKind::Xor:
9368     case RecurKind::FAdd:
9369     case RecurKind::FMul:
9370       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9371                                  Name);
9372     case RecurKind::FMax:
9373       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9374     case RecurKind::FMin:
9375       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9376     case RecurKind::SMax:
9377       if (UseSelect) {
9378         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9379         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9380       }
9381       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9382     case RecurKind::SMin:
9383       if (UseSelect) {
9384         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9385         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9386       }
9387       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9388     case RecurKind::UMax:
9389       if (UseSelect) {
9390         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9391         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9392       }
9393       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9394     case RecurKind::UMin:
9395       if (UseSelect) {
9396         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9397         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9398       }
9399       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9400     default:
9401       llvm_unreachable("Unknown reduction operation.");
9402     }
9403   }
9404 
9405   /// Creates reduction operation with the current opcode with the IR flags
9406   /// from \p ReductionOps.
9407   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9408                          Value *RHS, const Twine &Name,
9409                          const ReductionOpsListType &ReductionOps) {
9410     bool UseSelect = ReductionOps.size() == 2 ||
9411                      // Logical or/and.
9412                      (ReductionOps.size() == 1 &&
9413                       isa<SelectInst>(ReductionOps.front().front()));
9414     assert((!UseSelect || ReductionOps.size() != 2 ||
9415             isa<SelectInst>(ReductionOps[1][0])) &&
9416            "Expected cmp + select pairs for reduction");
9417     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9418     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9419       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9420         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9421         propagateIRFlags(Op, ReductionOps[1]);
9422         return Op;
9423       }
9424     }
9425     propagateIRFlags(Op, ReductionOps[0]);
9426     return Op;
9427   }
9428 
9429   /// Creates reduction operation with the current opcode with the IR flags
9430   /// from \p I.
9431   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9432                          Value *RHS, const Twine &Name, Instruction *I) {
9433     auto *SelI = dyn_cast<SelectInst>(I);
9434     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9435     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9436       if (auto *Sel = dyn_cast<SelectInst>(Op))
9437         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9438     }
9439     propagateIRFlags(Op, I);
9440     return Op;
9441   }
9442 
9443   static RecurKind getRdxKind(Instruction *I) {
9444     assert(I && "Expected instruction for reduction matching");
9445     if (match(I, m_Add(m_Value(), m_Value())))
9446       return RecurKind::Add;
9447     if (match(I, m_Mul(m_Value(), m_Value())))
9448       return RecurKind::Mul;
9449     if (match(I, m_And(m_Value(), m_Value())) ||
9450         match(I, m_LogicalAnd(m_Value(), m_Value())))
9451       return RecurKind::And;
9452     if (match(I, m_Or(m_Value(), m_Value())) ||
9453         match(I, m_LogicalOr(m_Value(), m_Value())))
9454       return RecurKind::Or;
9455     if (match(I, m_Xor(m_Value(), m_Value())))
9456       return RecurKind::Xor;
9457     if (match(I, m_FAdd(m_Value(), m_Value())))
9458       return RecurKind::FAdd;
9459     if (match(I, m_FMul(m_Value(), m_Value())))
9460       return RecurKind::FMul;
9461 
9462     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9463       return RecurKind::FMax;
9464     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9465       return RecurKind::FMin;
9466 
9467     // This matches either cmp+select or intrinsics. SLP is expected to handle
9468     // either form.
9469     // TODO: If we are canonicalizing to intrinsics, we can remove several
9470     //       special-case paths that deal with selects.
9471     if (match(I, m_SMax(m_Value(), m_Value())))
9472       return RecurKind::SMax;
9473     if (match(I, m_SMin(m_Value(), m_Value())))
9474       return RecurKind::SMin;
9475     if (match(I, m_UMax(m_Value(), m_Value())))
9476       return RecurKind::UMax;
9477     if (match(I, m_UMin(m_Value(), m_Value())))
9478       return RecurKind::UMin;
9479 
9480     if (auto *Select = dyn_cast<SelectInst>(I)) {
9481       // Try harder: look for min/max pattern based on instructions producing
9482       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9483       // During the intermediate stages of SLP, it's very common to have
9484       // pattern like this (since optimizeGatherSequence is run only once
9485       // at the end):
9486       // %1 = extractelement <2 x i32> %a, i32 0
9487       // %2 = extractelement <2 x i32> %a, i32 1
9488       // %cond = icmp sgt i32 %1, %2
9489       // %3 = extractelement <2 x i32> %a, i32 0
9490       // %4 = extractelement <2 x i32> %a, i32 1
9491       // %select = select i1 %cond, i32 %3, i32 %4
9492       CmpInst::Predicate Pred;
9493       Instruction *L1;
9494       Instruction *L2;
9495 
9496       Value *LHS = Select->getTrueValue();
9497       Value *RHS = Select->getFalseValue();
9498       Value *Cond = Select->getCondition();
9499 
9500       // TODO: Support inverse predicates.
9501       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9502         if (!isa<ExtractElementInst>(RHS) ||
9503             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9504           return RecurKind::None;
9505       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9506         if (!isa<ExtractElementInst>(LHS) ||
9507             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9508           return RecurKind::None;
9509       } else {
9510         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9511           return RecurKind::None;
9512         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9513             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9514             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9515           return RecurKind::None;
9516       }
9517 
9518       switch (Pred) {
9519       default:
9520         return RecurKind::None;
9521       case CmpInst::ICMP_SGT:
9522       case CmpInst::ICMP_SGE:
9523         return RecurKind::SMax;
9524       case CmpInst::ICMP_SLT:
9525       case CmpInst::ICMP_SLE:
9526         return RecurKind::SMin;
9527       case CmpInst::ICMP_UGT:
9528       case CmpInst::ICMP_UGE:
9529         return RecurKind::UMax;
9530       case CmpInst::ICMP_ULT:
9531       case CmpInst::ICMP_ULE:
9532         return RecurKind::UMin;
9533       }
9534     }
9535     return RecurKind::None;
9536   }
9537 
9538   /// Get the index of the first operand.
9539   static unsigned getFirstOperandIndex(Instruction *I) {
9540     return isCmpSelMinMax(I) ? 1 : 0;
9541   }
9542 
9543   /// Total number of operands in the reduction operation.
9544   static unsigned getNumberOfOperands(Instruction *I) {
9545     return isCmpSelMinMax(I) ? 3 : 2;
9546   }
9547 
9548   /// Checks if the instruction is in basic block \p BB.
9549   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9550   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9551     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9552       auto *Sel = cast<SelectInst>(I);
9553       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9554       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9555     }
9556     return I->getParent() == BB;
9557   }
9558 
9559   /// Expected number of uses for reduction operations/reduced values.
9560   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9561     if (IsCmpSelMinMax) {
9562       // SelectInst must be used twice while the condition op must have single
9563       // use only.
9564       if (auto *Sel = dyn_cast<SelectInst>(I))
9565         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9566       return I->hasNUses(2);
9567     }
9568 
9569     // Arithmetic reduction operation must be used once only.
9570     return I->hasOneUse();
9571   }
9572 
9573   /// Initializes the list of reduction operations.
9574   void initReductionOps(Instruction *I) {
9575     if (isCmpSelMinMax(I))
9576       ReductionOps.assign(2, ReductionOpsType());
9577     else
9578       ReductionOps.assign(1, ReductionOpsType());
9579   }
9580 
9581   /// Add all reduction operations for the reduction instruction \p I.
9582   void addReductionOps(Instruction *I) {
9583     if (isCmpSelMinMax(I)) {
9584       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9585       ReductionOps[1].emplace_back(I);
9586     } else {
9587       ReductionOps[0].emplace_back(I);
9588     }
9589   }
9590 
9591   static Value *getLHS(RecurKind Kind, Instruction *I) {
9592     if (Kind == RecurKind::None)
9593       return nullptr;
9594     return I->getOperand(getFirstOperandIndex(I));
9595   }
9596   static Value *getRHS(RecurKind Kind, Instruction *I) {
9597     if (Kind == RecurKind::None)
9598       return nullptr;
9599     return I->getOperand(getFirstOperandIndex(I) + 1);
9600   }
9601 
9602 public:
9603   HorizontalReduction() = default;
9604 
9605   /// Try to find a reduction tree.
9606   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9607     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9608            "Phi needs to use the binary operator");
9609     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9610             isa<IntrinsicInst>(Inst)) &&
9611            "Expected binop, select, or intrinsic for reduction matching");
9612     RdxKind = getRdxKind(Inst);
9613 
9614     // We could have a initial reductions that is not an add.
9615     //  r *= v1 + v2 + v3 + v4
9616     // In such a case start looking for a tree rooted in the first '+'.
9617     if (Phi) {
9618       if (getLHS(RdxKind, Inst) == Phi) {
9619         Phi = nullptr;
9620         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9621         if (!Inst)
9622           return false;
9623         RdxKind = getRdxKind(Inst);
9624       } else if (getRHS(RdxKind, Inst) == Phi) {
9625         Phi = nullptr;
9626         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9627         if (!Inst)
9628           return false;
9629         RdxKind = getRdxKind(Inst);
9630       }
9631     }
9632 
9633     if (!isVectorizable(RdxKind, Inst))
9634       return false;
9635 
9636     // Analyze "regular" integer/FP types for reductions - no target-specific
9637     // types or pointers.
9638     Type *Ty = Inst->getType();
9639     if (!isValidElementType(Ty) || Ty->isPointerTy())
9640       return false;
9641 
9642     // Though the ultimate reduction may have multiple uses, its condition must
9643     // have only single use.
9644     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9645       if (!Sel->getCondition()->hasOneUse())
9646         return false;
9647 
9648     ReductionRoot = Inst;
9649 
9650     // The opcode for leaf values that we perform a reduction on.
9651     // For example: load(x) + load(y) + load(z) + fptoui(w)
9652     // The leaf opcode for 'w' does not match, so we don't include it as a
9653     // potential candidate for the reduction.
9654     unsigned LeafOpcode = 0;
9655 
9656     // Post-order traverse the reduction tree starting at Inst. We only handle
9657     // true trees containing binary operators or selects.
9658     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9659     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9660     initReductionOps(Inst);
9661     while (!Stack.empty()) {
9662       Instruction *TreeN = Stack.back().first;
9663       unsigned EdgeToVisit = Stack.back().second++;
9664       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9665       bool IsReducedValue = TreeRdxKind != RdxKind;
9666 
9667       // Postorder visit.
9668       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9669         if (IsReducedValue)
9670           ReducedVals.push_back(TreeN);
9671         else {
9672           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9673           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9674             // Check if TreeN is an extra argument of its parent operation.
9675             if (Stack.size() <= 1) {
9676               // TreeN can't be an extra argument as it is a root reduction
9677               // operation.
9678               return false;
9679             }
9680             // Yes, TreeN is an extra argument, do not add it to a list of
9681             // reduction operations.
9682             // Stack[Stack.size() - 2] always points to the parent operation.
9683             markExtraArg(Stack[Stack.size() - 2], TreeN);
9684             ExtraArgs.erase(TreeN);
9685           } else
9686             addReductionOps(TreeN);
9687         }
9688         // Retract.
9689         Stack.pop_back();
9690         continue;
9691       }
9692 
9693       // Visit operands.
9694       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9695       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9696       if (!EdgeInst) {
9697         // Edge value is not a reduction instruction or a leaf instruction.
9698         // (It may be a constant, function argument, or something else.)
9699         markExtraArg(Stack.back(), EdgeVal);
9700         continue;
9701       }
9702       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9703       // Continue analysis if the next operand is a reduction operation or
9704       // (possibly) a leaf value. If the leaf value opcode is not set,
9705       // the first met operation != reduction operation is considered as the
9706       // leaf opcode.
9707       // Only handle trees in the current basic block.
9708       // Each tree node needs to have minimal number of users except for the
9709       // ultimate reduction.
9710       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9711       if (EdgeInst != Phi && EdgeInst != Inst &&
9712           hasSameParent(EdgeInst, Inst->getParent()) &&
9713           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9714           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9715         if (IsRdxInst) {
9716           // We need to be able to reassociate the reduction operations.
9717           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9718             // I is an extra argument for TreeN (its parent operation).
9719             markExtraArg(Stack.back(), EdgeInst);
9720             continue;
9721           }
9722         } else if (!LeafOpcode) {
9723           LeafOpcode = EdgeInst->getOpcode();
9724         }
9725         Stack.push_back(
9726             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9727         continue;
9728       }
9729       // I is an extra argument for TreeN (its parent operation).
9730       markExtraArg(Stack.back(), EdgeInst);
9731     }
9732     return true;
9733   }
9734 
9735   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9736   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9737     // If there are a sufficient number of reduction values, reduce
9738     // to a nearby power-of-2. We can safely generate oversized
9739     // vectors and rely on the backend to split them to legal sizes.
9740     unsigned NumReducedVals = ReducedVals.size();
9741     if (NumReducedVals < 4)
9742       return nullptr;
9743 
9744     // Intersect the fast-math-flags from all reduction operations.
9745     FastMathFlags RdxFMF;
9746     RdxFMF.set();
9747     for (ReductionOpsType &RdxOp : ReductionOps) {
9748       for (Value *RdxVal : RdxOp) {
9749         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9750           RdxFMF &= FPMO->getFastMathFlags();
9751       }
9752     }
9753 
9754     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9755     Builder.setFastMathFlags(RdxFMF);
9756 
9757     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9758     // The same extra argument may be used several times, so log each attempt
9759     // to use it.
9760     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9761       assert(Pair.first && "DebugLoc must be set.");
9762       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9763     }
9764 
9765     // The compare instruction of a min/max is the insertion point for new
9766     // instructions and may be replaced with a new compare instruction.
9767     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9768       assert(isa<SelectInst>(RdxRootInst) &&
9769              "Expected min/max reduction to have select root instruction");
9770       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9771       assert(isa<Instruction>(ScalarCond) &&
9772              "Expected min/max reduction to have compare condition");
9773       return cast<Instruction>(ScalarCond);
9774     };
9775 
9776     // The reduction root is used as the insertion point for new instructions,
9777     // so set it as externally used to prevent it from being deleted.
9778     ExternallyUsedValues[ReductionRoot];
9779     SmallVector<Value *, 16> IgnoreList;
9780     for (ReductionOpsType &RdxOp : ReductionOps)
9781       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9782 
9783     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9784     if (NumReducedVals > ReduxWidth) {
9785       // In the loop below, we are building a tree based on a window of
9786       // 'ReduxWidth' values.
9787       // If the operands of those values have common traits (compare predicate,
9788       // constant operand, etc), then we want to group those together to
9789       // minimize the cost of the reduction.
9790 
9791       // TODO: This should be extended to count common operands for
9792       //       compares and binops.
9793 
9794       // Step 1: Count the number of times each compare predicate occurs.
9795       SmallDenseMap<unsigned, unsigned> PredCountMap;
9796       for (Value *RdxVal : ReducedVals) {
9797         CmpInst::Predicate Pred;
9798         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9799           ++PredCountMap[Pred];
9800       }
9801       // Step 2: Sort the values so the most common predicates come first.
9802       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9803         CmpInst::Predicate PredA, PredB;
9804         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9805             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9806           return PredCountMap[PredA] > PredCountMap[PredB];
9807         }
9808         return false;
9809       });
9810     }
9811 
9812     Value *VectorizedTree = nullptr;
9813     unsigned i = 0;
9814     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9815       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9816       V.buildTree(VL, IgnoreList);
9817       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9818         break;
9819       if (V.isLoadCombineReductionCandidate(RdxKind))
9820         break;
9821       V.reorderTopToBottom();
9822       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9823       V.buildExternalUses(ExternallyUsedValues);
9824 
9825       // For a poison-safe boolean logic reduction, do not replace select
9826       // instructions with logic ops. All reduced values will be frozen (see
9827       // below) to prevent leaking poison.
9828       if (isa<SelectInst>(ReductionRoot) &&
9829           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9830           NumReducedVals != ReduxWidth)
9831         break;
9832 
9833       V.computeMinimumValueSizes();
9834 
9835       // Estimate cost.
9836       InstructionCost TreeCost =
9837           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9838       InstructionCost ReductionCost =
9839           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9840       InstructionCost Cost = TreeCost + ReductionCost;
9841       if (!Cost.isValid()) {
9842         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9843         return nullptr;
9844       }
9845       if (Cost >= -SLPCostThreshold) {
9846         V.getORE()->emit([&]() {
9847           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9848                                           cast<Instruction>(VL[0]))
9849                  << "Vectorizing horizontal reduction is possible"
9850                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9851                  << " and threshold "
9852                  << ore::NV("Threshold", -SLPCostThreshold);
9853         });
9854         break;
9855       }
9856 
9857       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9858                         << Cost << ". (HorRdx)\n");
9859       V.getORE()->emit([&]() {
9860         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9861                                   cast<Instruction>(VL[0]))
9862                << "Vectorized horizontal reduction with cost "
9863                << ore::NV("Cost", Cost) << " and with tree size "
9864                << ore::NV("TreeSize", V.getTreeSize());
9865       });
9866 
9867       // Vectorize a tree.
9868       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9869       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9870 
9871       // Emit a reduction. If the root is a select (min/max idiom), the insert
9872       // point is the compare condition of that select.
9873       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9874       if (isCmpSelMinMax(RdxRootInst))
9875         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9876       else
9877         Builder.SetInsertPoint(RdxRootInst);
9878 
9879       // To prevent poison from leaking across what used to be sequential, safe,
9880       // scalar boolean logic operations, the reduction operand must be frozen.
9881       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9882         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9883 
9884       Value *ReducedSubTree =
9885           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9886 
9887       if (!VectorizedTree) {
9888         // Initialize the final value in the reduction.
9889         VectorizedTree = ReducedSubTree;
9890       } else {
9891         // Update the final value in the reduction.
9892         Builder.SetCurrentDebugLocation(Loc);
9893         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9894                                   ReducedSubTree, "op.rdx", ReductionOps);
9895       }
9896       i += ReduxWidth;
9897       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9898     }
9899 
9900     if (VectorizedTree) {
9901       // Finish the reduction.
9902       for (; i < NumReducedVals; ++i) {
9903         auto *I = cast<Instruction>(ReducedVals[i]);
9904         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9905         VectorizedTree =
9906             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9907       }
9908       for (auto &Pair : ExternallyUsedValues) {
9909         // Add each externally used value to the final reduction.
9910         for (auto *I : Pair.second) {
9911           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9912           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9913                                     Pair.first, "op.extra", I);
9914         }
9915       }
9916 
9917       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9918 
9919       // The original scalar reduction is expected to have no remaining
9920       // uses outside the reduction tree itself.  Assert that we got this
9921       // correct, replace internal uses with undef, and mark for eventual
9922       // deletion.
9923 #ifndef NDEBUG
9924       SmallSet<Value *, 4> IgnoreSet;
9925       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9926 #endif
9927       for (auto *Ignore : IgnoreList) {
9928 #ifndef NDEBUG
9929         for (auto *U : Ignore->users()) {
9930           assert(IgnoreSet.count(U));
9931         }
9932 #endif
9933         if (!Ignore->use_empty()) {
9934           Value *Undef = UndefValue::get(Ignore->getType());
9935           Ignore->replaceAllUsesWith(Undef);
9936         }
9937         V.eraseInstruction(cast<Instruction>(Ignore));
9938       }
9939     }
9940     return VectorizedTree;
9941   }
9942 
9943   unsigned numReductionValues() const { return ReducedVals.size(); }
9944 
9945 private:
9946   /// Calculate the cost of a reduction.
9947   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9948                                    Value *FirstReducedVal, unsigned ReduxWidth,
9949                                    FastMathFlags FMF) {
9950     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9951     Type *ScalarTy = FirstReducedVal->getType();
9952     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9953     InstructionCost VectorCost, ScalarCost;
9954     switch (RdxKind) {
9955     case RecurKind::Add:
9956     case RecurKind::Mul:
9957     case RecurKind::Or:
9958     case RecurKind::And:
9959     case RecurKind::Xor:
9960     case RecurKind::FAdd:
9961     case RecurKind::FMul: {
9962       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9963       VectorCost =
9964           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9965       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9966       break;
9967     }
9968     case RecurKind::FMax:
9969     case RecurKind::FMin: {
9970       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9971       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9972       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9973                                                /*IsUnsigned=*/false, CostKind);
9974       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9975       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9976                                            SclCondTy, RdxPred, CostKind) +
9977                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9978                                            SclCondTy, RdxPred, CostKind);
9979       break;
9980     }
9981     case RecurKind::SMax:
9982     case RecurKind::SMin:
9983     case RecurKind::UMax:
9984     case RecurKind::UMin: {
9985       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9986       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9987       bool IsUnsigned =
9988           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9989       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9990                                                CostKind);
9991       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9992       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9993                                            SclCondTy, RdxPred, CostKind) +
9994                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9995                                            SclCondTy, RdxPred, CostKind);
9996       break;
9997     }
9998     default:
9999       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10000     }
10001 
10002     // Scalar cost is repeated for N-1 elements.
10003     ScalarCost *= (ReduxWidth - 1);
10004     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10005                       << " for reduction that starts with " << *FirstReducedVal
10006                       << " (It is a splitting reduction)\n");
10007     return VectorCost - ScalarCost;
10008   }
10009 
10010   /// Emit a horizontal reduction of the vectorized value.
10011   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10012                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10013     assert(VectorizedValue && "Need to have a vectorized tree node");
10014     assert(isPowerOf2_32(ReduxWidth) &&
10015            "We only handle power-of-two reductions for now");
10016     assert(RdxKind != RecurKind::FMulAdd &&
10017            "A call to the llvm.fmuladd intrinsic is not handled yet");
10018 
10019     ++NumVectorInstructions;
10020     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10021   }
10022 };
10023 
10024 } // end anonymous namespace
10025 
10026 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10027   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10028     return cast<FixedVectorType>(IE->getType())->getNumElements();
10029 
10030   unsigned AggregateSize = 1;
10031   auto *IV = cast<InsertValueInst>(InsertInst);
10032   Type *CurrentType = IV->getType();
10033   do {
10034     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10035       for (auto *Elt : ST->elements())
10036         if (Elt != ST->getElementType(0)) // check homogeneity
10037           return None;
10038       AggregateSize *= ST->getNumElements();
10039       CurrentType = ST->getElementType(0);
10040     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10041       AggregateSize *= AT->getNumElements();
10042       CurrentType = AT->getElementType();
10043     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10044       AggregateSize *= VT->getNumElements();
10045       return AggregateSize;
10046     } else if (CurrentType->isSingleValueType()) {
10047       return AggregateSize;
10048     } else {
10049       return None;
10050     }
10051   } while (true);
10052 }
10053 
10054 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10055                                    TargetTransformInfo *TTI,
10056                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10057                                    SmallVectorImpl<Value *> &InsertElts,
10058                                    unsigned OperandOffset) {
10059   do {
10060     Value *InsertedOperand = LastInsertInst->getOperand(1);
10061     Optional<unsigned> OperandIndex =
10062         getInsertIndex(LastInsertInst, OperandOffset);
10063     if (!OperandIndex)
10064       return;
10065     if (isa<InsertElementInst>(InsertedOperand) ||
10066         isa<InsertValueInst>(InsertedOperand)) {
10067       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10068                              BuildVectorOpds, InsertElts, *OperandIndex);
10069 
10070     } else {
10071       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10072       InsertElts[*OperandIndex] = LastInsertInst;
10073     }
10074     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10075   } while (LastInsertInst != nullptr &&
10076            (isa<InsertValueInst>(LastInsertInst) ||
10077             isa<InsertElementInst>(LastInsertInst)) &&
10078            LastInsertInst->hasOneUse());
10079 }
10080 
10081 /// Recognize construction of vectors like
10082 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10083 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10084 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10085 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10086 ///  starting from the last insertelement or insertvalue instruction.
10087 ///
10088 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10089 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10090 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10091 ///
10092 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10093 ///
10094 /// \return true if it matches.
10095 static bool findBuildAggregate(Instruction *LastInsertInst,
10096                                TargetTransformInfo *TTI,
10097                                SmallVectorImpl<Value *> &BuildVectorOpds,
10098                                SmallVectorImpl<Value *> &InsertElts) {
10099 
10100   assert((isa<InsertElementInst>(LastInsertInst) ||
10101           isa<InsertValueInst>(LastInsertInst)) &&
10102          "Expected insertelement or insertvalue instruction!");
10103 
10104   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10105          "Expected empty result vectors!");
10106 
10107   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10108   if (!AggregateSize)
10109     return false;
10110   BuildVectorOpds.resize(*AggregateSize);
10111   InsertElts.resize(*AggregateSize);
10112 
10113   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10114   llvm::erase_value(BuildVectorOpds, nullptr);
10115   llvm::erase_value(InsertElts, nullptr);
10116   if (BuildVectorOpds.size() >= 2)
10117     return true;
10118 
10119   return false;
10120 }
10121 
10122 /// Try and get a reduction value from a phi node.
10123 ///
10124 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10125 /// if they come from either \p ParentBB or a containing loop latch.
10126 ///
10127 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10128 /// if not possible.
10129 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10130                                 BasicBlock *ParentBB, LoopInfo *LI) {
10131   // There are situations where the reduction value is not dominated by the
10132   // reduction phi. Vectorizing such cases has been reported to cause
10133   // miscompiles. See PR25787.
10134   auto DominatedReduxValue = [&](Value *R) {
10135     return isa<Instruction>(R) &&
10136            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10137   };
10138 
10139   Value *Rdx = nullptr;
10140 
10141   // Return the incoming value if it comes from the same BB as the phi node.
10142   if (P->getIncomingBlock(0) == ParentBB) {
10143     Rdx = P->getIncomingValue(0);
10144   } else if (P->getIncomingBlock(1) == ParentBB) {
10145     Rdx = P->getIncomingValue(1);
10146   }
10147 
10148   if (Rdx && DominatedReduxValue(Rdx))
10149     return Rdx;
10150 
10151   // Otherwise, check whether we have a loop latch to look at.
10152   Loop *BBL = LI->getLoopFor(ParentBB);
10153   if (!BBL)
10154     return nullptr;
10155   BasicBlock *BBLatch = BBL->getLoopLatch();
10156   if (!BBLatch)
10157     return nullptr;
10158 
10159   // There is a loop latch, return the incoming value if it comes from
10160   // that. This reduction pattern occasionally turns up.
10161   if (P->getIncomingBlock(0) == BBLatch) {
10162     Rdx = P->getIncomingValue(0);
10163   } else if (P->getIncomingBlock(1) == BBLatch) {
10164     Rdx = P->getIncomingValue(1);
10165   }
10166 
10167   if (Rdx && DominatedReduxValue(Rdx))
10168     return Rdx;
10169 
10170   return nullptr;
10171 }
10172 
10173 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10174   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10175     return true;
10176   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10177     return true;
10178   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10179     return true;
10180   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10181     return true;
10182   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10183     return true;
10184   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10185     return true;
10186   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10187     return true;
10188   return false;
10189 }
10190 
10191 /// Attempt to reduce a horizontal reduction.
10192 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10193 /// with reduction operators \a Root (or one of its operands) in a basic block
10194 /// \a BB, then check if it can be done. If horizontal reduction is not found
10195 /// and root instruction is a binary operation, vectorization of the operands is
10196 /// attempted.
10197 /// \returns true if a horizontal reduction was matched and reduced or operands
10198 /// of one of the binary instruction were vectorized.
10199 /// \returns false if a horizontal reduction was not matched (or not possible)
10200 /// or no vectorization of any binary operation feeding \a Root instruction was
10201 /// performed.
10202 static bool tryToVectorizeHorReductionOrInstOperands(
10203     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10204     TargetTransformInfo *TTI,
10205     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10206   if (!ShouldVectorizeHor)
10207     return false;
10208 
10209   if (!Root)
10210     return false;
10211 
10212   if (Root->getParent() != BB || isa<PHINode>(Root))
10213     return false;
10214   // Start analysis starting from Root instruction. If horizontal reduction is
10215   // found, try to vectorize it. If it is not a horizontal reduction or
10216   // vectorization is not possible or not effective, and currently analyzed
10217   // instruction is a binary operation, try to vectorize the operands, using
10218   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10219   // the same procedure considering each operand as a possible root of the
10220   // horizontal reduction.
10221   // Interrupt the process if the Root instruction itself was vectorized or all
10222   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10223   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10224   // CmpInsts so we can skip extra attempts in
10225   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10226   std::queue<std::pair<Instruction *, unsigned>> Stack;
10227   Stack.emplace(Root, 0);
10228   SmallPtrSet<Value *, 8> VisitedInstrs;
10229   SmallVector<WeakTrackingVH> PostponedInsts;
10230   bool Res = false;
10231   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10232                                      Value *&B1) -> Value * {
10233     bool IsBinop = matchRdxBop(Inst, B0, B1);
10234     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10235     if (IsBinop || IsSelect) {
10236       HorizontalReduction HorRdx;
10237       if (HorRdx.matchAssociativeReduction(P, Inst))
10238         return HorRdx.tryToReduce(R, TTI);
10239     }
10240     return nullptr;
10241   };
10242   while (!Stack.empty()) {
10243     Instruction *Inst;
10244     unsigned Level;
10245     std::tie(Inst, Level) = Stack.front();
10246     Stack.pop();
10247     // Do not try to analyze instruction that has already been vectorized.
10248     // This may happen when we vectorize instruction operands on a previous
10249     // iteration while stack was populated before that happened.
10250     if (R.isDeleted(Inst))
10251       continue;
10252     Value *B0 = nullptr, *B1 = nullptr;
10253     if (Value *V = TryToReduce(Inst, B0, B1)) {
10254       Res = true;
10255       // Set P to nullptr to avoid re-analysis of phi node in
10256       // matchAssociativeReduction function unless this is the root node.
10257       P = nullptr;
10258       if (auto *I = dyn_cast<Instruction>(V)) {
10259         // Try to find another reduction.
10260         Stack.emplace(I, Level);
10261         continue;
10262       }
10263     } else {
10264       bool IsBinop = B0 && B1;
10265       if (P && IsBinop) {
10266         Inst = dyn_cast<Instruction>(B0);
10267         if (Inst == P)
10268           Inst = dyn_cast<Instruction>(B1);
10269         if (!Inst) {
10270           // Set P to nullptr to avoid re-analysis of phi node in
10271           // matchAssociativeReduction function unless this is the root node.
10272           P = nullptr;
10273           continue;
10274         }
10275       }
10276       // Set P to nullptr to avoid re-analysis of phi node in
10277       // matchAssociativeReduction function unless this is the root node.
10278       P = nullptr;
10279       // Do not try to vectorize CmpInst operands, this is done separately.
10280       // Final attempt for binop args vectorization should happen after the loop
10281       // to try to find reductions.
10282       if (!isa<CmpInst>(Inst))
10283         PostponedInsts.push_back(Inst);
10284     }
10285 
10286     // Try to vectorize operands.
10287     // Continue analysis for the instruction from the same basic block only to
10288     // save compile time.
10289     if (++Level < RecursionMaxDepth)
10290       for (auto *Op : Inst->operand_values())
10291         if (VisitedInstrs.insert(Op).second)
10292           if (auto *I = dyn_cast<Instruction>(Op))
10293             // Do not try to vectorize CmpInst operands,  this is done
10294             // separately.
10295             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10296                 I->getParent() == BB)
10297               Stack.emplace(I, Level);
10298   }
10299   // Try to vectorized binops where reductions were not found.
10300   for (Value *V : PostponedInsts)
10301     if (auto *Inst = dyn_cast<Instruction>(V))
10302       if (!R.isDeleted(Inst))
10303         Res |= Vectorize(Inst, R);
10304   return Res;
10305 }
10306 
10307 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10308                                                  BasicBlock *BB, BoUpSLP &R,
10309                                                  TargetTransformInfo *TTI) {
10310   auto *I = dyn_cast_or_null<Instruction>(V);
10311   if (!I)
10312     return false;
10313 
10314   if (!isa<BinaryOperator>(I))
10315     P = nullptr;
10316   // Try to match and vectorize a horizontal reduction.
10317   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10318     return tryToVectorize(I, R);
10319   };
10320   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10321                                                   ExtraVectorization);
10322 }
10323 
10324 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10325                                                  BasicBlock *BB, BoUpSLP &R) {
10326   const DataLayout &DL = BB->getModule()->getDataLayout();
10327   if (!R.canMapToVector(IVI->getType(), DL))
10328     return false;
10329 
10330   SmallVector<Value *, 16> BuildVectorOpds;
10331   SmallVector<Value *, 16> BuildVectorInsts;
10332   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10333     return false;
10334 
10335   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10336   // Aggregate value is unlikely to be processed in vector register.
10337   return tryToVectorizeList(BuildVectorOpds, R);
10338 }
10339 
10340 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10341                                                    BasicBlock *BB, BoUpSLP &R) {
10342   SmallVector<Value *, 16> BuildVectorInsts;
10343   SmallVector<Value *, 16> BuildVectorOpds;
10344   SmallVector<int> Mask;
10345   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10346       (llvm::all_of(
10347            BuildVectorOpds,
10348            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10349        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10350     return false;
10351 
10352   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10353   return tryToVectorizeList(BuildVectorInsts, R);
10354 }
10355 
10356 template <typename T>
10357 static bool
10358 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10359                        function_ref<unsigned(T *)> Limit,
10360                        function_ref<bool(T *, T *)> Comparator,
10361                        function_ref<bool(T *, T *)> AreCompatible,
10362                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10363                        bool LimitForRegisterSize) {
10364   bool Changed = false;
10365   // Sort by type, parent, operands.
10366   stable_sort(Incoming, Comparator);
10367 
10368   // Try to vectorize elements base on their type.
10369   SmallVector<T *> Candidates;
10370   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10371     // Look for the next elements with the same type, parent and operand
10372     // kinds.
10373     auto *SameTypeIt = IncIt;
10374     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10375       ++SameTypeIt;
10376 
10377     // Try to vectorize them.
10378     unsigned NumElts = (SameTypeIt - IncIt);
10379     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10380                       << NumElts << ")\n");
10381     // The vectorization is a 3-state attempt:
10382     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10383     // size of maximal register at first.
10384     // 2. Try to vectorize remaining instructions with the same type, if
10385     // possible. This may result in the better vectorization results rather than
10386     // if we try just to vectorize instructions with the same/alternate opcodes.
10387     // 3. Final attempt to try to vectorize all instructions with the
10388     // same/alternate ops only, this may result in some extra final
10389     // vectorization.
10390     if (NumElts > 1 &&
10391         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10392       // Success start over because instructions might have been changed.
10393       Changed = true;
10394     } else if (NumElts < Limit(*IncIt) &&
10395                (Candidates.empty() ||
10396                 Candidates.front()->getType() == (*IncIt)->getType())) {
10397       Candidates.append(IncIt, std::next(IncIt, NumElts));
10398     }
10399     // Final attempt to vectorize instructions with the same types.
10400     if (Candidates.size() > 1 &&
10401         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10402       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10403         // Success start over because instructions might have been changed.
10404         Changed = true;
10405       } else if (LimitForRegisterSize) {
10406         // Try to vectorize using small vectors.
10407         for (auto *It = Candidates.begin(), *End = Candidates.end();
10408              It != End;) {
10409           auto *SameTypeIt = It;
10410           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10411             ++SameTypeIt;
10412           unsigned NumElts = (SameTypeIt - It);
10413           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10414                                             /*LimitForRegisterSize=*/false))
10415             Changed = true;
10416           It = SameTypeIt;
10417         }
10418       }
10419       Candidates.clear();
10420     }
10421 
10422     // Start over at the next instruction of a different type (or the end).
10423     IncIt = SameTypeIt;
10424   }
10425   return Changed;
10426 }
10427 
10428 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10429 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10430 /// operands. If IsCompatibility is false, function implements strict weak
10431 /// ordering relation between two cmp instructions, returning true if the first
10432 /// instruction is "less" than the second, i.e. its predicate is less than the
10433 /// predicate of the second or the operands IDs are less than the operands IDs
10434 /// of the second cmp instruction.
10435 template <bool IsCompatibility>
10436 static bool compareCmp(Value *V, Value *V2,
10437                        function_ref<bool(Instruction *)> IsDeleted) {
10438   auto *CI1 = cast<CmpInst>(V);
10439   auto *CI2 = cast<CmpInst>(V2);
10440   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10441     return false;
10442   if (CI1->getOperand(0)->getType()->getTypeID() <
10443       CI2->getOperand(0)->getType()->getTypeID())
10444     return !IsCompatibility;
10445   if (CI1->getOperand(0)->getType()->getTypeID() >
10446       CI2->getOperand(0)->getType()->getTypeID())
10447     return false;
10448   CmpInst::Predicate Pred1 = CI1->getPredicate();
10449   CmpInst::Predicate Pred2 = CI2->getPredicate();
10450   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10451   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10452   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10453   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10454   if (BasePred1 < BasePred2)
10455     return !IsCompatibility;
10456   if (BasePred1 > BasePred2)
10457     return false;
10458   // Compare operands.
10459   bool LEPreds = Pred1 <= Pred2;
10460   bool GEPreds = Pred1 >= Pred2;
10461   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10462     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10463     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10464     if (Op1->getValueID() < Op2->getValueID())
10465       return !IsCompatibility;
10466     if (Op1->getValueID() > Op2->getValueID())
10467       return false;
10468     if (auto *I1 = dyn_cast<Instruction>(Op1))
10469       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10470         if (I1->getParent() != I2->getParent())
10471           return false;
10472         InstructionsState S = getSameOpcode({I1, I2});
10473         if (S.getOpcode())
10474           continue;
10475         return false;
10476       }
10477   }
10478   return IsCompatibility;
10479 }
10480 
10481 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10482     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10483     bool AtTerminator) {
10484   bool OpsChanged = false;
10485   SmallVector<Instruction *, 4> PostponedCmps;
10486   for (auto *I : reverse(Instructions)) {
10487     if (R.isDeleted(I))
10488       continue;
10489     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10490       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10491     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10492       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10493     else if (isa<CmpInst>(I))
10494       PostponedCmps.push_back(I);
10495   }
10496   if (AtTerminator) {
10497     // Try to find reductions first.
10498     for (Instruction *I : PostponedCmps) {
10499       if (R.isDeleted(I))
10500         continue;
10501       for (Value *Op : I->operands())
10502         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10503     }
10504     // Try to vectorize operands as vector bundles.
10505     for (Instruction *I : PostponedCmps) {
10506       if (R.isDeleted(I))
10507         continue;
10508       OpsChanged |= tryToVectorize(I, R);
10509     }
10510     // Try to vectorize list of compares.
10511     // Sort by type, compare predicate, etc.
10512     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10513       return compareCmp<false>(V, V2,
10514                                [&R](Instruction *I) { return R.isDeleted(I); });
10515     };
10516 
10517     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10518       if (V1 == V2)
10519         return true;
10520       return compareCmp<true>(V1, V2,
10521                               [&R](Instruction *I) { return R.isDeleted(I); });
10522     };
10523     auto Limit = [&R](Value *V) {
10524       unsigned EltSize = R.getVectorElementSize(V);
10525       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10526     };
10527 
10528     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10529     OpsChanged |= tryToVectorizeSequence<Value>(
10530         Vals, Limit, CompareSorter, AreCompatibleCompares,
10531         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10532           // Exclude possible reductions from other blocks.
10533           bool ArePossiblyReducedInOtherBlock =
10534               any_of(Candidates, [](Value *V) {
10535                 return any_of(V->users(), [V](User *U) {
10536                   return isa<SelectInst>(U) &&
10537                          cast<SelectInst>(U)->getParent() !=
10538                              cast<Instruction>(V)->getParent();
10539                 });
10540               });
10541           if (ArePossiblyReducedInOtherBlock)
10542             return false;
10543           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10544         },
10545         /*LimitForRegisterSize=*/true);
10546     Instructions.clear();
10547   } else {
10548     // Insert in reverse order since the PostponedCmps vector was filled in
10549     // reverse order.
10550     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10551   }
10552   return OpsChanged;
10553 }
10554 
10555 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10556   bool Changed = false;
10557   SmallVector<Value *, 4> Incoming;
10558   SmallPtrSet<Value *, 16> VisitedInstrs;
10559   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10560   // node. Allows better to identify the chains that can be vectorized in the
10561   // better way.
10562   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10563   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10564     assert(isValidElementType(V1->getType()) &&
10565            isValidElementType(V2->getType()) &&
10566            "Expected vectorizable types only.");
10567     // It is fine to compare type IDs here, since we expect only vectorizable
10568     // types, like ints, floats and pointers, we don't care about other type.
10569     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10570       return true;
10571     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10572       return false;
10573     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10574     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10575     if (Opcodes1.size() < Opcodes2.size())
10576       return true;
10577     if (Opcodes1.size() > Opcodes2.size())
10578       return false;
10579     Optional<bool> ConstOrder;
10580     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10581       // Undefs are compatible with any other value.
10582       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10583         if (!ConstOrder)
10584           ConstOrder =
10585               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10586         continue;
10587       }
10588       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10589         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10590           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10591           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10592           if (!NodeI1)
10593             return NodeI2 != nullptr;
10594           if (!NodeI2)
10595             return false;
10596           assert((NodeI1 == NodeI2) ==
10597                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10598                  "Different nodes should have different DFS numbers");
10599           if (NodeI1 != NodeI2)
10600             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10601           InstructionsState S = getSameOpcode({I1, I2});
10602           if (S.getOpcode())
10603             continue;
10604           return I1->getOpcode() < I2->getOpcode();
10605         }
10606       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10607         if (!ConstOrder)
10608           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10609         continue;
10610       }
10611       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10612         return true;
10613       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10614         return false;
10615     }
10616     return ConstOrder && *ConstOrder;
10617   };
10618   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10619     if (V1 == V2)
10620       return true;
10621     if (V1->getType() != V2->getType())
10622       return false;
10623     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10624     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10625     if (Opcodes1.size() != Opcodes2.size())
10626       return false;
10627     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10628       // Undefs are compatible with any other value.
10629       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10630         continue;
10631       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10632         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10633           if (I1->getParent() != I2->getParent())
10634             return false;
10635           InstructionsState S = getSameOpcode({I1, I2});
10636           if (S.getOpcode())
10637             continue;
10638           return false;
10639         }
10640       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10641         continue;
10642       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10643         return false;
10644     }
10645     return true;
10646   };
10647   auto Limit = [&R](Value *V) {
10648     unsigned EltSize = R.getVectorElementSize(V);
10649     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10650   };
10651 
10652   bool HaveVectorizedPhiNodes = false;
10653   do {
10654     // Collect the incoming values from the PHIs.
10655     Incoming.clear();
10656     for (Instruction &I : *BB) {
10657       PHINode *P = dyn_cast<PHINode>(&I);
10658       if (!P)
10659         break;
10660 
10661       // No need to analyze deleted, vectorized and non-vectorizable
10662       // instructions.
10663       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10664           isValidElementType(P->getType()))
10665         Incoming.push_back(P);
10666     }
10667 
10668     // Find the corresponding non-phi nodes for better matching when trying to
10669     // build the tree.
10670     for (Value *V : Incoming) {
10671       SmallVectorImpl<Value *> &Opcodes =
10672           PHIToOpcodes.try_emplace(V).first->getSecond();
10673       if (!Opcodes.empty())
10674         continue;
10675       SmallVector<Value *, 4> Nodes(1, V);
10676       SmallPtrSet<Value *, 4> Visited;
10677       while (!Nodes.empty()) {
10678         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10679         if (!Visited.insert(PHI).second)
10680           continue;
10681         for (Value *V : PHI->incoming_values()) {
10682           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10683             Nodes.push_back(PHI1);
10684             continue;
10685           }
10686           Opcodes.emplace_back(V);
10687         }
10688       }
10689     }
10690 
10691     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10692         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10693         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10694           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10695         },
10696         /*LimitForRegisterSize=*/true);
10697     Changed |= HaveVectorizedPhiNodes;
10698     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10699   } while (HaveVectorizedPhiNodes);
10700 
10701   VisitedInstrs.clear();
10702 
10703   SmallVector<Instruction *, 8> PostProcessInstructions;
10704   SmallDenseSet<Instruction *, 4> KeyNodes;
10705   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10706     // Skip instructions with scalable type. The num of elements is unknown at
10707     // compile-time for scalable type.
10708     if (isa<ScalableVectorType>(it->getType()))
10709       continue;
10710 
10711     // Skip instructions marked for the deletion.
10712     if (R.isDeleted(&*it))
10713       continue;
10714     // We may go through BB multiple times so skip the one we have checked.
10715     if (!VisitedInstrs.insert(&*it).second) {
10716       if (it->use_empty() && KeyNodes.contains(&*it) &&
10717           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10718                                       it->isTerminator())) {
10719         // We would like to start over since some instructions are deleted
10720         // and the iterator may become invalid value.
10721         Changed = true;
10722         it = BB->begin();
10723         e = BB->end();
10724       }
10725       continue;
10726     }
10727 
10728     if (isa<DbgInfoIntrinsic>(it))
10729       continue;
10730 
10731     // Try to vectorize reductions that use PHINodes.
10732     if (PHINode *P = dyn_cast<PHINode>(it)) {
10733       // Check that the PHI is a reduction PHI.
10734       if (P->getNumIncomingValues() == 2) {
10735         // Try to match and vectorize a horizontal reduction.
10736         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10737                                      TTI)) {
10738           Changed = true;
10739           it = BB->begin();
10740           e = BB->end();
10741           continue;
10742         }
10743       }
10744       // Try to vectorize the incoming values of the PHI, to catch reductions
10745       // that feed into PHIs.
10746       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10747         // Skip if the incoming block is the current BB for now. Also, bypass
10748         // unreachable IR for efficiency and to avoid crashing.
10749         // TODO: Collect the skipped incoming values and try to vectorize them
10750         // after processing BB.
10751         if (BB == P->getIncomingBlock(I) ||
10752             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10753           continue;
10754 
10755         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10756                                             P->getIncomingBlock(I), R, TTI);
10757       }
10758       continue;
10759     }
10760 
10761     // Ran into an instruction without users, like terminator, or function call
10762     // with ignored return value, store. Ignore unused instructions (basing on
10763     // instruction type, except for CallInst and InvokeInst).
10764     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10765                             isa<InvokeInst>(it))) {
10766       KeyNodes.insert(&*it);
10767       bool OpsChanged = false;
10768       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10769         for (auto *V : it->operand_values()) {
10770           // Try to match and vectorize a horizontal reduction.
10771           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10772         }
10773       }
10774       // Start vectorization of post-process list of instructions from the
10775       // top-tree instructions to try to vectorize as many instructions as
10776       // possible.
10777       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10778                                                 it->isTerminator());
10779       if (OpsChanged) {
10780         // We would like to start over since some instructions are deleted
10781         // and the iterator may become invalid value.
10782         Changed = true;
10783         it = BB->begin();
10784         e = BB->end();
10785         continue;
10786       }
10787     }
10788 
10789     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10790         isa<InsertValueInst>(it))
10791       PostProcessInstructions.push_back(&*it);
10792   }
10793 
10794   return Changed;
10795 }
10796 
10797 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10798   auto Changed = false;
10799   for (auto &Entry : GEPs) {
10800     // If the getelementptr list has fewer than two elements, there's nothing
10801     // to do.
10802     if (Entry.second.size() < 2)
10803       continue;
10804 
10805     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10806                       << Entry.second.size() << ".\n");
10807 
10808     // Process the GEP list in chunks suitable for the target's supported
10809     // vector size. If a vector register can't hold 1 element, we are done. We
10810     // are trying to vectorize the index computations, so the maximum number of
10811     // elements is based on the size of the index expression, rather than the
10812     // size of the GEP itself (the target's pointer size).
10813     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10814     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10815     if (MaxVecRegSize < EltSize)
10816       continue;
10817 
10818     unsigned MaxElts = MaxVecRegSize / EltSize;
10819     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10820       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10821       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10822 
10823       // Initialize a set a candidate getelementptrs. Note that we use a
10824       // SetVector here to preserve program order. If the index computations
10825       // are vectorizable and begin with loads, we want to minimize the chance
10826       // of having to reorder them later.
10827       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10828 
10829       // Some of the candidates may have already been vectorized after we
10830       // initially collected them. If so, they are marked as deleted, so remove
10831       // them from the set of candidates.
10832       Candidates.remove_if(
10833           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10834 
10835       // Remove from the set of candidates all pairs of getelementptrs with
10836       // constant differences. Such getelementptrs are likely not good
10837       // candidates for vectorization in a bottom-up phase since one can be
10838       // computed from the other. We also ensure all candidate getelementptr
10839       // indices are unique.
10840       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10841         auto *GEPI = GEPList[I];
10842         if (!Candidates.count(GEPI))
10843           continue;
10844         auto *SCEVI = SE->getSCEV(GEPList[I]);
10845         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10846           auto *GEPJ = GEPList[J];
10847           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10848           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10849             Candidates.remove(GEPI);
10850             Candidates.remove(GEPJ);
10851           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10852             Candidates.remove(GEPJ);
10853           }
10854         }
10855       }
10856 
10857       // We break out of the above computation as soon as we know there are
10858       // fewer than two candidates remaining.
10859       if (Candidates.size() < 2)
10860         continue;
10861 
10862       // Add the single, non-constant index of each candidate to the bundle. We
10863       // ensured the indices met these constraints when we originally collected
10864       // the getelementptrs.
10865       SmallVector<Value *, 16> Bundle(Candidates.size());
10866       auto BundleIndex = 0u;
10867       for (auto *V : Candidates) {
10868         auto *GEP = cast<GetElementPtrInst>(V);
10869         auto *GEPIdx = GEP->idx_begin()->get();
10870         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10871         Bundle[BundleIndex++] = GEPIdx;
10872       }
10873 
10874       // Try and vectorize the indices. We are currently only interested in
10875       // gather-like cases of the form:
10876       //
10877       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10878       //
10879       // where the loads of "a", the loads of "b", and the subtractions can be
10880       // performed in parallel. It's likely that detecting this pattern in a
10881       // bottom-up phase will be simpler and less costly than building a
10882       // full-blown top-down phase beginning at the consecutive loads.
10883       Changed |= tryToVectorizeList(Bundle, R);
10884     }
10885   }
10886   return Changed;
10887 }
10888 
10889 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10890   bool Changed = false;
10891   // Sort by type, base pointers and values operand. Value operands must be
10892   // compatible (have the same opcode, same parent), otherwise it is
10893   // definitely not profitable to try to vectorize them.
10894   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10895     if (V->getPointerOperandType()->getTypeID() <
10896         V2->getPointerOperandType()->getTypeID())
10897       return true;
10898     if (V->getPointerOperandType()->getTypeID() >
10899         V2->getPointerOperandType()->getTypeID())
10900       return false;
10901     // UndefValues are compatible with all other values.
10902     if (isa<UndefValue>(V->getValueOperand()) ||
10903         isa<UndefValue>(V2->getValueOperand()))
10904       return false;
10905     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10906       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10907         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10908             DT->getNode(I1->getParent());
10909         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10910             DT->getNode(I2->getParent());
10911         assert(NodeI1 && "Should only process reachable instructions");
10912         assert(NodeI2 && "Should only process reachable instructions");
10913         assert((NodeI1 == NodeI2) ==
10914                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10915                "Different nodes should have different DFS numbers");
10916         if (NodeI1 != NodeI2)
10917           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10918         InstructionsState S = getSameOpcode({I1, I2});
10919         if (S.getOpcode())
10920           return false;
10921         return I1->getOpcode() < I2->getOpcode();
10922       }
10923     if (isa<Constant>(V->getValueOperand()) &&
10924         isa<Constant>(V2->getValueOperand()))
10925       return false;
10926     return V->getValueOperand()->getValueID() <
10927            V2->getValueOperand()->getValueID();
10928   };
10929 
10930   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10931     if (V1 == V2)
10932       return true;
10933     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10934       return false;
10935     // Undefs are compatible with any other value.
10936     if (isa<UndefValue>(V1->getValueOperand()) ||
10937         isa<UndefValue>(V2->getValueOperand()))
10938       return true;
10939     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10940       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10941         if (I1->getParent() != I2->getParent())
10942           return false;
10943         InstructionsState S = getSameOpcode({I1, I2});
10944         return S.getOpcode() > 0;
10945       }
10946     if (isa<Constant>(V1->getValueOperand()) &&
10947         isa<Constant>(V2->getValueOperand()))
10948       return true;
10949     return V1->getValueOperand()->getValueID() ==
10950            V2->getValueOperand()->getValueID();
10951   };
10952   auto Limit = [&R, this](StoreInst *SI) {
10953     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10954     return R.getMinVF(EltSize);
10955   };
10956 
10957   // Attempt to sort and vectorize each of the store-groups.
10958   for (auto &Pair : Stores) {
10959     if (Pair.second.size() < 2)
10960       continue;
10961 
10962     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10963                       << Pair.second.size() << ".\n");
10964 
10965     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10966       continue;
10967 
10968     Changed |= tryToVectorizeSequence<StoreInst>(
10969         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10970         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10971           return vectorizeStores(Candidates, R);
10972         },
10973         /*LimitForRegisterSize=*/false);
10974   }
10975   return Changed;
10976 }
10977 
10978 char SLPVectorizer::ID = 0;
10979 
10980 static const char lv_name[] = "SLP Vectorizer";
10981 
10982 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10983 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10984 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10985 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10986 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10987 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10988 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10989 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10990 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10991 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10992 
10993 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10994