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 (isVectorIntrinsicWithScalarOpAtArg(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(const Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (const 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   const auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (const 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                  const SmallDenseSet<Value *> &UserIgnoreLst);
899 
900   /// Construct a vectorizable tree that starts at \p Roots.
901   void buildTree(ArrayRef<Value *> Roots);
902 
903   /// Builds external uses of the vectorized scalars, i.e. the list of
904   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
905   /// ExternallyUsedValues contains additional list of external uses to handle
906   /// vectorization of reductions.
907   void
908   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
909 
910   /// Clear the internal data structures that are created by 'buildTree'.
911   void deleteTree() {
912     VectorizableTree.clear();
913     ScalarToTreeEntry.clear();
914     MustGather.clear();
915     ExternalUses.clear();
916     for (auto &Iter : BlocksSchedules) {
917       BlockScheduling *BS = Iter.second.get();
918       BS->clear();
919     }
920     MinBWs.clear();
921     InstrElementSize.clear();
922     UserIgnoreList = nullptr;
923   }
924 
925   unsigned getTreeSize() const { return VectorizableTree.size(); }
926 
927   /// Perform LICM and CSE on the newly generated gather sequences.
928   void optimizeGatherSequence();
929 
930   /// Checks if the specified gather tree entry \p TE can be represented as a
931   /// shuffled vector entry + (possibly) permutation with other gathers. It
932   /// implements the checks only for possibly ordered scalars (Loads,
933   /// ExtractElement, ExtractValue), which can be part of the graph.
934   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
935 
936   /// Sort loads into increasing pointers offsets to allow greater clustering.
937   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
938 
939   /// Gets reordering data for the given tree entry. If the entry is vectorized
940   /// - just return ReorderIndices, otherwise check if the scalars can be
941   /// reordered and return the most optimal order.
942   /// \param TopToBottom If true, include the order of vectorized stores and
943   /// insertelement nodes, otherwise skip them.
944   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
945 
946   /// Reorders the current graph to the most profitable order starting from the
947   /// root node to the leaf nodes. The best order is chosen only from the nodes
948   /// of the same size (vectorization factor). Smaller nodes are considered
949   /// parts of subgraph with smaller VF and they are reordered independently. We
950   /// can make it because we still need to extend smaller nodes to the wider VF
951   /// and we can merge reordering shuffles with the widening shuffles.
952   void reorderTopToBottom();
953 
954   /// Reorders the current graph to the most profitable order starting from
955   /// leaves to the root. It allows to rotate small subgraphs and reduce the
956   /// number of reshuffles if the leaf nodes use the same order. In this case we
957   /// can merge the orders and just shuffle user node instead of shuffling its
958   /// operands. Plus, even the leaf nodes have different orders, it allows to
959   /// sink reordering in the graph closer to the root node and merge it later
960   /// during analysis.
961   void reorderBottomToTop(bool IgnoreReorder = false);
962 
963   /// \return The vector element size in bits to use when vectorizing the
964   /// expression tree ending at \p V. If V is a store, the size is the width of
965   /// the stored value. Otherwise, the size is the width of the largest loaded
966   /// value reaching V. This method is used by the vectorizer to calculate
967   /// vectorization factors.
968   unsigned getVectorElementSize(Value *V);
969 
970   /// Compute the minimum type sizes required to represent the entries in a
971   /// vectorizable tree.
972   void computeMinimumValueSizes();
973 
974   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
975   unsigned getMaxVecRegSize() const {
976     return MaxVecRegSize;
977   }
978 
979   // \returns minimum vector register size as set by cl::opt.
980   unsigned getMinVecRegSize() const {
981     return MinVecRegSize;
982   }
983 
984   unsigned getMinVF(unsigned Sz) const {
985     return std::max(2U, getMinVecRegSize() / Sz);
986   }
987 
988   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
989     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
990       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
991     return MaxVF ? MaxVF : UINT_MAX;
992   }
993 
994   /// Check if homogeneous aggregate is isomorphic to some VectorType.
995   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
996   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
997   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
998   ///
999   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
1000   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
1001 
1002   /// \returns True if the VectorizableTree is both tiny and not fully
1003   /// vectorizable. We do not vectorize such trees.
1004   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1005 
1006   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1007   /// can be load combined in the backend. Load combining may not be allowed in
1008   /// the IR optimizer, so we do not want to alter the pattern. For example,
1009   /// partially transforming a scalar bswap() pattern into vector code is
1010   /// effectively impossible for the backend to undo.
1011   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1012   ///       may not be necessary.
1013   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1014 
1015   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1016   /// can be load combined in the backend. Load combining may not be allowed in
1017   /// the IR optimizer, so we do not want to alter the pattern. For example,
1018   /// partially transforming a scalar bswap() pattern into vector code is
1019   /// effectively impossible for the backend to undo.
1020   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1021   ///       may not be necessary.
1022   bool isLoadCombineCandidate() const;
1023 
1024   OptimizationRemarkEmitter *getORE() { return ORE; }
1025 
1026   /// This structure holds any data we need about the edges being traversed
1027   /// during buildTree_rec(). We keep track of:
1028   /// (i) the user TreeEntry index, and
1029   /// (ii) the index of the edge.
1030   struct EdgeInfo {
1031     EdgeInfo() = default;
1032     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1033         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1034     /// The user TreeEntry.
1035     TreeEntry *UserTE = nullptr;
1036     /// The operand index of the use.
1037     unsigned EdgeIdx = UINT_MAX;
1038 #ifndef NDEBUG
1039     friend inline raw_ostream &operator<<(raw_ostream &OS,
1040                                           const BoUpSLP::EdgeInfo &EI) {
1041       EI.dump(OS);
1042       return OS;
1043     }
1044     /// Debug print.
1045     void dump(raw_ostream &OS) const {
1046       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1047          << " EdgeIdx:" << EdgeIdx << "}";
1048     }
1049     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1050 #endif
1051   };
1052 
1053   /// A helper class used for scoring candidates for two consecutive lanes.
1054   class LookAheadHeuristics {
1055     const DataLayout &DL;
1056     ScalarEvolution &SE;
1057     const BoUpSLP &R;
1058     int NumLanes; // Total number of lanes (aka vectorization factor).
1059     int MaxLevel; // The maximum recursion depth for accumulating score.
1060 
1061   public:
1062     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1063                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1064         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1065 
1066     // The hard-coded scores listed here are not very important, though it shall
1067     // be higher for better matches to improve the resulting cost. When
1068     // computing the scores of matching one sub-tree with another, we are
1069     // basically counting the number of values that are matching. So even if all
1070     // scores are set to 1, we would still get a decent matching result.
1071     // However, sometimes we have to break ties. For example we may have to
1072     // choose between matching loads vs matching opcodes. This is what these
1073     // scores are helping us with: they provide the order of preference. Also,
1074     // this is important if the scalar is externally used or used in another
1075     // tree entry node in the different lane.
1076 
1077     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1078     static const int ScoreConsecutiveLoads = 4;
1079     /// The same load multiple times. This should have a better score than
1080     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1081     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1082     /// a vector load and 1.0 for a broadcast.
1083     static const int ScoreSplatLoads = 3;
1084     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1085     static const int ScoreReversedLoads = 3;
1086     /// ExtractElementInst from same vector and consecutive indexes.
1087     static const int ScoreConsecutiveExtracts = 4;
1088     /// ExtractElementInst from same vector and reversed indices.
1089     static const int ScoreReversedExtracts = 3;
1090     /// Constants.
1091     static const int ScoreConstants = 2;
1092     /// Instructions with the same opcode.
1093     static const int ScoreSameOpcode = 2;
1094     /// Instructions with alt opcodes (e.g, add + sub).
1095     static const int ScoreAltOpcodes = 1;
1096     /// Identical instructions (a.k.a. splat or broadcast).
1097     static const int ScoreSplat = 1;
1098     /// Matching with an undef is preferable to failing.
1099     static const int ScoreUndef = 1;
1100     /// Score for failing to find a decent match.
1101     static const int ScoreFail = 0;
1102     /// Score if all users are vectorized.
1103     static const int ScoreAllUserVectorized = 1;
1104 
1105     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1106     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1107     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1108     /// MainAltOps.
1109     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1110                         ArrayRef<Value *> MainAltOps) const {
1111       if (V1 == V2) {
1112         if (isa<LoadInst>(V1)) {
1113           // Retruns true if the users of V1 and V2 won't need to be extracted.
1114           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1115             // Bail out if we have too many uses to save compilation time.
1116             static constexpr unsigned Limit = 8;
1117             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1118               return false;
1119 
1120             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1121               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1122                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1123               });
1124             };
1125             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1126           };
1127           // A broadcast of a load can be cheaper on some targets.
1128           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1129                                           ElementCount::getFixed(NumLanes)) &&
1130               ((int)V1->getNumUses() == NumLanes ||
1131                AllUsersAreInternal(V1, V2)))
1132             return LookAheadHeuristics::ScoreSplatLoads;
1133         }
1134         return LookAheadHeuristics::ScoreSplat;
1135       }
1136 
1137       auto *LI1 = dyn_cast<LoadInst>(V1);
1138       auto *LI2 = dyn_cast<LoadInst>(V2);
1139       if (LI1 && LI2) {
1140         if (LI1->getParent() != LI2->getParent())
1141           return LookAheadHeuristics::ScoreFail;
1142 
1143         Optional<int> Dist = getPointersDiff(
1144             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1145             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1146         if (!Dist || *Dist == 0)
1147           return LookAheadHeuristics::ScoreFail;
1148         // The distance is too large - still may be profitable to use masked
1149         // loads/gathers.
1150         if (std::abs(*Dist) > NumLanes / 2)
1151           return LookAheadHeuristics::ScoreAltOpcodes;
1152         // This still will detect consecutive loads, but we might have "holes"
1153         // in some cases. It is ok for non-power-2 vectorization and may produce
1154         // better results. It should not affect current vectorization.
1155         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1156                            : LookAheadHeuristics::ScoreReversedLoads;
1157       }
1158 
1159       auto *C1 = dyn_cast<Constant>(V1);
1160       auto *C2 = dyn_cast<Constant>(V2);
1161       if (C1 && C2)
1162         return LookAheadHeuristics::ScoreConstants;
1163 
1164       // Extracts from consecutive indexes of the same vector better score as
1165       // the extracts could be optimized away.
1166       Value *EV1;
1167       ConstantInt *Ex1Idx;
1168       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1169         // Undefs are always profitable for extractelements.
1170         if (isa<UndefValue>(V2))
1171           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1172         Value *EV2 = nullptr;
1173         ConstantInt *Ex2Idx = nullptr;
1174         if (match(V2,
1175                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1176                                                          m_Undef())))) {
1177           // Undefs are always profitable for extractelements.
1178           if (!Ex2Idx)
1179             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1180           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1181             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1182           if (EV2 == EV1) {
1183             int Idx1 = Ex1Idx->getZExtValue();
1184             int Idx2 = Ex2Idx->getZExtValue();
1185             int Dist = Idx2 - Idx1;
1186             // The distance is too large - still may be profitable to use
1187             // shuffles.
1188             if (std::abs(Dist) == 0)
1189               return LookAheadHeuristics::ScoreSplat;
1190             if (std::abs(Dist) > NumLanes / 2)
1191               return LookAheadHeuristics::ScoreSameOpcode;
1192             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1193                               : LookAheadHeuristics::ScoreReversedExtracts;
1194           }
1195           return LookAheadHeuristics::ScoreAltOpcodes;
1196         }
1197         return LookAheadHeuristics::ScoreFail;
1198       }
1199 
1200       auto *I1 = dyn_cast<Instruction>(V1);
1201       auto *I2 = dyn_cast<Instruction>(V2);
1202       if (I1 && I2) {
1203         if (I1->getParent() != I2->getParent())
1204           return LookAheadHeuristics::ScoreFail;
1205         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1206         Ops.push_back(I1);
1207         Ops.push_back(I2);
1208         InstructionsState S = getSameOpcode(Ops);
1209         // Note: Only consider instructions with <= 2 operands to avoid
1210         // complexity explosion.
1211         if (S.getOpcode() &&
1212             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1213              !S.isAltShuffle()) &&
1214             all_of(Ops, [&S](Value *V) {
1215               return cast<Instruction>(V)->getNumOperands() ==
1216                      S.MainOp->getNumOperands();
1217             }))
1218           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1219                                   : LookAheadHeuristics::ScoreSameOpcode;
1220       }
1221 
1222       if (isa<UndefValue>(V2))
1223         return LookAheadHeuristics::ScoreUndef;
1224 
1225       return LookAheadHeuristics::ScoreFail;
1226     }
1227 
1228     /// Go through the operands of \p LHS and \p RHS recursively until
1229     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1230     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1231     /// of \p U1 and \p U2), except at the beginning of the recursion where
1232     /// these are set to nullptr.
1233     ///
1234     /// For example:
1235     /// \verbatim
1236     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1237     ///     \ /         \ /         \ /        \ /
1238     ///      +           +           +          +
1239     ///     G1          G2          G3         G4
1240     /// \endverbatim
1241     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1242     /// each level recursively, accumulating the score. It starts from matching
1243     /// the additions at level 0, then moves on to the loads (level 1). The
1244     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1245     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1246     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1247     /// Please note that the order of the operands does not matter, as we
1248     /// evaluate the score of all profitable combinations of operands. In
1249     /// other words the score of G1 and G4 is the same as G1 and G2. This
1250     /// heuristic is based on ideas described in:
1251     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1252     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1253     ///   Luís F. W. Góes
1254     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1255                            Instruction *U2, int CurrLevel,
1256                            ArrayRef<Value *> MainAltOps) const {
1257 
1258       // Get the shallow score of V1 and V2.
1259       int ShallowScoreAtThisLevel =
1260           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1261 
1262       // If reached MaxLevel,
1263       //  or if V1 and V2 are not instructions,
1264       //  or if they are SPLAT,
1265       //  or if they are not consecutive,
1266       //  or if profitable to vectorize loads or extractelements, early return
1267       //  the current cost.
1268       auto *I1 = dyn_cast<Instruction>(LHS);
1269       auto *I2 = dyn_cast<Instruction>(RHS);
1270       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1271           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1272           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1273             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1274             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1275            ShallowScoreAtThisLevel))
1276         return ShallowScoreAtThisLevel;
1277       assert(I1 && I2 && "Should have early exited.");
1278 
1279       // Contains the I2 operand indexes that got matched with I1 operands.
1280       SmallSet<unsigned, 4> Op2Used;
1281 
1282       // Recursion towards the operands of I1 and I2. We are trying all possible
1283       // operand pairs, and keeping track of the best score.
1284       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1285            OpIdx1 != NumOperands1; ++OpIdx1) {
1286         // Try to pair op1I with the best operand of I2.
1287         int MaxTmpScore = 0;
1288         unsigned MaxOpIdx2 = 0;
1289         bool FoundBest = false;
1290         // If I2 is commutative try all combinations.
1291         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1292         unsigned ToIdx = isCommutative(I2)
1293                              ? I2->getNumOperands()
1294                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1295         assert(FromIdx <= ToIdx && "Bad index");
1296         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1297           // Skip operands already paired with OpIdx1.
1298           if (Op2Used.count(OpIdx2))
1299             continue;
1300           // Recursively calculate the cost at each level
1301           int TmpScore =
1302               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1303                                  I1, I2, CurrLevel + 1, None);
1304           // Look for the best score.
1305           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1306               TmpScore > MaxTmpScore) {
1307             MaxTmpScore = TmpScore;
1308             MaxOpIdx2 = OpIdx2;
1309             FoundBest = true;
1310           }
1311         }
1312         if (FoundBest) {
1313           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1314           Op2Used.insert(MaxOpIdx2);
1315           ShallowScoreAtThisLevel += MaxTmpScore;
1316         }
1317       }
1318       return ShallowScoreAtThisLevel;
1319     }
1320   };
1321   /// A helper data structure to hold the operands of a vector of instructions.
1322   /// This supports a fixed vector length for all operand vectors.
1323   class VLOperands {
1324     /// For each operand we need (i) the value, and (ii) the opcode that it
1325     /// would be attached to if the expression was in a left-linearized form.
1326     /// This is required to avoid illegal operand reordering.
1327     /// For example:
1328     /// \verbatim
1329     ///                         0 Op1
1330     ///                         |/
1331     /// Op1 Op2   Linearized    + Op2
1332     ///   \ /     ---------->   |/
1333     ///    -                    -
1334     ///
1335     /// Op1 - Op2            (0 + Op1) - Op2
1336     /// \endverbatim
1337     ///
1338     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1339     ///
1340     /// Another way to think of this is to track all the operations across the
1341     /// path from the operand all the way to the root of the tree and to
1342     /// calculate the operation that corresponds to this path. For example, the
1343     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1344     /// corresponding operation is a '-' (which matches the one in the
1345     /// linearized tree, as shown above).
1346     ///
1347     /// For lack of a better term, we refer to this operation as Accumulated
1348     /// Path Operation (APO).
1349     struct OperandData {
1350       OperandData() = default;
1351       OperandData(Value *V, bool APO, bool IsUsed)
1352           : V(V), APO(APO), IsUsed(IsUsed) {}
1353       /// The operand value.
1354       Value *V = nullptr;
1355       /// TreeEntries only allow a single opcode, or an alternate sequence of
1356       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1357       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1358       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1359       /// (e.g., Add/Mul)
1360       bool APO = false;
1361       /// Helper data for the reordering function.
1362       bool IsUsed = false;
1363     };
1364 
1365     /// During operand reordering, we are trying to select the operand at lane
1366     /// that matches best with the operand at the neighboring lane. Our
1367     /// selection is based on the type of value we are looking for. For example,
1368     /// if the neighboring lane has a load, we need to look for a load that is
1369     /// accessing a consecutive address. These strategies are summarized in the
1370     /// 'ReorderingMode' enumerator.
1371     enum class ReorderingMode {
1372       Load,     ///< Matching loads to consecutive memory addresses
1373       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1374       Constant, ///< Matching constants
1375       Splat,    ///< Matching the same instruction multiple times (broadcast)
1376       Failed,   ///< We failed to create a vectorizable group
1377     };
1378 
1379     using OperandDataVec = SmallVector<OperandData, 2>;
1380 
1381     /// A vector of operand vectors.
1382     SmallVector<OperandDataVec, 4> OpsVec;
1383 
1384     const DataLayout &DL;
1385     ScalarEvolution &SE;
1386     const BoUpSLP &R;
1387 
1388     /// \returns the operand data at \p OpIdx and \p Lane.
1389     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1390       return OpsVec[OpIdx][Lane];
1391     }
1392 
1393     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1394     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1395       return OpsVec[OpIdx][Lane];
1396     }
1397 
1398     /// Clears the used flag for all entries.
1399     void clearUsed() {
1400       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1401            OpIdx != NumOperands; ++OpIdx)
1402         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1403              ++Lane)
1404           OpsVec[OpIdx][Lane].IsUsed = false;
1405     }
1406 
1407     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1408     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1409       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1410     }
1411 
1412     /// \param Lane lane of the operands under analysis.
1413     /// \param OpIdx operand index in \p Lane lane we're looking the best
1414     /// candidate for.
1415     /// \param Idx operand index of the current candidate value.
1416     /// \returns The additional score due to possible broadcasting of the
1417     /// elements in the lane. It is more profitable to have power-of-2 unique
1418     /// elements in the lane, it will be vectorized with higher probability
1419     /// after removing duplicates. Currently the SLP vectorizer supports only
1420     /// vectorization of the power-of-2 number of unique scalars.
1421     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1422       Value *IdxLaneV = getData(Idx, Lane).V;
1423       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1424         return 0;
1425       SmallPtrSet<Value *, 4> Uniques;
1426       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1427         if (Ln == Lane)
1428           continue;
1429         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1430         if (!isa<Instruction>(OpIdxLnV))
1431           return 0;
1432         Uniques.insert(OpIdxLnV);
1433       }
1434       int UniquesCount = Uniques.size();
1435       int UniquesCntWithIdxLaneV =
1436           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1437       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1438       int UniquesCntWithOpIdxLaneV =
1439           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1440       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1441         return 0;
1442       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1443               UniquesCntWithOpIdxLaneV) -
1444              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1445     }
1446 
1447     /// \param Lane lane of the operands under analysis.
1448     /// \param OpIdx operand index in \p Lane lane we're looking the best
1449     /// candidate for.
1450     /// \param Idx operand index of the current candidate value.
1451     /// \returns The additional score for the scalar which users are all
1452     /// vectorized.
1453     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1454       Value *IdxLaneV = getData(Idx, Lane).V;
1455       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1456       // Do not care about number of uses for vector-like instructions
1457       // (extractelement/extractvalue with constant indices), they are extracts
1458       // themselves and already externally used. Vectorization of such
1459       // instructions does not add extra extractelement instruction, just may
1460       // remove it.
1461       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1462           isVectorLikeInstWithConstOps(OpIdxLaneV))
1463         return LookAheadHeuristics::ScoreAllUserVectorized;
1464       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1465       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1466         return 0;
1467       return R.areAllUsersVectorized(IdxLaneI, None)
1468                  ? LookAheadHeuristics::ScoreAllUserVectorized
1469                  : 0;
1470     }
1471 
1472     /// Score scaling factor for fully compatible instructions but with
1473     /// different number of external uses. Allows better selection of the
1474     /// instructions with less external uses.
1475     static const int ScoreScaleFactor = 10;
1476 
1477     /// \Returns the look-ahead score, which tells us how much the sub-trees
1478     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1479     /// score. This helps break ties in an informed way when we cannot decide on
1480     /// the order of the operands by just considering the immediate
1481     /// predecessors.
1482     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1483                           int Lane, unsigned OpIdx, unsigned Idx,
1484                           bool &IsUsed) {
1485       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1486                                     LookAheadMaxDepth);
1487       // Keep track of the instruction stack as we recurse into the operands
1488       // during the look-ahead score exploration.
1489       int Score =
1490           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1491                                        /*CurrLevel=*/1, MainAltOps);
1492       if (Score) {
1493         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1494         if (Score <= -SplatScore) {
1495           // Set the minimum score for splat-like sequence to avoid setting
1496           // failed state.
1497           Score = 1;
1498         } else {
1499           Score += SplatScore;
1500           // Scale score to see the difference between different operands
1501           // and similar operands but all vectorized/not all vectorized
1502           // uses. It does not affect actual selection of the best
1503           // compatible operand in general, just allows to select the
1504           // operand with all vectorized uses.
1505           Score *= ScoreScaleFactor;
1506           Score += getExternalUseScore(Lane, OpIdx, Idx);
1507           IsUsed = true;
1508         }
1509       }
1510       return Score;
1511     }
1512 
1513     /// Best defined scores per lanes between the passes. Used to choose the
1514     /// best operand (with the highest score) between the passes.
1515     /// The key - {Operand Index, Lane}.
1516     /// The value - the best score between the passes for the lane and the
1517     /// operand.
1518     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1519         BestScoresPerLanes;
1520 
1521     // Search all operands in Ops[*][Lane] for the one that matches best
1522     // Ops[OpIdx][LastLane] and return its opreand index.
1523     // If no good match can be found, return None.
1524     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1525                                       ArrayRef<ReorderingMode> ReorderingModes,
1526                                       ArrayRef<Value *> MainAltOps) {
1527       unsigned NumOperands = getNumOperands();
1528 
1529       // The operand of the previous lane at OpIdx.
1530       Value *OpLastLane = getData(OpIdx, LastLane).V;
1531 
1532       // Our strategy mode for OpIdx.
1533       ReorderingMode RMode = ReorderingModes[OpIdx];
1534       if (RMode == ReorderingMode::Failed)
1535         return None;
1536 
1537       // The linearized opcode of the operand at OpIdx, Lane.
1538       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1539 
1540       // The best operand index and its score.
1541       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1542       // are using the score to differentiate between the two.
1543       struct BestOpData {
1544         Optional<unsigned> Idx = None;
1545         unsigned Score = 0;
1546       } BestOp;
1547       BestOp.Score =
1548           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1549               .first->second;
1550 
1551       // Track if the operand must be marked as used. If the operand is set to
1552       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1553       // want to reestimate the operands again on the following iterations).
1554       bool IsUsed =
1555           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1556       // Iterate through all unused operands and look for the best.
1557       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1558         // Get the operand at Idx and Lane.
1559         OperandData &OpData = getData(Idx, Lane);
1560         Value *Op = OpData.V;
1561         bool OpAPO = OpData.APO;
1562 
1563         // Skip already selected operands.
1564         if (OpData.IsUsed)
1565           continue;
1566 
1567         // Skip if we are trying to move the operand to a position with a
1568         // different opcode in the linearized tree form. This would break the
1569         // semantics.
1570         if (OpAPO != OpIdxAPO)
1571           continue;
1572 
1573         // Look for an operand that matches the current mode.
1574         switch (RMode) {
1575         case ReorderingMode::Load:
1576         case ReorderingMode::Constant:
1577         case ReorderingMode::Opcode: {
1578           bool LeftToRight = Lane > LastLane;
1579           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1580           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1581           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1582                                         OpIdx, Idx, IsUsed);
1583           if (Score > static_cast<int>(BestOp.Score)) {
1584             BestOp.Idx = Idx;
1585             BestOp.Score = Score;
1586             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1587           }
1588           break;
1589         }
1590         case ReorderingMode::Splat:
1591           if (Op == OpLastLane)
1592             BestOp.Idx = Idx;
1593           break;
1594         case ReorderingMode::Failed:
1595           llvm_unreachable("Not expected Failed reordering mode.");
1596         }
1597       }
1598 
1599       if (BestOp.Idx) {
1600         getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
1601         return BestOp.Idx;
1602       }
1603       // If we could not find a good match return None.
1604       return None;
1605     }
1606 
1607     /// Helper for reorderOperandVecs.
1608     /// \returns the lane that we should start reordering from. This is the one
1609     /// which has the least number of operands that can freely move about or
1610     /// less profitable because it already has the most optimal set of operands.
1611     unsigned getBestLaneToStartReordering() const {
1612       unsigned Min = UINT_MAX;
1613       unsigned SameOpNumber = 0;
1614       // std::pair<unsigned, unsigned> is used to implement a simple voting
1615       // algorithm and choose the lane with the least number of operands that
1616       // can freely move about or less profitable because it already has the
1617       // most optimal set of operands. The first unsigned is a counter for
1618       // voting, the second unsigned is the counter of lanes with instructions
1619       // with same/alternate opcodes and same parent basic block.
1620       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1621       // Try to be closer to the original results, if we have multiple lanes
1622       // with same cost. If 2 lanes have the same cost, use the one with the
1623       // lowest index.
1624       for (int I = getNumLanes(); I > 0; --I) {
1625         unsigned Lane = I - 1;
1626         OperandsOrderData NumFreeOpsHash =
1627             getMaxNumOperandsThatCanBeReordered(Lane);
1628         // Compare the number of operands that can move and choose the one with
1629         // the least number.
1630         if (NumFreeOpsHash.NumOfAPOs < Min) {
1631           Min = NumFreeOpsHash.NumOfAPOs;
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap.clear();
1634           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1635         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1636                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1637           // Select the most optimal lane in terms of number of operands that
1638           // should be moved around.
1639           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1640           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1641         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1642                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1643           auto It = HashMap.find(NumFreeOpsHash.Hash);
1644           if (It == HashMap.end())
1645             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1646           else
1647             ++It->second.first;
1648         }
1649       }
1650       // Select the lane with the minimum counter.
1651       unsigned BestLane = 0;
1652       unsigned CntMin = UINT_MAX;
1653       for (const auto &Data : reverse(HashMap)) {
1654         if (Data.second.first < CntMin) {
1655           CntMin = Data.second.first;
1656           BestLane = Data.second.second;
1657         }
1658       }
1659       return BestLane;
1660     }
1661 
1662     /// Data structure that helps to reorder operands.
1663     struct OperandsOrderData {
1664       /// The best number of operands with the same APOs, which can be
1665       /// reordered.
1666       unsigned NumOfAPOs = UINT_MAX;
1667       /// Number of operands with the same/alternate instruction opcode and
1668       /// parent.
1669       unsigned NumOpsWithSameOpcodeParent = 0;
1670       /// Hash for the actual operands ordering.
1671       /// Used to count operands, actually their position id and opcode
1672       /// value. It is used in the voting mechanism to find the lane with the
1673       /// least number of operands that can freely move about or less profitable
1674       /// because it already has the most optimal set of operands. Can be
1675       /// replaced with SmallVector<unsigned> instead but hash code is faster
1676       /// and requires less memory.
1677       unsigned Hash = 0;
1678     };
1679     /// \returns the maximum number of operands that are allowed to be reordered
1680     /// for \p Lane and the number of compatible instructions(with the same
1681     /// parent/opcode). This is used as a heuristic for selecting the first lane
1682     /// to start operand reordering.
1683     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1684       unsigned CntTrue = 0;
1685       unsigned NumOperands = getNumOperands();
1686       // Operands with the same APO can be reordered. We therefore need to count
1687       // how many of them we have for each APO, like this: Cnt[APO] = x.
1688       // Since we only have two APOs, namely true and false, we can avoid using
1689       // a map. Instead we can simply count the number of operands that
1690       // correspond to one of them (in this case the 'true' APO), and calculate
1691       // the other by subtracting it from the total number of operands.
1692       // Operands with the same instruction opcode and parent are more
1693       // profitable since we don't need to move them in many cases, with a high
1694       // probability such lane already can be vectorized effectively.
1695       bool AllUndefs = true;
1696       unsigned NumOpsWithSameOpcodeParent = 0;
1697       Instruction *OpcodeI = nullptr;
1698       BasicBlock *Parent = nullptr;
1699       unsigned Hash = 0;
1700       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1701         const OperandData &OpData = getData(OpIdx, Lane);
1702         if (OpData.APO)
1703           ++CntTrue;
1704         // Use Boyer-Moore majority voting for finding the majority opcode and
1705         // the number of times it occurs.
1706         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1707           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1708               I->getParent() != Parent) {
1709             if (NumOpsWithSameOpcodeParent == 0) {
1710               NumOpsWithSameOpcodeParent = 1;
1711               OpcodeI = I;
1712               Parent = I->getParent();
1713             } else {
1714               --NumOpsWithSameOpcodeParent;
1715             }
1716           } else {
1717             ++NumOpsWithSameOpcodeParent;
1718           }
1719         }
1720         Hash = hash_combine(
1721             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1722         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1723       }
1724       if (AllUndefs)
1725         return {};
1726       OperandsOrderData Data;
1727       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1728       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1729       Data.Hash = Hash;
1730       return Data;
1731     }
1732 
1733     /// Go through the instructions in VL and append their operands.
1734     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1735       assert(!VL.empty() && "Bad VL");
1736       assert((empty() || VL.size() == getNumLanes()) &&
1737              "Expected same number of lanes");
1738       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1739       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1740       OpsVec.resize(NumOperands);
1741       unsigned NumLanes = VL.size();
1742       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1743         OpsVec[OpIdx].resize(NumLanes);
1744         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1745           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1746           // Our tree has just 3 nodes: the root and two operands.
1747           // It is therefore trivial to get the APO. We only need to check the
1748           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1749           // RHS operand. The LHS operand of both add and sub is never attached
1750           // to an inversese operation in the linearized form, therefore its APO
1751           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1752 
1753           // Since operand reordering is performed on groups of commutative
1754           // operations or alternating sequences (e.g., +, -), we can safely
1755           // tell the inverse operations by checking commutativity.
1756           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1757           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1758           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1759                                  APO, false};
1760         }
1761       }
1762     }
1763 
1764     /// \returns the number of operands.
1765     unsigned getNumOperands() const { return OpsVec.size(); }
1766 
1767     /// \returns the number of lanes.
1768     unsigned getNumLanes() const { return OpsVec[0].size(); }
1769 
1770     /// \returns the operand value at \p OpIdx and \p Lane.
1771     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1772       return getData(OpIdx, Lane).V;
1773     }
1774 
1775     /// \returns true if the data structure is empty.
1776     bool empty() const { return OpsVec.empty(); }
1777 
1778     /// Clears the data.
1779     void clear() { OpsVec.clear(); }
1780 
1781     /// \Returns true if there are enough operands identical to \p Op to fill
1782     /// the whole vector.
1783     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1784     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1785       bool OpAPO = getData(OpIdx, Lane).APO;
1786       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1787         if (Ln == Lane)
1788           continue;
1789         // This is set to true if we found a candidate for broadcast at Lane.
1790         bool FoundCandidate = false;
1791         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1792           OperandData &Data = getData(OpI, Ln);
1793           if (Data.APO != OpAPO || Data.IsUsed)
1794             continue;
1795           if (Data.V == Op) {
1796             FoundCandidate = true;
1797             Data.IsUsed = true;
1798             break;
1799           }
1800         }
1801         if (!FoundCandidate)
1802           return false;
1803       }
1804       return true;
1805     }
1806 
1807   public:
1808     /// Initialize with all the operands of the instruction vector \p RootVL.
1809     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1810                ScalarEvolution &SE, const BoUpSLP &R)
1811         : DL(DL), SE(SE), R(R) {
1812       // Append all the operands of RootVL.
1813       appendOperandsOfVL(RootVL);
1814     }
1815 
1816     /// \Returns a value vector with the operands across all lanes for the
1817     /// opearnd at \p OpIdx.
1818     ValueList getVL(unsigned OpIdx) const {
1819       ValueList OpVL(OpsVec[OpIdx].size());
1820       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1821              "Expected same num of lanes across all operands");
1822       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1823         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1824       return OpVL;
1825     }
1826 
1827     // Performs operand reordering for 2 or more operands.
1828     // The original operands are in OrigOps[OpIdx][Lane].
1829     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1830     void reorder() {
1831       unsigned NumOperands = getNumOperands();
1832       unsigned NumLanes = getNumLanes();
1833       // Each operand has its own mode. We are using this mode to help us select
1834       // the instructions for each lane, so that they match best with the ones
1835       // we have selected so far.
1836       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1837 
1838       // This is a greedy single-pass algorithm. We are going over each lane
1839       // once and deciding on the best order right away with no back-tracking.
1840       // However, in order to increase its effectiveness, we start with the lane
1841       // that has operands that can move the least. For example, given the
1842       // following lanes:
1843       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1844       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1845       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1846       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1847       // we will start at Lane 1, since the operands of the subtraction cannot
1848       // be reordered. Then we will visit the rest of the lanes in a circular
1849       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1850 
1851       // Find the first lane that we will start our search from.
1852       unsigned FirstLane = getBestLaneToStartReordering();
1853 
1854       // Initialize the modes.
1855       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1856         Value *OpLane0 = getValue(OpIdx, FirstLane);
1857         // Keep track if we have instructions with all the same opcode on one
1858         // side.
1859         if (isa<LoadInst>(OpLane0))
1860           ReorderingModes[OpIdx] = ReorderingMode::Load;
1861         else if (isa<Instruction>(OpLane0)) {
1862           // Check if OpLane0 should be broadcast.
1863           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1864             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1865           else
1866             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1867         }
1868         else if (isa<Constant>(OpLane0))
1869           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1870         else if (isa<Argument>(OpLane0))
1871           // Our best hope is a Splat. It may save some cost in some cases.
1872           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1873         else
1874           // NOTE: This should be unreachable.
1875           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1876       }
1877 
1878       // Check that we don't have same operands. No need to reorder if operands
1879       // are just perfect diamond or shuffled diamond match. Do not do it only
1880       // for possible broadcasts or non-power of 2 number of scalars (just for
1881       // now).
1882       auto &&SkipReordering = [this]() {
1883         SmallPtrSet<Value *, 4> UniqueValues;
1884         ArrayRef<OperandData> Op0 = OpsVec.front();
1885         for (const OperandData &Data : Op0)
1886           UniqueValues.insert(Data.V);
1887         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1888           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1889                 return !UniqueValues.contains(Data.V);
1890               }))
1891             return false;
1892         }
1893         // TODO: Check if we can remove a check for non-power-2 number of
1894         // scalars after full support of non-power-2 vectorization.
1895         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1896       };
1897 
1898       // If the initial strategy fails for any of the operand indexes, then we
1899       // perform reordering again in a second pass. This helps avoid assigning
1900       // high priority to the failed strategy, and should improve reordering for
1901       // the non-failed operand indexes.
1902       for (int Pass = 0; Pass != 2; ++Pass) {
1903         // Check if no need to reorder operands since they're are perfect or
1904         // shuffled diamond match.
1905         // Need to to do it to avoid extra external use cost counting for
1906         // shuffled matches, which may cause regressions.
1907         if (SkipReordering())
1908           break;
1909         // Skip the second pass if the first pass did not fail.
1910         bool StrategyFailed = false;
1911         // Mark all operand data as free to use.
1912         clearUsed();
1913         // We keep the original operand order for the FirstLane, so reorder the
1914         // rest of the lanes. We are visiting the nodes in a circular fashion,
1915         // using FirstLane as the center point and increasing the radius
1916         // distance.
1917         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1918         for (unsigned I = 0; I < NumOperands; ++I)
1919           MainAltOps[I].push_back(getData(I, FirstLane).V);
1920 
1921         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1922           // Visit the lane on the right and then the lane on the left.
1923           for (int Direction : {+1, -1}) {
1924             int Lane = FirstLane + Direction * Distance;
1925             if (Lane < 0 || Lane >= (int)NumLanes)
1926               continue;
1927             int LastLane = Lane - Direction;
1928             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1929                    "Out of bounds");
1930             // Look for a good match for each operand.
1931             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1932               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1933               Optional<unsigned> BestIdx = getBestOperand(
1934                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1935               // By not selecting a value, we allow the operands that follow to
1936               // select a better matching value. We will get a non-null value in
1937               // the next run of getBestOperand().
1938               if (BestIdx) {
1939                 // Swap the current operand with the one returned by
1940                 // getBestOperand().
1941                 swap(OpIdx, *BestIdx, Lane);
1942               } else {
1943                 // We failed to find a best operand, set mode to 'Failed'.
1944                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1945                 // Enable the second pass.
1946                 StrategyFailed = true;
1947               }
1948               // Try to get the alternate opcode and follow it during analysis.
1949               if (MainAltOps[OpIdx].size() != 2) {
1950                 OperandData &AltOp = getData(OpIdx, Lane);
1951                 InstructionsState OpS =
1952                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1953                 if (OpS.getOpcode() && OpS.isAltShuffle())
1954                   MainAltOps[OpIdx].push_back(AltOp.V);
1955               }
1956             }
1957           }
1958         }
1959         // Skip second pass if the strategy did not fail.
1960         if (!StrategyFailed)
1961           break;
1962       }
1963     }
1964 
1965 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1966     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1967       switch (RMode) {
1968       case ReorderingMode::Load:
1969         return "Load";
1970       case ReorderingMode::Opcode:
1971         return "Opcode";
1972       case ReorderingMode::Constant:
1973         return "Constant";
1974       case ReorderingMode::Splat:
1975         return "Splat";
1976       case ReorderingMode::Failed:
1977         return "Failed";
1978       }
1979       llvm_unreachable("Unimplemented Reordering Type");
1980     }
1981 
1982     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1983                                                    raw_ostream &OS) {
1984       return OS << getModeStr(RMode);
1985     }
1986 
1987     /// Debug print.
1988     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1989       printMode(RMode, dbgs());
1990     }
1991 
1992     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1993       return printMode(RMode, OS);
1994     }
1995 
1996     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1997       const unsigned Indent = 2;
1998       unsigned Cnt = 0;
1999       for (const OperandDataVec &OpDataVec : OpsVec) {
2000         OS << "Operand " << Cnt++ << "\n";
2001         for (const OperandData &OpData : OpDataVec) {
2002           OS.indent(Indent) << "{";
2003           if (Value *V = OpData.V)
2004             OS << *V;
2005           else
2006             OS << "null";
2007           OS << ", APO:" << OpData.APO << "}\n";
2008         }
2009         OS << "\n";
2010       }
2011       return OS;
2012     }
2013 
2014     /// Debug print.
2015     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2016 #endif
2017   };
2018 
2019   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2020   /// for a pair which have highest score deemed to have best chance to form
2021   /// root of profitable tree to vectorize. Return None if no candidate scored
2022   /// above the LookAheadHeuristics::ScoreFail.
2023   /// \param Limit Lower limit of the cost, considered to be good enough score.
2024   Optional<int>
2025   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2026                    int Limit = LookAheadHeuristics::ScoreFail) {
2027     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2028                                   RootLookAheadMaxDepth);
2029     int BestScore = Limit;
2030     Optional<int> Index = None;
2031     for (int I : seq<int>(0, Candidates.size())) {
2032       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2033                                                Candidates[I].second,
2034                                                /*U1=*/nullptr, /*U2=*/nullptr,
2035                                                /*Level=*/1, None);
2036       if (Score > BestScore) {
2037         BestScore = Score;
2038         Index = I;
2039       }
2040     }
2041     return Index;
2042   }
2043 
2044   /// Checks if the instruction is marked for deletion.
2045   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2046 
2047   /// Removes an instruction from its block and eventually deletes it.
2048   /// It's like Instruction::eraseFromParent() except that the actual deletion
2049   /// is delayed until BoUpSLP is destructed.
2050   void eraseInstruction(Instruction *I) {
2051     DeletedInstructions.insert(I);
2052   }
2053 
2054   /// Checks if the instruction was already analyzed for being possible
2055   /// reduction root.
2056   bool isAnalyzedReductionRoot(Instruction *I) const {
2057     return AnalyzedReductionsRoots.count(I);
2058   }
2059   /// Register given instruction as already analyzed for being possible
2060   /// reduction root.
2061   void analyzedReductionRoot(Instruction *I) {
2062     AnalyzedReductionsRoots.insert(I);
2063   }
2064   /// Checks if the provided list of reduced values was checked already for
2065   /// vectorization.
2066   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2067     return AnalyzedReductionVals.contains(hash_value(VL));
2068   }
2069   /// Adds the list of reduced values to list of already checked values for the
2070   /// vectorization.
2071   void analyzedReductionVals(ArrayRef<Value *> VL) {
2072     AnalyzedReductionVals.insert(hash_value(VL));
2073   }
2074   /// Clear the list of the analyzed reduction root instructions.
2075   void clearReductionData() {
2076     AnalyzedReductionsRoots.clear();
2077     AnalyzedReductionVals.clear();
2078   }
2079   /// Checks if the given value is gathered in one of the nodes.
2080   bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2081     return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2082   }
2083 
2084   ~BoUpSLP();
2085 
2086 private:
2087   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2088   /// reordering (i.e. the operands can be reordered because they have only one
2089   /// user and reordarable).
2090   /// \param ReorderableGathers List of all gather nodes that require reordering
2091   /// (e.g., gather of extractlements or partially vectorizable loads).
2092   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2093   /// reordering, subset of \p NonVectorized.
2094   bool
2095   canReorderOperands(TreeEntry *UserTE,
2096                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2097                      ArrayRef<TreeEntry *> ReorderableGathers,
2098                      SmallVectorImpl<TreeEntry *> &GatherOps);
2099 
2100   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2101   /// if any. If it is not vectorized (gather node), returns nullptr.
2102   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2103     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2104     TreeEntry *TE = nullptr;
2105     const auto *It = find_if(VL, [this, &TE](Value *V) {
2106       TE = getTreeEntry(V);
2107       return TE;
2108     });
2109     if (It != VL.end() && TE->isSame(VL))
2110       return TE;
2111     return nullptr;
2112   }
2113 
2114   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2115   /// if any. If it is not vectorized (gather node), returns nullptr.
2116   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2117                                         unsigned OpIdx) const {
2118     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2119         const_cast<TreeEntry *>(UserTE), OpIdx);
2120   }
2121 
2122   /// Checks if all users of \p I are the part of the vectorization tree.
2123   bool areAllUsersVectorized(Instruction *I,
2124                              ArrayRef<Value *> VectorizedVals) const;
2125 
2126   /// \returns the cost of the vectorizable entry.
2127   InstructionCost getEntryCost(const TreeEntry *E,
2128                                ArrayRef<Value *> VectorizedVals);
2129 
2130   /// This is the recursive part of buildTree.
2131   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2132                      const EdgeInfo &EI);
2133 
2134   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2135   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2136   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2137   /// returns false, setting \p CurrentOrder to either an empty vector or a
2138   /// non-identity permutation that allows to reuse extract instructions.
2139   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2140                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2141 
2142   /// Vectorize a single entry in the tree.
2143   Value *vectorizeTree(TreeEntry *E);
2144 
2145   /// Vectorize a single entry in the tree, starting in \p VL.
2146   Value *vectorizeTree(ArrayRef<Value *> VL);
2147 
2148   /// Create a new vector from a list of scalar values.  Produces a sequence
2149   /// which exploits values reused across lanes, and arranges the inserts
2150   /// for ease of later optimization.
2151   Value *createBuildVector(ArrayRef<Value *> VL);
2152 
2153   /// \returns the scalarization cost for this type. Scalarization in this
2154   /// context means the creation of vectors from a group of scalars. If \p
2155   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2156   /// vector elements.
2157   InstructionCost getGatherCost(FixedVectorType *Ty,
2158                                 const APInt &ShuffledIndices,
2159                                 bool NeedToShuffle) const;
2160 
2161   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2162   /// tree entries.
2163   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2164   /// previous tree entries. \p Mask is filled with the shuffle mask.
2165   Optional<TargetTransformInfo::ShuffleKind>
2166   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2167                         SmallVectorImpl<const TreeEntry *> &Entries);
2168 
2169   /// \returns the scalarization cost for this list of values. Assuming that
2170   /// this subtree gets vectorized, we may need to extract the values from the
2171   /// roots. This method calculates the cost of extracting the values.
2172   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2173 
2174   /// Set the Builder insert point to one after the last instruction in
2175   /// the bundle
2176   void setInsertPointAfterBundle(const TreeEntry *E);
2177 
2178   /// \returns a vector from a collection of scalars in \p VL.
2179   Value *gather(ArrayRef<Value *> VL);
2180 
2181   /// \returns whether the VectorizableTree is fully vectorizable and will
2182   /// be beneficial even the tree height is tiny.
2183   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2184 
2185   /// Reorder commutative or alt operands to get better probability of
2186   /// generating vectorized code.
2187   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2188                                              SmallVectorImpl<Value *> &Left,
2189                                              SmallVectorImpl<Value *> &Right,
2190                                              const DataLayout &DL,
2191                                              ScalarEvolution &SE,
2192                                              const BoUpSLP &R);
2193 
2194   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2195   /// users of \p TE and collects the stores. It returns the map from the store
2196   /// pointers to the collected stores.
2197   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2198   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2199 
2200   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2201   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2202   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2203   /// when compared to the sorted vector.
2204   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2205                      OrdersType &ReorderIndices) const;
2206 
2207   /// Iterates through the users of \p TE, looking for scalar stores that can be
2208   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2209   /// their order and builds an order index vector for each store bundle. It
2210   /// returns all these order vectors found.
2211   /// We run this after the tree has formed, otherwise we may come across user
2212   /// instructions that are not yet in the tree.
2213   SmallVector<OrdersType, 1>
2214   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2215 
2216   struct TreeEntry {
2217     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2218     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2219 
2220     /// \returns true if the scalars in VL are equal to this entry.
2221     bool isSame(ArrayRef<Value *> VL) const {
2222       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2223         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2224           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2225         return VL.size() == Mask.size() &&
2226                std::equal(VL.begin(), VL.end(), Mask.begin(),
2227                           [Scalars](Value *V, int Idx) {
2228                             return (isa<UndefValue>(V) &&
2229                                     Idx == UndefMaskElem) ||
2230                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2231                           });
2232       };
2233       if (!ReorderIndices.empty()) {
2234         // TODO: implement matching if the nodes are just reordered, still can
2235         // treat the vector as the same if the list of scalars matches VL
2236         // directly, without reordering.
2237         SmallVector<int> Mask;
2238         inversePermutation(ReorderIndices, Mask);
2239         if (VL.size() == Scalars.size())
2240           return IsSame(Scalars, Mask);
2241         if (VL.size() == ReuseShuffleIndices.size()) {
2242           ::addMask(Mask, ReuseShuffleIndices);
2243           return IsSame(Scalars, Mask);
2244         }
2245         return false;
2246       }
2247       return IsSame(Scalars, ReuseShuffleIndices);
2248     }
2249 
2250     /// \returns true if current entry has same operands as \p TE.
2251     bool hasEqualOperands(const TreeEntry &TE) const {
2252       if (TE.getNumOperands() != getNumOperands())
2253         return false;
2254       SmallBitVector Used(getNumOperands());
2255       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2256         unsigned PrevCount = Used.count();
2257         for (unsigned K = 0; K < E; ++K) {
2258           if (Used.test(K))
2259             continue;
2260           if (getOperand(K) == TE.getOperand(I)) {
2261             Used.set(K);
2262             break;
2263           }
2264         }
2265         // Check if we actually found the matching operand.
2266         if (PrevCount == Used.count())
2267           return false;
2268       }
2269       return true;
2270     }
2271 
2272     /// \return Final vectorization factor for the node. Defined by the total
2273     /// number of vectorized scalars, including those, used several times in the
2274     /// entry and counted in the \a ReuseShuffleIndices, if any.
2275     unsigned getVectorFactor() const {
2276       if (!ReuseShuffleIndices.empty())
2277         return ReuseShuffleIndices.size();
2278       return Scalars.size();
2279     };
2280 
2281     /// A vector of scalars.
2282     ValueList Scalars;
2283 
2284     /// The Scalars are vectorized into this value. It is initialized to Null.
2285     Value *VectorizedValue = nullptr;
2286 
2287     /// Do we need to gather this sequence or vectorize it
2288     /// (either with vector instruction or with scatter/gather
2289     /// intrinsics for store/load)?
2290     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2291     EntryState State;
2292 
2293     /// Does this sequence require some shuffling?
2294     SmallVector<int, 4> ReuseShuffleIndices;
2295 
2296     /// Does this entry require reordering?
2297     SmallVector<unsigned, 4> ReorderIndices;
2298 
2299     /// Points back to the VectorizableTree.
2300     ///
2301     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2302     /// to be a pointer and needs to be able to initialize the child iterator.
2303     /// Thus we need a reference back to the container to translate the indices
2304     /// to entries.
2305     VecTreeTy &Container;
2306 
2307     /// The TreeEntry index containing the user of this entry.  We can actually
2308     /// have multiple users so the data structure is not truly a tree.
2309     SmallVector<EdgeInfo, 1> UserTreeIndices;
2310 
2311     /// The index of this treeEntry in VectorizableTree.
2312     int Idx = -1;
2313 
2314   private:
2315     /// The operands of each instruction in each lane Operands[op_index][lane].
2316     /// Note: This helps avoid the replication of the code that performs the
2317     /// reordering of operands during buildTree_rec() and vectorizeTree().
2318     SmallVector<ValueList, 2> Operands;
2319 
2320     /// The main/alternate instruction.
2321     Instruction *MainOp = nullptr;
2322     Instruction *AltOp = nullptr;
2323 
2324   public:
2325     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2326     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2327       if (Operands.size() < OpIdx + 1)
2328         Operands.resize(OpIdx + 1);
2329       assert(Operands[OpIdx].empty() && "Already resized?");
2330       assert(OpVL.size() <= Scalars.size() &&
2331              "Number of operands is greater than the number of scalars.");
2332       Operands[OpIdx].resize(OpVL.size());
2333       copy(OpVL, Operands[OpIdx].begin());
2334     }
2335 
2336     /// Set the operands of this bundle in their original order.
2337     void setOperandsInOrder() {
2338       assert(Operands.empty() && "Already initialized?");
2339       auto *I0 = cast<Instruction>(Scalars[0]);
2340       Operands.resize(I0->getNumOperands());
2341       unsigned NumLanes = Scalars.size();
2342       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2343            OpIdx != NumOperands; ++OpIdx) {
2344         Operands[OpIdx].resize(NumLanes);
2345         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2346           auto *I = cast<Instruction>(Scalars[Lane]);
2347           assert(I->getNumOperands() == NumOperands &&
2348                  "Expected same number of operands");
2349           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2350         }
2351       }
2352     }
2353 
2354     /// Reorders operands of the node to the given mask \p Mask.
2355     void reorderOperands(ArrayRef<int> Mask) {
2356       for (ValueList &Operand : Operands)
2357         reorderScalars(Operand, Mask);
2358     }
2359 
2360     /// \returns the \p OpIdx operand of this TreeEntry.
2361     ValueList &getOperand(unsigned OpIdx) {
2362       assert(OpIdx < Operands.size() && "Off bounds");
2363       return Operands[OpIdx];
2364     }
2365 
2366     /// \returns the \p OpIdx operand of this TreeEntry.
2367     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2368       assert(OpIdx < Operands.size() && "Off bounds");
2369       return Operands[OpIdx];
2370     }
2371 
2372     /// \returns the number of operands.
2373     unsigned getNumOperands() const { return Operands.size(); }
2374 
2375     /// \return the single \p OpIdx operand.
2376     Value *getSingleOperand(unsigned OpIdx) const {
2377       assert(OpIdx < Operands.size() && "Off bounds");
2378       assert(!Operands[OpIdx].empty() && "No operand available");
2379       return Operands[OpIdx][0];
2380     }
2381 
2382     /// Some of the instructions in the list have alternate opcodes.
2383     bool isAltShuffle() const { return MainOp != AltOp; }
2384 
2385     bool isOpcodeOrAlt(Instruction *I) const {
2386       unsigned CheckedOpcode = I->getOpcode();
2387       return (getOpcode() == CheckedOpcode ||
2388               getAltOpcode() == CheckedOpcode);
2389     }
2390 
2391     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2392     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2393     /// \p OpValue.
2394     Value *isOneOf(Value *Op) const {
2395       auto *I = dyn_cast<Instruction>(Op);
2396       if (I && isOpcodeOrAlt(I))
2397         return Op;
2398       return MainOp;
2399     }
2400 
2401     void setOperations(const InstructionsState &S) {
2402       MainOp = S.MainOp;
2403       AltOp = S.AltOp;
2404     }
2405 
2406     Instruction *getMainOp() const {
2407       return MainOp;
2408     }
2409 
2410     Instruction *getAltOp() const {
2411       return AltOp;
2412     }
2413 
2414     /// The main/alternate opcodes for the list of instructions.
2415     unsigned getOpcode() const {
2416       return MainOp ? MainOp->getOpcode() : 0;
2417     }
2418 
2419     unsigned getAltOpcode() const {
2420       return AltOp ? AltOp->getOpcode() : 0;
2421     }
2422 
2423     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2424     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2425     int findLaneForValue(Value *V) const {
2426       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2427       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2428       if (!ReorderIndices.empty())
2429         FoundLane = ReorderIndices[FoundLane];
2430       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2431       if (!ReuseShuffleIndices.empty()) {
2432         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2433                                   find(ReuseShuffleIndices, FoundLane));
2434       }
2435       return FoundLane;
2436     }
2437 
2438 #ifndef NDEBUG
2439     /// Debug printer.
2440     LLVM_DUMP_METHOD void dump() const {
2441       dbgs() << Idx << ".\n";
2442       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2443         dbgs() << "Operand " << OpI << ":\n";
2444         for (const Value *V : Operands[OpI])
2445           dbgs().indent(2) << *V << "\n";
2446       }
2447       dbgs() << "Scalars: \n";
2448       for (Value *V : Scalars)
2449         dbgs().indent(2) << *V << "\n";
2450       dbgs() << "State: ";
2451       switch (State) {
2452       case Vectorize:
2453         dbgs() << "Vectorize\n";
2454         break;
2455       case ScatterVectorize:
2456         dbgs() << "ScatterVectorize\n";
2457         break;
2458       case NeedToGather:
2459         dbgs() << "NeedToGather\n";
2460         break;
2461       }
2462       dbgs() << "MainOp: ";
2463       if (MainOp)
2464         dbgs() << *MainOp << "\n";
2465       else
2466         dbgs() << "NULL\n";
2467       dbgs() << "AltOp: ";
2468       if (AltOp)
2469         dbgs() << *AltOp << "\n";
2470       else
2471         dbgs() << "NULL\n";
2472       dbgs() << "VectorizedValue: ";
2473       if (VectorizedValue)
2474         dbgs() << *VectorizedValue << "\n";
2475       else
2476         dbgs() << "NULL\n";
2477       dbgs() << "ReuseShuffleIndices: ";
2478       if (ReuseShuffleIndices.empty())
2479         dbgs() << "Empty";
2480       else
2481         for (int ReuseIdx : ReuseShuffleIndices)
2482           dbgs() << ReuseIdx << ", ";
2483       dbgs() << "\n";
2484       dbgs() << "ReorderIndices: ";
2485       for (unsigned ReorderIdx : ReorderIndices)
2486         dbgs() << ReorderIdx << ", ";
2487       dbgs() << "\n";
2488       dbgs() << "UserTreeIndices: ";
2489       for (const auto &EInfo : UserTreeIndices)
2490         dbgs() << EInfo << ", ";
2491       dbgs() << "\n";
2492     }
2493 #endif
2494   };
2495 
2496 #ifndef NDEBUG
2497   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2498                      InstructionCost VecCost,
2499                      InstructionCost ScalarCost) const {
2500     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2501     dbgs() << "SLP: Costs:\n";
2502     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2503     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2504     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2505     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2506                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2507   }
2508 #endif
2509 
2510   /// Create a new VectorizableTree entry.
2511   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2512                           const InstructionsState &S,
2513                           const EdgeInfo &UserTreeIdx,
2514                           ArrayRef<int> ReuseShuffleIndices = None,
2515                           ArrayRef<unsigned> ReorderIndices = None) {
2516     TreeEntry::EntryState EntryState =
2517         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2518     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2519                         ReuseShuffleIndices, ReorderIndices);
2520   }
2521 
2522   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2523                           TreeEntry::EntryState EntryState,
2524                           Optional<ScheduleData *> Bundle,
2525                           const InstructionsState &S,
2526                           const EdgeInfo &UserTreeIdx,
2527                           ArrayRef<int> ReuseShuffleIndices = None,
2528                           ArrayRef<unsigned> ReorderIndices = None) {
2529     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2530             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2531            "Need to vectorize gather entry?");
2532     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2533     TreeEntry *Last = VectorizableTree.back().get();
2534     Last->Idx = VectorizableTree.size() - 1;
2535     Last->State = EntryState;
2536     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2537                                      ReuseShuffleIndices.end());
2538     if (ReorderIndices.empty()) {
2539       Last->Scalars.assign(VL.begin(), VL.end());
2540       Last->setOperations(S);
2541     } else {
2542       // Reorder scalars and build final mask.
2543       Last->Scalars.assign(VL.size(), nullptr);
2544       transform(ReorderIndices, Last->Scalars.begin(),
2545                 [VL](unsigned Idx) -> Value * {
2546                   if (Idx >= VL.size())
2547                     return UndefValue::get(VL.front()->getType());
2548                   return VL[Idx];
2549                 });
2550       InstructionsState S = getSameOpcode(Last->Scalars);
2551       Last->setOperations(S);
2552       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2553     }
2554     if (Last->State != TreeEntry::NeedToGather) {
2555       for (Value *V : VL) {
2556         assert(!getTreeEntry(V) && "Scalar already in tree!");
2557         ScalarToTreeEntry[V] = Last;
2558       }
2559       // Update the scheduler bundle to point to this TreeEntry.
2560       ScheduleData *BundleMember = *Bundle;
2561       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2562               isVectorLikeInstWithConstOps(S.MainOp) ||
2563               doesNotNeedToSchedule(VL)) &&
2564              "Bundle and VL out of sync");
2565       if (BundleMember) {
2566         for (Value *V : VL) {
2567           if (doesNotNeedToBeScheduled(V))
2568             continue;
2569           assert(BundleMember && "Unexpected end of bundle.");
2570           BundleMember->TE = Last;
2571           BundleMember = BundleMember->NextInBundle;
2572         }
2573       }
2574       assert(!BundleMember && "Bundle and VL out of sync");
2575     } else {
2576       MustGather.insert(VL.begin(), VL.end());
2577     }
2578 
2579     if (UserTreeIdx.UserTE)
2580       Last->UserTreeIndices.push_back(UserTreeIdx);
2581 
2582     return Last;
2583   }
2584 
2585   /// -- Vectorization State --
2586   /// Holds all of the tree entries.
2587   TreeEntry::VecTreeTy VectorizableTree;
2588 
2589 #ifndef NDEBUG
2590   /// Debug printer.
2591   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2592     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2593       VectorizableTree[Id]->dump();
2594       dbgs() << "\n";
2595     }
2596   }
2597 #endif
2598 
2599   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2600 
2601   const TreeEntry *getTreeEntry(Value *V) const {
2602     return ScalarToTreeEntry.lookup(V);
2603   }
2604 
2605   /// Maps a specific scalar to its tree entry.
2606   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2607 
2608   /// Maps a value to the proposed vectorizable size.
2609   SmallDenseMap<Value *, unsigned> InstrElementSize;
2610 
2611   /// A list of scalars that we found that we need to keep as scalars.
2612   ValueSet MustGather;
2613 
2614   /// This POD struct describes one external user in the vectorized tree.
2615   struct ExternalUser {
2616     ExternalUser(Value *S, llvm::User *U, int L)
2617         : Scalar(S), User(U), Lane(L) {}
2618 
2619     // Which scalar in our function.
2620     Value *Scalar;
2621 
2622     // Which user that uses the scalar.
2623     llvm::User *User;
2624 
2625     // Which lane does the scalar belong to.
2626     int Lane;
2627   };
2628   using UserList = SmallVector<ExternalUser, 16>;
2629 
2630   /// Checks if two instructions may access the same memory.
2631   ///
2632   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2633   /// is invariant in the calling loop.
2634   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2635                  Instruction *Inst2) {
2636     // First check if the result is already in the cache.
2637     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2638     Optional<bool> &result = AliasCache[key];
2639     if (result) {
2640       return *result;
2641     }
2642     bool aliased = true;
2643     if (Loc1.Ptr && isSimple(Inst1))
2644       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2645     // Store the result in the cache.
2646     result = aliased;
2647     return aliased;
2648   }
2649 
2650   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2651 
2652   /// Cache for alias results.
2653   /// TODO: consider moving this to the AliasAnalysis itself.
2654   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2655 
2656   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2657   // globally through SLP because we don't perform any action which
2658   // invalidates capture results.
2659   BatchAAResults BatchAA;
2660 
2661   /// Temporary store for deleted instructions. Instructions will be deleted
2662   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2663   /// ensure that there are no incorrect collisions in the AliasCache, which
2664   /// can happen if a new instruction is allocated at the same address as a
2665   /// previously deleted instruction.
2666   DenseSet<Instruction *> DeletedInstructions;
2667 
2668   /// Set of the instruction, being analyzed already for reductions.
2669   SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2670 
2671   /// Set of hashes for the list of reduction values already being analyzed.
2672   DenseSet<size_t> AnalyzedReductionVals;
2673 
2674   /// A list of values that need to extracted out of the tree.
2675   /// This list holds pairs of (Internal Scalar : External User). External User
2676   /// can be nullptr, it means that this Internal Scalar will be used later,
2677   /// after vectorization.
2678   UserList ExternalUses;
2679 
2680   /// Values used only by @llvm.assume calls.
2681   SmallPtrSet<const Value *, 32> EphValues;
2682 
2683   /// Holds all of the instructions that we gathered.
2684   SetVector<Instruction *> GatherShuffleSeq;
2685 
2686   /// A list of blocks that we are going to CSE.
2687   SetVector<BasicBlock *> CSEBlocks;
2688 
2689   /// Contains all scheduling relevant data for an instruction.
2690   /// A ScheduleData either represents a single instruction or a member of an
2691   /// instruction bundle (= a group of instructions which is combined into a
2692   /// vector instruction).
2693   struct ScheduleData {
2694     // The initial value for the dependency counters. It means that the
2695     // dependencies are not calculated yet.
2696     enum { InvalidDeps = -1 };
2697 
2698     ScheduleData() = default;
2699 
2700     void init(int BlockSchedulingRegionID, Value *OpVal) {
2701       FirstInBundle = this;
2702       NextInBundle = nullptr;
2703       NextLoadStore = nullptr;
2704       IsScheduled = false;
2705       SchedulingRegionID = BlockSchedulingRegionID;
2706       clearDependencies();
2707       OpValue = OpVal;
2708       TE = nullptr;
2709     }
2710 
2711     /// Verify basic self consistency properties
2712     void verify() {
2713       if (hasValidDependencies()) {
2714         assert(UnscheduledDeps <= Dependencies && "invariant");
2715       } else {
2716         assert(UnscheduledDeps == Dependencies && "invariant");
2717       }
2718 
2719       if (IsScheduled) {
2720         assert(isSchedulingEntity() &&
2721                 "unexpected scheduled state");
2722         for (const ScheduleData *BundleMember = this; BundleMember;
2723              BundleMember = BundleMember->NextInBundle) {
2724           assert(BundleMember->hasValidDependencies() &&
2725                  BundleMember->UnscheduledDeps == 0 &&
2726                  "unexpected scheduled state");
2727           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2728                  "only bundle is marked scheduled");
2729         }
2730       }
2731 
2732       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2733              "all bundle members must be in same basic block");
2734     }
2735 
2736     /// Returns true if the dependency information has been calculated.
2737     /// Note that depenendency validity can vary between instructions within
2738     /// a single bundle.
2739     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2740 
2741     /// Returns true for single instructions and for bundle representatives
2742     /// (= the head of a bundle).
2743     bool isSchedulingEntity() const { return FirstInBundle == this; }
2744 
2745     /// Returns true if it represents an instruction bundle and not only a
2746     /// single instruction.
2747     bool isPartOfBundle() const {
2748       return NextInBundle != nullptr || FirstInBundle != this || TE;
2749     }
2750 
2751     /// Returns true if it is ready for scheduling, i.e. it has no more
2752     /// unscheduled depending instructions/bundles.
2753     bool isReady() const {
2754       assert(isSchedulingEntity() &&
2755              "can't consider non-scheduling entity for ready list");
2756       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2757     }
2758 
2759     /// Modifies the number of unscheduled dependencies for this instruction,
2760     /// and returns the number of remaining dependencies for the containing
2761     /// bundle.
2762     int incrementUnscheduledDeps(int Incr) {
2763       assert(hasValidDependencies() &&
2764              "increment of unscheduled deps would be meaningless");
2765       UnscheduledDeps += Incr;
2766       return FirstInBundle->unscheduledDepsInBundle();
2767     }
2768 
2769     /// Sets the number of unscheduled dependencies to the number of
2770     /// dependencies.
2771     void resetUnscheduledDeps() {
2772       UnscheduledDeps = Dependencies;
2773     }
2774 
2775     /// Clears all dependency information.
2776     void clearDependencies() {
2777       Dependencies = InvalidDeps;
2778       resetUnscheduledDeps();
2779       MemoryDependencies.clear();
2780       ControlDependencies.clear();
2781     }
2782 
2783     int unscheduledDepsInBundle() const {
2784       assert(isSchedulingEntity() && "only meaningful on the bundle");
2785       int Sum = 0;
2786       for (const ScheduleData *BundleMember = this; BundleMember;
2787            BundleMember = BundleMember->NextInBundle) {
2788         if (BundleMember->UnscheduledDeps == InvalidDeps)
2789           return InvalidDeps;
2790         Sum += BundleMember->UnscheduledDeps;
2791       }
2792       return Sum;
2793     }
2794 
2795     void dump(raw_ostream &os) const {
2796       if (!isSchedulingEntity()) {
2797         os << "/ " << *Inst;
2798       } else if (NextInBundle) {
2799         os << '[' << *Inst;
2800         ScheduleData *SD = NextInBundle;
2801         while (SD) {
2802           os << ';' << *SD->Inst;
2803           SD = SD->NextInBundle;
2804         }
2805         os << ']';
2806       } else {
2807         os << *Inst;
2808       }
2809     }
2810 
2811     Instruction *Inst = nullptr;
2812 
2813     /// Opcode of the current instruction in the schedule data.
2814     Value *OpValue = nullptr;
2815 
2816     /// The TreeEntry that this instruction corresponds to.
2817     TreeEntry *TE = nullptr;
2818 
2819     /// Points to the head in an instruction bundle (and always to this for
2820     /// single instructions).
2821     ScheduleData *FirstInBundle = nullptr;
2822 
2823     /// Single linked list of all instructions in a bundle. Null if it is a
2824     /// single instruction.
2825     ScheduleData *NextInBundle = nullptr;
2826 
2827     /// Single linked list of all memory instructions (e.g. load, store, call)
2828     /// in the block - until the end of the scheduling region.
2829     ScheduleData *NextLoadStore = nullptr;
2830 
2831     /// The dependent memory instructions.
2832     /// This list is derived on demand in calculateDependencies().
2833     SmallVector<ScheduleData *, 4> MemoryDependencies;
2834 
2835     /// List of instructions which this instruction could be control dependent
2836     /// on.  Allowing such nodes to be scheduled below this one could introduce
2837     /// a runtime fault which didn't exist in the original program.
2838     /// ex: this is a load or udiv following a readonly call which inf loops
2839     SmallVector<ScheduleData *, 4> ControlDependencies;
2840 
2841     /// This ScheduleData is in the current scheduling region if this matches
2842     /// the current SchedulingRegionID of BlockScheduling.
2843     int SchedulingRegionID = 0;
2844 
2845     /// Used for getting a "good" final ordering of instructions.
2846     int SchedulingPriority = 0;
2847 
2848     /// The number of dependencies. Constitutes of the number of users of the
2849     /// instruction plus the number of dependent memory instructions (if any).
2850     /// This value is calculated on demand.
2851     /// If InvalidDeps, the number of dependencies is not calculated yet.
2852     int Dependencies = InvalidDeps;
2853 
2854     /// The number of dependencies minus the number of dependencies of scheduled
2855     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2856     /// for scheduling.
2857     /// Note that this is negative as long as Dependencies is not calculated.
2858     int UnscheduledDeps = InvalidDeps;
2859 
2860     /// True if this instruction is scheduled (or considered as scheduled in the
2861     /// dry-run).
2862     bool IsScheduled = false;
2863   };
2864 
2865 #ifndef NDEBUG
2866   friend inline raw_ostream &operator<<(raw_ostream &os,
2867                                         const BoUpSLP::ScheduleData &SD) {
2868     SD.dump(os);
2869     return os;
2870   }
2871 #endif
2872 
2873   friend struct GraphTraits<BoUpSLP *>;
2874   friend struct DOTGraphTraits<BoUpSLP *>;
2875 
2876   /// Contains all scheduling data for a basic block.
2877   /// It does not schedules instructions, which are not memory read/write
2878   /// instructions and their operands are either constants, or arguments, or
2879   /// phis, or instructions from others blocks, or their users are phis or from
2880   /// the other blocks. The resulting vector instructions can be placed at the
2881   /// beginning of the basic block without scheduling (if operands does not need
2882   /// to be scheduled) or at the end of the block (if users are outside of the
2883   /// block). It allows to save some compile time and memory used by the
2884   /// compiler.
2885   /// ScheduleData is assigned for each instruction in between the boundaries of
2886   /// the tree entry, even for those, which are not part of the graph. It is
2887   /// required to correctly follow the dependencies between the instructions and
2888   /// their correct scheduling. The ScheduleData is not allocated for the
2889   /// instructions, which do not require scheduling, like phis, nodes with
2890   /// extractelements/insertelements only or nodes with instructions, with
2891   /// uses/operands outside of the block.
2892   struct BlockScheduling {
2893     BlockScheduling(BasicBlock *BB)
2894         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2895 
2896     void clear() {
2897       ReadyInsts.clear();
2898       ScheduleStart = nullptr;
2899       ScheduleEnd = nullptr;
2900       FirstLoadStoreInRegion = nullptr;
2901       LastLoadStoreInRegion = nullptr;
2902       RegionHasStackSave = false;
2903 
2904       // Reduce the maximum schedule region size by the size of the
2905       // previous scheduling run.
2906       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2907       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2908         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2909       ScheduleRegionSize = 0;
2910 
2911       // Make a new scheduling region, i.e. all existing ScheduleData is not
2912       // in the new region yet.
2913       ++SchedulingRegionID;
2914     }
2915 
2916     ScheduleData *getScheduleData(Instruction *I) {
2917       if (BB != I->getParent())
2918         // Avoid lookup if can't possibly be in map.
2919         return nullptr;
2920       ScheduleData *SD = ScheduleDataMap.lookup(I);
2921       if (SD && isInSchedulingRegion(SD))
2922         return SD;
2923       return nullptr;
2924     }
2925 
2926     ScheduleData *getScheduleData(Value *V) {
2927       if (auto *I = dyn_cast<Instruction>(V))
2928         return getScheduleData(I);
2929       return nullptr;
2930     }
2931 
2932     ScheduleData *getScheduleData(Value *V, Value *Key) {
2933       if (V == Key)
2934         return getScheduleData(V);
2935       auto I = ExtraScheduleDataMap.find(V);
2936       if (I != ExtraScheduleDataMap.end()) {
2937         ScheduleData *SD = I->second.lookup(Key);
2938         if (SD && isInSchedulingRegion(SD))
2939           return SD;
2940       }
2941       return nullptr;
2942     }
2943 
2944     bool isInSchedulingRegion(ScheduleData *SD) const {
2945       return SD->SchedulingRegionID == SchedulingRegionID;
2946     }
2947 
2948     /// Marks an instruction as scheduled and puts all dependent ready
2949     /// instructions into the ready-list.
2950     template <typename ReadyListType>
2951     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2952       SD->IsScheduled = true;
2953       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2954 
2955       for (ScheduleData *BundleMember = SD; BundleMember;
2956            BundleMember = BundleMember->NextInBundle) {
2957         if (BundleMember->Inst != BundleMember->OpValue)
2958           continue;
2959 
2960         // Handle the def-use chain dependencies.
2961 
2962         // Decrement the unscheduled counter and insert to ready list if ready.
2963         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2964           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2965             if (OpDef && OpDef->hasValidDependencies() &&
2966                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2967               // There are no more unscheduled dependencies after
2968               // decrementing, so we can put the dependent instruction
2969               // into the ready list.
2970               ScheduleData *DepBundle = OpDef->FirstInBundle;
2971               assert(!DepBundle->IsScheduled &&
2972                      "already scheduled bundle gets ready");
2973               ReadyList.insert(DepBundle);
2974               LLVM_DEBUG(dbgs()
2975                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2976             }
2977           });
2978         };
2979 
2980         // If BundleMember is a vector bundle, its operands may have been
2981         // reordered during buildTree(). We therefore need to get its operands
2982         // through the TreeEntry.
2983         if (TreeEntry *TE = BundleMember->TE) {
2984           // Need to search for the lane since the tree entry can be reordered.
2985           int Lane = std::distance(TE->Scalars.begin(),
2986                                    find(TE->Scalars, BundleMember->Inst));
2987           assert(Lane >= 0 && "Lane not set");
2988 
2989           // Since vectorization tree is being built recursively this assertion
2990           // ensures that the tree entry has all operands set before reaching
2991           // this code. Couple of exceptions known at the moment are extracts
2992           // where their second (immediate) operand is not added. Since
2993           // immediates do not affect scheduler behavior this is considered
2994           // okay.
2995           auto *In = BundleMember->Inst;
2996           assert(In &&
2997                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2998                   In->getNumOperands() == TE->getNumOperands()) &&
2999                  "Missed TreeEntry operands?");
3000           (void)In; // fake use to avoid build failure when assertions disabled
3001 
3002           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
3003                OpIdx != NumOperands; ++OpIdx)
3004             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3005               DecrUnsched(I);
3006         } else {
3007           // If BundleMember is a stand-alone instruction, no operand reordering
3008           // has taken place, so we directly access its operands.
3009           for (Use &U : BundleMember->Inst->operands())
3010             if (auto *I = dyn_cast<Instruction>(U.get()))
3011               DecrUnsched(I);
3012         }
3013         // Handle the memory dependencies.
3014         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3015           if (MemoryDepSD->hasValidDependencies() &&
3016               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3017             // There are no more unscheduled dependencies after decrementing,
3018             // so we can put the dependent instruction into the ready list.
3019             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3020             assert(!DepBundle->IsScheduled &&
3021                    "already scheduled bundle gets ready");
3022             ReadyList.insert(DepBundle);
3023             LLVM_DEBUG(dbgs()
3024                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3025           }
3026         }
3027         // Handle the control dependencies.
3028         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3029           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3030             // There are no more unscheduled dependencies after decrementing,
3031             // so we can put the dependent instruction into the ready list.
3032             ScheduleData *DepBundle = DepSD->FirstInBundle;
3033             assert(!DepBundle->IsScheduled &&
3034                    "already scheduled bundle gets ready");
3035             ReadyList.insert(DepBundle);
3036             LLVM_DEBUG(dbgs()
3037                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3038           }
3039         }
3040 
3041       }
3042     }
3043 
3044     /// Verify basic self consistency properties of the data structure.
3045     void verify() {
3046       if (!ScheduleStart)
3047         return;
3048 
3049       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3050              ScheduleStart->comesBefore(ScheduleEnd) &&
3051              "Not a valid scheduling region?");
3052 
3053       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3054         auto *SD = getScheduleData(I);
3055         if (!SD)
3056           continue;
3057         assert(isInSchedulingRegion(SD) &&
3058                "primary schedule data not in window?");
3059         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3060                "entire bundle in window!");
3061         (void)SD;
3062         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3063       }
3064 
3065       for (auto *SD : ReadyInsts) {
3066         assert(SD->isSchedulingEntity() && SD->isReady() &&
3067                "item in ready list not ready?");
3068         (void)SD;
3069       }
3070     }
3071 
3072     void doForAllOpcodes(Value *V,
3073                          function_ref<void(ScheduleData *SD)> Action) {
3074       if (ScheduleData *SD = getScheduleData(V))
3075         Action(SD);
3076       auto I = ExtraScheduleDataMap.find(V);
3077       if (I != ExtraScheduleDataMap.end())
3078         for (auto &P : I->second)
3079           if (isInSchedulingRegion(P.second))
3080             Action(P.second);
3081     }
3082 
3083     /// Put all instructions into the ReadyList which are ready for scheduling.
3084     template <typename ReadyListType>
3085     void initialFillReadyList(ReadyListType &ReadyList) {
3086       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3087         doForAllOpcodes(I, [&](ScheduleData *SD) {
3088           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3089               SD->isReady()) {
3090             ReadyList.insert(SD);
3091             LLVM_DEBUG(dbgs()
3092                        << "SLP:    initially in ready list: " << *SD << "\n");
3093           }
3094         });
3095       }
3096     }
3097 
3098     /// Build a bundle from the ScheduleData nodes corresponding to the
3099     /// scalar instruction for each lane.
3100     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3101 
3102     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3103     /// cyclic dependencies. This is only a dry-run, no instructions are
3104     /// actually moved at this stage.
3105     /// \returns the scheduling bundle. The returned Optional value is non-None
3106     /// if \p VL is allowed to be scheduled.
3107     Optional<ScheduleData *>
3108     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3109                       const InstructionsState &S);
3110 
3111     /// Un-bundles a group of instructions.
3112     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3113 
3114     /// Allocates schedule data chunk.
3115     ScheduleData *allocateScheduleDataChunks();
3116 
3117     /// Extends the scheduling region so that V is inside the region.
3118     /// \returns true if the region size is within the limit.
3119     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3120 
3121     /// Initialize the ScheduleData structures for new instructions in the
3122     /// scheduling region.
3123     void initScheduleData(Instruction *FromI, Instruction *ToI,
3124                           ScheduleData *PrevLoadStore,
3125                           ScheduleData *NextLoadStore);
3126 
3127     /// Updates the dependency information of a bundle and of all instructions/
3128     /// bundles which depend on the original bundle.
3129     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3130                                BoUpSLP *SLP);
3131 
3132     /// Sets all instruction in the scheduling region to un-scheduled.
3133     void resetSchedule();
3134 
3135     BasicBlock *BB;
3136 
3137     /// Simple memory allocation for ScheduleData.
3138     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3139 
3140     /// The size of a ScheduleData array in ScheduleDataChunks.
3141     int ChunkSize;
3142 
3143     /// The allocator position in the current chunk, which is the last entry
3144     /// of ScheduleDataChunks.
3145     int ChunkPos;
3146 
3147     /// Attaches ScheduleData to Instruction.
3148     /// Note that the mapping survives during all vectorization iterations, i.e.
3149     /// ScheduleData structures are recycled.
3150     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3151 
3152     /// Attaches ScheduleData to Instruction with the leading key.
3153     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3154         ExtraScheduleDataMap;
3155 
3156     /// The ready-list for scheduling (only used for the dry-run).
3157     SetVector<ScheduleData *> ReadyInsts;
3158 
3159     /// The first instruction of the scheduling region.
3160     Instruction *ScheduleStart = nullptr;
3161 
3162     /// The first instruction _after_ the scheduling region.
3163     Instruction *ScheduleEnd = nullptr;
3164 
3165     /// The first memory accessing instruction in the scheduling region
3166     /// (can be null).
3167     ScheduleData *FirstLoadStoreInRegion = nullptr;
3168 
3169     /// The last memory accessing instruction in the scheduling region
3170     /// (can be null).
3171     ScheduleData *LastLoadStoreInRegion = nullptr;
3172 
3173     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3174     /// region?  Used to optimize the dependence calculation for the
3175     /// common case where there isn't.
3176     bool RegionHasStackSave = false;
3177 
3178     /// The current size of the scheduling region.
3179     int ScheduleRegionSize = 0;
3180 
3181     /// The maximum size allowed for the scheduling region.
3182     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3183 
3184     /// The ID of the scheduling region. For a new vectorization iteration this
3185     /// is incremented which "removes" all ScheduleData from the region.
3186     /// Make sure that the initial SchedulingRegionID is greater than the
3187     /// initial SchedulingRegionID in ScheduleData (which is 0).
3188     int SchedulingRegionID = 1;
3189   };
3190 
3191   /// Attaches the BlockScheduling structures to basic blocks.
3192   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3193 
3194   /// Performs the "real" scheduling. Done before vectorization is actually
3195   /// performed in a basic block.
3196   void scheduleBlock(BlockScheduling *BS);
3197 
3198   /// List of users to ignore during scheduling and that don't need extracting.
3199   const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
3200 
3201   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3202   /// sorted SmallVectors of unsigned.
3203   struct OrdersTypeDenseMapInfo {
3204     static OrdersType getEmptyKey() {
3205       OrdersType V;
3206       V.push_back(~1U);
3207       return V;
3208     }
3209 
3210     static OrdersType getTombstoneKey() {
3211       OrdersType V;
3212       V.push_back(~2U);
3213       return V;
3214     }
3215 
3216     static unsigned getHashValue(const OrdersType &V) {
3217       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3218     }
3219 
3220     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3221       return LHS == RHS;
3222     }
3223   };
3224 
3225   // Analysis and block reference.
3226   Function *F;
3227   ScalarEvolution *SE;
3228   TargetTransformInfo *TTI;
3229   TargetLibraryInfo *TLI;
3230   LoopInfo *LI;
3231   DominatorTree *DT;
3232   AssumptionCache *AC;
3233   DemandedBits *DB;
3234   const DataLayout *DL;
3235   OptimizationRemarkEmitter *ORE;
3236 
3237   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3238   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3239 
3240   /// Instruction builder to construct the vectorized tree.
3241   IRBuilder<> Builder;
3242 
3243   /// A map of scalar integer values to the smallest bit width with which they
3244   /// can legally be represented. The values map to (width, signed) pairs,
3245   /// where "width" indicates the minimum bit width and "signed" is True if the
3246   /// value must be signed-extended, rather than zero-extended, back to its
3247   /// original width.
3248   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3249 };
3250 
3251 } // end namespace slpvectorizer
3252 
3253 template <> struct GraphTraits<BoUpSLP *> {
3254   using TreeEntry = BoUpSLP::TreeEntry;
3255 
3256   /// NodeRef has to be a pointer per the GraphWriter.
3257   using NodeRef = TreeEntry *;
3258 
3259   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3260 
3261   /// Add the VectorizableTree to the index iterator to be able to return
3262   /// TreeEntry pointers.
3263   struct ChildIteratorType
3264       : public iterator_adaptor_base<
3265             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3266     ContainerTy &VectorizableTree;
3267 
3268     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3269                       ContainerTy &VT)
3270         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3271 
3272     NodeRef operator*() { return I->UserTE; }
3273   };
3274 
3275   static NodeRef getEntryNode(BoUpSLP &R) {
3276     return R.VectorizableTree[0].get();
3277   }
3278 
3279   static ChildIteratorType child_begin(NodeRef N) {
3280     return {N->UserTreeIndices.begin(), N->Container};
3281   }
3282 
3283   static ChildIteratorType child_end(NodeRef N) {
3284     return {N->UserTreeIndices.end(), N->Container};
3285   }
3286 
3287   /// For the node iterator we just need to turn the TreeEntry iterator into a
3288   /// TreeEntry* iterator so that it dereferences to NodeRef.
3289   class nodes_iterator {
3290     using ItTy = ContainerTy::iterator;
3291     ItTy It;
3292 
3293   public:
3294     nodes_iterator(const ItTy &It2) : It(It2) {}
3295     NodeRef operator*() { return It->get(); }
3296     nodes_iterator operator++() {
3297       ++It;
3298       return *this;
3299     }
3300     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3301   };
3302 
3303   static nodes_iterator nodes_begin(BoUpSLP *R) {
3304     return nodes_iterator(R->VectorizableTree.begin());
3305   }
3306 
3307   static nodes_iterator nodes_end(BoUpSLP *R) {
3308     return nodes_iterator(R->VectorizableTree.end());
3309   }
3310 
3311   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3312 };
3313 
3314 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3315   using TreeEntry = BoUpSLP::TreeEntry;
3316 
3317   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3318 
3319   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3320     std::string Str;
3321     raw_string_ostream OS(Str);
3322     if (isSplat(Entry->Scalars))
3323       OS << "<splat> ";
3324     for (auto V : Entry->Scalars) {
3325       OS << *V;
3326       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3327             return EU.Scalar == V;
3328           }))
3329         OS << " <extract>";
3330       OS << "\n";
3331     }
3332     return Str;
3333   }
3334 
3335   static std::string getNodeAttributes(const TreeEntry *Entry,
3336                                        const BoUpSLP *) {
3337     if (Entry->State == TreeEntry::NeedToGather)
3338       return "color=red";
3339     return "";
3340   }
3341 };
3342 
3343 } // end namespace llvm
3344 
3345 BoUpSLP::~BoUpSLP() {
3346   SmallVector<WeakTrackingVH> DeadInsts;
3347   for (auto *I : DeletedInstructions) {
3348     for (Use &U : I->operands()) {
3349       auto *Op = dyn_cast<Instruction>(U.get());
3350       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3351           wouldInstructionBeTriviallyDead(Op, TLI))
3352         DeadInsts.emplace_back(Op);
3353     }
3354     I->dropAllReferences();
3355   }
3356   for (auto *I : DeletedInstructions) {
3357     assert(I->use_empty() &&
3358            "trying to erase instruction with users.");
3359     I->eraseFromParent();
3360   }
3361 
3362   // Cleanup any dead scalar code feeding the vectorized instructions
3363   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3364 
3365 #ifdef EXPENSIVE_CHECKS
3366   // If we could guarantee that this call is not extremely slow, we could
3367   // remove the ifdef limitation (see PR47712).
3368   assert(!verifyFunction(*F, &dbgs()));
3369 #endif
3370 }
3371 
3372 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3373 /// contains original mask for the scalars reused in the node. Procedure
3374 /// transform this mask in accordance with the given \p Mask.
3375 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3376   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3377          "Expected non-empty mask.");
3378   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3379   Prev.swap(Reuses);
3380   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3381     if (Mask[I] != UndefMaskElem)
3382       Reuses[Mask[I]] = Prev[I];
3383 }
3384 
3385 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3386 /// the original order of the scalars. Procedure transforms the provided order
3387 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3388 /// identity order, \p Order is cleared.
3389 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3390   assert(!Mask.empty() && "Expected non-empty mask.");
3391   SmallVector<int> MaskOrder;
3392   if (Order.empty()) {
3393     MaskOrder.resize(Mask.size());
3394     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3395   } else {
3396     inversePermutation(Order, MaskOrder);
3397   }
3398   reorderReuses(MaskOrder, Mask);
3399   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3400     Order.clear();
3401     return;
3402   }
3403   Order.assign(Mask.size(), Mask.size());
3404   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3405     if (MaskOrder[I] != UndefMaskElem)
3406       Order[MaskOrder[I]] = I;
3407   fixupOrderingIndices(Order);
3408 }
3409 
3410 Optional<BoUpSLP::OrdersType>
3411 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3412   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3413   unsigned NumScalars = TE.Scalars.size();
3414   OrdersType CurrentOrder(NumScalars, NumScalars);
3415   SmallVector<int> Positions;
3416   SmallBitVector UsedPositions(NumScalars);
3417   const TreeEntry *STE = nullptr;
3418   // Try to find all gathered scalars that are gets vectorized in other
3419   // vectorize node. Here we can have only one single tree vector node to
3420   // correctly identify order of the gathered scalars.
3421   for (unsigned I = 0; I < NumScalars; ++I) {
3422     Value *V = TE.Scalars[I];
3423     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3424       continue;
3425     if (const auto *LocalSTE = getTreeEntry(V)) {
3426       if (!STE)
3427         STE = LocalSTE;
3428       else if (STE != LocalSTE)
3429         // Take the order only from the single vector node.
3430         return None;
3431       unsigned Lane =
3432           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3433       if (Lane >= NumScalars)
3434         return None;
3435       if (CurrentOrder[Lane] != NumScalars) {
3436         if (Lane != I)
3437           continue;
3438         UsedPositions.reset(CurrentOrder[Lane]);
3439       }
3440       // The partial identity (where only some elements of the gather node are
3441       // in the identity order) is good.
3442       CurrentOrder[Lane] = I;
3443       UsedPositions.set(I);
3444     }
3445   }
3446   // Need to keep the order if we have a vector entry and at least 2 scalars or
3447   // the vectorized entry has just 2 scalars.
3448   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3449     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3450       for (unsigned I = 0; I < NumScalars; ++I)
3451         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3452           return false;
3453       return true;
3454     };
3455     if (IsIdentityOrder(CurrentOrder)) {
3456       CurrentOrder.clear();
3457       return CurrentOrder;
3458     }
3459     auto *It = CurrentOrder.begin();
3460     for (unsigned I = 0; I < NumScalars;) {
3461       if (UsedPositions.test(I)) {
3462         ++I;
3463         continue;
3464       }
3465       if (*It == NumScalars) {
3466         *It = I;
3467         ++I;
3468       }
3469       ++It;
3470     }
3471     return CurrentOrder;
3472   }
3473   return None;
3474 }
3475 
3476 namespace {
3477 /// Tracks the state we can represent the loads in the given sequence.
3478 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3479 } // anonymous namespace
3480 
3481 /// Checks if the given array of loads can be represented as a vectorized,
3482 /// scatter or just simple gather.
3483 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3484                                     const TargetTransformInfo &TTI,
3485                                     const DataLayout &DL, ScalarEvolution &SE,
3486                                     LoopInfo &LI,
3487                                     SmallVectorImpl<unsigned> &Order,
3488                                     SmallVectorImpl<Value *> &PointerOps) {
3489   // Check that a vectorized load would load the same memory as a scalar
3490   // load. For example, we don't want to vectorize loads that are smaller
3491   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3492   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3493   // from such a struct, we read/write packed bits disagreeing with the
3494   // unvectorized version.
3495   Type *ScalarTy = VL0->getType();
3496 
3497   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3498     return LoadsState::Gather;
3499 
3500   // Make sure all loads in the bundle are simple - we can't vectorize
3501   // atomic or volatile loads.
3502   PointerOps.clear();
3503   PointerOps.resize(VL.size());
3504   auto *POIter = PointerOps.begin();
3505   for (Value *V : VL) {
3506     auto *L = cast<LoadInst>(V);
3507     if (!L->isSimple())
3508       return LoadsState::Gather;
3509     *POIter = L->getPointerOperand();
3510     ++POIter;
3511   }
3512 
3513   Order.clear();
3514   // Check the order of pointer operands or that all pointers are the same.
3515   bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order);
3516   if (IsSorted || all_of(PointerOps, [&PointerOps](Value *P) {
3517         if (getUnderlyingObject(P) != getUnderlyingObject(PointerOps.front()))
3518           return false;
3519         auto *GEP = dyn_cast<GetElementPtrInst>(P);
3520         if (!GEP)
3521           return false;
3522         auto *GEP0 = cast<GetElementPtrInst>(PointerOps.front());
3523         return GEP->getNumOperands() == 2 &&
3524                ((isConstant(GEP->getOperand(1)) &&
3525                  isConstant(GEP0->getOperand(1))) ||
3526                 getSameOpcode({GEP->getOperand(1), GEP0->getOperand(1)})
3527                     .getOpcode());
3528       })) {
3529     if (IsSorted) {
3530       Value *Ptr0;
3531       Value *PtrN;
3532       if (Order.empty()) {
3533         Ptr0 = PointerOps.front();
3534         PtrN = PointerOps.back();
3535       } else {
3536         Ptr0 = PointerOps[Order.front()];
3537         PtrN = PointerOps[Order.back()];
3538       }
3539       Optional<int> Diff =
3540           getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3541       // Check that the sorted loads are consecutive.
3542       if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3543         return LoadsState::Vectorize;
3544     }
3545     // TODO: need to improve analysis of the pointers, if not all of them are
3546     // GEPs or have > 2 operands, we end up with a gather node, which just
3547     // increases the cost.
3548     Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent());
3549     bool ProfitableGatherPointers =
3550         static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
3551           return L && L->isLoopInvariant(V);
3552         })) <= VL.size() / 2 && VL.size() > 2;
3553     if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) {
3554           auto *GEP = dyn_cast<GetElementPtrInst>(P);
3555           return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) ||
3556                  (GEP && GEP->getNumOperands() == 2);
3557         })) {
3558       Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3559       for (Value *V : VL)
3560         CommonAlignment =
3561             commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3562       auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3563       if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
3564           !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
3565         return LoadsState::ScatterVectorize;
3566     }
3567   }
3568 
3569   return LoadsState::Gather;
3570 }
3571 
3572 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3573                             const DataLayout &DL, ScalarEvolution &SE,
3574                             SmallVectorImpl<unsigned> &SortedIndices) {
3575   assert(llvm::all_of(
3576              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3577          "Expected list of pointer operands.");
3578   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3579   // Ptr into, sort and return the sorted indices with values next to one
3580   // another.
3581   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3582   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3583 
3584   unsigned Cnt = 1;
3585   for (Value *Ptr : VL.drop_front()) {
3586     bool Found = any_of(Bases, [&](auto &Base) {
3587       Optional<int> Diff =
3588           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3589                           /*StrictCheck=*/true);
3590       if (!Diff)
3591         return false;
3592 
3593       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3594       return true;
3595     });
3596 
3597     if (!Found) {
3598       // If we haven't found enough to usefully cluster, return early.
3599       if (Bases.size() > VL.size() / 2 - 1)
3600         return false;
3601 
3602       // Not found already - add a new Base
3603       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3604     }
3605   }
3606 
3607   // For each of the bases sort the pointers by Offset and check if any of the
3608   // base become consecutively allocated.
3609   bool AnyConsecutive = false;
3610   for (auto &Base : Bases) {
3611     auto &Vec = Base.second;
3612     if (Vec.size() > 1) {
3613       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3614                                 const std::tuple<Value *, int, unsigned> &Y) {
3615         return std::get<1>(X) < std::get<1>(Y);
3616       });
3617       int InitialOffset = std::get<1>(Vec[0]);
3618       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3619         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3620       });
3621     }
3622   }
3623 
3624   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3625   SortedIndices.clear();
3626   if (!AnyConsecutive)
3627     return false;
3628 
3629   for (auto &Base : Bases) {
3630     for (auto &T : Base.second)
3631       SortedIndices.push_back(std::get<2>(T));
3632   }
3633 
3634   assert(SortedIndices.size() == VL.size() &&
3635          "Expected SortedIndices to be the size of VL");
3636   return true;
3637 }
3638 
3639 Optional<BoUpSLP::OrdersType>
3640 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3641   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3642   Type *ScalarTy = TE.Scalars[0]->getType();
3643 
3644   SmallVector<Value *> Ptrs;
3645   Ptrs.reserve(TE.Scalars.size());
3646   for (Value *V : TE.Scalars) {
3647     auto *L = dyn_cast<LoadInst>(V);
3648     if (!L || !L->isSimple())
3649       return None;
3650     Ptrs.push_back(L->getPointerOperand());
3651   }
3652 
3653   BoUpSLP::OrdersType Order;
3654   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3655     return Order;
3656   return None;
3657 }
3658 
3659 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3660                                                          bool TopToBottom) {
3661   // No need to reorder if need to shuffle reuses, still need to shuffle the
3662   // node.
3663   if (!TE.ReuseShuffleIndices.empty())
3664     return None;
3665   if (TE.State == TreeEntry::Vectorize &&
3666       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3667        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3668       !TE.isAltShuffle())
3669     return TE.ReorderIndices;
3670   if (TE.State == TreeEntry::NeedToGather) {
3671     // TODO: add analysis of other gather nodes with extractelement
3672     // instructions and other values/instructions, not only undefs.
3673     if (((TE.getOpcode() == Instruction::ExtractElement &&
3674           !TE.isAltShuffle()) ||
3675          (all_of(TE.Scalars,
3676                  [](Value *V) {
3677                    return isa<UndefValue, ExtractElementInst>(V);
3678                  }) &&
3679           any_of(TE.Scalars,
3680                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3681         all_of(TE.Scalars,
3682                [](Value *V) {
3683                  auto *EE = dyn_cast<ExtractElementInst>(V);
3684                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3685                }) &&
3686         allSameType(TE.Scalars)) {
3687       // Check that gather of extractelements can be represented as
3688       // just a shuffle of a single vector.
3689       OrdersType CurrentOrder;
3690       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3691       if (Reuse || !CurrentOrder.empty()) {
3692         if (!CurrentOrder.empty())
3693           fixupOrderingIndices(CurrentOrder);
3694         return CurrentOrder;
3695       }
3696     }
3697     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3698       return CurrentOrder;
3699     if (TE.Scalars.size() >= 4)
3700       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3701         return Order;
3702   }
3703   return None;
3704 }
3705 
3706 void BoUpSLP::reorderTopToBottom() {
3707   // Maps VF to the graph nodes.
3708   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3709   // ExtractElement gather nodes which can be vectorized and need to handle
3710   // their ordering.
3711   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3712 
3713   // AltShuffles can also have a preferred ordering that leads to fewer
3714   // instructions, e.g., the addsub instruction in x86.
3715   DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
3716 
3717   // Maps a TreeEntry to the reorder indices of external users.
3718   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3719       ExternalUserReorderMap;
3720   // FIXME: Workaround for syntax error reported by MSVC buildbots.
3721   TargetTransformInfo &TTIRef = *TTI;
3722   // Find all reorderable nodes with the given VF.
3723   // Currently the are vectorized stores,loads,extracts + some gathering of
3724   // extracts.
3725   for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries,
3726                               &GathersToOrders, &ExternalUserReorderMap,
3727                               &AltShufflesToOrders](
3728                                  const std::unique_ptr<TreeEntry> &TE) {
3729     // Look for external users that will probably be vectorized.
3730     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3731         findExternalStoreUsersReorderIndices(TE.get());
3732     if (!ExternalUserReorderIndices.empty()) {
3733       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3734       ExternalUserReorderMap.try_emplace(TE.get(),
3735                                          std::move(ExternalUserReorderIndices));
3736     }
3737 
3738     // Patterns like [fadd,fsub] can be combined into a single instruction in
3739     // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
3740     // to take into account their order when looking for the most used order.
3741     if (TE->isAltShuffle()) {
3742       VectorType *VecTy =
3743           FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size());
3744       unsigned Opcode0 = TE->getOpcode();
3745       unsigned Opcode1 = TE->getAltOpcode();
3746       // The opcode mask selects between the two opcodes.
3747       SmallBitVector OpcodeMask(TE->Scalars.size(), 0);
3748       for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size()))
3749         if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1)
3750           OpcodeMask.set(Lane);
3751       // If this pattern is supported by the target then we consider the order.
3752       if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
3753         VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3754         AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
3755       }
3756       // TODO: Check the reverse order too.
3757     }
3758 
3759     if (Optional<OrdersType> CurrentOrder =
3760             getReorderingData(*TE, /*TopToBottom=*/true)) {
3761       // Do not include ordering for nodes used in the alt opcode vectorization,
3762       // better to reorder them during bottom-to-top stage. If follow the order
3763       // here, it causes reordering of the whole graph though actually it is
3764       // profitable just to reorder the subgraph that starts from the alternate
3765       // opcode vectorization node. Such nodes already end-up with the shuffle
3766       // instruction and it is just enough to change this shuffle rather than
3767       // rotate the scalars for the whole graph.
3768       unsigned Cnt = 0;
3769       const TreeEntry *UserTE = TE.get();
3770       while (UserTE && Cnt < RecursionMaxDepth) {
3771         if (UserTE->UserTreeIndices.size() != 1)
3772           break;
3773         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3774               return EI.UserTE->State == TreeEntry::Vectorize &&
3775                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3776             }))
3777           return;
3778         UserTE = UserTE->UserTreeIndices.back().UserTE;
3779         ++Cnt;
3780       }
3781       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3782       if (TE->State != TreeEntry::Vectorize)
3783         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3784     }
3785   });
3786 
3787   // Reorder the graph nodes according to their vectorization factor.
3788   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3789        VF /= 2) {
3790     auto It = VFToOrderedEntries.find(VF);
3791     if (It == VFToOrderedEntries.end())
3792       continue;
3793     // Try to find the most profitable order. We just are looking for the most
3794     // used order and reorder scalar elements in the nodes according to this
3795     // mostly used order.
3796     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3797     // All operands are reordered and used only in this node - propagate the
3798     // most used order to the user node.
3799     MapVector<OrdersType, unsigned,
3800               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3801         OrdersUses;
3802     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3803     for (const TreeEntry *OpTE : OrderedEntries) {
3804       // No need to reorder this nodes, still need to extend and to use shuffle,
3805       // just need to merge reordering shuffle and the reuse shuffle.
3806       if (!OpTE->ReuseShuffleIndices.empty())
3807         continue;
3808       // Count number of orders uses.
3809       const auto &Order = [OpTE, &GathersToOrders,
3810                            &AltShufflesToOrders]() -> const OrdersType & {
3811         if (OpTE->State == TreeEntry::NeedToGather) {
3812           auto It = GathersToOrders.find(OpTE);
3813           if (It != GathersToOrders.end())
3814             return It->second;
3815         }
3816         if (OpTE->isAltShuffle()) {
3817           auto It = AltShufflesToOrders.find(OpTE);
3818           if (It != AltShufflesToOrders.end())
3819             return It->second;
3820         }
3821         return OpTE->ReorderIndices;
3822       }();
3823       // First consider the order of the external scalar users.
3824       auto It = ExternalUserReorderMap.find(OpTE);
3825       if (It != ExternalUserReorderMap.end()) {
3826         const auto &ExternalUserReorderIndices = It->second;
3827         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3828           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3829         // No other useful reorder data in this entry.
3830         if (Order.empty())
3831           continue;
3832       }
3833       // Stores actually store the mask, not the order, need to invert.
3834       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3835           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3836         SmallVector<int> Mask;
3837         inversePermutation(Order, Mask);
3838         unsigned E = Order.size();
3839         OrdersType CurrentOrder(E, E);
3840         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3841           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3842         });
3843         fixupOrderingIndices(CurrentOrder);
3844         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3845       } else {
3846         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3847       }
3848     }
3849     // Set order of the user node.
3850     if (OrdersUses.empty())
3851       continue;
3852     // Choose the most used order.
3853     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3854     unsigned Cnt = OrdersUses.front().second;
3855     for (const auto &Pair : drop_begin(OrdersUses)) {
3856       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3857         BestOrder = Pair.first;
3858         Cnt = Pair.second;
3859       }
3860     }
3861     // Set order of the user node.
3862     if (BestOrder.empty())
3863       continue;
3864     SmallVector<int> Mask;
3865     inversePermutation(BestOrder, Mask);
3866     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3867     unsigned E = BestOrder.size();
3868     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3869       return I < E ? static_cast<int>(I) : UndefMaskElem;
3870     });
3871     // Do an actual reordering, if profitable.
3872     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3873       // Just do the reordering for the nodes with the given VF.
3874       if (TE->Scalars.size() != VF) {
3875         if (TE->ReuseShuffleIndices.size() == VF) {
3876           // Need to reorder the reuses masks of the operands with smaller VF to
3877           // be able to find the match between the graph nodes and scalar
3878           // operands of the given node during vectorization/cost estimation.
3879           assert(all_of(TE->UserTreeIndices,
3880                         [VF, &TE](const EdgeInfo &EI) {
3881                           return EI.UserTE->Scalars.size() == VF ||
3882                                  EI.UserTE->Scalars.size() ==
3883                                      TE->Scalars.size();
3884                         }) &&
3885                  "All users must be of VF size.");
3886           // Update ordering of the operands with the smaller VF than the given
3887           // one.
3888           reorderReuses(TE->ReuseShuffleIndices, Mask);
3889         }
3890         continue;
3891       }
3892       if (TE->State == TreeEntry::Vectorize &&
3893           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3894               InsertElementInst>(TE->getMainOp()) &&
3895           !TE->isAltShuffle()) {
3896         // Build correct orders for extract{element,value}, loads and
3897         // stores.
3898         reorderOrder(TE->ReorderIndices, Mask);
3899         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3900           TE->reorderOperands(Mask);
3901       } else {
3902         // Reorder the node and its operands.
3903         TE->reorderOperands(Mask);
3904         assert(TE->ReorderIndices.empty() &&
3905                "Expected empty reorder sequence.");
3906         reorderScalars(TE->Scalars, Mask);
3907       }
3908       if (!TE->ReuseShuffleIndices.empty()) {
3909         // Apply reversed order to keep the original ordering of the reused
3910         // elements to avoid extra reorder indices shuffling.
3911         OrdersType CurrentOrder;
3912         reorderOrder(CurrentOrder, MaskOrder);
3913         SmallVector<int> NewReuses;
3914         inversePermutation(CurrentOrder, NewReuses);
3915         addMask(NewReuses, TE->ReuseShuffleIndices);
3916         TE->ReuseShuffleIndices.swap(NewReuses);
3917       }
3918     }
3919   }
3920 }
3921 
3922 bool BoUpSLP::canReorderOperands(
3923     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3924     ArrayRef<TreeEntry *> ReorderableGathers,
3925     SmallVectorImpl<TreeEntry *> &GatherOps) {
3926   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3927     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3928           return OpData.first == I &&
3929                  OpData.second->State == TreeEntry::Vectorize;
3930         }))
3931       continue;
3932     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3933       // Do not reorder if operand node is used by many user nodes.
3934       if (any_of(TE->UserTreeIndices,
3935                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3936         return false;
3937       // Add the node to the list of the ordered nodes with the identity
3938       // order.
3939       Edges.emplace_back(I, TE);
3940       // Add ScatterVectorize nodes to the list of operands, where just
3941       // reordering of the scalars is required. Similar to the gathers, so
3942       // simply add to the list of gathered ops.
3943       // If there are reused scalars, process this node as a regular vectorize
3944       // node, just reorder reuses mask.
3945       if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty())
3946         GatherOps.push_back(TE);
3947       continue;
3948     }
3949     ArrayRef<Value *> VL = UserTE->getOperand(I);
3950     TreeEntry *Gather = nullptr;
3951     if (count_if(ReorderableGathers,
3952                  [VL, &Gather](TreeEntry *TE) {
3953                    assert(TE->State != TreeEntry::Vectorize &&
3954                           "Only non-vectorized nodes are expected.");
3955                    if (TE->isSame(VL)) {
3956                      Gather = TE;
3957                      return true;
3958                    }
3959                    return false;
3960                  }) > 1 &&
3961         !all_of(VL, isConstant))
3962       return false;
3963     if (Gather)
3964       GatherOps.push_back(Gather);
3965   }
3966   return true;
3967 }
3968 
3969 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3970   SetVector<TreeEntry *> OrderedEntries;
3971   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3972   // Find all reorderable leaf nodes with the given VF.
3973   // Currently the are vectorized loads,extracts without alternate operands +
3974   // some gathering of extracts.
3975   SmallVector<TreeEntry *> NonVectorized;
3976   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3977                               &NonVectorized](
3978                                  const std::unique_ptr<TreeEntry> &TE) {
3979     if (TE->State != TreeEntry::Vectorize)
3980       NonVectorized.push_back(TE.get());
3981     if (Optional<OrdersType> CurrentOrder =
3982             getReorderingData(*TE, /*TopToBottom=*/false)) {
3983       OrderedEntries.insert(TE.get());
3984       if (TE->State != TreeEntry::Vectorize)
3985         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3986     }
3987   });
3988 
3989   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3990   // I.e., if the node has operands, that are reordered, try to make at least
3991   // one operand order in the natural order and reorder others + reorder the
3992   // user node itself.
3993   SmallPtrSet<const TreeEntry *, 4> Visited;
3994   while (!OrderedEntries.empty()) {
3995     // 1. Filter out only reordered nodes.
3996     // 2. If the entry has multiple uses - skip it and jump to the next node.
3997     DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3998     SmallVector<TreeEntry *> Filtered;
3999     for (TreeEntry *TE : OrderedEntries) {
4000       if (!(TE->State == TreeEntry::Vectorize ||
4001             (TE->State == TreeEntry::NeedToGather &&
4002              GathersToOrders.count(TE))) ||
4003           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4004           !all_of(drop_begin(TE->UserTreeIndices),
4005                   [TE](const EdgeInfo &EI) {
4006                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
4007                   }) ||
4008           !Visited.insert(TE).second) {
4009         Filtered.push_back(TE);
4010         continue;
4011       }
4012       // Build a map between user nodes and their operands order to speedup
4013       // search. The graph currently does not provide this dependency directly.
4014       for (EdgeInfo &EI : TE->UserTreeIndices) {
4015         TreeEntry *UserTE = EI.UserTE;
4016         auto It = Users.find(UserTE);
4017         if (It == Users.end())
4018           It = Users.insert({UserTE, {}}).first;
4019         It->second.emplace_back(EI.EdgeIdx, TE);
4020       }
4021     }
4022     // Erase filtered entries.
4023     for_each(Filtered,
4024              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
4025     SmallVector<
4026         std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
4027         UsersVec(Users.begin(), Users.end());
4028     sort(UsersVec, [](const auto &Data1, const auto &Data2) {
4029       return Data1.first->Idx > Data2.first->Idx;
4030     });
4031     for (auto &Data : UsersVec) {
4032       // Check that operands are used only in the User node.
4033       SmallVector<TreeEntry *> GatherOps;
4034       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
4035                               GatherOps)) {
4036         for_each(Data.second,
4037                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4038                    OrderedEntries.remove(Op.second);
4039                  });
4040         continue;
4041       }
4042       // All operands are reordered and used only in this node - propagate the
4043       // most used order to the user node.
4044       MapVector<OrdersType, unsigned,
4045                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
4046           OrdersUses;
4047       // Do the analysis for each tree entry only once, otherwise the order of
4048       // the same node my be considered several times, though might be not
4049       // profitable.
4050       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
4051       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
4052       for (const auto &Op : Data.second) {
4053         TreeEntry *OpTE = Op.second;
4054         if (!VisitedOps.insert(OpTE).second)
4055           continue;
4056         if (!OpTE->ReuseShuffleIndices.empty() ||
4057             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
4058           continue;
4059         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
4060           if (OpTE->State == TreeEntry::NeedToGather)
4061             return GathersToOrders.find(OpTE)->second;
4062           return OpTE->ReorderIndices;
4063         }();
4064         unsigned NumOps = count_if(
4065             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
4066               return P.second == OpTE;
4067             });
4068         // Stores actually store the mask, not the order, need to invert.
4069         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4070             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4071           SmallVector<int> Mask;
4072           inversePermutation(Order, Mask);
4073           unsigned E = Order.size();
4074           OrdersType CurrentOrder(E, E);
4075           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4076             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4077           });
4078           fixupOrderingIndices(CurrentOrder);
4079           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
4080               NumOps;
4081         } else {
4082           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
4083         }
4084         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
4085         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
4086                                             const TreeEntry *TE) {
4087           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4088               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
4089               (IgnoreReorder && TE->Idx == 0))
4090             return true;
4091           if (TE->State == TreeEntry::NeedToGather) {
4092             auto It = GathersToOrders.find(TE);
4093             if (It != GathersToOrders.end())
4094               return !It->second.empty();
4095             return true;
4096           }
4097           return false;
4098         };
4099         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
4100           TreeEntry *UserTE = EI.UserTE;
4101           if (!VisitedUsers.insert(UserTE).second)
4102             continue;
4103           // May reorder user node if it requires reordering, has reused
4104           // scalars, is an alternate op vectorize node or its op nodes require
4105           // reordering.
4106           if (AllowsReordering(UserTE))
4107             continue;
4108           // Check if users allow reordering.
4109           // Currently look up just 1 level of operands to avoid increase of
4110           // the compile time.
4111           // Profitable to reorder if definitely more operands allow
4112           // reordering rather than those with natural order.
4113           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
4114           if (static_cast<unsigned>(count_if(
4115                   Ops, [UserTE, &AllowsReordering](
4116                            const std::pair<unsigned, TreeEntry *> &Op) {
4117                     return AllowsReordering(Op.second) &&
4118                            all_of(Op.second->UserTreeIndices,
4119                                   [UserTE](const EdgeInfo &EI) {
4120                                     return EI.UserTE == UserTE;
4121                                   });
4122                   })) <= Ops.size() / 2)
4123             ++Res.first->second;
4124         }
4125       }
4126       // If no orders - skip current nodes and jump to the next one, if any.
4127       if (OrdersUses.empty()) {
4128         for_each(Data.second,
4129                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4130                    OrderedEntries.remove(Op.second);
4131                  });
4132         continue;
4133       }
4134       // Choose the best order.
4135       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4136       unsigned Cnt = OrdersUses.front().second;
4137       for (const auto &Pair : drop_begin(OrdersUses)) {
4138         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4139           BestOrder = Pair.first;
4140           Cnt = Pair.second;
4141         }
4142       }
4143       // Set order of the user node (reordering of operands and user nodes).
4144       if (BestOrder.empty()) {
4145         for_each(Data.second,
4146                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4147                    OrderedEntries.remove(Op.second);
4148                  });
4149         continue;
4150       }
4151       // Erase operands from OrderedEntries list and adjust their orders.
4152       VisitedOps.clear();
4153       SmallVector<int> Mask;
4154       inversePermutation(BestOrder, Mask);
4155       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4156       unsigned E = BestOrder.size();
4157       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4158         return I < E ? static_cast<int>(I) : UndefMaskElem;
4159       });
4160       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4161         TreeEntry *TE = Op.second;
4162         OrderedEntries.remove(TE);
4163         if (!VisitedOps.insert(TE).second)
4164           continue;
4165         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4166           // Just reorder reuses indices.
4167           reorderReuses(TE->ReuseShuffleIndices, Mask);
4168           continue;
4169         }
4170         // Gathers are processed separately.
4171         if (TE->State != TreeEntry::Vectorize)
4172           continue;
4173         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4174                 TE->ReorderIndices.empty()) &&
4175                "Non-matching sizes of user/operand entries.");
4176         reorderOrder(TE->ReorderIndices, Mask);
4177       }
4178       // For gathers just need to reorder its scalars.
4179       for (TreeEntry *Gather : GatherOps) {
4180         assert(Gather->ReorderIndices.empty() &&
4181                "Unexpected reordering of gathers.");
4182         if (!Gather->ReuseShuffleIndices.empty()) {
4183           // Just reorder reuses indices.
4184           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4185           continue;
4186         }
4187         reorderScalars(Gather->Scalars, Mask);
4188         OrderedEntries.remove(Gather);
4189       }
4190       // Reorder operands of the user node and set the ordering for the user
4191       // node itself.
4192       if (Data.first->State != TreeEntry::Vectorize ||
4193           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4194               Data.first->getMainOp()) ||
4195           Data.first->isAltShuffle())
4196         Data.first->reorderOperands(Mask);
4197       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4198           Data.first->isAltShuffle()) {
4199         reorderScalars(Data.first->Scalars, Mask);
4200         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4201         if (Data.first->ReuseShuffleIndices.empty() &&
4202             !Data.first->ReorderIndices.empty() &&
4203             !Data.first->isAltShuffle()) {
4204           // Insert user node to the list to try to sink reordering deeper in
4205           // the graph.
4206           OrderedEntries.insert(Data.first);
4207         }
4208       } else {
4209         reorderOrder(Data.first->ReorderIndices, Mask);
4210       }
4211     }
4212   }
4213   // If the reordering is unnecessary, just remove the reorder.
4214   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4215       VectorizableTree.front()->ReuseShuffleIndices.empty())
4216     VectorizableTree.front()->ReorderIndices.clear();
4217 }
4218 
4219 void BoUpSLP::buildExternalUses(
4220     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4221   // Collect the values that we need to extract from the tree.
4222   for (auto &TEPtr : VectorizableTree) {
4223     TreeEntry *Entry = TEPtr.get();
4224 
4225     // No need to handle users of gathered values.
4226     if (Entry->State == TreeEntry::NeedToGather)
4227       continue;
4228 
4229     // For each lane:
4230     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4231       Value *Scalar = Entry->Scalars[Lane];
4232       int FoundLane = Entry->findLaneForValue(Scalar);
4233 
4234       // Check if the scalar is externally used as an extra arg.
4235       auto ExtI = ExternallyUsedValues.find(Scalar);
4236       if (ExtI != ExternallyUsedValues.end()) {
4237         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4238                           << Lane << " from " << *Scalar << ".\n");
4239         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4240       }
4241       for (User *U : Scalar->users()) {
4242         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4243 
4244         Instruction *UserInst = dyn_cast<Instruction>(U);
4245         if (!UserInst)
4246           continue;
4247 
4248         if (isDeleted(UserInst))
4249           continue;
4250 
4251         // Skip in-tree scalars that become vectors
4252         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4253           Value *UseScalar = UseEntry->Scalars[0];
4254           // Some in-tree scalars will remain as scalar in vectorized
4255           // instructions. If that is the case, the one in Lane 0 will
4256           // be used.
4257           if (UseScalar != U ||
4258               UseEntry->State == TreeEntry::ScatterVectorize ||
4259               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4260             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4261                               << ".\n");
4262             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4263             continue;
4264           }
4265         }
4266 
4267         // Ignore users in the user ignore list.
4268         if (UserIgnoreList && UserIgnoreList->contains(UserInst))
4269           continue;
4270 
4271         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4272                           << Lane << " from " << *Scalar << ".\n");
4273         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4274       }
4275     }
4276   }
4277 }
4278 
4279 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4280 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4281   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4282   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4283     Value *V = TE->Scalars[Lane];
4284     // To save compilation time we don't visit if we have too many users.
4285     static constexpr unsigned UsersLimit = 4;
4286     if (V->hasNUsesOrMore(UsersLimit))
4287       break;
4288 
4289     // Collect stores per pointer object.
4290     for (User *U : V->users()) {
4291       auto *SI = dyn_cast<StoreInst>(U);
4292       if (SI == nullptr || !SI->isSimple() ||
4293           !isValidElementType(SI->getValueOperand()->getType()))
4294         continue;
4295       // Skip entry if already
4296       if (getTreeEntry(U))
4297         continue;
4298 
4299       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4300       auto &StoresVec = PtrToStoresMap[Ptr];
4301       // For now just keep one store per pointer object per lane.
4302       // TODO: Extend this to support multiple stores per pointer per lane
4303       if (StoresVec.size() > Lane)
4304         continue;
4305       // Skip if in different BBs.
4306       if (!StoresVec.empty() &&
4307           SI->getParent() != StoresVec.back()->getParent())
4308         continue;
4309       // Make sure that the stores are of the same type.
4310       if (!StoresVec.empty() &&
4311           SI->getValueOperand()->getType() !=
4312               StoresVec.back()->getValueOperand()->getType())
4313         continue;
4314       StoresVec.push_back(SI);
4315     }
4316   }
4317   return PtrToStoresMap;
4318 }
4319 
4320 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4321                             OrdersType &ReorderIndices) const {
4322   // We check whether the stores in StoreVec can form a vector by sorting them
4323   // and checking whether they are consecutive.
4324 
4325   // To avoid calling getPointersDiff() while sorting we create a vector of
4326   // pairs {store, offset from first} and sort this instead.
4327   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4328   StoreInst *S0 = StoresVec[0];
4329   StoreOffsetVec[0] = {S0, 0};
4330   Type *S0Ty = S0->getValueOperand()->getType();
4331   Value *S0Ptr = S0->getPointerOperand();
4332   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4333     StoreInst *SI = StoresVec[Idx];
4334     Optional<int> Diff =
4335         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4336                         SI->getPointerOperand(), *DL, *SE,
4337                         /*StrictCheck=*/true);
4338     // We failed to compare the pointers so just abandon this StoresVec.
4339     if (!Diff)
4340       return false;
4341     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4342   }
4343 
4344   // Sort the vector based on the pointers. We create a copy because we may
4345   // need the original later for calculating the reorder (shuffle) indices.
4346   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4347                                  const std::pair<StoreInst *, int> &Pair2) {
4348     int Offset1 = Pair1.second;
4349     int Offset2 = Pair2.second;
4350     return Offset1 < Offset2;
4351   });
4352 
4353   // Check if the stores are consecutive by checking if their difference is 1.
4354   for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4355     if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4356       return false;
4357 
4358   // Calculate the shuffle indices according to their offset against the sorted
4359   // StoreOffsetVec.
4360   ReorderIndices.reserve(StoresVec.size());
4361   for (StoreInst *SI : StoresVec) {
4362     unsigned Idx = find_if(StoreOffsetVec,
4363                            [SI](const std::pair<StoreInst *, int> &Pair) {
4364                              return Pair.first == SI;
4365                            }) -
4366                    StoreOffsetVec.begin();
4367     ReorderIndices.push_back(Idx);
4368   }
4369   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4370   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4371   // same convention here.
4372   auto IsIdentityOrder = [](const OrdersType &Order) {
4373     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4374       if (Idx != Order[Idx])
4375         return false;
4376     return true;
4377   };
4378   if (IsIdentityOrder(ReorderIndices))
4379     ReorderIndices.clear();
4380 
4381   return true;
4382 }
4383 
4384 #ifndef NDEBUG
4385 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4386   for (unsigned Idx : Order)
4387     dbgs() << Idx << ", ";
4388   dbgs() << "\n";
4389 }
4390 #endif
4391 
4392 SmallVector<BoUpSLP::OrdersType, 1>
4393 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4394   unsigned NumLanes = TE->Scalars.size();
4395 
4396   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4397       collectUserStores(TE);
4398 
4399   // Holds the reorder indices for each candidate store vector that is a user of
4400   // the current TreeEntry.
4401   SmallVector<OrdersType, 1> ExternalReorderIndices;
4402 
4403   // Now inspect the stores collected per pointer and look for vectorization
4404   // candidates. For each candidate calculate the reorder index vector and push
4405   // it into `ExternalReorderIndices`
4406   for (const auto &Pair : PtrToStoresMap) {
4407     auto &StoresVec = Pair.second;
4408     // If we have fewer than NumLanes stores, then we can't form a vector.
4409     if (StoresVec.size() != NumLanes)
4410       continue;
4411 
4412     // If the stores are not consecutive then abandon this StoresVec.
4413     OrdersType ReorderIndices;
4414     if (!CanFormVector(StoresVec, ReorderIndices))
4415       continue;
4416 
4417     // We now know that the scalars in StoresVec can form a vector instruction,
4418     // so set the reorder indices.
4419     ExternalReorderIndices.push_back(ReorderIndices);
4420   }
4421   return ExternalReorderIndices;
4422 }
4423 
4424 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4425                         const SmallDenseSet<Value *> &UserIgnoreLst) {
4426   deleteTree();
4427   UserIgnoreList = &UserIgnoreLst;
4428   if (!allSameType(Roots))
4429     return;
4430   buildTree_rec(Roots, 0, EdgeInfo());
4431 }
4432 
4433 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
4434   deleteTree();
4435   if (!allSameType(Roots))
4436     return;
4437   buildTree_rec(Roots, 0, EdgeInfo());
4438 }
4439 
4440 /// \return true if the specified list of values has only one instruction that
4441 /// requires scheduling, false otherwise.
4442 #ifndef NDEBUG
4443 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4444   Value *NeedsScheduling = nullptr;
4445   for (Value *V : VL) {
4446     if (doesNotNeedToBeScheduled(V))
4447       continue;
4448     if (!NeedsScheduling) {
4449       NeedsScheduling = V;
4450       continue;
4451     }
4452     return false;
4453   }
4454   return NeedsScheduling;
4455 }
4456 #endif
4457 
4458 /// Generates key/subkey pair for the given value to provide effective sorting
4459 /// of the values and better detection of the vectorizable values sequences. The
4460 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4461 /// and in values subgroups (subkeys).
4462 static std::pair<size_t, size_t> generateKeySubkey(
4463     Value *V, const TargetLibraryInfo *TLI,
4464     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4465     bool AllowAlternate) {
4466   hash_code Key = hash_value(V->getValueID() + 2);
4467   hash_code SubKey = hash_value(0);
4468   // Sort the loads by the distance between the pointers.
4469   if (auto *LI = dyn_cast<LoadInst>(V)) {
4470     Key = hash_combine(hash_value(Instruction::Load), Key);
4471     if (LI->isSimple())
4472       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4473     else
4474       SubKey = hash_value(LI);
4475   } else if (isVectorLikeInstWithConstOps(V)) {
4476     // Sort extracts by the vector operands.
4477     if (isa<ExtractElementInst, UndefValue>(V))
4478       Key = hash_value(Value::UndefValueVal + 1);
4479     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4480       if (!isUndefVector(EI->getVectorOperand()) &&
4481           !isa<UndefValue>(EI->getIndexOperand()))
4482         SubKey = hash_value(EI->getVectorOperand());
4483     }
4484   } else if (auto *I = dyn_cast<Instruction>(V)) {
4485     // Sort other instructions just by the opcodes except for CMPInst.
4486     // For CMP also sort by the predicate kind.
4487     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4488         isValidForAlternation(I->getOpcode())) {
4489       if (AllowAlternate)
4490         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4491       else
4492         Key = hash_combine(hash_value(I->getOpcode()), Key);
4493       SubKey = hash_combine(
4494           hash_value(I->getOpcode()), hash_value(I->getType()),
4495           hash_value(isa<BinaryOperator>(I)
4496                          ? I->getType()
4497                          : cast<CastInst>(I)->getOperand(0)->getType()));
4498       // For casts, look through the only operand to improve compile time.
4499       if (isa<CastInst>(I)) {
4500         std::pair<size_t, size_t> OpVals =
4501             generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
4502                               /*=AllowAlternate*/ true);
4503         Key = hash_combine(OpVals.first, Key);
4504         SubKey = hash_combine(OpVals.first, SubKey);
4505       }
4506     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4507       CmpInst::Predicate Pred = CI->getPredicate();
4508       if (CI->isCommutative())
4509         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4510       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4511       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4512                             hash_value(SwapPred),
4513                             hash_value(CI->getOperand(0)->getType()));
4514     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4515       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4516       if (isTriviallyVectorizable(ID)) {
4517         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4518       } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
4519         SubKey = hash_combine(hash_value(I->getOpcode()),
4520                               hash_value(Call->getCalledFunction()));
4521       } else {
4522         Key = hash_combine(hash_value(Call), Key);
4523         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4524       }
4525       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4526         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4527                               hash_value(Op.Tag), SubKey);
4528     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4529       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4530         SubKey = hash_value(Gep->getPointerOperand());
4531       else
4532         SubKey = hash_value(Gep);
4533     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4534                !isa<ConstantInt>(I->getOperand(1))) {
4535       // Do not try to vectorize instructions with potentially high cost.
4536       SubKey = hash_value(I);
4537     } else {
4538       SubKey = hash_value(I->getOpcode());
4539     }
4540     Key = hash_combine(hash_value(I->getParent()), Key);
4541   }
4542   return std::make_pair(Key, SubKey);
4543 }
4544 
4545 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4546                             const EdgeInfo &UserTreeIdx) {
4547   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4548 
4549   SmallVector<int> ReuseShuffleIndicies;
4550   SmallVector<Value *> UniqueValues;
4551   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4552                                 &UserTreeIdx,
4553                                 this](const InstructionsState &S) {
4554     // Check that every instruction appears once in this bundle.
4555     DenseMap<Value *, unsigned> UniquePositions;
4556     for (Value *V : VL) {
4557       if (isConstant(V)) {
4558         ReuseShuffleIndicies.emplace_back(
4559             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4560         UniqueValues.emplace_back(V);
4561         continue;
4562       }
4563       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4564       ReuseShuffleIndicies.emplace_back(Res.first->second);
4565       if (Res.second)
4566         UniqueValues.emplace_back(V);
4567     }
4568     size_t NumUniqueScalarValues = UniqueValues.size();
4569     if (NumUniqueScalarValues == VL.size()) {
4570       ReuseShuffleIndicies.clear();
4571     } else {
4572       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4573       if (NumUniqueScalarValues <= 1 ||
4574           (UniquePositions.size() == 1 && all_of(UniqueValues,
4575                                                  [](Value *V) {
4576                                                    return isa<UndefValue>(V) ||
4577                                                           !isConstant(V);
4578                                                  })) ||
4579           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4580         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4581         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4582         return false;
4583       }
4584       VL = UniqueValues;
4585     }
4586     return true;
4587   };
4588 
4589   InstructionsState S = getSameOpcode(VL);
4590   if (Depth == RecursionMaxDepth) {
4591     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4592     if (TryToFindDuplicates(S))
4593       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4594                    ReuseShuffleIndicies);
4595     return;
4596   }
4597 
4598   // Don't handle scalable vectors
4599   if (S.getOpcode() == Instruction::ExtractElement &&
4600       isa<ScalableVectorType>(
4601           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4602     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4603     if (TryToFindDuplicates(S))
4604       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4605                    ReuseShuffleIndicies);
4606     return;
4607   }
4608 
4609   // Don't handle vectors.
4610   if (S.OpValue->getType()->isVectorTy() &&
4611       !isa<InsertElementInst>(S.OpValue)) {
4612     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4613     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4614     return;
4615   }
4616 
4617   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4618     if (SI->getValueOperand()->getType()->isVectorTy()) {
4619       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4620       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4621       return;
4622     }
4623 
4624   // If all of the operands are identical or constant we have a simple solution.
4625   // If we deal with insert/extract instructions, they all must have constant
4626   // indices, otherwise we should gather them, not try to vectorize.
4627   // If alternate op node with 2 elements with gathered operands - do not
4628   // vectorize.
4629   auto &&NotProfitableForVectorization = [&S, this,
4630                                           Depth](ArrayRef<Value *> VL) {
4631     if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
4632       return false;
4633     if (VectorizableTree.size() < MinTreeSize)
4634       return false;
4635     if (Depth >= RecursionMaxDepth - 1)
4636       return true;
4637     // Check if all operands are extracts, part of vector node or can build a
4638     // regular vectorize node.
4639     SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
4640     for (Value *V : VL) {
4641       auto *I = cast<Instruction>(V);
4642       InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
4643         return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
4644       }));
4645     }
4646     bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
4647     if ((IsCommutative &&
4648          std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
4649         (!IsCommutative &&
4650          all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
4651       return true;
4652     assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
4653     SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
4654     auto *I1 = cast<Instruction>(VL.front());
4655     auto *I2 = cast<Instruction>(VL.back());
4656     for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4657       Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4658                                              I2->getOperand(Op));
4659     if (static_cast<unsigned>(count_if(
4660             Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4661               return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4662             })) >= S.MainOp->getNumOperands() / 2)
4663       return false;
4664     if (S.MainOp->getNumOperands() > 2)
4665       return true;
4666     if (IsCommutative) {
4667       // Check permuted operands.
4668       Candidates.clear();
4669       for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4670         Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4671                                                I2->getOperand((Op + 1) % E));
4672       if (any_of(
4673               Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4674                 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4675               }))
4676         return false;
4677     }
4678     return true;
4679   };
4680   SmallVector<unsigned> SortedIndices;
4681   BasicBlock *BB = nullptr;
4682   bool AreAllSameInsts =
4683       (S.getOpcode() && allSameBlock(VL)) ||
4684       (S.OpValue->getType()->isPointerTy() && UserTreeIdx.UserTE &&
4685        UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize &&
4686        VL.size() > 2 &&
4687        all_of(VL,
4688               [&BB](Value *V) {
4689                 auto *I = dyn_cast<GetElementPtrInst>(V);
4690                 if (!I)
4691                   return doesNotNeedToBeScheduled(V);
4692                 if (!BB)
4693                   BB = I->getParent();
4694                 return BB == I->getParent() && I->getNumOperands() == 2;
4695               }) &&
4696        BB &&
4697        sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE,
4698                        SortedIndices));
4699   if (allConstant(VL) || isSplat(VL) || !AreAllSameInsts ||
4700       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(
4701            S.OpValue) &&
4702        !all_of(VL, isVectorLikeInstWithConstOps)) ||
4703       NotProfitableForVectorization(VL)) {
4704     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
4705     if (TryToFindDuplicates(S))
4706       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4707                    ReuseShuffleIndicies);
4708     return;
4709   }
4710 
4711   // We now know that this is a vector of instructions of the same type from
4712   // the same block.
4713 
4714   // Don't vectorize ephemeral values.
4715   if (!EphValues.empty()) {
4716     for (Value *V : VL) {
4717       if (EphValues.count(V)) {
4718         LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4719                           << ") is ephemeral.\n");
4720         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4721         return;
4722       }
4723     }
4724   }
4725 
4726   // Check if this is a duplicate of another entry.
4727   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4728     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4729     if (!E->isSame(VL)) {
4730       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4731       if (TryToFindDuplicates(S))
4732         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4733                      ReuseShuffleIndicies);
4734       return;
4735     }
4736     // Record the reuse of the tree node.  FIXME, currently this is only used to
4737     // properly draw the graph rather than for the actual vectorization.
4738     E->UserTreeIndices.push_back(UserTreeIdx);
4739     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4740                       << ".\n");
4741     return;
4742   }
4743 
4744   // Check that none of the instructions in the bundle are already in the tree.
4745   for (Value *V : VL) {
4746     auto *I = dyn_cast<Instruction>(V);
4747     if (!I)
4748       continue;
4749     if (getTreeEntry(I)) {
4750       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4751                         << ") is already in tree.\n");
4752       if (TryToFindDuplicates(S))
4753         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4754                      ReuseShuffleIndicies);
4755       return;
4756     }
4757   }
4758 
4759   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4760   if (UserIgnoreList && !UserIgnoreList->empty()) {
4761     for (Value *V : VL) {
4762       if (UserIgnoreList && UserIgnoreList->contains(V)) {
4763         LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4764         if (TryToFindDuplicates(S))
4765           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4766                        ReuseShuffleIndicies);
4767         return;
4768       }
4769     }
4770   }
4771 
4772   // Special processing for sorted pointers for ScatterVectorize node with
4773   // constant indeces only.
4774   if (AreAllSameInsts && !(S.getOpcode() && allSameBlock(VL)) &&
4775       UserTreeIdx.UserTE &&
4776       UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize) {
4777     assert(S.OpValue->getType()->isPointerTy() &&
4778            count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >=
4779                2 &&
4780            "Expected pointers only.");
4781     // Reset S to make it GetElementPtr kind of node.
4782     const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
4783     assert(It != VL.end() && "Expected at least one GEP.");
4784     S = getSameOpcode(*It);
4785   }
4786 
4787   // Check that all of the users of the scalars that we want to vectorize are
4788   // schedulable.
4789   auto *VL0 = cast<Instruction>(S.OpValue);
4790   BB = VL0->getParent();
4791 
4792   if (!DT->isReachableFromEntry(BB)) {
4793     // Don't go into unreachable blocks. They may contain instructions with
4794     // dependency cycles which confuse the final scheduling.
4795     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4796     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4797     return;
4798   }
4799 
4800   // Check that every instruction appears once in this bundle.
4801   if (!TryToFindDuplicates(S))
4802     return;
4803 
4804   auto &BSRef = BlocksSchedules[BB];
4805   if (!BSRef)
4806     BSRef = std::make_unique<BlockScheduling>(BB);
4807 
4808   BlockScheduling &BS = *BSRef;
4809 
4810   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4811 #ifdef EXPENSIVE_CHECKS
4812   // Make sure we didn't break any internal invariants
4813   BS.verify();
4814 #endif
4815   if (!Bundle) {
4816     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4817     assert((!BS.getScheduleData(VL0) ||
4818             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4819            "tryScheduleBundle should cancelScheduling on failure");
4820     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4821                  ReuseShuffleIndicies);
4822     return;
4823   }
4824   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4825 
4826   unsigned ShuffleOrOp = S.isAltShuffle() ?
4827                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4828   switch (ShuffleOrOp) {
4829     case Instruction::PHI: {
4830       auto *PH = cast<PHINode>(VL0);
4831 
4832       // Check for terminator values (e.g. invoke).
4833       for (Value *V : VL)
4834         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4835           Instruction *Term = dyn_cast<Instruction>(Incoming);
4836           if (Term && Term->isTerminator()) {
4837             LLVM_DEBUG(dbgs()
4838                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4839             BS.cancelScheduling(VL, VL0);
4840             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4841                          ReuseShuffleIndicies);
4842             return;
4843           }
4844         }
4845 
4846       TreeEntry *TE =
4847           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4848       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4849 
4850       // Keeps the reordered operands to avoid code duplication.
4851       SmallVector<ValueList, 2> OperandsVec;
4852       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4853         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4854           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4855           TE->setOperand(I, Operands);
4856           OperandsVec.push_back(Operands);
4857           continue;
4858         }
4859         ValueList Operands;
4860         // Prepare the operand vector.
4861         for (Value *V : VL)
4862           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4863               PH->getIncomingBlock(I)));
4864         TE->setOperand(I, Operands);
4865         OperandsVec.push_back(Operands);
4866       }
4867       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4868         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4869       return;
4870     }
4871     case Instruction::ExtractValue:
4872     case Instruction::ExtractElement: {
4873       OrdersType CurrentOrder;
4874       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4875       if (Reuse) {
4876         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4877         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4878                      ReuseShuffleIndicies);
4879         // This is a special case, as it does not gather, but at the same time
4880         // we are not extending buildTree_rec() towards the operands.
4881         ValueList Op0;
4882         Op0.assign(VL.size(), VL0->getOperand(0));
4883         VectorizableTree.back()->setOperand(0, Op0);
4884         return;
4885       }
4886       if (!CurrentOrder.empty()) {
4887         LLVM_DEBUG({
4888           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4889                     "with order";
4890           for (unsigned Idx : CurrentOrder)
4891             dbgs() << " " << Idx;
4892           dbgs() << "\n";
4893         });
4894         fixupOrderingIndices(CurrentOrder);
4895         // Insert new order with initial value 0, if it does not exist,
4896         // otherwise return the iterator to the existing one.
4897         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4898                      ReuseShuffleIndicies, CurrentOrder);
4899         // This is a special case, as it does not gather, but at the same time
4900         // we are not extending buildTree_rec() towards the operands.
4901         ValueList Op0;
4902         Op0.assign(VL.size(), VL0->getOperand(0));
4903         VectorizableTree.back()->setOperand(0, Op0);
4904         return;
4905       }
4906       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4907       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4908                    ReuseShuffleIndicies);
4909       BS.cancelScheduling(VL, VL0);
4910       return;
4911     }
4912     case Instruction::InsertElement: {
4913       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4914 
4915       // Check that we have a buildvector and not a shuffle of 2 or more
4916       // different vectors.
4917       ValueSet SourceVectors;
4918       for (Value *V : VL) {
4919         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4920         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4921       }
4922 
4923       if (count_if(VL, [&SourceVectors](Value *V) {
4924             return !SourceVectors.contains(V);
4925           }) >= 2) {
4926         // Found 2nd source vector - cancel.
4927         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4928                              "different source vectors.\n");
4929         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4930         BS.cancelScheduling(VL, VL0);
4931         return;
4932       }
4933 
4934       auto OrdCompare = [](const std::pair<int, int> &P1,
4935                            const std::pair<int, int> &P2) {
4936         return P1.first > P2.first;
4937       };
4938       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4939                     decltype(OrdCompare)>
4940           Indices(OrdCompare);
4941       for (int I = 0, E = VL.size(); I < E; ++I) {
4942         unsigned Idx = *getInsertIndex(VL[I]);
4943         Indices.emplace(Idx, I);
4944       }
4945       OrdersType CurrentOrder(VL.size(), VL.size());
4946       bool IsIdentity = true;
4947       for (int I = 0, E = VL.size(); I < E; ++I) {
4948         CurrentOrder[Indices.top().second] = I;
4949         IsIdentity &= Indices.top().second == I;
4950         Indices.pop();
4951       }
4952       if (IsIdentity)
4953         CurrentOrder.clear();
4954       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4955                                    None, CurrentOrder);
4956       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4957 
4958       constexpr int NumOps = 2;
4959       ValueList VectorOperands[NumOps];
4960       for (int I = 0; I < NumOps; ++I) {
4961         for (Value *V : VL)
4962           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4963 
4964         TE->setOperand(I, VectorOperands[I]);
4965       }
4966       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4967       return;
4968     }
4969     case Instruction::Load: {
4970       // Check that a vectorized load would load the same memory as a scalar
4971       // load. For example, we don't want to vectorize loads that are smaller
4972       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4973       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4974       // from such a struct, we read/write packed bits disagreeing with the
4975       // unvectorized version.
4976       SmallVector<Value *> PointerOps;
4977       OrdersType CurrentOrder;
4978       TreeEntry *TE = nullptr;
4979       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, CurrentOrder,
4980                                 PointerOps)) {
4981       case LoadsState::Vectorize:
4982         if (CurrentOrder.empty()) {
4983           // Original loads are consecutive and does not require reordering.
4984           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4985                             ReuseShuffleIndicies);
4986           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4987         } else {
4988           fixupOrderingIndices(CurrentOrder);
4989           // Need to reorder.
4990           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4991                             ReuseShuffleIndicies, CurrentOrder);
4992           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4993         }
4994         TE->setOperandsInOrder();
4995         break;
4996       case LoadsState::ScatterVectorize:
4997         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4998         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4999                           UserTreeIdx, ReuseShuffleIndicies);
5000         TE->setOperandsInOrder();
5001         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
5002         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
5003         break;
5004       case LoadsState::Gather:
5005         BS.cancelScheduling(VL, VL0);
5006         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5007                      ReuseShuffleIndicies);
5008 #ifndef NDEBUG
5009         Type *ScalarTy = VL0->getType();
5010         if (DL->getTypeSizeInBits(ScalarTy) !=
5011             DL->getTypeAllocSizeInBits(ScalarTy))
5012           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
5013         else if (any_of(VL, [](Value *V) {
5014                    return !cast<LoadInst>(V)->isSimple();
5015                  }))
5016           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
5017         else
5018           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
5019 #endif // NDEBUG
5020         break;
5021       }
5022       return;
5023     }
5024     case Instruction::ZExt:
5025     case Instruction::SExt:
5026     case Instruction::FPToUI:
5027     case Instruction::FPToSI:
5028     case Instruction::FPExt:
5029     case Instruction::PtrToInt:
5030     case Instruction::IntToPtr:
5031     case Instruction::SIToFP:
5032     case Instruction::UIToFP:
5033     case Instruction::Trunc:
5034     case Instruction::FPTrunc:
5035     case Instruction::BitCast: {
5036       Type *SrcTy = VL0->getOperand(0)->getType();
5037       for (Value *V : VL) {
5038         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
5039         if (Ty != SrcTy || !isValidElementType(Ty)) {
5040           BS.cancelScheduling(VL, VL0);
5041           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5042                        ReuseShuffleIndicies);
5043           LLVM_DEBUG(dbgs()
5044                      << "SLP: Gathering casts with different src types.\n");
5045           return;
5046         }
5047       }
5048       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5049                                    ReuseShuffleIndicies);
5050       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
5051 
5052       TE->setOperandsInOrder();
5053       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5054         ValueList Operands;
5055         // Prepare the operand vector.
5056         for (Value *V : VL)
5057           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5058 
5059         buildTree_rec(Operands, Depth + 1, {TE, i});
5060       }
5061       return;
5062     }
5063     case Instruction::ICmp:
5064     case Instruction::FCmp: {
5065       // Check that all of the compares have the same predicate.
5066       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
5067       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
5068       Type *ComparedTy = VL0->getOperand(0)->getType();
5069       for (Value *V : VL) {
5070         CmpInst *Cmp = cast<CmpInst>(V);
5071         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
5072             Cmp->getOperand(0)->getType() != ComparedTy) {
5073           BS.cancelScheduling(VL, VL0);
5074           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5075                        ReuseShuffleIndicies);
5076           LLVM_DEBUG(dbgs()
5077                      << "SLP: Gathering cmp with different predicate.\n");
5078           return;
5079         }
5080       }
5081 
5082       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5083                                    ReuseShuffleIndicies);
5084       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
5085 
5086       ValueList Left, Right;
5087       if (cast<CmpInst>(VL0)->isCommutative()) {
5088         // Commutative predicate - collect + sort operands of the instructions
5089         // so that each side is more likely to have the same opcode.
5090         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
5091         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5092       } else {
5093         // Collect operands - commute if it uses the swapped predicate.
5094         for (Value *V : VL) {
5095           auto *Cmp = cast<CmpInst>(V);
5096           Value *LHS = Cmp->getOperand(0);
5097           Value *RHS = Cmp->getOperand(1);
5098           if (Cmp->getPredicate() != P0)
5099             std::swap(LHS, RHS);
5100           Left.push_back(LHS);
5101           Right.push_back(RHS);
5102         }
5103       }
5104       TE->setOperand(0, Left);
5105       TE->setOperand(1, Right);
5106       buildTree_rec(Left, Depth + 1, {TE, 0});
5107       buildTree_rec(Right, Depth + 1, {TE, 1});
5108       return;
5109     }
5110     case Instruction::Select:
5111     case Instruction::FNeg:
5112     case Instruction::Add:
5113     case Instruction::FAdd:
5114     case Instruction::Sub:
5115     case Instruction::FSub:
5116     case Instruction::Mul:
5117     case Instruction::FMul:
5118     case Instruction::UDiv:
5119     case Instruction::SDiv:
5120     case Instruction::FDiv:
5121     case Instruction::URem:
5122     case Instruction::SRem:
5123     case Instruction::FRem:
5124     case Instruction::Shl:
5125     case Instruction::LShr:
5126     case Instruction::AShr:
5127     case Instruction::And:
5128     case Instruction::Or:
5129     case Instruction::Xor: {
5130       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5131                                    ReuseShuffleIndicies);
5132       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
5133 
5134       // Sort operands of the instructions so that each side is more likely to
5135       // have the same opcode.
5136       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
5137         ValueList Left, Right;
5138         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5139         TE->setOperand(0, Left);
5140         TE->setOperand(1, Right);
5141         buildTree_rec(Left, Depth + 1, {TE, 0});
5142         buildTree_rec(Right, Depth + 1, {TE, 1});
5143         return;
5144       }
5145 
5146       TE->setOperandsInOrder();
5147       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5148         ValueList Operands;
5149         // Prepare the operand vector.
5150         for (Value *V : VL)
5151           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5152 
5153         buildTree_rec(Operands, Depth + 1, {TE, i});
5154       }
5155       return;
5156     }
5157     case Instruction::GetElementPtr: {
5158       // We don't combine GEPs with complicated (nested) indexing.
5159       for (Value *V : VL) {
5160         auto *I = dyn_cast<GetElementPtrInst>(V);
5161         if (!I)
5162           continue;
5163         if (I->getNumOperands() != 2) {
5164           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
5165           BS.cancelScheduling(VL, VL0);
5166           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5167                        ReuseShuffleIndicies);
5168           return;
5169         }
5170       }
5171 
5172       // We can't combine several GEPs into one vector if they operate on
5173       // different types.
5174       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
5175       for (Value *V : VL) {
5176         auto *GEP = dyn_cast<GEPOperator>(V);
5177         if (!GEP)
5178           continue;
5179         Type *CurTy = GEP->getSourceElementType();
5180         if (Ty0 != CurTy) {
5181           LLVM_DEBUG(dbgs()
5182                      << "SLP: not-vectorizable GEP (different types).\n");
5183           BS.cancelScheduling(VL, VL0);
5184           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5185                        ReuseShuffleIndicies);
5186           return;
5187         }
5188       }
5189 
5190       bool IsScatterUser =
5191           UserTreeIdx.UserTE &&
5192           UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
5193       // We don't combine GEPs with non-constant indexes.
5194       Type *Ty1 = VL0->getOperand(1)->getType();
5195       for (Value *V : VL) {
5196         auto *I = dyn_cast<GetElementPtrInst>(V);
5197         if (!I)
5198           continue;
5199         auto *Op = I->getOperand(1);
5200         if ((!IsScatterUser && !isa<ConstantInt>(Op)) ||
5201             (Op->getType() != Ty1 &&
5202              ((IsScatterUser && !isa<ConstantInt>(Op)) ||
5203               Op->getType()->getScalarSizeInBits() >
5204                   DL->getIndexSizeInBits(
5205                       V->getType()->getPointerAddressSpace())))) {
5206           LLVM_DEBUG(dbgs()
5207                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5208           BS.cancelScheduling(VL, VL0);
5209           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5210                        ReuseShuffleIndicies);
5211           return;
5212         }
5213       }
5214 
5215       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5216                                    ReuseShuffleIndicies);
5217       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5218       SmallVector<ValueList, 2> Operands(2);
5219       // Prepare the operand vector for pointer operands.
5220       for (Value *V : VL) {
5221         auto *GEP = dyn_cast<GetElementPtrInst>(V);
5222         if (!GEP) {
5223           Operands.front().push_back(V);
5224           continue;
5225         }
5226         Operands.front().push_back(GEP->getPointerOperand());
5227       }
5228       TE->setOperand(0, Operands.front());
5229       // Need to cast all indices to the same type before vectorization to
5230       // avoid crash.
5231       // Required to be able to find correct matches between different gather
5232       // nodes and reuse the vectorized values rather than trying to gather them
5233       // again.
5234       int IndexIdx = 1;
5235       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5236       Type *Ty = all_of(VL,
5237                         [VL0Ty, IndexIdx](Value *V) {
5238                           auto *GEP = dyn_cast<GetElementPtrInst>(V);
5239                           if (!GEP)
5240                             return true;
5241                           return VL0Ty == GEP->getOperand(IndexIdx)->getType();
5242                         })
5243                      ? VL0Ty
5244                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5245                                             ->getPointerOperandType()
5246                                             ->getScalarType());
5247       // Prepare the operand vector.
5248       for (Value *V : VL) {
5249         auto *I = dyn_cast<GetElementPtrInst>(V);
5250         if (!I) {
5251           Operands.back().push_back(
5252               ConstantInt::get(Ty, 0, /*isSigned=*/false));
5253           continue;
5254         }
5255         auto *Op = I->getOperand(IndexIdx);
5256         auto *CI = dyn_cast<ConstantInt>(Op);
5257         if (!CI)
5258           Operands.back().push_back(Op);
5259         else
5260           Operands.back().push_back(ConstantExpr::getIntegerCast(
5261               CI, Ty, CI->getValue().isSignBitSet()));
5262       }
5263       TE->setOperand(IndexIdx, Operands.back());
5264 
5265       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5266         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5267       return;
5268     }
5269     case Instruction::Store: {
5270       // Check if the stores are consecutive or if we need to swizzle them.
5271       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5272       // Avoid types that are padded when being allocated as scalars, while
5273       // being packed together in a vector (such as i1).
5274       if (DL->getTypeSizeInBits(ScalarTy) !=
5275           DL->getTypeAllocSizeInBits(ScalarTy)) {
5276         BS.cancelScheduling(VL, VL0);
5277         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5278                      ReuseShuffleIndicies);
5279         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5280         return;
5281       }
5282       // Make sure all stores in the bundle are simple - we can't vectorize
5283       // atomic or volatile stores.
5284       SmallVector<Value *, 4> PointerOps(VL.size());
5285       ValueList Operands(VL.size());
5286       auto POIter = PointerOps.begin();
5287       auto OIter = Operands.begin();
5288       for (Value *V : VL) {
5289         auto *SI = cast<StoreInst>(V);
5290         if (!SI->isSimple()) {
5291           BS.cancelScheduling(VL, VL0);
5292           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5293                        ReuseShuffleIndicies);
5294           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5295           return;
5296         }
5297         *POIter = SI->getPointerOperand();
5298         *OIter = SI->getValueOperand();
5299         ++POIter;
5300         ++OIter;
5301       }
5302 
5303       OrdersType CurrentOrder;
5304       // Check the order of pointer operands.
5305       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5306         Value *Ptr0;
5307         Value *PtrN;
5308         if (CurrentOrder.empty()) {
5309           Ptr0 = PointerOps.front();
5310           PtrN = PointerOps.back();
5311         } else {
5312           Ptr0 = PointerOps[CurrentOrder.front()];
5313           PtrN = PointerOps[CurrentOrder.back()];
5314         }
5315         Optional<int> Dist =
5316             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5317         // Check that the sorted pointer operands are consecutive.
5318         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5319           if (CurrentOrder.empty()) {
5320             // Original stores are consecutive and does not require reordering.
5321             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5322                                          UserTreeIdx, ReuseShuffleIndicies);
5323             TE->setOperandsInOrder();
5324             buildTree_rec(Operands, Depth + 1, {TE, 0});
5325             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5326           } else {
5327             fixupOrderingIndices(CurrentOrder);
5328             TreeEntry *TE =
5329                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5330                              ReuseShuffleIndicies, CurrentOrder);
5331             TE->setOperandsInOrder();
5332             buildTree_rec(Operands, Depth + 1, {TE, 0});
5333             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5334           }
5335           return;
5336         }
5337       }
5338 
5339       BS.cancelScheduling(VL, VL0);
5340       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5341                    ReuseShuffleIndicies);
5342       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5343       return;
5344     }
5345     case Instruction::Call: {
5346       // Check if the calls are all to the same vectorizable intrinsic or
5347       // library function.
5348       CallInst *CI = cast<CallInst>(VL0);
5349       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5350 
5351       VFShape Shape = VFShape::get(
5352           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5353           false /*HasGlobalPred*/);
5354       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5355 
5356       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5357         BS.cancelScheduling(VL, VL0);
5358         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5359                      ReuseShuffleIndicies);
5360         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5361         return;
5362       }
5363       Function *F = CI->getCalledFunction();
5364       unsigned NumArgs = CI->arg_size();
5365       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5366       for (unsigned j = 0; j != NumArgs; ++j)
5367         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5368           ScalarArgs[j] = CI->getArgOperand(j);
5369       for (Value *V : VL) {
5370         CallInst *CI2 = dyn_cast<CallInst>(V);
5371         if (!CI2 || CI2->getCalledFunction() != F ||
5372             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5373             (VecFunc &&
5374              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5375             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5376           BS.cancelScheduling(VL, VL0);
5377           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5378                        ReuseShuffleIndicies);
5379           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5380                             << "\n");
5381           return;
5382         }
5383         // Some intrinsics have scalar arguments and should be same in order for
5384         // them to be vectorized.
5385         for (unsigned j = 0; j != NumArgs; ++j) {
5386           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5387             Value *A1J = CI2->getArgOperand(j);
5388             if (ScalarArgs[j] != A1J) {
5389               BS.cancelScheduling(VL, VL0);
5390               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5391                            ReuseShuffleIndicies);
5392               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5393                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5394                                 << "\n");
5395               return;
5396             }
5397           }
5398         }
5399         // Verify that the bundle operands are identical between the two calls.
5400         if (CI->hasOperandBundles() &&
5401             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5402                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5403                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5404           BS.cancelScheduling(VL, VL0);
5405           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5406                        ReuseShuffleIndicies);
5407           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5408                             << *CI << "!=" << *V << '\n');
5409           return;
5410         }
5411       }
5412 
5413       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5414                                    ReuseShuffleIndicies);
5415       TE->setOperandsInOrder();
5416       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5417         // For scalar operands no need to to create an entry since no need to
5418         // vectorize it.
5419         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5420           continue;
5421         ValueList Operands;
5422         // Prepare the operand vector.
5423         for (Value *V : VL) {
5424           auto *CI2 = cast<CallInst>(V);
5425           Operands.push_back(CI2->getArgOperand(i));
5426         }
5427         buildTree_rec(Operands, Depth + 1, {TE, i});
5428       }
5429       return;
5430     }
5431     case Instruction::ShuffleVector: {
5432       // If this is not an alternate sequence of opcode like add-sub
5433       // then do not vectorize this instruction.
5434       if (!S.isAltShuffle()) {
5435         BS.cancelScheduling(VL, VL0);
5436         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5437                      ReuseShuffleIndicies);
5438         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5439         return;
5440       }
5441       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5442                                    ReuseShuffleIndicies);
5443       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5444 
5445       // Reorder operands if reordering would enable vectorization.
5446       auto *CI = dyn_cast<CmpInst>(VL0);
5447       if (isa<BinaryOperator>(VL0) || CI) {
5448         ValueList Left, Right;
5449         if (!CI || all_of(VL, [](Value *V) {
5450               return cast<CmpInst>(V)->isCommutative();
5451             })) {
5452           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5453         } else {
5454           CmpInst::Predicate P0 = CI->getPredicate();
5455           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5456           assert(P0 != AltP0 &&
5457                  "Expected different main/alternate predicates.");
5458           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5459           Value *BaseOp0 = VL0->getOperand(0);
5460           Value *BaseOp1 = VL0->getOperand(1);
5461           // Collect operands - commute if it uses the swapped predicate or
5462           // alternate operation.
5463           for (Value *V : VL) {
5464             auto *Cmp = cast<CmpInst>(V);
5465             Value *LHS = Cmp->getOperand(0);
5466             Value *RHS = Cmp->getOperand(1);
5467             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5468             if (P0 == AltP0Swapped) {
5469               if (CI != Cmp && S.AltOp != Cmp &&
5470                   ((P0 == CurrentPred &&
5471                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5472                    (AltP0 == CurrentPred &&
5473                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5474                 std::swap(LHS, RHS);
5475             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5476               std::swap(LHS, RHS);
5477             }
5478             Left.push_back(LHS);
5479             Right.push_back(RHS);
5480           }
5481         }
5482         TE->setOperand(0, Left);
5483         TE->setOperand(1, Right);
5484         buildTree_rec(Left, Depth + 1, {TE, 0});
5485         buildTree_rec(Right, Depth + 1, {TE, 1});
5486         return;
5487       }
5488 
5489       TE->setOperandsInOrder();
5490       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5491         ValueList Operands;
5492         // Prepare the operand vector.
5493         for (Value *V : VL)
5494           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5495 
5496         buildTree_rec(Operands, Depth + 1, {TE, i});
5497       }
5498       return;
5499     }
5500     default:
5501       BS.cancelScheduling(VL, VL0);
5502       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5503                    ReuseShuffleIndicies);
5504       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5505       return;
5506   }
5507 }
5508 
5509 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5510   unsigned N = 1;
5511   Type *EltTy = T;
5512 
5513   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5514          isa<VectorType>(EltTy)) {
5515     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5516       // Check that struct is homogeneous.
5517       for (const auto *Ty : ST->elements())
5518         if (Ty != *ST->element_begin())
5519           return 0;
5520       N *= ST->getNumElements();
5521       EltTy = *ST->element_begin();
5522     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5523       N *= AT->getNumElements();
5524       EltTy = AT->getElementType();
5525     } else {
5526       auto *VT = cast<FixedVectorType>(EltTy);
5527       N *= VT->getNumElements();
5528       EltTy = VT->getElementType();
5529     }
5530   }
5531 
5532   if (!isValidElementType(EltTy))
5533     return 0;
5534   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5535   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5536     return 0;
5537   return N;
5538 }
5539 
5540 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5541                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5542   const auto *It = find_if(VL, [](Value *V) {
5543     return isa<ExtractElementInst, ExtractValueInst>(V);
5544   });
5545   assert(It != VL.end() && "Expected at least one extract instruction.");
5546   auto *E0 = cast<Instruction>(*It);
5547   assert(all_of(VL,
5548                 [](Value *V) {
5549                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5550                       V);
5551                 }) &&
5552          "Invalid opcode");
5553   // Check if all of the extracts come from the same vector and from the
5554   // correct offset.
5555   Value *Vec = E0->getOperand(0);
5556 
5557   CurrentOrder.clear();
5558 
5559   // We have to extract from a vector/aggregate with the same number of elements.
5560   unsigned NElts;
5561   if (E0->getOpcode() == Instruction::ExtractValue) {
5562     const DataLayout &DL = E0->getModule()->getDataLayout();
5563     NElts = canMapToVector(Vec->getType(), DL);
5564     if (!NElts)
5565       return false;
5566     // Check if load can be rewritten as load of vector.
5567     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5568     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5569       return false;
5570   } else {
5571     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5572   }
5573 
5574   if (NElts != VL.size())
5575     return false;
5576 
5577   // Check that all of the indices extract from the correct offset.
5578   bool ShouldKeepOrder = true;
5579   unsigned E = VL.size();
5580   // Assign to all items the initial value E + 1 so we can check if the extract
5581   // instruction index was used already.
5582   // Also, later we can check that all the indices are used and we have a
5583   // consecutive access in the extract instructions, by checking that no
5584   // element of CurrentOrder still has value E + 1.
5585   CurrentOrder.assign(E, E);
5586   unsigned I = 0;
5587   for (; I < E; ++I) {
5588     auto *Inst = dyn_cast<Instruction>(VL[I]);
5589     if (!Inst)
5590       continue;
5591     if (Inst->getOperand(0) != Vec)
5592       break;
5593     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5594       if (isa<UndefValue>(EE->getIndexOperand()))
5595         continue;
5596     Optional<unsigned> Idx = getExtractIndex(Inst);
5597     if (!Idx)
5598       break;
5599     const unsigned ExtIdx = *Idx;
5600     if (ExtIdx != I) {
5601       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5602         break;
5603       ShouldKeepOrder = false;
5604       CurrentOrder[ExtIdx] = I;
5605     } else {
5606       if (CurrentOrder[I] != E)
5607         break;
5608       CurrentOrder[I] = I;
5609     }
5610   }
5611   if (I < E) {
5612     CurrentOrder.clear();
5613     return false;
5614   }
5615   if (ShouldKeepOrder)
5616     CurrentOrder.clear();
5617 
5618   return ShouldKeepOrder;
5619 }
5620 
5621 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5622                                     ArrayRef<Value *> VectorizedVals) const {
5623   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5624          all_of(I->users(), [this](User *U) {
5625            return ScalarToTreeEntry.count(U) > 0 ||
5626                   isVectorLikeInstWithConstOps(U) ||
5627                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5628          });
5629 }
5630 
5631 static std::pair<InstructionCost, InstructionCost>
5632 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5633                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5634   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5635 
5636   // Calculate the cost of the scalar and vector calls.
5637   SmallVector<Type *, 4> VecTys;
5638   for (Use &Arg : CI->args())
5639     VecTys.push_back(
5640         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5641   FastMathFlags FMF;
5642   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5643     FMF = FPCI->getFastMathFlags();
5644   SmallVector<const Value *> Arguments(CI->args());
5645   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5646                                     dyn_cast<IntrinsicInst>(CI));
5647   auto IntrinsicCost =
5648     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5649 
5650   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5651                                      VecTy->getNumElements())),
5652                             false /*HasGlobalPred*/);
5653   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5654   auto LibCost = IntrinsicCost;
5655   if (!CI->isNoBuiltin() && VecFunc) {
5656     // Calculate the cost of the vector library call.
5657     // If the corresponding vector call is cheaper, return its cost.
5658     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5659                                     TTI::TCK_RecipThroughput);
5660   }
5661   return {IntrinsicCost, LibCost};
5662 }
5663 
5664 /// Compute the cost of creating a vector of type \p VecTy containing the
5665 /// extracted values from \p VL.
5666 static InstructionCost
5667 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5668                    TargetTransformInfo::ShuffleKind ShuffleKind,
5669                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5670   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5671 
5672   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5673       VecTy->getNumElements() < NumOfParts)
5674     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5675 
5676   bool AllConsecutive = true;
5677   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5678   unsigned Idx = -1;
5679   InstructionCost Cost = 0;
5680 
5681   // Process extracts in blocks of EltsPerVector to check if the source vector
5682   // operand can be re-used directly. If not, add the cost of creating a shuffle
5683   // to extract the values into a vector register.
5684   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5685   for (auto *V : VL) {
5686     ++Idx;
5687 
5688     // Reached the start of a new vector registers.
5689     if (Idx % EltsPerVector == 0) {
5690       RegMask.assign(EltsPerVector, UndefMaskElem);
5691       AllConsecutive = true;
5692       continue;
5693     }
5694 
5695     // Need to exclude undefs from analysis.
5696     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5697       continue;
5698 
5699     // Check all extracts for a vector register on the target directly
5700     // extract values in order.
5701     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5702     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5703       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5704       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5705                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5706       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5707     }
5708 
5709     if (AllConsecutive)
5710       continue;
5711 
5712     // Skip all indices, except for the last index per vector block.
5713     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5714       continue;
5715 
5716     // If we have a series of extracts which are not consecutive and hence
5717     // cannot re-use the source vector register directly, compute the shuffle
5718     // cost to extract the vector with EltsPerVector elements.
5719     Cost += TTI.getShuffleCost(
5720         TargetTransformInfo::SK_PermuteSingleSrc,
5721         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5722   }
5723   return Cost;
5724 }
5725 
5726 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5727 /// operations operands.
5728 static void
5729 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5730                       ArrayRef<int> ReusesIndices,
5731                       const function_ref<bool(Instruction *)> IsAltOp,
5732                       SmallVectorImpl<int> &Mask,
5733                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5734                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5735   unsigned Sz = VL.size();
5736   Mask.assign(Sz, UndefMaskElem);
5737   SmallVector<int> OrderMask;
5738   if (!ReorderIndices.empty())
5739     inversePermutation(ReorderIndices, OrderMask);
5740   for (unsigned I = 0; I < Sz; ++I) {
5741     unsigned Idx = I;
5742     if (!ReorderIndices.empty())
5743       Idx = OrderMask[I];
5744     auto *OpInst = cast<Instruction>(VL[Idx]);
5745     if (IsAltOp(OpInst)) {
5746       Mask[I] = Sz + Idx;
5747       if (AltScalars)
5748         AltScalars->push_back(OpInst);
5749     } else {
5750       Mask[I] = Idx;
5751       if (OpScalars)
5752         OpScalars->push_back(OpInst);
5753     }
5754   }
5755   if (!ReusesIndices.empty()) {
5756     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5757     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5758       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5759     });
5760     Mask.swap(NewMask);
5761   }
5762 }
5763 
5764 /// Checks if the specified instruction \p I is an alternate operation for the
5765 /// given \p MainOp and \p AltOp instructions.
5766 static bool isAlternateInstruction(const Instruction *I,
5767                                    const Instruction *MainOp,
5768                                    const Instruction *AltOp) {
5769   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5770     auto *AltCI0 = cast<CmpInst>(AltOp);
5771     auto *CI = cast<CmpInst>(I);
5772     CmpInst::Predicate P0 = CI0->getPredicate();
5773     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5774     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5775     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5776     CmpInst::Predicate CurrentPred = CI->getPredicate();
5777     if (P0 == AltP0Swapped)
5778       return I == AltCI0 ||
5779              (I != MainOp &&
5780               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5781                                    CI->getOperand(0), CI->getOperand(1)));
5782     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5783   }
5784   return I->getOpcode() == AltOp->getOpcode();
5785 }
5786 
5787 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5788                                       ArrayRef<Value *> VectorizedVals) {
5789   ArrayRef<Value*> VL = E->Scalars;
5790 
5791   Type *ScalarTy = VL[0]->getType();
5792   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5793     ScalarTy = SI->getValueOperand()->getType();
5794   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5795     ScalarTy = CI->getOperand(0)->getType();
5796   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5797     ScalarTy = IE->getOperand(1)->getType();
5798   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5799   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5800 
5801   // If we have computed a smaller type for the expression, update VecTy so
5802   // that the costs will be accurate.
5803   if (MinBWs.count(VL[0]))
5804     VecTy = FixedVectorType::get(
5805         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5806   unsigned EntryVF = E->getVectorFactor();
5807   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5808 
5809   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5810   // FIXME: it tries to fix a problem with MSVC buildbots.
5811   TargetTransformInfo &TTIRef = *TTI;
5812   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5813                                VectorizedVals, E](InstructionCost &Cost) {
5814     DenseMap<Value *, int> ExtractVectorsTys;
5815     SmallPtrSet<Value *, 4> CheckedExtracts;
5816     for (auto *V : VL) {
5817       if (isa<UndefValue>(V))
5818         continue;
5819       // If all users of instruction are going to be vectorized and this
5820       // instruction itself is not going to be vectorized, consider this
5821       // instruction as dead and remove its cost from the final cost of the
5822       // vectorized tree.
5823       // Also, avoid adjusting the cost for extractelements with multiple uses
5824       // in different graph entries.
5825       const TreeEntry *VE = getTreeEntry(V);
5826       if (!CheckedExtracts.insert(V).second ||
5827           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5828           (VE && VE != E))
5829         continue;
5830       auto *EE = cast<ExtractElementInst>(V);
5831       Optional<unsigned> EEIdx = getExtractIndex(EE);
5832       if (!EEIdx)
5833         continue;
5834       unsigned Idx = *EEIdx;
5835       if (TTIRef.getNumberOfParts(VecTy) !=
5836           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5837         auto It =
5838             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5839         It->getSecond() = std::min<int>(It->second, Idx);
5840       }
5841       // Take credit for instruction that will become dead.
5842       if (EE->hasOneUse()) {
5843         Instruction *Ext = EE->user_back();
5844         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5845             all_of(Ext->users(),
5846                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5847           // Use getExtractWithExtendCost() to calculate the cost of
5848           // extractelement/ext pair.
5849           Cost -=
5850               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5851                                               EE->getVectorOperandType(), Idx);
5852           // Add back the cost of s|zext which is subtracted separately.
5853           Cost += TTIRef.getCastInstrCost(
5854               Ext->getOpcode(), Ext->getType(), EE->getType(),
5855               TTI::getCastContextHint(Ext), CostKind, Ext);
5856           continue;
5857         }
5858       }
5859       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5860                                         EE->getVectorOperandType(), Idx);
5861     }
5862     // Add a cost for subvector extracts/inserts if required.
5863     for (const auto &Data : ExtractVectorsTys) {
5864       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5865       unsigned NumElts = VecTy->getNumElements();
5866       if (Data.second % NumElts == 0)
5867         continue;
5868       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5869         unsigned Idx = (Data.second / NumElts) * NumElts;
5870         unsigned EENumElts = EEVTy->getNumElements();
5871         if (Idx + NumElts <= EENumElts) {
5872           Cost +=
5873               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5874                                     EEVTy, None, Idx, VecTy);
5875         } else {
5876           // Need to round up the subvector type vectorization factor to avoid a
5877           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5878           // <= EENumElts.
5879           auto *SubVT =
5880               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5881           Cost +=
5882               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5883                                     EEVTy, None, Idx, SubVT);
5884         }
5885       } else {
5886         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5887                                       VecTy, None, 0, EEVTy);
5888       }
5889     }
5890   };
5891   if (E->State == TreeEntry::NeedToGather) {
5892     if (allConstant(VL))
5893       return 0;
5894     if (isa<InsertElementInst>(VL[0]))
5895       return InstructionCost::getInvalid();
5896     SmallVector<int> Mask;
5897     SmallVector<const TreeEntry *> Entries;
5898     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5899         isGatherShuffledEntry(E, Mask, Entries);
5900     if (Shuffle) {
5901       InstructionCost GatherCost = 0;
5902       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5903         // Perfect match in the graph, will reuse the previously vectorized
5904         // node. Cost is 0.
5905         LLVM_DEBUG(
5906             dbgs()
5907             << "SLP: perfect diamond match for gather bundle that starts with "
5908             << *VL.front() << ".\n");
5909         if (NeedToShuffleReuses)
5910           GatherCost =
5911               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5912                                   FinalVecTy, E->ReuseShuffleIndices);
5913       } else {
5914         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5915                           << " entries for bundle that starts with "
5916                           << *VL.front() << ".\n");
5917         // Detected that instead of gather we can emit a shuffle of single/two
5918         // previously vectorized nodes. Add the cost of the permutation rather
5919         // than gather.
5920         ::addMask(Mask, E->ReuseShuffleIndices);
5921         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5922       }
5923       return GatherCost;
5924     }
5925     if ((E->getOpcode() == Instruction::ExtractElement ||
5926          all_of(E->Scalars,
5927                 [](Value *V) {
5928                   return isa<ExtractElementInst, UndefValue>(V);
5929                 })) &&
5930         allSameType(VL)) {
5931       // Check that gather of extractelements can be represented as just a
5932       // shuffle of a single/two vectors the scalars are extracted from.
5933       SmallVector<int> Mask;
5934       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5935           isFixedVectorShuffle(VL, Mask);
5936       if (ShuffleKind) {
5937         // Found the bunch of extractelement instructions that must be gathered
5938         // into a vector and can be represented as a permutation elements in a
5939         // single input vector or of 2 input vectors.
5940         InstructionCost Cost =
5941             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5942         AdjustExtractsCost(Cost);
5943         if (NeedToShuffleReuses)
5944           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5945                                       FinalVecTy, E->ReuseShuffleIndices);
5946         return Cost;
5947       }
5948     }
5949     if (isSplat(VL)) {
5950       // Found the broadcasting of the single scalar, calculate the cost as the
5951       // broadcast.
5952       assert(VecTy == FinalVecTy &&
5953              "No reused scalars expected for broadcast.");
5954       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5955                                  /*Mask=*/None, /*Index=*/0,
5956                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5957     }
5958     InstructionCost ReuseShuffleCost = 0;
5959     if (NeedToShuffleReuses)
5960       ReuseShuffleCost = TTI->getShuffleCost(
5961           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5962     // Improve gather cost for gather of loads, if we can group some of the
5963     // loads into vector loads.
5964     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5965         !E->isAltShuffle()) {
5966       BoUpSLP::ValueSet VectorizedLoads;
5967       unsigned StartIdx = 0;
5968       unsigned VF = VL.size() / 2;
5969       unsigned VectorizedCnt = 0;
5970       unsigned ScatterVectorizeCnt = 0;
5971       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5972       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5973         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5974              Cnt += VF) {
5975           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5976           if (!VectorizedLoads.count(Slice.front()) &&
5977               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5978             SmallVector<Value *> PointerOps;
5979             OrdersType CurrentOrder;
5980             LoadsState LS =
5981                 canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, *SE, *LI,
5982                                   CurrentOrder, PointerOps);
5983             switch (LS) {
5984             case LoadsState::Vectorize:
5985             case LoadsState::ScatterVectorize:
5986               // Mark the vectorized loads so that we don't vectorize them
5987               // again.
5988               if (LS == LoadsState::Vectorize)
5989                 ++VectorizedCnt;
5990               else
5991                 ++ScatterVectorizeCnt;
5992               VectorizedLoads.insert(Slice.begin(), Slice.end());
5993               // If we vectorized initial block, no need to try to vectorize it
5994               // again.
5995               if (Cnt == StartIdx)
5996                 StartIdx += VF;
5997               break;
5998             case LoadsState::Gather:
5999               break;
6000             }
6001           }
6002         }
6003         // Check if the whole array was vectorized already - exit.
6004         if (StartIdx >= VL.size())
6005           break;
6006         // Found vectorizable parts - exit.
6007         if (!VectorizedLoads.empty())
6008           break;
6009       }
6010       if (!VectorizedLoads.empty()) {
6011         InstructionCost GatherCost = 0;
6012         unsigned NumParts = TTI->getNumberOfParts(VecTy);
6013         bool NeedInsertSubvectorAnalysis =
6014             !NumParts || (VL.size() / VF) > NumParts;
6015         // Get the cost for gathered loads.
6016         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
6017           if (VectorizedLoads.contains(VL[I]))
6018             continue;
6019           GatherCost += getGatherCost(VL.slice(I, VF));
6020         }
6021         // The cost for vectorized loads.
6022         InstructionCost ScalarsCost = 0;
6023         for (Value *V : VectorizedLoads) {
6024           auto *LI = cast<LoadInst>(V);
6025           ScalarsCost += TTI->getMemoryOpCost(
6026               Instruction::Load, LI->getType(), LI->getAlign(),
6027               LI->getPointerAddressSpace(), CostKind, LI);
6028         }
6029         auto *LI = cast<LoadInst>(E->getMainOp());
6030         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
6031         Align Alignment = LI->getAlign();
6032         GatherCost +=
6033             VectorizedCnt *
6034             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
6035                                  LI->getPointerAddressSpace(), CostKind, LI);
6036         GatherCost += ScatterVectorizeCnt *
6037                       TTI->getGatherScatterOpCost(
6038                           Instruction::Load, LoadTy, LI->getPointerOperand(),
6039                           /*VariableMask=*/false, Alignment, CostKind, LI);
6040         if (NeedInsertSubvectorAnalysis) {
6041           // Add the cost for the subvectors insert.
6042           for (int I = VF, E = VL.size(); I < E; I += VF)
6043             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
6044                                               None, I, LoadTy);
6045         }
6046         return ReuseShuffleCost + GatherCost - ScalarsCost;
6047       }
6048     }
6049     return ReuseShuffleCost + getGatherCost(VL);
6050   }
6051   InstructionCost CommonCost = 0;
6052   SmallVector<int> Mask;
6053   if (!E->ReorderIndices.empty()) {
6054     SmallVector<int> NewMask;
6055     if (E->getOpcode() == Instruction::Store) {
6056       // For stores the order is actually a mask.
6057       NewMask.resize(E->ReorderIndices.size());
6058       copy(E->ReorderIndices, NewMask.begin());
6059     } else {
6060       inversePermutation(E->ReorderIndices, NewMask);
6061     }
6062     ::addMask(Mask, NewMask);
6063   }
6064   if (NeedToShuffleReuses)
6065     ::addMask(Mask, E->ReuseShuffleIndices);
6066   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
6067     CommonCost =
6068         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
6069   assert((E->State == TreeEntry::Vectorize ||
6070           E->State == TreeEntry::ScatterVectorize) &&
6071          "Unhandled state");
6072   assert(E->getOpcode() &&
6073          ((allSameType(VL) && allSameBlock(VL)) ||
6074           (E->getOpcode() == Instruction::GetElementPtr &&
6075            E->getMainOp()->getType()->isPointerTy())) &&
6076          "Invalid VL");
6077   Instruction *VL0 = E->getMainOp();
6078   unsigned ShuffleOrOp =
6079       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6080   switch (ShuffleOrOp) {
6081     case Instruction::PHI:
6082       return 0;
6083 
6084     case Instruction::ExtractValue:
6085     case Instruction::ExtractElement: {
6086       // The common cost of removal ExtractElement/ExtractValue instructions +
6087       // the cost of shuffles, if required to resuffle the original vector.
6088       if (NeedToShuffleReuses) {
6089         unsigned Idx = 0;
6090         for (unsigned I : E->ReuseShuffleIndices) {
6091           if (ShuffleOrOp == Instruction::ExtractElement) {
6092             auto *EE = cast<ExtractElementInst>(VL[I]);
6093             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
6094                                                   EE->getVectorOperandType(),
6095                                                   *getExtractIndex(EE));
6096           } else {
6097             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
6098                                                   VecTy, Idx);
6099             ++Idx;
6100           }
6101         }
6102         Idx = EntryVF;
6103         for (Value *V : VL) {
6104           if (ShuffleOrOp == Instruction::ExtractElement) {
6105             auto *EE = cast<ExtractElementInst>(V);
6106             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
6107                                                   EE->getVectorOperandType(),
6108                                                   *getExtractIndex(EE));
6109           } else {
6110             --Idx;
6111             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
6112                                                   VecTy, Idx);
6113           }
6114         }
6115       }
6116       if (ShuffleOrOp == Instruction::ExtractValue) {
6117         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
6118           auto *EI = cast<Instruction>(VL[I]);
6119           // Take credit for instruction that will become dead.
6120           if (EI->hasOneUse()) {
6121             Instruction *Ext = EI->user_back();
6122             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
6123                 all_of(Ext->users(),
6124                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
6125               // Use getExtractWithExtendCost() to calculate the cost of
6126               // extractelement/ext pair.
6127               CommonCost -= TTI->getExtractWithExtendCost(
6128                   Ext->getOpcode(), Ext->getType(), VecTy, I);
6129               // Add back the cost of s|zext which is subtracted separately.
6130               CommonCost += TTI->getCastInstrCost(
6131                   Ext->getOpcode(), Ext->getType(), EI->getType(),
6132                   TTI::getCastContextHint(Ext), CostKind, Ext);
6133               continue;
6134             }
6135           }
6136           CommonCost -=
6137               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
6138         }
6139       } else {
6140         AdjustExtractsCost(CommonCost);
6141       }
6142       return CommonCost;
6143     }
6144     case Instruction::InsertElement: {
6145       assert(E->ReuseShuffleIndices.empty() &&
6146              "Unique insertelements only are expected.");
6147       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
6148       unsigned const NumElts = SrcVecTy->getNumElements();
6149       unsigned const NumScalars = VL.size();
6150 
6151       unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy);
6152 
6153       unsigned OffsetBeg = *getInsertIndex(VL.front());
6154       unsigned OffsetEnd = OffsetBeg;
6155       for (Value *V : VL.drop_front()) {
6156         unsigned Idx = *getInsertIndex(V);
6157         if (OffsetBeg > Idx)
6158           OffsetBeg = Idx;
6159         else if (OffsetEnd < Idx)
6160           OffsetEnd = Idx;
6161       }
6162       unsigned VecScalarsSz = PowerOf2Ceil(NumElts);
6163       if (NumOfParts > 0)
6164         VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts);
6165       unsigned VecSz =
6166           (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) *
6167           VecScalarsSz;
6168       unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz);
6169       unsigned InsertVecSz = std::min<unsigned>(
6170           PowerOf2Ceil(OffsetEnd - OffsetBeg + 1),
6171           ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) *
6172               VecScalarsSz);
6173       bool IsWholeSubvector =
6174           OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0);
6175       // Check if we can safely insert a subvector. If it is not possible, just
6176       // generate a whole-sized vector and shuffle the source vector and the new
6177       // subvector.
6178       if (OffsetBeg + InsertVecSz > VecSz) {
6179         // Align OffsetBeg to generate correct mask.
6180         OffsetBeg = alignDown(OffsetBeg, VecSz, Offset);
6181         InsertVecSz = VecSz;
6182       }
6183 
6184       APInt DemandedElts = APInt::getZero(NumElts);
6185       // TODO: Add support for Instruction::InsertValue.
6186       SmallVector<int> Mask;
6187       if (!E->ReorderIndices.empty()) {
6188         inversePermutation(E->ReorderIndices, Mask);
6189         Mask.append(InsertVecSz - Mask.size(), UndefMaskElem);
6190       } else {
6191         Mask.assign(VecSz, UndefMaskElem);
6192         std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0);
6193       }
6194       bool IsIdentity = true;
6195       SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem);
6196       Mask.swap(PrevMask);
6197       for (unsigned I = 0; I < NumScalars; ++I) {
6198         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
6199         DemandedElts.setBit(InsertIdx);
6200         IsIdentity &= InsertIdx - OffsetBeg == I;
6201         Mask[InsertIdx - OffsetBeg] = I;
6202       }
6203       assert(Offset < NumElts && "Failed to find vector index offset");
6204 
6205       InstructionCost Cost = 0;
6206       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
6207                                             /*Insert*/ true, /*Extract*/ false);
6208 
6209       // First cost - resize to actual vector size if not identity shuffle or
6210       // need to shift the vector.
6211       // Do not calculate the cost if the actual size is the register size and
6212       // we can merge this shuffle with the following SK_Select.
6213       auto *InsertVecTy =
6214           FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz);
6215       if (!IsIdentity)
6216         Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
6217                                     InsertVecTy, Mask);
6218       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6219         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6220       }));
6221       // Second cost - permutation with subvector, if some elements are from the
6222       // initial vector or inserting a subvector.
6223       // TODO: Implement the analysis of the FirstInsert->getOperand(0)
6224       // subvector of ActualVecTy.
6225       if (!isUndefVector(FirstInsert->getOperand(0)) && NumScalars != NumElts &&
6226           !IsWholeSubvector) {
6227         if (InsertVecSz != VecSz) {
6228           auto *ActualVecTy =
6229               FixedVectorType::get(SrcVecTy->getElementType(), VecSz);
6230           Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy,
6231                                       None, OffsetBeg - Offset, InsertVecTy);
6232         } else {
6233           for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I)
6234             Mask[I] = I;
6235           for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset;
6236                I <= End; ++I)
6237             if (Mask[I] != UndefMaskElem)
6238               Mask[I] = I + VecSz;
6239           for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I)
6240             Mask[I] = I;
6241           Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask);
6242         }
6243       }
6244       return Cost;
6245     }
6246     case Instruction::ZExt:
6247     case Instruction::SExt:
6248     case Instruction::FPToUI:
6249     case Instruction::FPToSI:
6250     case Instruction::FPExt:
6251     case Instruction::PtrToInt:
6252     case Instruction::IntToPtr:
6253     case Instruction::SIToFP:
6254     case Instruction::UIToFP:
6255     case Instruction::Trunc:
6256     case Instruction::FPTrunc:
6257     case Instruction::BitCast: {
6258       Type *SrcTy = VL0->getOperand(0)->getType();
6259       InstructionCost ScalarEltCost =
6260           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
6261                                 TTI::getCastContextHint(VL0), CostKind, VL0);
6262       if (NeedToShuffleReuses) {
6263         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6264       }
6265 
6266       // Calculate the cost of this instruction.
6267       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6268 
6269       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6270       InstructionCost VecCost = 0;
6271       // Check if the values are candidates to demote.
6272       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6273         VecCost = CommonCost + TTI->getCastInstrCost(
6274                                    E->getOpcode(), VecTy, SrcVecTy,
6275                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6276       }
6277       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6278       return VecCost - ScalarCost;
6279     }
6280     case Instruction::FCmp:
6281     case Instruction::ICmp:
6282     case Instruction::Select: {
6283       // Calculate the cost of this instruction.
6284       InstructionCost ScalarEltCost =
6285           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6286                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6287       if (NeedToShuffleReuses) {
6288         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6289       }
6290       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6291       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6292 
6293       // Check if all entries in VL are either compares or selects with compares
6294       // as condition that have the same predicates.
6295       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6296       bool First = true;
6297       for (auto *V : VL) {
6298         CmpInst::Predicate CurrentPred;
6299         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6300         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6301              !match(V, MatchCmp)) ||
6302             (!First && VecPred != CurrentPred)) {
6303           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6304           break;
6305         }
6306         First = false;
6307         VecPred = CurrentPred;
6308       }
6309 
6310       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6311           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6312       // Check if it is possible and profitable to use min/max for selects in
6313       // VL.
6314       //
6315       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6316       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6317         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6318                                           {VecTy, VecTy});
6319         InstructionCost IntrinsicCost =
6320             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6321         // If the selects are the only uses of the compares, they will be dead
6322         // and we can adjust the cost by removing their cost.
6323         if (IntrinsicAndUse.second)
6324           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6325                                                    MaskTy, VecPred, CostKind);
6326         VecCost = std::min(VecCost, IntrinsicCost);
6327       }
6328       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6329       return CommonCost + VecCost - ScalarCost;
6330     }
6331     case Instruction::FNeg:
6332     case Instruction::Add:
6333     case Instruction::FAdd:
6334     case Instruction::Sub:
6335     case Instruction::FSub:
6336     case Instruction::Mul:
6337     case Instruction::FMul:
6338     case Instruction::UDiv:
6339     case Instruction::SDiv:
6340     case Instruction::FDiv:
6341     case Instruction::URem:
6342     case Instruction::SRem:
6343     case Instruction::FRem:
6344     case Instruction::Shl:
6345     case Instruction::LShr:
6346     case Instruction::AShr:
6347     case Instruction::And:
6348     case Instruction::Or:
6349     case Instruction::Xor: {
6350       // Certain instructions can be cheaper to vectorize if they have a
6351       // constant second vector operand.
6352       TargetTransformInfo::OperandValueKind Op1VK =
6353           TargetTransformInfo::OK_AnyValue;
6354       TargetTransformInfo::OperandValueKind Op2VK =
6355           TargetTransformInfo::OK_UniformConstantValue;
6356       TargetTransformInfo::OperandValueProperties Op1VP =
6357           TargetTransformInfo::OP_None;
6358       TargetTransformInfo::OperandValueProperties Op2VP =
6359           TargetTransformInfo::OP_PowerOf2;
6360 
6361       // If all operands are exactly the same ConstantInt then set the
6362       // operand kind to OK_UniformConstantValue.
6363       // If instead not all operands are constants, then set the operand kind
6364       // to OK_AnyValue. If all operands are constants but not the same,
6365       // then set the operand kind to OK_NonUniformConstantValue.
6366       ConstantInt *CInt0 = nullptr;
6367       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6368         const Instruction *I = cast<Instruction>(VL[i]);
6369         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6370         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6371         if (!CInt) {
6372           Op2VK = TargetTransformInfo::OK_AnyValue;
6373           Op2VP = TargetTransformInfo::OP_None;
6374           break;
6375         }
6376         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6377             !CInt->getValue().isPowerOf2())
6378           Op2VP = TargetTransformInfo::OP_None;
6379         if (i == 0) {
6380           CInt0 = CInt;
6381           continue;
6382         }
6383         if (CInt0 != CInt)
6384           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6385       }
6386 
6387       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6388       InstructionCost ScalarEltCost =
6389           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6390                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6391       if (NeedToShuffleReuses) {
6392         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6393       }
6394       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6395       InstructionCost VecCost =
6396           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6397                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6398       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6399       return CommonCost + VecCost - ScalarCost;
6400     }
6401     case Instruction::GetElementPtr: {
6402       TargetTransformInfo::OperandValueKind Op1VK =
6403           TargetTransformInfo::OK_AnyValue;
6404       TargetTransformInfo::OperandValueKind Op2VK =
6405           any_of(VL,
6406                  [](Value *V) {
6407                    return isa<GetElementPtrInst>(V) &&
6408                           !isConstant(
6409                               cast<GetElementPtrInst>(V)->getOperand(1));
6410                  })
6411               ? TargetTransformInfo::OK_AnyValue
6412               : TargetTransformInfo::OK_UniformConstantValue;
6413 
6414       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6415           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6416       if (NeedToShuffleReuses) {
6417         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6418       }
6419       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6420       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6421           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6422       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6423       return CommonCost + VecCost - ScalarCost;
6424     }
6425     case Instruction::Load: {
6426       // Cost of wide load - cost of scalar loads.
6427       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6428       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6429           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6430       if (NeedToShuffleReuses) {
6431         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6432       }
6433       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6434       InstructionCost VecLdCost;
6435       if (E->State == TreeEntry::Vectorize) {
6436         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6437                                          CostKind, VL0);
6438       } else {
6439         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6440         Align CommonAlignment = Alignment;
6441         for (Value *V : VL)
6442           CommonAlignment =
6443               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6444         VecLdCost = TTI->getGatherScatterOpCost(
6445             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6446             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6447       }
6448       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6449       return CommonCost + VecLdCost - ScalarLdCost;
6450     }
6451     case Instruction::Store: {
6452       // We know that we can merge the stores. Calculate the cost.
6453       bool IsReorder = !E->ReorderIndices.empty();
6454       auto *SI =
6455           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6456       Align Alignment = SI->getAlign();
6457       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6458           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6459       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6460       InstructionCost VecStCost = TTI->getMemoryOpCost(
6461           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6462       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6463       return CommonCost + VecStCost - ScalarStCost;
6464     }
6465     case Instruction::Call: {
6466       CallInst *CI = cast<CallInst>(VL0);
6467       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6468 
6469       // Calculate the cost of the scalar and vector calls.
6470       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6471       InstructionCost ScalarEltCost =
6472           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6473       if (NeedToShuffleReuses) {
6474         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6475       }
6476       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6477 
6478       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6479       InstructionCost VecCallCost =
6480           std::min(VecCallCosts.first, VecCallCosts.second);
6481 
6482       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6483                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6484                         << " for " << *CI << "\n");
6485 
6486       return CommonCost + VecCallCost - ScalarCallCost;
6487     }
6488     case Instruction::ShuffleVector: {
6489       assert(E->isAltShuffle() &&
6490              ((Instruction::isBinaryOp(E->getOpcode()) &&
6491                Instruction::isBinaryOp(E->getAltOpcode())) ||
6492               (Instruction::isCast(E->getOpcode()) &&
6493                Instruction::isCast(E->getAltOpcode())) ||
6494               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6495              "Invalid Shuffle Vector Operand");
6496       InstructionCost ScalarCost = 0;
6497       if (NeedToShuffleReuses) {
6498         for (unsigned Idx : E->ReuseShuffleIndices) {
6499           Instruction *I = cast<Instruction>(VL[Idx]);
6500           CommonCost -= TTI->getInstructionCost(I, CostKind);
6501         }
6502         for (Value *V : VL) {
6503           Instruction *I = cast<Instruction>(V);
6504           CommonCost += TTI->getInstructionCost(I, CostKind);
6505         }
6506       }
6507       for (Value *V : VL) {
6508         Instruction *I = cast<Instruction>(V);
6509         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6510         ScalarCost += TTI->getInstructionCost(I, CostKind);
6511       }
6512       // VecCost is equal to sum of the cost of creating 2 vectors
6513       // and the cost of creating shuffle.
6514       InstructionCost VecCost = 0;
6515       // Try to find the previous shuffle node with the same operands and same
6516       // main/alternate ops.
6517       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6518         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6519           if (TE.get() == E)
6520             break;
6521           if (TE->isAltShuffle() &&
6522               ((TE->getOpcode() == E->getOpcode() &&
6523                 TE->getAltOpcode() == E->getAltOpcode()) ||
6524                (TE->getOpcode() == E->getAltOpcode() &&
6525                 TE->getAltOpcode() == E->getOpcode())) &&
6526               TE->hasEqualOperands(*E))
6527             return true;
6528         }
6529         return false;
6530       };
6531       if (TryFindNodeWithEqualOperands()) {
6532         LLVM_DEBUG({
6533           dbgs() << "SLP: diamond match for alternate node found.\n";
6534           E->dump();
6535         });
6536         // No need to add new vector costs here since we're going to reuse
6537         // same main/alternate vector ops, just do different shuffling.
6538       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6539         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6540         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6541                                                CostKind);
6542       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6543         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6544                                           Builder.getInt1Ty(),
6545                                           CI0->getPredicate(), CostKind, VL0);
6546         VecCost += TTI->getCmpSelInstrCost(
6547             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6548             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6549             E->getAltOp());
6550       } else {
6551         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6552         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6553         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6554         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6555         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6556                                         TTI::CastContextHint::None, CostKind);
6557         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6558                                          TTI::CastContextHint::None, CostKind);
6559       }
6560 
6561       if (E->ReuseShuffleIndices.empty()) {
6562         CommonCost =
6563             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6564       } else {
6565         SmallVector<int> Mask;
6566         buildShuffleEntryMask(
6567             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6568             [E](Instruction *I) {
6569               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6570               return I->getOpcode() == E->getAltOpcode();
6571             },
6572             Mask);
6573         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6574                                          FinalVecTy, Mask);
6575       }
6576       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6577       return CommonCost + VecCost - ScalarCost;
6578     }
6579     default:
6580       llvm_unreachable("Unknown instruction");
6581   }
6582 }
6583 
6584 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6585   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6586                     << VectorizableTree.size() << " is fully vectorizable .\n");
6587 
6588   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6589     SmallVector<int> Mask;
6590     return TE->State == TreeEntry::NeedToGather &&
6591            !any_of(TE->Scalars,
6592                    [this](Value *V) { return EphValues.contains(V); }) &&
6593            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6594             TE->Scalars.size() < Limit ||
6595             ((TE->getOpcode() == Instruction::ExtractElement ||
6596               all_of(TE->Scalars,
6597                      [](Value *V) {
6598                        return isa<ExtractElementInst, UndefValue>(V);
6599                      })) &&
6600              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6601             (TE->State == TreeEntry::NeedToGather &&
6602              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6603   };
6604 
6605   // We only handle trees of heights 1 and 2.
6606   if (VectorizableTree.size() == 1 &&
6607       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6608        (ForReduction &&
6609         AreVectorizableGathers(VectorizableTree[0].get(),
6610                                VectorizableTree[0]->Scalars.size()) &&
6611         VectorizableTree[0]->getVectorFactor() > 2)))
6612     return true;
6613 
6614   if (VectorizableTree.size() != 2)
6615     return false;
6616 
6617   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6618   // with the second gather nodes if they have less scalar operands rather than
6619   // the initial tree element (may be profitable to shuffle the second gather)
6620   // or they are extractelements, which form shuffle.
6621   SmallVector<int> Mask;
6622   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6623       AreVectorizableGathers(VectorizableTree[1].get(),
6624                              VectorizableTree[0]->Scalars.size()))
6625     return true;
6626 
6627   // Gathering cost would be too much for tiny trees.
6628   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6629       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6630        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6631     return false;
6632 
6633   return true;
6634 }
6635 
6636 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6637                                        TargetTransformInfo *TTI,
6638                                        bool MustMatchOrInst) {
6639   // Look past the root to find a source value. Arbitrarily follow the
6640   // path through operand 0 of any 'or'. Also, peek through optional
6641   // shift-left-by-multiple-of-8-bits.
6642   Value *ZextLoad = Root;
6643   const APInt *ShAmtC;
6644   bool FoundOr = false;
6645   while (!isa<ConstantExpr>(ZextLoad) &&
6646          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6647           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6648            ShAmtC->urem(8) == 0))) {
6649     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6650     ZextLoad = BinOp->getOperand(0);
6651     if (BinOp->getOpcode() == Instruction::Or)
6652       FoundOr = true;
6653   }
6654   // Check if the input is an extended load of the required or/shift expression.
6655   Value *Load;
6656   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6657       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6658     return false;
6659 
6660   // Require that the total load bit width is a legal integer type.
6661   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6662   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6663   Type *SrcTy = Load->getType();
6664   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6665   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6666     return false;
6667 
6668   // Everything matched - assume that we can fold the whole sequence using
6669   // load combining.
6670   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6671              << *(cast<Instruction>(Root)) << "\n");
6672 
6673   return true;
6674 }
6675 
6676 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6677   if (RdxKind != RecurKind::Or)
6678     return false;
6679 
6680   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6681   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6682   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6683                                     /* MatchOr */ false);
6684 }
6685 
6686 bool BoUpSLP::isLoadCombineCandidate() const {
6687   // Peek through a final sequence of stores and check if all operations are
6688   // likely to be load-combined.
6689   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6690   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6691     Value *X;
6692     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6693         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6694       return false;
6695   }
6696   return true;
6697 }
6698 
6699 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6700   // No need to vectorize inserts of gathered values.
6701   if (VectorizableTree.size() == 2 &&
6702       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6703       VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6704       (VectorizableTree[1]->getVectorFactor() <= 2 ||
6705        !(isSplat(VectorizableTree[1]->Scalars) ||
6706          allConstant(VectorizableTree[1]->Scalars))))
6707     return true;
6708 
6709   // We can vectorize the tree if its size is greater than or equal to the
6710   // minimum size specified by the MinTreeSize command line option.
6711   if (VectorizableTree.size() >= MinTreeSize)
6712     return false;
6713 
6714   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6715   // can vectorize it if we can prove it fully vectorizable.
6716   if (isFullyVectorizableTinyTree(ForReduction))
6717     return false;
6718 
6719   assert(VectorizableTree.empty()
6720              ? ExternalUses.empty()
6721              : true && "We shouldn't have any external users");
6722 
6723   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6724   // vectorizable.
6725   return true;
6726 }
6727 
6728 InstructionCost BoUpSLP::getSpillCost() const {
6729   // Walk from the bottom of the tree to the top, tracking which values are
6730   // live. When we see a call instruction that is not part of our tree,
6731   // query TTI to see if there is a cost to keeping values live over it
6732   // (for example, if spills and fills are required).
6733   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6734   InstructionCost Cost = 0;
6735 
6736   SmallPtrSet<Instruction*, 4> LiveValues;
6737   Instruction *PrevInst = nullptr;
6738 
6739   // The entries in VectorizableTree are not necessarily ordered by their
6740   // position in basic blocks. Collect them and order them by dominance so later
6741   // instructions are guaranteed to be visited first. For instructions in
6742   // different basic blocks, we only scan to the beginning of the block, so
6743   // their order does not matter, as long as all instructions in a basic block
6744   // are grouped together. Using dominance ensures a deterministic order.
6745   SmallVector<Instruction *, 16> OrderedScalars;
6746   for (const auto &TEPtr : VectorizableTree) {
6747     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6748     if (!Inst)
6749       continue;
6750     OrderedScalars.push_back(Inst);
6751   }
6752   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6753     auto *NodeA = DT->getNode(A->getParent());
6754     auto *NodeB = DT->getNode(B->getParent());
6755     assert(NodeA && "Should only process reachable instructions");
6756     assert(NodeB && "Should only process reachable instructions");
6757     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6758            "Different nodes should have different DFS numbers");
6759     if (NodeA != NodeB)
6760       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6761     return B->comesBefore(A);
6762   });
6763 
6764   for (Instruction *Inst : OrderedScalars) {
6765     if (!PrevInst) {
6766       PrevInst = Inst;
6767       continue;
6768     }
6769 
6770     // Update LiveValues.
6771     LiveValues.erase(PrevInst);
6772     for (auto &J : PrevInst->operands()) {
6773       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6774         LiveValues.insert(cast<Instruction>(&*J));
6775     }
6776 
6777     LLVM_DEBUG({
6778       dbgs() << "SLP: #LV: " << LiveValues.size();
6779       for (auto *X : LiveValues)
6780         dbgs() << " " << X->getName();
6781       dbgs() << ", Looking at ";
6782       Inst->dump();
6783     });
6784 
6785     // Now find the sequence of instructions between PrevInst and Inst.
6786     unsigned NumCalls = 0;
6787     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6788                                  PrevInstIt =
6789                                      PrevInst->getIterator().getReverse();
6790     while (InstIt != PrevInstIt) {
6791       if (PrevInstIt == PrevInst->getParent()->rend()) {
6792         PrevInstIt = Inst->getParent()->rbegin();
6793         continue;
6794       }
6795 
6796       // Debug information does not impact spill cost.
6797       if ((isa<CallInst>(&*PrevInstIt) &&
6798            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6799           &*PrevInstIt != PrevInst)
6800         NumCalls++;
6801 
6802       ++PrevInstIt;
6803     }
6804 
6805     if (NumCalls) {
6806       SmallVector<Type*, 4> V;
6807       for (auto *II : LiveValues) {
6808         auto *ScalarTy = II->getType();
6809         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6810           ScalarTy = VectorTy->getElementType();
6811         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6812       }
6813       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6814     }
6815 
6816     PrevInst = Inst;
6817   }
6818 
6819   return Cost;
6820 }
6821 
6822 /// Check if two insertelement instructions are from the same buildvector.
6823 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6824                                             InsertElementInst *V) {
6825   // Instructions must be from the same basic blocks.
6826   if (VU->getParent() != V->getParent())
6827     return false;
6828   // Checks if 2 insertelements are from the same buildvector.
6829   if (VU->getType() != V->getType())
6830     return false;
6831   // Multiple used inserts are separate nodes.
6832   if (!VU->hasOneUse() && !V->hasOneUse())
6833     return false;
6834   auto *IE1 = VU;
6835   auto *IE2 = V;
6836   unsigned Idx1 = *getInsertIndex(IE1);
6837   unsigned Idx2 = *getInsertIndex(IE2);
6838   // Go through the vector operand of insertelement instructions trying to find
6839   // either VU as the original vector for IE2 or V as the original vector for
6840   // IE1.
6841   do {
6842     if (IE2 == VU)
6843       return VU->hasOneUse();
6844     if (IE1 == V)
6845       return V->hasOneUse();
6846     if (IE1) {
6847       if ((IE1 != VU && !IE1->hasOneUse()) ||
6848           getInsertIndex(IE1).value_or(Idx2) == Idx2)
6849         IE1 = nullptr;
6850       else
6851         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6852     }
6853     if (IE2) {
6854       if ((IE2 != V && !IE2->hasOneUse()) ||
6855           getInsertIndex(IE2).value_or(Idx1) == Idx1)
6856         IE2 = nullptr;
6857       else
6858         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6859     }
6860   } while (IE1 || IE2);
6861   return false;
6862 }
6863 
6864 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6865 /// buildvector sequence.
6866 static bool isFirstInsertElement(const InsertElementInst *IE1,
6867                                  const InsertElementInst *IE2) {
6868   if (IE1 == IE2)
6869     return false;
6870   const auto *I1 = IE1;
6871   const auto *I2 = IE2;
6872   const InsertElementInst *PrevI1;
6873   const InsertElementInst *PrevI2;
6874   unsigned Idx1 = *getInsertIndex(IE1);
6875   unsigned Idx2 = *getInsertIndex(IE2);
6876   do {
6877     if (I2 == IE1)
6878       return true;
6879     if (I1 == IE2)
6880       return false;
6881     PrevI1 = I1;
6882     PrevI2 = I2;
6883     if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
6884         getInsertIndex(I1).value_or(Idx2) != Idx2)
6885       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6886     if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
6887         getInsertIndex(I2).value_or(Idx1) != Idx1)
6888       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6889   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6890   llvm_unreachable("Two different buildvectors not expected.");
6891 }
6892 
6893 namespace {
6894 /// Returns incoming Value *, if the requested type is Value * too, or a default
6895 /// value, otherwise.
6896 struct ValueSelect {
6897   template <typename U>
6898   static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type
6899   get(Value *V) {
6900     return V;
6901   }
6902   template <typename U>
6903   static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type
6904   get(Value *) {
6905     return U();
6906   }
6907 };
6908 } // namespace
6909 
6910 /// Does the analysis of the provided shuffle masks and performs the requested
6911 /// actions on the vectors with the given shuffle masks. It tries to do it in
6912 /// several steps.
6913 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6914 /// have common VF and perform action for 2 input vectors (including non-undef
6915 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6916 /// and processed as a shuffle of 2 elements.
6917 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6918 /// action only for 1 vector with the given mask, if it is not the identity
6919 /// mask.
6920 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6921 /// vectors, combing the masks properly between the steps.
6922 template <typename T>
6923 static T *performExtractsShuffleAction(
6924     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6925     function_ref<unsigned(T *)> GetVF,
6926     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6927     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6928   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6929   SmallVector<int> Mask(ShuffleMask.begin()->second);
6930   auto VMIt = std::next(ShuffleMask.begin());
6931   T *Prev = nullptr;
6932   bool IsBaseNotUndef = !isUndefVector(Base);
6933   if (IsBaseNotUndef) {
6934     // Base is not undef, need to combine it with the next subvectors.
6935     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6936     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6937       if (Mask[Idx] == UndefMaskElem)
6938         Mask[Idx] = Idx;
6939       else
6940         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6941     }
6942     auto *V = ValueSelect::get<T *>(Base);
6943     (void)V;
6944     assert((!V || GetVF(V) == Mask.size()) &&
6945            "Expected base vector of VF number of elements.");
6946     Prev = Action(Mask, {nullptr, Res.first});
6947   } else if (ShuffleMask.size() == 1) {
6948     // Base is undef and only 1 vector is shuffled - perform the action only for
6949     // single vector, if the mask is not the identity mask.
6950     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6951     if (Res.second)
6952       // Identity mask is found.
6953       Prev = Res.first;
6954     else
6955       Prev = Action(Mask, {ShuffleMask.begin()->first});
6956   } else {
6957     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6958     // shuffles step by step, combining shuffle between the steps.
6959     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6960     unsigned Vec2VF = GetVF(VMIt->first);
6961     if (Vec1VF == Vec2VF) {
6962       // No need to resize the input vectors since they are of the same size, we
6963       // can shuffle them directly.
6964       ArrayRef<int> SecMask = VMIt->second;
6965       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6966         if (SecMask[I] != UndefMaskElem) {
6967           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6968           Mask[I] = SecMask[I] + Vec1VF;
6969         }
6970       }
6971       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6972     } else {
6973       // Vectors of different sizes - resize and reshuffle.
6974       std::pair<T *, bool> Res1 =
6975           ResizeAction(ShuffleMask.begin()->first, Mask);
6976       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6977       ArrayRef<int> SecMask = VMIt->second;
6978       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6979         if (Mask[I] != UndefMaskElem) {
6980           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6981           if (Res1.second)
6982             Mask[I] = I;
6983         } else if (SecMask[I] != UndefMaskElem) {
6984           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6985           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6986         }
6987       }
6988       Prev = Action(Mask, {Res1.first, Res2.first});
6989     }
6990     VMIt = std::next(VMIt);
6991   }
6992   // Perform requested actions for the remaining masks/vectors.
6993   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6994     // Shuffle other input vectors, if any.
6995     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6996     ArrayRef<int> SecMask = VMIt->second;
6997     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6998       if (SecMask[I] != UndefMaskElem) {
6999         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
7000                "Multiple uses of scalars.");
7001         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
7002       } else if (Mask[I] != UndefMaskElem) {
7003         Mask[I] = I;
7004       }
7005     }
7006     Prev = Action(Mask, {Prev, Res.first});
7007   }
7008   return Prev;
7009 }
7010 
7011 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
7012   InstructionCost Cost = 0;
7013   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
7014                     << VectorizableTree.size() << ".\n");
7015 
7016   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
7017 
7018   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
7019     TreeEntry &TE = *VectorizableTree[I];
7020 
7021     InstructionCost C = getEntryCost(&TE, VectorizedVals);
7022     Cost += C;
7023     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
7024                       << " for bundle that starts with " << *TE.Scalars[0]
7025                       << ".\n"
7026                       << "SLP: Current total cost = " << Cost << "\n");
7027   }
7028 
7029   SmallPtrSet<Value *, 16> ExtractCostCalculated;
7030   InstructionCost ExtractCost = 0;
7031   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
7032   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
7033   SmallVector<APInt> DemandedElts;
7034   for (ExternalUser &EU : ExternalUses) {
7035     // We only add extract cost once for the same scalar.
7036     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
7037         !ExtractCostCalculated.insert(EU.Scalar).second)
7038       continue;
7039 
7040     // Uses by ephemeral values are free (because the ephemeral value will be
7041     // removed prior to code generation, and so the extraction will be
7042     // removed as well).
7043     if (EphValues.count(EU.User))
7044       continue;
7045 
7046     // No extract cost for vector "scalar"
7047     if (isa<FixedVectorType>(EU.Scalar->getType()))
7048       continue;
7049 
7050     // Already counted the cost for external uses when tried to adjust the cost
7051     // for extractelements, no need to add it again.
7052     if (isa<ExtractElementInst>(EU.Scalar))
7053       continue;
7054 
7055     // If found user is an insertelement, do not calculate extract cost but try
7056     // to detect it as a final shuffled/identity match.
7057     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
7058       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
7059         Optional<unsigned> InsertIdx = getInsertIndex(VU);
7060         if (InsertIdx) {
7061           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
7062           auto *It =
7063               find_if(FirstUsers,
7064                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
7065                         return areTwoInsertFromSameBuildVector(
7066                             VU, cast<InsertElementInst>(Pair.first));
7067                       });
7068           int VecId = -1;
7069           if (It == FirstUsers.end()) {
7070             (void)ShuffleMasks.emplace_back();
7071             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
7072             if (Mask.empty())
7073               Mask.assign(FTy->getNumElements(), UndefMaskElem);
7074             // Find the insertvector, vectorized in tree, if any.
7075             Value *Base = VU;
7076             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
7077               if (IEBase != EU.User &&
7078                   (!IEBase->hasOneUse() ||
7079                    getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx))
7080                 break;
7081               // Build the mask for the vectorized insertelement instructions.
7082               if (const TreeEntry *E = getTreeEntry(IEBase)) {
7083                 VU = IEBase;
7084                 do {
7085                   IEBase = cast<InsertElementInst>(Base);
7086                   int Idx = *getInsertIndex(IEBase);
7087                   assert(Mask[Idx] == UndefMaskElem &&
7088                          "InsertElementInstruction used already.");
7089                   Mask[Idx] = Idx;
7090                   Base = IEBase->getOperand(0);
7091                 } while (E == getTreeEntry(Base));
7092                 break;
7093               }
7094               Base = cast<InsertElementInst>(Base)->getOperand(0);
7095             }
7096             FirstUsers.emplace_back(VU, ScalarTE);
7097             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
7098             VecId = FirstUsers.size() - 1;
7099           } else {
7100             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
7101               It->first = VU;
7102             VecId = std::distance(FirstUsers.begin(), It);
7103           }
7104           int InIdx = *InsertIdx;
7105           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
7106           if (Mask.empty())
7107             Mask.assign(FTy->getNumElements(), UndefMaskElem);
7108           Mask[InIdx] = EU.Lane;
7109           DemandedElts[VecId].setBit(InIdx);
7110           continue;
7111         }
7112       }
7113     }
7114 
7115     // If we plan to rewrite the tree in a smaller type, we will need to sign
7116     // extend the extracted value back to the original type. Here, we account
7117     // for the extract and the added cost of the sign extend if needed.
7118     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
7119     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7120     if (MinBWs.count(ScalarRoot)) {
7121       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7122       auto Extend =
7123           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
7124       VecTy = FixedVectorType::get(MinTy, BundleWidth);
7125       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
7126                                                    VecTy, EU.Lane);
7127     } else {
7128       ExtractCost +=
7129           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
7130     }
7131   }
7132 
7133   InstructionCost SpillCost = getSpillCost();
7134   Cost += SpillCost + ExtractCost;
7135   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
7136     InstructionCost C = 0;
7137     unsigned VF = Mask.size();
7138     unsigned VecVF = TE->getVectorFactor();
7139     if (VF != VecVF &&
7140         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
7141          (all_of(Mask,
7142                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
7143           !ShuffleVectorInst::isIdentityMask(Mask)))) {
7144       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
7145       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
7146                 OrigMask.begin());
7147       C = TTI->getShuffleCost(
7148           TTI::SK_PermuteSingleSrc,
7149           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
7150       LLVM_DEBUG(
7151           dbgs() << "SLP: Adding cost " << C
7152                  << " for final shuffle of insertelement external users.\n";
7153           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
7154       Cost += C;
7155       return std::make_pair(TE, true);
7156     }
7157     return std::make_pair(TE, false);
7158   };
7159   // Calculate the cost of the reshuffled vectors, if any.
7160   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
7161     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
7162     unsigned VF = ShuffleMasks[I].begin()->second.size();
7163     auto *FTy = FixedVectorType::get(
7164         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
7165     auto Vector = ShuffleMasks[I].takeVector();
7166     auto &&EstimateShufflesCost = [this, FTy,
7167                                    &Cost](ArrayRef<int> Mask,
7168                                           ArrayRef<const TreeEntry *> TEs) {
7169       assert((TEs.size() == 1 || TEs.size() == 2) &&
7170              "Expected exactly 1 or 2 tree entries.");
7171       if (TEs.size() == 1) {
7172         int Limit = 2 * Mask.size();
7173         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
7174             !ShuffleVectorInst::isIdentityMask(Mask)) {
7175           InstructionCost C =
7176               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
7177           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
7178                             << " for final shuffle of insertelement "
7179                                "external users.\n";
7180                      TEs.front()->dump();
7181                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
7182           Cost += C;
7183         }
7184       } else {
7185         InstructionCost C =
7186             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
7187         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
7188                           << " for final shuffle of vector node and external "
7189                              "insertelement users.\n";
7190                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
7191                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
7192         Cost += C;
7193       }
7194       return TEs.back();
7195     };
7196     (void)performExtractsShuffleAction<const TreeEntry>(
7197         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
7198         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
7199         EstimateShufflesCost);
7200     InstructionCost InsertCost = TTI->getScalarizationOverhead(
7201         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
7202         /*Insert*/ true, /*Extract*/ false);
7203     Cost -= InsertCost;
7204   }
7205 
7206 #ifndef NDEBUG
7207   SmallString<256> Str;
7208   {
7209     raw_svector_ostream OS(Str);
7210     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
7211        << "SLP: Extract Cost = " << ExtractCost << ".\n"
7212        << "SLP: Total Cost = " << Cost << ".\n";
7213   }
7214   LLVM_DEBUG(dbgs() << Str);
7215   if (ViewSLPTree)
7216     ViewGraph(this, "SLP" + F->getName(), false, Str);
7217 #endif
7218 
7219   return Cost;
7220 }
7221 
7222 Optional<TargetTransformInfo::ShuffleKind>
7223 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
7224                                SmallVectorImpl<const TreeEntry *> &Entries) {
7225   // TODO: currently checking only for Scalars in the tree entry, need to count
7226   // reused elements too for better cost estimation.
7227   Mask.assign(TE->Scalars.size(), UndefMaskElem);
7228   Entries.clear();
7229   // Build a lists of values to tree entries.
7230   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
7231   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
7232     if (EntryPtr.get() == TE)
7233       break;
7234     if (EntryPtr->State != TreeEntry::NeedToGather)
7235       continue;
7236     for (Value *V : EntryPtr->Scalars)
7237       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
7238   }
7239   // Find all tree entries used by the gathered values. If no common entries
7240   // found - not a shuffle.
7241   // Here we build a set of tree nodes for each gathered value and trying to
7242   // find the intersection between these sets. If we have at least one common
7243   // tree node for each gathered value - we have just a permutation of the
7244   // single vector. If we have 2 different sets, we're in situation where we
7245   // have a permutation of 2 input vectors.
7246   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
7247   DenseMap<Value *, int> UsedValuesEntry;
7248   for (Value *V : TE->Scalars) {
7249     if (isa<UndefValue>(V))
7250       continue;
7251     // Build a list of tree entries where V is used.
7252     SmallPtrSet<const TreeEntry *, 4> VToTEs;
7253     auto It = ValueToTEs.find(V);
7254     if (It != ValueToTEs.end())
7255       VToTEs = It->second;
7256     if (const TreeEntry *VTE = getTreeEntry(V))
7257       VToTEs.insert(VTE);
7258     if (VToTEs.empty())
7259       return None;
7260     if (UsedTEs.empty()) {
7261       // The first iteration, just insert the list of nodes to vector.
7262       UsedTEs.push_back(VToTEs);
7263     } else {
7264       // Need to check if there are any previously used tree nodes which use V.
7265       // If there are no such nodes, consider that we have another one input
7266       // vector.
7267       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
7268       unsigned Idx = 0;
7269       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
7270         // Do we have a non-empty intersection of previously listed tree entries
7271         // and tree entries using current V?
7272         set_intersect(VToTEs, Set);
7273         if (!VToTEs.empty()) {
7274           // Yes, write the new subset and continue analysis for the next
7275           // scalar.
7276           Set.swap(VToTEs);
7277           break;
7278         }
7279         VToTEs = SavedVToTEs;
7280         ++Idx;
7281       }
7282       // No non-empty intersection found - need to add a second set of possible
7283       // source vectors.
7284       if (Idx == UsedTEs.size()) {
7285         // If the number of input vectors is greater than 2 - not a permutation,
7286         // fallback to the regular gather.
7287         if (UsedTEs.size() == 2)
7288           return None;
7289         UsedTEs.push_back(SavedVToTEs);
7290         Idx = UsedTEs.size() - 1;
7291       }
7292       UsedValuesEntry.try_emplace(V, Idx);
7293     }
7294   }
7295 
7296   if (UsedTEs.empty()) {
7297     assert(all_of(TE->Scalars, UndefValue::classof) &&
7298            "Expected vector of undefs only.");
7299     return None;
7300   }
7301 
7302   unsigned VF = 0;
7303   if (UsedTEs.size() == 1) {
7304     // Try to find the perfect match in another gather node at first.
7305     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
7306       return EntryPtr->isSame(TE->Scalars);
7307     });
7308     if (It != UsedTEs.front().end()) {
7309       Entries.push_back(*It);
7310       std::iota(Mask.begin(), Mask.end(), 0);
7311       return TargetTransformInfo::SK_PermuteSingleSrc;
7312     }
7313     // No perfect match, just shuffle, so choose the first tree node.
7314     Entries.push_back(*UsedTEs.front().begin());
7315   } else {
7316     // Try to find nodes with the same vector factor.
7317     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7318     DenseMap<int, const TreeEntry *> VFToTE;
7319     for (const TreeEntry *TE : UsedTEs.front())
7320       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7321     for (const TreeEntry *TE : UsedTEs.back()) {
7322       auto It = VFToTE.find(TE->getVectorFactor());
7323       if (It != VFToTE.end()) {
7324         VF = It->first;
7325         Entries.push_back(It->second);
7326         Entries.push_back(TE);
7327         break;
7328       }
7329     }
7330     // No 2 source vectors with the same vector factor - give up and do regular
7331     // gather.
7332     if (Entries.empty())
7333       return None;
7334   }
7335 
7336   // Build a shuffle mask for better cost estimation and vector emission.
7337   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7338     Value *V = TE->Scalars[I];
7339     if (isa<UndefValue>(V))
7340       continue;
7341     unsigned Idx = UsedValuesEntry.lookup(V);
7342     const TreeEntry *VTE = Entries[Idx];
7343     int FoundLane = VTE->findLaneForValue(V);
7344     Mask[I] = Idx * VF + FoundLane;
7345     // Extra check required by isSingleSourceMaskImpl function (called by
7346     // ShuffleVectorInst::isSingleSourceMask).
7347     if (Mask[I] >= 2 * E)
7348       return None;
7349   }
7350   switch (Entries.size()) {
7351   case 1:
7352     return TargetTransformInfo::SK_PermuteSingleSrc;
7353   case 2:
7354     return TargetTransformInfo::SK_PermuteTwoSrc;
7355   default:
7356     break;
7357   }
7358   return None;
7359 }
7360 
7361 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7362                                        const APInt &ShuffledIndices,
7363                                        bool NeedToShuffle) const {
7364   InstructionCost Cost =
7365       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7366                                     /*Extract*/ false);
7367   if (NeedToShuffle)
7368     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7369   return Cost;
7370 }
7371 
7372 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7373   // Find the type of the operands in VL.
7374   Type *ScalarTy = VL[0]->getType();
7375   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7376     ScalarTy = SI->getValueOperand()->getType();
7377   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7378   bool DuplicateNonConst = false;
7379   // Find the cost of inserting/extracting values from the vector.
7380   // Check if the same elements are inserted several times and count them as
7381   // shuffle candidates.
7382   APInt ShuffledElements = APInt::getZero(VL.size());
7383   DenseSet<Value *> UniqueElements;
7384   // Iterate in reverse order to consider insert elements with the high cost.
7385   for (unsigned I = VL.size(); I > 0; --I) {
7386     unsigned Idx = I - 1;
7387     // No need to shuffle duplicates for constants.
7388     if (isConstant(VL[Idx])) {
7389       ShuffledElements.setBit(Idx);
7390       continue;
7391     }
7392     if (!UniqueElements.insert(VL[Idx]).second) {
7393       DuplicateNonConst = true;
7394       ShuffledElements.setBit(Idx);
7395     }
7396   }
7397   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7398 }
7399 
7400 // Perform operand reordering on the instructions in VL and return the reordered
7401 // operands in Left and Right.
7402 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7403                                              SmallVectorImpl<Value *> &Left,
7404                                              SmallVectorImpl<Value *> &Right,
7405                                              const DataLayout &DL,
7406                                              ScalarEvolution &SE,
7407                                              const BoUpSLP &R) {
7408   if (VL.empty())
7409     return;
7410   VLOperands Ops(VL, DL, SE, R);
7411   // Reorder the operands in place.
7412   Ops.reorder();
7413   Left = Ops.getVL(0);
7414   Right = Ops.getVL(1);
7415 }
7416 
7417 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7418   // Get the basic block this bundle is in. All instructions in the bundle
7419   // should be in this block (except for extractelement-like instructions with
7420   // constant indeces).
7421   auto *Front = E->getMainOp();
7422   auto *BB = Front->getParent();
7423   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7424     if (E->getOpcode() == Instruction::GetElementPtr &&
7425         !isa<GetElementPtrInst>(V))
7426       return true;
7427     auto *I = cast<Instruction>(V);
7428     return !E->isOpcodeOrAlt(I) || I->getParent() == BB ||
7429            isVectorLikeInstWithConstOps(I);
7430   }));
7431 
7432   auto &&FindLastInst = [E, Front, this, &BB]() {
7433     Instruction *LastInst = Front;
7434     for (Value *V : E->Scalars) {
7435       auto *I = dyn_cast<Instruction>(V);
7436       if (!I)
7437         continue;
7438       if (LastInst->getParent() == I->getParent()) {
7439         if (LastInst->comesBefore(I))
7440           LastInst = I;
7441         continue;
7442       }
7443       assert(isVectorLikeInstWithConstOps(LastInst) &&
7444              isVectorLikeInstWithConstOps(I) &&
7445              "Expected vector-like insts only.");
7446       if (!DT->isReachableFromEntry(LastInst->getParent())) {
7447         LastInst = I;
7448         continue;
7449       }
7450       if (!DT->isReachableFromEntry(I->getParent()))
7451         continue;
7452       auto *NodeA = DT->getNode(LastInst->getParent());
7453       auto *NodeB = DT->getNode(I->getParent());
7454       assert(NodeA && "Should only process reachable instructions");
7455       assert(NodeB && "Should only process reachable instructions");
7456       assert((NodeA == NodeB) ==
7457                  (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
7458              "Different nodes should have different DFS numbers");
7459       if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn())
7460         LastInst = I;
7461     }
7462     BB = LastInst->getParent();
7463     return LastInst;
7464   };
7465 
7466   auto &&FindFirstInst = [E, Front]() {
7467     Instruction *FirstInst = Front;
7468     for (Value *V : E->Scalars) {
7469       auto *I = dyn_cast<Instruction>(V);
7470       if (!I)
7471         continue;
7472       if (I->comesBefore(FirstInst))
7473         FirstInst = I;
7474     }
7475     return FirstInst;
7476   };
7477 
7478   // Set the insert point to the beginning of the basic block if the entry
7479   // should not be scheduled.
7480   if (E->State != TreeEntry::NeedToGather &&
7481       doesNotNeedToSchedule(E->Scalars)) {
7482     Instruction *InsertInst;
7483     if (all_of(E->Scalars, isUsedOutsideBlock))
7484       InsertInst = FindLastInst();
7485     else
7486       InsertInst = FindFirstInst();
7487     // If the instruction is PHI, set the insert point after all the PHIs.
7488     if (isa<PHINode>(InsertInst))
7489       InsertInst = BB->getFirstNonPHI();
7490     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7491     Builder.SetInsertPoint(BB, InsertPt);
7492     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7493     return;
7494   }
7495 
7496   // The last instruction in the bundle in program order.
7497   Instruction *LastInst = nullptr;
7498 
7499   // Find the last instruction. The common case should be that BB has been
7500   // scheduled, and the last instruction is VL.back(). So we start with
7501   // VL.back() and iterate over schedule data until we reach the end of the
7502   // bundle. The end of the bundle is marked by null ScheduleData.
7503   if (BlocksSchedules.count(BB)) {
7504     Value *V = E->isOneOf(E->Scalars.back());
7505     if (doesNotNeedToBeScheduled(V))
7506       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7507     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7508     if (Bundle && Bundle->isPartOfBundle())
7509       for (; Bundle; Bundle = Bundle->NextInBundle)
7510         if (Bundle->OpValue == Bundle->Inst)
7511           LastInst = Bundle->Inst;
7512   }
7513 
7514   // LastInst can still be null at this point if there's either not an entry
7515   // for BB in BlocksSchedules or there's no ScheduleData available for
7516   // VL.back(). This can be the case if buildTree_rec aborts for various
7517   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7518   // size is reached, etc.). ScheduleData is initialized in the scheduling
7519   // "dry-run".
7520   //
7521   // If this happens, we can still find the last instruction by brute force. We
7522   // iterate forwards from Front (inclusive) until we either see all
7523   // instructions in the bundle or reach the end of the block. If Front is the
7524   // last instruction in program order, LastInst will be set to Front, and we
7525   // will visit all the remaining instructions in the block.
7526   //
7527   // One of the reasons we exit early from buildTree_rec is to place an upper
7528   // bound on compile-time. Thus, taking an additional compile-time hit here is
7529   // not ideal. However, this should be exceedingly rare since it requires that
7530   // we both exit early from buildTree_rec and that the bundle be out-of-order
7531   // (causing us to iterate all the way to the end of the block).
7532   if (!LastInst) {
7533     LastInst = FindLastInst();
7534     // If the instruction is PHI, set the insert point after all the PHIs.
7535     if (isa<PHINode>(LastInst))
7536       LastInst = BB->getFirstNonPHI()->getPrevNode();
7537   }
7538   assert(LastInst && "Failed to find last instruction in bundle");
7539 
7540   // Set the insertion point after the last instruction in the bundle. Set the
7541   // debug location to Front.
7542   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7543   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7544 }
7545 
7546 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7547   // List of instructions/lanes from current block and/or the blocks which are
7548   // part of the current loop. These instructions will be inserted at the end to
7549   // make it possible to optimize loops and hoist invariant instructions out of
7550   // the loops body with better chances for success.
7551   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7552   SmallSet<int, 4> PostponedIndices;
7553   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7554   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7555     SmallPtrSet<BasicBlock *, 4> Visited;
7556     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7557       InsertBB = InsertBB->getSinglePredecessor();
7558     return InsertBB && InsertBB == InstBB;
7559   };
7560   for (int I = 0, E = VL.size(); I < E; ++I) {
7561     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7562       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7563            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7564           PostponedIndices.insert(I).second)
7565         PostponedInsts.emplace_back(Inst, I);
7566   }
7567 
7568   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7569     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7570     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7571     if (!InsElt)
7572       return Vec;
7573     GatherShuffleSeq.insert(InsElt);
7574     CSEBlocks.insert(InsElt->getParent());
7575     // Add to our 'need-to-extract' list.
7576     if (TreeEntry *Entry = getTreeEntry(V)) {
7577       // Find which lane we need to extract.
7578       unsigned FoundLane = Entry->findLaneForValue(V);
7579       ExternalUses.emplace_back(V, InsElt, FoundLane);
7580     }
7581     return Vec;
7582   };
7583   Value *Val0 =
7584       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7585   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7586   Value *Vec = PoisonValue::get(VecTy);
7587   SmallVector<int> NonConsts;
7588   // Insert constant values at first.
7589   for (int I = 0, E = VL.size(); I < E; ++I) {
7590     if (PostponedIndices.contains(I))
7591       continue;
7592     if (!isConstant(VL[I])) {
7593       NonConsts.push_back(I);
7594       continue;
7595     }
7596     Vec = CreateInsertElement(Vec, VL[I], I);
7597   }
7598   // Insert non-constant values.
7599   for (int I : NonConsts)
7600     Vec = CreateInsertElement(Vec, VL[I], I);
7601   // Append instructions, which are/may be part of the loop, in the end to make
7602   // it possible to hoist non-loop-based instructions.
7603   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7604     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7605 
7606   return Vec;
7607 }
7608 
7609 namespace {
7610 /// Merges shuffle masks and emits final shuffle instruction, if required.
7611 class ShuffleInstructionBuilder {
7612   IRBuilderBase &Builder;
7613   const unsigned VF = 0;
7614   bool IsFinalized = false;
7615   SmallVector<int, 4> Mask;
7616   /// Holds all of the instructions that we gathered.
7617   SetVector<Instruction *> &GatherShuffleSeq;
7618   /// A list of blocks that we are going to CSE.
7619   SetVector<BasicBlock *> &CSEBlocks;
7620 
7621 public:
7622   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7623                             SetVector<Instruction *> &GatherShuffleSeq,
7624                             SetVector<BasicBlock *> &CSEBlocks)
7625       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7626         CSEBlocks(CSEBlocks) {}
7627 
7628   /// Adds a mask, inverting it before applying.
7629   void addInversedMask(ArrayRef<unsigned> SubMask) {
7630     if (SubMask.empty())
7631       return;
7632     SmallVector<int, 4> NewMask;
7633     inversePermutation(SubMask, NewMask);
7634     addMask(NewMask);
7635   }
7636 
7637   /// Functions adds masks, merging them into  single one.
7638   void addMask(ArrayRef<unsigned> SubMask) {
7639     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7640     addMask(NewMask);
7641   }
7642 
7643   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7644 
7645   Value *finalize(Value *V) {
7646     IsFinalized = true;
7647     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7648     if (VF == ValueVF && Mask.empty())
7649       return V;
7650     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7651     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7652     addMask(NormalizedMask);
7653 
7654     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7655       return V;
7656     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7657     if (auto *I = dyn_cast<Instruction>(Vec)) {
7658       GatherShuffleSeq.insert(I);
7659       CSEBlocks.insert(I->getParent());
7660     }
7661     return Vec;
7662   }
7663 
7664   ~ShuffleInstructionBuilder() {
7665     assert((IsFinalized || Mask.empty()) &&
7666            "Shuffle construction must be finalized.");
7667   }
7668 };
7669 } // namespace
7670 
7671 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7672   const unsigned VF = VL.size();
7673   InstructionsState S = getSameOpcode(VL);
7674   // Special processing for GEPs bundle, which may include non-gep values.
7675   if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) {
7676     const auto *It =
7677         find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
7678     if (It != VL.end())
7679       S = getSameOpcode(*It);
7680   }
7681   if (S.getOpcode()) {
7682     if (TreeEntry *E = getTreeEntry(S.OpValue))
7683       if (E->isSame(VL)) {
7684         Value *V = vectorizeTree(E);
7685         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7686           if (!E->ReuseShuffleIndices.empty()) {
7687             // Reshuffle to get only unique values.
7688             // If some of the scalars are duplicated in the vectorization tree
7689             // entry, we do not vectorize them but instead generate a mask for
7690             // the reuses. But if there are several users of the same entry,
7691             // they may have different vectorization factors. This is especially
7692             // important for PHI nodes. In this case, we need to adapt the
7693             // resulting instruction for the user vectorization factor and have
7694             // to reshuffle it again to take only unique elements of the vector.
7695             // Without this code the function incorrectly returns reduced vector
7696             // instruction with the same elements, not with the unique ones.
7697 
7698             // block:
7699             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7700             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7701             // ... (use %2)
7702             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7703             // br %block
7704             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7705             SmallSet<int, 4> UsedIdxs;
7706             int Pos = 0;
7707             int Sz = VL.size();
7708             for (int Idx : E->ReuseShuffleIndices) {
7709               if (Idx != Sz && Idx != UndefMaskElem &&
7710                   UsedIdxs.insert(Idx).second)
7711                 UniqueIdxs[Idx] = Pos;
7712               ++Pos;
7713             }
7714             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7715                                             "less than original vector size.");
7716             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7717             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7718           } else {
7719             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7720                    "Expected vectorization factor less "
7721                    "than original vector size.");
7722             SmallVector<int> UniformMask(VF, 0);
7723             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7724             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7725           }
7726           if (auto *I = dyn_cast<Instruction>(V)) {
7727             GatherShuffleSeq.insert(I);
7728             CSEBlocks.insert(I->getParent());
7729           }
7730         }
7731         return V;
7732       }
7733   }
7734 
7735   // Can't vectorize this, so simply build a new vector with each lane
7736   // corresponding to the requested value.
7737   return createBuildVector(VL);
7738 }
7739 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7740   assert(any_of(VectorizableTree,
7741                 [VL](const std::unique_ptr<TreeEntry> &TE) {
7742                   return TE->State == TreeEntry::NeedToGather && TE->isSame(VL);
7743                 }) &&
7744          "Non-matching gather node.");
7745   unsigned VF = VL.size();
7746   // Exploit possible reuse of values across lanes.
7747   SmallVector<int> ReuseShuffleIndicies;
7748   SmallVector<Value *> UniqueValues;
7749   if (VL.size() > 2) {
7750     DenseMap<Value *, unsigned> UniquePositions;
7751     unsigned NumValues =
7752         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7753                                     return !isa<UndefValue>(V);
7754                                   }).base());
7755     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7756     int UniqueVals = 0;
7757     for (Value *V : VL.drop_back(VL.size() - VF)) {
7758       if (isa<UndefValue>(V)) {
7759         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7760         continue;
7761       }
7762       if (isConstant(V)) {
7763         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7764         UniqueValues.emplace_back(V);
7765         continue;
7766       }
7767       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7768       ReuseShuffleIndicies.emplace_back(Res.first->second);
7769       if (Res.second) {
7770         UniqueValues.emplace_back(V);
7771         ++UniqueVals;
7772       }
7773     }
7774     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7775       // Emit pure splat vector.
7776       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7777                                   UndefMaskElem);
7778     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7779       if (UniqueValues.empty()) {
7780         assert(all_of(VL, UndefValue::classof) && "Expected list of undefs.");
7781         NumValues = VF;
7782       }
7783       ReuseShuffleIndicies.clear();
7784       UniqueValues.clear();
7785       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7786     }
7787     UniqueValues.append(VF - UniqueValues.size(),
7788                         PoisonValue::get(VL[0]->getType()));
7789     VL = UniqueValues;
7790   }
7791 
7792   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7793                                            CSEBlocks);
7794   Value *Vec = gather(VL);
7795   if (!ReuseShuffleIndicies.empty()) {
7796     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7797     Vec = ShuffleBuilder.finalize(Vec);
7798   }
7799   return Vec;
7800 }
7801 
7802 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7803   IRBuilder<>::InsertPointGuard Guard(Builder);
7804 
7805   if (E->VectorizedValue) {
7806     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7807     return E->VectorizedValue;
7808   }
7809 
7810   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7811   unsigned VF = E->getVectorFactor();
7812   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7813                                            CSEBlocks);
7814   if (E->State == TreeEntry::NeedToGather) {
7815     if (E->getMainOp())
7816       setInsertPointAfterBundle(E);
7817     Value *Vec;
7818     SmallVector<int> Mask;
7819     SmallVector<const TreeEntry *> Entries;
7820     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7821         isGatherShuffledEntry(E, Mask, Entries);
7822     if (Shuffle) {
7823       assert((Entries.size() == 1 || Entries.size() == 2) &&
7824              "Expected shuffle of 1 or 2 entries.");
7825       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7826                                         Entries.back()->VectorizedValue, Mask);
7827       if (auto *I = dyn_cast<Instruction>(Vec)) {
7828         GatherShuffleSeq.insert(I);
7829         CSEBlocks.insert(I->getParent());
7830       }
7831     } else {
7832       Vec = gather(E->Scalars);
7833     }
7834     if (NeedToShuffleReuses) {
7835       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7836       Vec = ShuffleBuilder.finalize(Vec);
7837     }
7838     E->VectorizedValue = Vec;
7839     return Vec;
7840   }
7841 
7842   assert((E->State == TreeEntry::Vectorize ||
7843           E->State == TreeEntry::ScatterVectorize) &&
7844          "Unhandled state");
7845   unsigned ShuffleOrOp =
7846       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7847   Instruction *VL0 = E->getMainOp();
7848   Type *ScalarTy = VL0->getType();
7849   if (auto *Store = dyn_cast<StoreInst>(VL0))
7850     ScalarTy = Store->getValueOperand()->getType();
7851   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7852     ScalarTy = IE->getOperand(1)->getType();
7853   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7854   switch (ShuffleOrOp) {
7855     case Instruction::PHI: {
7856       assert(
7857           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7858           "PHI reordering is free.");
7859       auto *PH = cast<PHINode>(VL0);
7860       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7861       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7862       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7863       Value *V = NewPhi;
7864 
7865       // Adjust insertion point once all PHI's have been generated.
7866       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7867       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7868 
7869       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7870       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7871       V = ShuffleBuilder.finalize(V);
7872 
7873       E->VectorizedValue = V;
7874 
7875       // PHINodes may have multiple entries from the same block. We want to
7876       // visit every block once.
7877       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7878 
7879       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7880         ValueList Operands;
7881         BasicBlock *IBB = PH->getIncomingBlock(i);
7882 
7883         if (!VisitedBBs.insert(IBB).second) {
7884           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7885           continue;
7886         }
7887 
7888         Builder.SetInsertPoint(IBB->getTerminator());
7889         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7890         Value *Vec = vectorizeTree(E->getOperand(i));
7891         NewPhi->addIncoming(Vec, IBB);
7892       }
7893 
7894       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7895              "Invalid number of incoming values");
7896       return V;
7897     }
7898 
7899     case Instruction::ExtractElement: {
7900       Value *V = E->getSingleOperand(0);
7901       Builder.SetInsertPoint(VL0);
7902       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7903       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7904       V = ShuffleBuilder.finalize(V);
7905       E->VectorizedValue = V;
7906       return V;
7907     }
7908     case Instruction::ExtractValue: {
7909       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7910       Builder.SetInsertPoint(LI);
7911       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7912       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7913       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7914       Value *NewV = propagateMetadata(V, E->Scalars);
7915       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7916       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7917       NewV = ShuffleBuilder.finalize(NewV);
7918       E->VectorizedValue = NewV;
7919       return NewV;
7920     }
7921     case Instruction::InsertElement: {
7922       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7923       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7924       Value *V = vectorizeTree(E->getOperand(1));
7925 
7926       // Create InsertVector shuffle if necessary
7927       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7928         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7929       }));
7930       const unsigned NumElts =
7931           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7932       const unsigned NumScalars = E->Scalars.size();
7933 
7934       unsigned Offset = *getInsertIndex(VL0);
7935       assert(Offset < NumElts && "Failed to find vector index offset");
7936 
7937       // Create shuffle to resize vector
7938       SmallVector<int> Mask;
7939       if (!E->ReorderIndices.empty()) {
7940         inversePermutation(E->ReorderIndices, Mask);
7941         Mask.append(NumElts - NumScalars, UndefMaskElem);
7942       } else {
7943         Mask.assign(NumElts, UndefMaskElem);
7944         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7945       }
7946       // Create InsertVector shuffle if necessary
7947       bool IsIdentity = true;
7948       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7949       Mask.swap(PrevMask);
7950       for (unsigned I = 0; I < NumScalars; ++I) {
7951         Value *Scalar = E->Scalars[PrevMask[I]];
7952         unsigned InsertIdx = *getInsertIndex(Scalar);
7953         IsIdentity &= InsertIdx - Offset == I;
7954         Mask[InsertIdx - Offset] = I;
7955       }
7956       if (!IsIdentity || NumElts != NumScalars) {
7957         V = Builder.CreateShuffleVector(V, Mask);
7958         if (auto *I = dyn_cast<Instruction>(V)) {
7959           GatherShuffleSeq.insert(I);
7960           CSEBlocks.insert(I->getParent());
7961         }
7962       }
7963 
7964       if ((!IsIdentity || Offset != 0 ||
7965            !isUndefVector(FirstInsert->getOperand(0))) &&
7966           NumElts != NumScalars) {
7967         SmallVector<int> InsertMask(NumElts);
7968         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7969         for (unsigned I = 0; I < NumElts; I++) {
7970           if (Mask[I] != UndefMaskElem)
7971             InsertMask[Offset + I] = NumElts + I;
7972         }
7973 
7974         V = Builder.CreateShuffleVector(
7975             FirstInsert->getOperand(0), V, InsertMask,
7976             cast<Instruction>(E->Scalars.back())->getName());
7977         if (auto *I = dyn_cast<Instruction>(V)) {
7978           GatherShuffleSeq.insert(I);
7979           CSEBlocks.insert(I->getParent());
7980         }
7981       }
7982 
7983       ++NumVectorInstructions;
7984       E->VectorizedValue = V;
7985       return V;
7986     }
7987     case Instruction::ZExt:
7988     case Instruction::SExt:
7989     case Instruction::FPToUI:
7990     case Instruction::FPToSI:
7991     case Instruction::FPExt:
7992     case Instruction::PtrToInt:
7993     case Instruction::IntToPtr:
7994     case Instruction::SIToFP:
7995     case Instruction::UIToFP:
7996     case Instruction::Trunc:
7997     case Instruction::FPTrunc:
7998     case Instruction::BitCast: {
7999       setInsertPointAfterBundle(E);
8000 
8001       Value *InVec = vectorizeTree(E->getOperand(0));
8002 
8003       if (E->VectorizedValue) {
8004         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8005         return E->VectorizedValue;
8006       }
8007 
8008       auto *CI = cast<CastInst>(VL0);
8009       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
8010       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8011       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8012       V = ShuffleBuilder.finalize(V);
8013 
8014       E->VectorizedValue = V;
8015       ++NumVectorInstructions;
8016       return V;
8017     }
8018     case Instruction::FCmp:
8019     case Instruction::ICmp: {
8020       setInsertPointAfterBundle(E);
8021 
8022       Value *L = vectorizeTree(E->getOperand(0));
8023       Value *R = vectorizeTree(E->getOperand(1));
8024 
8025       if (E->VectorizedValue) {
8026         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8027         return E->VectorizedValue;
8028       }
8029 
8030       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
8031       Value *V = Builder.CreateCmp(P0, L, R);
8032       propagateIRFlags(V, E->Scalars, VL0);
8033       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8034       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8035       V = ShuffleBuilder.finalize(V);
8036 
8037       E->VectorizedValue = V;
8038       ++NumVectorInstructions;
8039       return V;
8040     }
8041     case Instruction::Select: {
8042       setInsertPointAfterBundle(E);
8043 
8044       Value *Cond = vectorizeTree(E->getOperand(0));
8045       Value *True = vectorizeTree(E->getOperand(1));
8046       Value *False = vectorizeTree(E->getOperand(2));
8047 
8048       if (E->VectorizedValue) {
8049         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8050         return E->VectorizedValue;
8051       }
8052 
8053       Value *V = Builder.CreateSelect(Cond, True, False);
8054       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8055       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8056       V = ShuffleBuilder.finalize(V);
8057 
8058       E->VectorizedValue = V;
8059       ++NumVectorInstructions;
8060       return V;
8061     }
8062     case Instruction::FNeg: {
8063       setInsertPointAfterBundle(E);
8064 
8065       Value *Op = vectorizeTree(E->getOperand(0));
8066 
8067       if (E->VectorizedValue) {
8068         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8069         return E->VectorizedValue;
8070       }
8071 
8072       Value *V = Builder.CreateUnOp(
8073           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
8074       propagateIRFlags(V, E->Scalars, VL0);
8075       if (auto *I = dyn_cast<Instruction>(V))
8076         V = propagateMetadata(I, E->Scalars);
8077 
8078       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8079       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8080       V = ShuffleBuilder.finalize(V);
8081 
8082       E->VectorizedValue = V;
8083       ++NumVectorInstructions;
8084 
8085       return V;
8086     }
8087     case Instruction::Add:
8088     case Instruction::FAdd:
8089     case Instruction::Sub:
8090     case Instruction::FSub:
8091     case Instruction::Mul:
8092     case Instruction::FMul:
8093     case Instruction::UDiv:
8094     case Instruction::SDiv:
8095     case Instruction::FDiv:
8096     case Instruction::URem:
8097     case Instruction::SRem:
8098     case Instruction::FRem:
8099     case Instruction::Shl:
8100     case Instruction::LShr:
8101     case Instruction::AShr:
8102     case Instruction::And:
8103     case Instruction::Or:
8104     case Instruction::Xor: {
8105       setInsertPointAfterBundle(E);
8106 
8107       Value *LHS = vectorizeTree(E->getOperand(0));
8108       Value *RHS = vectorizeTree(E->getOperand(1));
8109 
8110       if (E->VectorizedValue) {
8111         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8112         return E->VectorizedValue;
8113       }
8114 
8115       Value *V = Builder.CreateBinOp(
8116           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
8117           RHS);
8118       propagateIRFlags(V, E->Scalars, VL0);
8119       if (auto *I = dyn_cast<Instruction>(V))
8120         V = propagateMetadata(I, E->Scalars);
8121 
8122       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8123       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8124       V = ShuffleBuilder.finalize(V);
8125 
8126       E->VectorizedValue = V;
8127       ++NumVectorInstructions;
8128 
8129       return V;
8130     }
8131     case Instruction::Load: {
8132       // Loads are inserted at the head of the tree because we don't want to
8133       // sink them all the way down past store instructions.
8134       setInsertPointAfterBundle(E);
8135 
8136       LoadInst *LI = cast<LoadInst>(VL0);
8137       Instruction *NewLI;
8138       unsigned AS = LI->getPointerAddressSpace();
8139       Value *PO = LI->getPointerOperand();
8140       if (E->State == TreeEntry::Vectorize) {
8141         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
8142         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
8143 
8144         // The pointer operand uses an in-tree scalar so we add the new BitCast
8145         // or LoadInst to ExternalUses list to make sure that an extract will
8146         // be generated in the future.
8147         if (TreeEntry *Entry = getTreeEntry(PO)) {
8148           // Find which lane we need to extract.
8149           unsigned FoundLane = Entry->findLaneForValue(PO);
8150           ExternalUses.emplace_back(
8151               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
8152         }
8153       } else {
8154         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
8155         Value *VecPtr = vectorizeTree(E->getOperand(0));
8156         // Use the minimum alignment of the gathered loads.
8157         Align CommonAlignment = LI->getAlign();
8158         for (Value *V : E->Scalars)
8159           CommonAlignment =
8160               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
8161         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
8162       }
8163       Value *V = propagateMetadata(NewLI, E->Scalars);
8164 
8165       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8166       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8167       V = ShuffleBuilder.finalize(V);
8168       E->VectorizedValue = V;
8169       ++NumVectorInstructions;
8170       return V;
8171     }
8172     case Instruction::Store: {
8173       auto *SI = cast<StoreInst>(VL0);
8174       unsigned AS = SI->getPointerAddressSpace();
8175 
8176       setInsertPointAfterBundle(E);
8177 
8178       Value *VecValue = vectorizeTree(E->getOperand(0));
8179       ShuffleBuilder.addMask(E->ReorderIndices);
8180       VecValue = ShuffleBuilder.finalize(VecValue);
8181 
8182       Value *ScalarPtr = SI->getPointerOperand();
8183       Value *VecPtr = Builder.CreateBitCast(
8184           ScalarPtr, VecValue->getType()->getPointerTo(AS));
8185       StoreInst *ST =
8186           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
8187 
8188       // The pointer operand uses an in-tree scalar, so add the new BitCast or
8189       // StoreInst to ExternalUses to make sure that an extract will be
8190       // generated in the future.
8191       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
8192         // Find which lane we need to extract.
8193         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
8194         ExternalUses.push_back(ExternalUser(
8195             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
8196             FoundLane));
8197       }
8198 
8199       Value *V = propagateMetadata(ST, E->Scalars);
8200 
8201       E->VectorizedValue = V;
8202       ++NumVectorInstructions;
8203       return V;
8204     }
8205     case Instruction::GetElementPtr: {
8206       auto *GEP0 = cast<GetElementPtrInst>(VL0);
8207       setInsertPointAfterBundle(E);
8208 
8209       Value *Op0 = vectorizeTree(E->getOperand(0));
8210 
8211       SmallVector<Value *> OpVecs;
8212       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
8213         Value *OpVec = vectorizeTree(E->getOperand(J));
8214         OpVecs.push_back(OpVec);
8215       }
8216 
8217       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
8218       if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) {
8219         SmallVector<Value *> GEPs;
8220         for (Value *V : E->Scalars) {
8221           if (isa<GetElementPtrInst>(V))
8222             GEPs.push_back(V);
8223         }
8224         V = propagateMetadata(I, GEPs);
8225       }
8226 
8227       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8228       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8229       V = ShuffleBuilder.finalize(V);
8230 
8231       E->VectorizedValue = V;
8232       ++NumVectorInstructions;
8233 
8234       return V;
8235     }
8236     case Instruction::Call: {
8237       CallInst *CI = cast<CallInst>(VL0);
8238       setInsertPointAfterBundle(E);
8239 
8240       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
8241       if (Function *FI = CI->getCalledFunction())
8242         IID = FI->getIntrinsicID();
8243 
8244       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8245 
8246       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
8247       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
8248                           VecCallCosts.first <= VecCallCosts.second;
8249 
8250       Value *ScalarArg = nullptr;
8251       std::vector<Value *> OpVecs;
8252       SmallVector<Type *, 2> TysForDecl =
8253           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
8254       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
8255         ValueList OpVL;
8256         // Some intrinsics have scalar arguments. This argument should not be
8257         // vectorized.
8258         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
8259           CallInst *CEI = cast<CallInst>(VL0);
8260           ScalarArg = CEI->getArgOperand(j);
8261           OpVecs.push_back(CEI->getArgOperand(j));
8262           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
8263             TysForDecl.push_back(ScalarArg->getType());
8264           continue;
8265         }
8266 
8267         Value *OpVec = vectorizeTree(E->getOperand(j));
8268         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
8269         OpVecs.push_back(OpVec);
8270         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
8271           TysForDecl.push_back(OpVec->getType());
8272       }
8273 
8274       Function *CF;
8275       if (!UseIntrinsic) {
8276         VFShape Shape =
8277             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
8278                                   VecTy->getNumElements())),
8279                          false /*HasGlobalPred*/);
8280         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
8281       } else {
8282         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
8283       }
8284 
8285       SmallVector<OperandBundleDef, 1> OpBundles;
8286       CI->getOperandBundlesAsDefs(OpBundles);
8287       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
8288 
8289       // The scalar argument uses an in-tree scalar so we add the new vectorized
8290       // call to ExternalUses list to make sure that an extract will be
8291       // generated in the future.
8292       if (ScalarArg) {
8293         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
8294           // Find which lane we need to extract.
8295           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
8296           ExternalUses.push_back(
8297               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
8298         }
8299       }
8300 
8301       propagateIRFlags(V, E->Scalars, VL0);
8302       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8303       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8304       V = ShuffleBuilder.finalize(V);
8305 
8306       E->VectorizedValue = V;
8307       ++NumVectorInstructions;
8308       return V;
8309     }
8310     case Instruction::ShuffleVector: {
8311       assert(E->isAltShuffle() &&
8312              ((Instruction::isBinaryOp(E->getOpcode()) &&
8313                Instruction::isBinaryOp(E->getAltOpcode())) ||
8314               (Instruction::isCast(E->getOpcode()) &&
8315                Instruction::isCast(E->getAltOpcode())) ||
8316               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
8317              "Invalid Shuffle Vector Operand");
8318 
8319       Value *LHS = nullptr, *RHS = nullptr;
8320       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
8321         setInsertPointAfterBundle(E);
8322         LHS = vectorizeTree(E->getOperand(0));
8323         RHS = vectorizeTree(E->getOperand(1));
8324       } else {
8325         setInsertPointAfterBundle(E);
8326         LHS = vectorizeTree(E->getOperand(0));
8327       }
8328 
8329       if (E->VectorizedValue) {
8330         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8331         return E->VectorizedValue;
8332       }
8333 
8334       Value *V0, *V1;
8335       if (Instruction::isBinaryOp(E->getOpcode())) {
8336         V0 = Builder.CreateBinOp(
8337             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
8338         V1 = Builder.CreateBinOp(
8339             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
8340       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
8341         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
8342         auto *AltCI = cast<CmpInst>(E->getAltOp());
8343         CmpInst::Predicate AltPred = AltCI->getPredicate();
8344         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
8345       } else {
8346         V0 = Builder.CreateCast(
8347             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
8348         V1 = Builder.CreateCast(
8349             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
8350       }
8351       // Add V0 and V1 to later analysis to try to find and remove matching
8352       // instruction, if any.
8353       for (Value *V : {V0, V1}) {
8354         if (auto *I = dyn_cast<Instruction>(V)) {
8355           GatherShuffleSeq.insert(I);
8356           CSEBlocks.insert(I->getParent());
8357         }
8358       }
8359 
8360       // Create shuffle to take alternate operations from the vector.
8361       // Also, gather up main and alt scalar ops to propagate IR flags to
8362       // each vector operation.
8363       ValueList OpScalars, AltScalars;
8364       SmallVector<int> Mask;
8365       buildShuffleEntryMask(
8366           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8367           [E](Instruction *I) {
8368             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8369             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8370           },
8371           Mask, &OpScalars, &AltScalars);
8372 
8373       propagateIRFlags(V0, OpScalars);
8374       propagateIRFlags(V1, AltScalars);
8375 
8376       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8377       if (auto *I = dyn_cast<Instruction>(V)) {
8378         V = propagateMetadata(I, E->Scalars);
8379         GatherShuffleSeq.insert(I);
8380         CSEBlocks.insert(I->getParent());
8381       }
8382       V = ShuffleBuilder.finalize(V);
8383 
8384       E->VectorizedValue = V;
8385       ++NumVectorInstructions;
8386 
8387       return V;
8388     }
8389     default:
8390     llvm_unreachable("unknown inst");
8391   }
8392   return nullptr;
8393 }
8394 
8395 Value *BoUpSLP::vectorizeTree() {
8396   ExtraValueToDebugLocsMap ExternallyUsedValues;
8397   return vectorizeTree(ExternallyUsedValues);
8398 }
8399 
8400 namespace {
8401 /// Data type for handling buildvector sequences with the reused scalars from
8402 /// other tree entries.
8403 struct ShuffledInsertData {
8404   /// List of insertelements to be replaced by shuffles.
8405   SmallVector<InsertElementInst *> InsertElements;
8406   /// The parent vectors and shuffle mask for the given list of inserts.
8407   MapVector<Value *, SmallVector<int>> ValueMasks;
8408 };
8409 } // namespace
8410 
8411 Value *
8412 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8413   // All blocks must be scheduled before any instructions are inserted.
8414   for (auto &BSIter : BlocksSchedules) {
8415     scheduleBlock(BSIter.second.get());
8416   }
8417 
8418   Builder.SetInsertPoint(&F->getEntryBlock().front());
8419   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8420 
8421   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8422   // vectorized root. InstCombine will then rewrite the entire expression. We
8423   // sign extend the extracted values below.
8424   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8425   if (MinBWs.count(ScalarRoot)) {
8426     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8427       // If current instr is a phi and not the last phi, insert it after the
8428       // last phi node.
8429       if (isa<PHINode>(I))
8430         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8431       else
8432         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8433     }
8434     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8435     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8436     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8437     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8438     VectorizableTree[0]->VectorizedValue = Trunc;
8439   }
8440 
8441   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8442                     << " values .\n");
8443 
8444   SmallVector<ShuffledInsertData> ShuffledInserts;
8445   // Maps vector instruction to original insertelement instruction
8446   DenseMap<Value *, InsertElementInst *> VectorToInsertElement;
8447   // Extract all of the elements with the external uses.
8448   for (const auto &ExternalUse : ExternalUses) {
8449     Value *Scalar = ExternalUse.Scalar;
8450     llvm::User *User = ExternalUse.User;
8451 
8452     // Skip users that we already RAUW. This happens when one instruction
8453     // has multiple uses of the same value.
8454     if (User && !is_contained(Scalar->users(), User))
8455       continue;
8456     TreeEntry *E = getTreeEntry(Scalar);
8457     assert(E && "Invalid scalar");
8458     assert(E->State != TreeEntry::NeedToGather &&
8459            "Extracting from a gather list");
8460     // Non-instruction pointers are not deleted, just skip them.
8461     if (E->getOpcode() == Instruction::GetElementPtr &&
8462         !isa<GetElementPtrInst>(Scalar))
8463       continue;
8464 
8465     Value *Vec = E->VectorizedValue;
8466     assert(Vec && "Can't find vectorizable value");
8467 
8468     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8469     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8470       if (Scalar->getType() != Vec->getType()) {
8471         Value *Ex;
8472         // "Reuse" the existing extract to improve final codegen.
8473         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8474           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8475                                             ES->getOperand(1));
8476         } else {
8477           Ex = Builder.CreateExtractElement(Vec, Lane);
8478         }
8479         // If necessary, sign-extend or zero-extend ScalarRoot
8480         // to the larger type.
8481         if (!MinBWs.count(ScalarRoot))
8482           return Ex;
8483         if (MinBWs[ScalarRoot].second)
8484           return Builder.CreateSExt(Ex, Scalar->getType());
8485         return Builder.CreateZExt(Ex, Scalar->getType());
8486       }
8487       assert(isa<FixedVectorType>(Scalar->getType()) &&
8488              isa<InsertElementInst>(Scalar) &&
8489              "In-tree scalar of vector type is not insertelement?");
8490       auto *IE = cast<InsertElementInst>(Scalar);
8491       VectorToInsertElement.try_emplace(Vec, IE);
8492       return Vec;
8493     };
8494     // If User == nullptr, the Scalar is used as extra arg. Generate
8495     // ExtractElement instruction and update the record for this scalar in
8496     // ExternallyUsedValues.
8497     if (!User) {
8498       assert(ExternallyUsedValues.count(Scalar) &&
8499              "Scalar with nullptr as an external user must be registered in "
8500              "ExternallyUsedValues map");
8501       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8502         Builder.SetInsertPoint(VecI->getParent(),
8503                                std::next(VecI->getIterator()));
8504       } else {
8505         Builder.SetInsertPoint(&F->getEntryBlock().front());
8506       }
8507       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8508       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8509       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8510       auto It = ExternallyUsedValues.find(Scalar);
8511       assert(It != ExternallyUsedValues.end() &&
8512              "Externally used scalar is not found in ExternallyUsedValues");
8513       NewInstLocs.append(It->second);
8514       ExternallyUsedValues.erase(Scalar);
8515       // Required to update internally referenced instructions.
8516       Scalar->replaceAllUsesWith(NewInst);
8517       continue;
8518     }
8519 
8520     if (auto *VU = dyn_cast<InsertElementInst>(User)) {
8521       // Skip if the scalar is another vector op or Vec is not an instruction.
8522       if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) {
8523         if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) {
8524           Optional<unsigned> InsertIdx = getInsertIndex(VU);
8525           if (InsertIdx) {
8526             // Need to use original vector, if the root is truncated.
8527             if (MinBWs.count(Scalar) &&
8528                 VectorizableTree[0]->VectorizedValue == Vec)
8529               Vec = VectorRoot;
8530             auto *It =
8531                 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) {
8532                   // Checks if 2 insertelements are from the same buildvector.
8533                   InsertElementInst *VecInsert = Data.InsertElements.front();
8534                   return areTwoInsertFromSameBuildVector(VU, VecInsert);
8535                 });
8536             unsigned Idx = *InsertIdx;
8537             if (It == ShuffledInserts.end()) {
8538               (void)ShuffledInserts.emplace_back();
8539               It = std::next(ShuffledInserts.begin(),
8540                              ShuffledInserts.size() - 1);
8541               SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8542               if (Mask.empty())
8543                 Mask.assign(FTy->getNumElements(), UndefMaskElem);
8544               // Find the insertvector, vectorized in tree, if any.
8545               Value *Base = VU;
8546               while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
8547                 if (IEBase != User &&
8548                     (!IEBase->hasOneUse() ||
8549                      getInsertIndex(IEBase).value_or(Idx) == Idx))
8550                   break;
8551                 // Build the mask for the vectorized insertelement instructions.
8552                 if (const TreeEntry *E = getTreeEntry(IEBase)) {
8553                   do {
8554                     IEBase = cast<InsertElementInst>(Base);
8555                     int IEIdx = *getInsertIndex(IEBase);
8556                     assert(Mask[Idx] == UndefMaskElem &&
8557                            "InsertElementInstruction used already.");
8558                     Mask[IEIdx] = IEIdx;
8559                     Base = IEBase->getOperand(0);
8560                   } while (E == getTreeEntry(Base));
8561                   break;
8562                 }
8563                 Base = cast<InsertElementInst>(Base)->getOperand(0);
8564                 // After the vectorization the def-use chain has changed, need
8565                 // to look through original insertelement instructions, if they
8566                 // get replaced by vector instructions.
8567                 auto It = VectorToInsertElement.find(Base);
8568                 if (It != VectorToInsertElement.end())
8569                   Base = It->second;
8570               }
8571             }
8572             SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8573             if (Mask.empty())
8574               Mask.assign(FTy->getNumElements(), UndefMaskElem);
8575             Mask[Idx] = ExternalUse.Lane;
8576             It->InsertElements.push_back(cast<InsertElementInst>(User));
8577             continue;
8578           }
8579         }
8580       }
8581     }
8582 
8583     // Generate extracts for out-of-tree users.
8584     // Find the insertion point for the extractelement lane.
8585     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8586       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8587         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8588           if (PH->getIncomingValue(i) == Scalar) {
8589             Instruction *IncomingTerminator =
8590                 PH->getIncomingBlock(i)->getTerminator();
8591             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8592               Builder.SetInsertPoint(VecI->getParent(),
8593                                      std::next(VecI->getIterator()));
8594             } else {
8595               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8596             }
8597             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8598             CSEBlocks.insert(PH->getIncomingBlock(i));
8599             PH->setOperand(i, NewInst);
8600           }
8601         }
8602       } else {
8603         Builder.SetInsertPoint(cast<Instruction>(User));
8604         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8605         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8606         User->replaceUsesOfWith(Scalar, NewInst);
8607       }
8608     } else {
8609       Builder.SetInsertPoint(&F->getEntryBlock().front());
8610       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8611       CSEBlocks.insert(&F->getEntryBlock());
8612       User->replaceUsesOfWith(Scalar, NewInst);
8613     }
8614 
8615     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8616   }
8617 
8618   // Checks if the mask is an identity mask.
8619   auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) {
8620     int Limit = Mask.size();
8621     return VecTy->getNumElements() == Mask.size() &&
8622            all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
8623            ShuffleVectorInst::isIdentityMask(Mask);
8624   };
8625   // Tries to combine 2 different masks into single one.
8626   auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) {
8627     SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem);
8628     for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
8629       if (ExtMask[I] == UndefMaskElem)
8630         continue;
8631       NewMask[I] = Mask[ExtMask[I]];
8632     }
8633     Mask.swap(NewMask);
8634   };
8635   // Peek through shuffles, trying to simplify the final shuffle code.
8636   auto &&PeekThroughShuffles =
8637       [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask,
8638                                        bool CheckForLengthChange = false) {
8639         while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
8640           // Exit if not a fixed vector type or changing size shuffle.
8641           if (!isa<FixedVectorType>(SV->getType()) ||
8642               (CheckForLengthChange && SV->changesLength()))
8643             break;
8644           // Exit if the identity or broadcast mask is found.
8645           if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) ||
8646               SV->isZeroEltSplat())
8647             break;
8648           bool IsOp1Undef = isUndefVector(SV->getOperand(0));
8649           bool IsOp2Undef = isUndefVector(SV->getOperand(1));
8650           if (!IsOp1Undef && !IsOp2Undef)
8651             break;
8652           SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(),
8653                                        SV->getShuffleMask().end());
8654           CombineMasks(ShuffleMask, Mask);
8655           Mask.swap(ShuffleMask);
8656           if (IsOp2Undef)
8657             V = SV->getOperand(0);
8658           else
8659             V = SV->getOperand(1);
8660         }
8661       };
8662   // Smart shuffle instruction emission, walks through shuffles trees and
8663   // tries to find the best matching vector for the actual shuffle
8664   // instruction.
8665   auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles,
8666                           &CombineMasks](Value *V1, Value *V2,
8667                                          ArrayRef<int> Mask) -> Value * {
8668     assert(V1 && "Expected at least one vector value.");
8669     if (V2 && !isUndefVector(V2)) {
8670       // Peek through shuffles.
8671       Value *Op1 = V1;
8672       Value *Op2 = V2;
8673       int VF =
8674           cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
8675       SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem);
8676       SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem);
8677       for (int I = 0, E = Mask.size(); I < E; ++I) {
8678         if (Mask[I] < VF)
8679           CombinedMask1[I] = Mask[I];
8680         else
8681           CombinedMask2[I] = Mask[I] - VF;
8682       }
8683       Value *PrevOp1;
8684       Value *PrevOp2;
8685       do {
8686         PrevOp1 = Op1;
8687         PrevOp2 = Op2;
8688         PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true);
8689         PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true);
8690         // Check if we have 2 resizing shuffles - need to peek through operands
8691         // again.
8692         if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1))
8693           if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2))
8694             if (SV1->getOperand(0)->getType() ==
8695                     SV2->getOperand(0)->getType() &&
8696                 SV1->getOperand(0)->getType() != SV1->getType() &&
8697                 isUndefVector(SV1->getOperand(1)) &&
8698                 isUndefVector(SV2->getOperand(1))) {
8699               Op1 = SV1->getOperand(0);
8700               Op2 = SV2->getOperand(0);
8701               SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(),
8702                                             SV1->getShuffleMask().end());
8703               CombineMasks(ShuffleMask1, CombinedMask1);
8704               CombinedMask1.swap(ShuffleMask1);
8705               SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(),
8706                                             SV2->getShuffleMask().end());
8707               CombineMasks(ShuffleMask2, CombinedMask2);
8708               CombinedMask2.swap(ShuffleMask2);
8709             }
8710       } while (PrevOp1 != Op1 || PrevOp2 != Op2);
8711       VF = cast<VectorType>(Op1->getType())
8712                ->getElementCount()
8713                .getKnownMinValue();
8714       for (int I = 0, E = Mask.size(); I < E; ++I) {
8715         if (CombinedMask2[I] != UndefMaskElem) {
8716           assert(CombinedMask1[I] == UndefMaskElem &&
8717                  "Expected undefined mask element");
8718           CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF);
8719         }
8720       }
8721       Value *Vec = Builder.CreateShuffleVector(
8722           Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2,
8723           CombinedMask1);
8724       if (auto *I = dyn_cast<Instruction>(Vec)) {
8725         GatherShuffleSeq.insert(I);
8726         CSEBlocks.insert(I->getParent());
8727       }
8728       return Vec;
8729     }
8730     if (isa<PoisonValue>(V1))
8731       return PoisonValue::get(FixedVectorType::get(
8732           cast<VectorType>(V1->getType())->getElementType(), Mask.size()));
8733     Value *Op = V1;
8734     SmallVector<int> CombinedMask(Mask.begin(), Mask.end());
8735     PeekThroughShuffles(Op, CombinedMask);
8736     if (!isa<FixedVectorType>(Op->getType()) ||
8737         !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) {
8738       Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask);
8739       if (auto *I = dyn_cast<Instruction>(Vec)) {
8740         GatherShuffleSeq.insert(I);
8741         CSEBlocks.insert(I->getParent());
8742       }
8743       return Vec;
8744     }
8745     return Op;
8746   };
8747 
8748   auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) {
8749     unsigned VF = Mask.size();
8750     unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
8751     if (VF != VecVF) {
8752       if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) {
8753         Vec = CreateShuffle(Vec, nullptr, Mask);
8754         return std::make_pair(Vec, true);
8755       }
8756       SmallVector<int> ResizeMask(VF, UndefMaskElem);
8757       for (unsigned I = 0; I < VF; ++I) {
8758         if (Mask[I] != UndefMaskElem)
8759           ResizeMask[Mask[I]] = Mask[I];
8760       }
8761       Vec = CreateShuffle(Vec, nullptr, ResizeMask);
8762     }
8763 
8764     return std::make_pair(Vec, false);
8765   };
8766   // Perform shuffling of the vectorize tree entries for better handling of
8767   // external extracts.
8768   for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
8769     // Find the first and the last instruction in the list of insertelements.
8770     sort(ShuffledInserts[I].InsertElements, isFirstInsertElement);
8771     InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front();
8772     InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back();
8773     Builder.SetInsertPoint(LastInsert);
8774     auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
8775     Value *NewInst = performExtractsShuffleAction<Value>(
8776         makeMutableArrayRef(Vector.data(), Vector.size()),
8777         FirstInsert->getOperand(0),
8778         [](Value *Vec) {
8779           return cast<VectorType>(Vec->getType())
8780               ->getElementCount()
8781               .getKnownMinValue();
8782         },
8783         ResizeToVF,
8784         [FirstInsert, &CreateShuffle](ArrayRef<int> Mask,
8785                                       ArrayRef<Value *> Vals) {
8786           assert((Vals.size() == 1 || Vals.size() == 2) &&
8787                  "Expected exactly 1 or 2 input values.");
8788           if (Vals.size() == 1) {
8789             // Do not create shuffle if the mask is a simple identity
8790             // non-resizing mask.
8791             if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType())
8792                                    ->getNumElements() ||
8793                 !ShuffleVectorInst::isIdentityMask(Mask))
8794               return CreateShuffle(Vals.front(), nullptr, Mask);
8795             return Vals.front();
8796           }
8797           return CreateShuffle(Vals.front() ? Vals.front()
8798                                             : FirstInsert->getOperand(0),
8799                                Vals.back(), Mask);
8800         });
8801     auto It = ShuffledInserts[I].InsertElements.rbegin();
8802     // Rebuild buildvector chain.
8803     InsertElementInst *II = nullptr;
8804     if (It != ShuffledInserts[I].InsertElements.rend())
8805       II = *It;
8806     SmallVector<Instruction *> Inserts;
8807     while (It != ShuffledInserts[I].InsertElements.rend()) {
8808       assert(II && "Must be an insertelement instruction.");
8809       if (*It == II)
8810         ++It;
8811       else
8812         Inserts.push_back(cast<Instruction>(II));
8813       II = dyn_cast<InsertElementInst>(II->getOperand(0));
8814     }
8815     for (Instruction *II : reverse(Inserts)) {
8816       II->replaceUsesOfWith(II->getOperand(0), NewInst);
8817       if (auto *NewI = dyn_cast<Instruction>(NewInst))
8818         if (II->getParent() == NewI->getParent() && II->comesBefore(NewI))
8819           II->moveAfter(NewI);
8820       NewInst = II;
8821     }
8822     LastInsert->replaceAllUsesWith(NewInst);
8823     for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) {
8824       IE->replaceUsesOfWith(IE->getOperand(1),
8825                             PoisonValue::get(IE->getOperand(1)->getType()));
8826       eraseInstruction(IE);
8827     }
8828     CSEBlocks.insert(LastInsert->getParent());
8829   }
8830 
8831   // For each vectorized value:
8832   for (auto &TEPtr : VectorizableTree) {
8833     TreeEntry *Entry = TEPtr.get();
8834 
8835     // No need to handle users of gathered values.
8836     if (Entry->State == TreeEntry::NeedToGather)
8837       continue;
8838 
8839     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8840 
8841     // For each lane:
8842     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8843       Value *Scalar = Entry->Scalars[Lane];
8844 
8845       if (Entry->getOpcode() == Instruction::GetElementPtr &&
8846           !isa<GetElementPtrInst>(Scalar))
8847         continue;
8848 #ifndef NDEBUG
8849       Type *Ty = Scalar->getType();
8850       if (!Ty->isVoidTy()) {
8851         for (User *U : Scalar->users()) {
8852           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8853 
8854           // It is legal to delete users in the ignorelist.
8855           assert((getTreeEntry(U) ||
8856                   (UserIgnoreList && UserIgnoreList->contains(U)) ||
8857                   (isa_and_nonnull<Instruction>(U) &&
8858                    isDeleted(cast<Instruction>(U)))) &&
8859                  "Deleting out-of-tree value");
8860         }
8861       }
8862 #endif
8863       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8864       eraseInstruction(cast<Instruction>(Scalar));
8865     }
8866   }
8867 
8868   Builder.ClearInsertionPoint();
8869   InstrElementSize.clear();
8870 
8871   return VectorizableTree[0]->VectorizedValue;
8872 }
8873 
8874 void BoUpSLP::optimizeGatherSequence() {
8875   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8876                     << " gather sequences instructions.\n");
8877   // LICM InsertElementInst sequences.
8878   for (Instruction *I : GatherShuffleSeq) {
8879     if (isDeleted(I))
8880       continue;
8881 
8882     // Check if this block is inside a loop.
8883     Loop *L = LI->getLoopFor(I->getParent());
8884     if (!L)
8885       continue;
8886 
8887     // Check if it has a preheader.
8888     BasicBlock *PreHeader = L->getLoopPreheader();
8889     if (!PreHeader)
8890       continue;
8891 
8892     // If the vector or the element that we insert into it are
8893     // instructions that are defined in this basic block then we can't
8894     // hoist this instruction.
8895     if (any_of(I->operands(), [L](Value *V) {
8896           auto *OpI = dyn_cast<Instruction>(V);
8897           return OpI && L->contains(OpI);
8898         }))
8899       continue;
8900 
8901     // We can hoist this instruction. Move it to the pre-header.
8902     I->moveBefore(PreHeader->getTerminator());
8903   }
8904 
8905   // Make a list of all reachable blocks in our CSE queue.
8906   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8907   CSEWorkList.reserve(CSEBlocks.size());
8908   for (BasicBlock *BB : CSEBlocks)
8909     if (DomTreeNode *N = DT->getNode(BB)) {
8910       assert(DT->isReachableFromEntry(N));
8911       CSEWorkList.push_back(N);
8912     }
8913 
8914   // Sort blocks by domination. This ensures we visit a block after all blocks
8915   // dominating it are visited.
8916   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8917     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8918            "Different nodes should have different DFS numbers");
8919     return A->getDFSNumIn() < B->getDFSNumIn();
8920   });
8921 
8922   // Less defined shuffles can be replaced by the more defined copies.
8923   // Between two shuffles one is less defined if it has the same vector operands
8924   // and its mask indeces are the same as in the first one or undefs. E.g.
8925   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8926   // poison, <0, 0, 0, 0>.
8927   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8928                                            SmallVectorImpl<int> &NewMask) {
8929     if (I1->getType() != I2->getType())
8930       return false;
8931     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8932     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8933     if (!SI1 || !SI2)
8934       return I1->isIdenticalTo(I2);
8935     if (SI1->isIdenticalTo(SI2))
8936       return true;
8937     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8938       if (SI1->getOperand(I) != SI2->getOperand(I))
8939         return false;
8940     // Check if the second instruction is more defined than the first one.
8941     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8942     ArrayRef<int> SM1 = SI1->getShuffleMask();
8943     // Count trailing undefs in the mask to check the final number of used
8944     // registers.
8945     unsigned LastUndefsCnt = 0;
8946     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8947       if (SM1[I] == UndefMaskElem)
8948         ++LastUndefsCnt;
8949       else
8950         LastUndefsCnt = 0;
8951       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8952           NewMask[I] != SM1[I])
8953         return false;
8954       if (NewMask[I] == UndefMaskElem)
8955         NewMask[I] = SM1[I];
8956     }
8957     // Check if the last undefs actually change the final number of used vector
8958     // registers.
8959     return SM1.size() - LastUndefsCnt > 1 &&
8960            TTI->getNumberOfParts(SI1->getType()) ==
8961                TTI->getNumberOfParts(
8962                    FixedVectorType::get(SI1->getType()->getElementType(),
8963                                         SM1.size() - LastUndefsCnt));
8964   };
8965   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8966   // instructions. TODO: We can further optimize this scan if we split the
8967   // instructions into different buckets based on the insert lane.
8968   SmallVector<Instruction *, 16> Visited;
8969   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8970     assert(*I &&
8971            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8972            "Worklist not sorted properly!");
8973     BasicBlock *BB = (*I)->getBlock();
8974     // For all instructions in blocks containing gather sequences:
8975     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8976       if (isDeleted(&In))
8977         continue;
8978       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8979           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8980         continue;
8981 
8982       // Check if we can replace this instruction with any of the
8983       // visited instructions.
8984       bool Replaced = false;
8985       for (Instruction *&V : Visited) {
8986         SmallVector<int> NewMask;
8987         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8988             DT->dominates(V->getParent(), In.getParent())) {
8989           In.replaceAllUsesWith(V);
8990           eraseInstruction(&In);
8991           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8992             if (!NewMask.empty())
8993               SI->setShuffleMask(NewMask);
8994           Replaced = true;
8995           break;
8996         }
8997         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8998             GatherShuffleSeq.contains(V) &&
8999             IsIdenticalOrLessDefined(V, &In, NewMask) &&
9000             DT->dominates(In.getParent(), V->getParent())) {
9001           In.moveAfter(V);
9002           V->replaceAllUsesWith(&In);
9003           eraseInstruction(V);
9004           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
9005             if (!NewMask.empty())
9006               SI->setShuffleMask(NewMask);
9007           V = &In;
9008           Replaced = true;
9009           break;
9010         }
9011       }
9012       if (!Replaced) {
9013         assert(!is_contained(Visited, &In));
9014         Visited.push_back(&In);
9015       }
9016     }
9017   }
9018   CSEBlocks.clear();
9019   GatherShuffleSeq.clear();
9020 }
9021 
9022 BoUpSLP::ScheduleData *
9023 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
9024   ScheduleData *Bundle = nullptr;
9025   ScheduleData *PrevInBundle = nullptr;
9026   for (Value *V : VL) {
9027     if (doesNotNeedToBeScheduled(V))
9028       continue;
9029     ScheduleData *BundleMember = getScheduleData(V);
9030     assert(BundleMember &&
9031            "no ScheduleData for bundle member "
9032            "(maybe not in same basic block)");
9033     assert(BundleMember->isSchedulingEntity() &&
9034            "bundle member already part of other bundle");
9035     if (PrevInBundle) {
9036       PrevInBundle->NextInBundle = BundleMember;
9037     } else {
9038       Bundle = BundleMember;
9039     }
9040 
9041     // Group the instructions to a bundle.
9042     BundleMember->FirstInBundle = Bundle;
9043     PrevInBundle = BundleMember;
9044   }
9045   assert(Bundle && "Failed to find schedule bundle");
9046   return Bundle;
9047 }
9048 
9049 // Groups the instructions to a bundle (which is then a single scheduling entity)
9050 // and schedules instructions until the bundle gets ready.
9051 Optional<BoUpSLP::ScheduleData *>
9052 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
9053                                             const InstructionsState &S) {
9054   // No need to schedule PHIs, insertelement, extractelement and extractvalue
9055   // instructions.
9056   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
9057       doesNotNeedToSchedule(VL))
9058     return nullptr;
9059 
9060   // Initialize the instruction bundle.
9061   Instruction *OldScheduleEnd = ScheduleEnd;
9062   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
9063 
9064   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
9065                                                          ScheduleData *Bundle) {
9066     // The scheduling region got new instructions at the lower end (or it is a
9067     // new region for the first bundle). This makes it necessary to
9068     // recalculate all dependencies.
9069     // It is seldom that this needs to be done a second time after adding the
9070     // initial bundle to the region.
9071     if (ScheduleEnd != OldScheduleEnd) {
9072       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
9073         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
9074       ReSchedule = true;
9075     }
9076     if (Bundle) {
9077       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
9078                         << " in block " << BB->getName() << "\n");
9079       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
9080     }
9081 
9082     if (ReSchedule) {
9083       resetSchedule();
9084       initialFillReadyList(ReadyInsts);
9085     }
9086 
9087     // Now try to schedule the new bundle or (if no bundle) just calculate
9088     // dependencies. As soon as the bundle is "ready" it means that there are no
9089     // cyclic dependencies and we can schedule it. Note that's important that we
9090     // don't "schedule" the bundle yet (see cancelScheduling).
9091     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
9092            !ReadyInsts.empty()) {
9093       ScheduleData *Picked = ReadyInsts.pop_back_val();
9094       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
9095              "must be ready to schedule");
9096       schedule(Picked, ReadyInsts);
9097     }
9098   };
9099 
9100   // Make sure that the scheduling region contains all
9101   // instructions of the bundle.
9102   for (Value *V : VL) {
9103     if (doesNotNeedToBeScheduled(V))
9104       continue;
9105     if (!extendSchedulingRegion(V, S)) {
9106       // If the scheduling region got new instructions at the lower end (or it
9107       // is a new region for the first bundle). This makes it necessary to
9108       // recalculate all dependencies.
9109       // Otherwise the compiler may crash trying to incorrectly calculate
9110       // dependencies and emit instruction in the wrong order at the actual
9111       // scheduling.
9112       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
9113       return None;
9114     }
9115   }
9116 
9117   bool ReSchedule = false;
9118   for (Value *V : VL) {
9119     if (doesNotNeedToBeScheduled(V))
9120       continue;
9121     ScheduleData *BundleMember = getScheduleData(V);
9122     assert(BundleMember &&
9123            "no ScheduleData for bundle member (maybe not in same basic block)");
9124 
9125     // Make sure we don't leave the pieces of the bundle in the ready list when
9126     // whole bundle might not be ready.
9127     ReadyInsts.remove(BundleMember);
9128 
9129     if (!BundleMember->IsScheduled)
9130       continue;
9131     // A bundle member was scheduled as single instruction before and now
9132     // needs to be scheduled as part of the bundle. We just get rid of the
9133     // existing schedule.
9134     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
9135                       << " was already scheduled\n");
9136     ReSchedule = true;
9137   }
9138 
9139   auto *Bundle = buildBundle(VL);
9140   TryScheduleBundleImpl(ReSchedule, Bundle);
9141   if (!Bundle->isReady()) {
9142     cancelScheduling(VL, S.OpValue);
9143     return None;
9144   }
9145   return Bundle;
9146 }
9147 
9148 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
9149                                                 Value *OpValue) {
9150   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
9151       doesNotNeedToSchedule(VL))
9152     return;
9153 
9154   if (doesNotNeedToBeScheduled(OpValue))
9155     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
9156   ScheduleData *Bundle = getScheduleData(OpValue);
9157   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
9158   assert(!Bundle->IsScheduled &&
9159          "Can't cancel bundle which is already scheduled");
9160   assert(Bundle->isSchedulingEntity() &&
9161          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
9162          "tried to unbundle something which is not a bundle");
9163 
9164   // Remove the bundle from the ready list.
9165   if (Bundle->isReady())
9166     ReadyInsts.remove(Bundle);
9167 
9168   // Un-bundle: make single instructions out of the bundle.
9169   ScheduleData *BundleMember = Bundle;
9170   while (BundleMember) {
9171     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
9172     BundleMember->FirstInBundle = BundleMember;
9173     ScheduleData *Next = BundleMember->NextInBundle;
9174     BundleMember->NextInBundle = nullptr;
9175     BundleMember->TE = nullptr;
9176     if (BundleMember->unscheduledDepsInBundle() == 0) {
9177       ReadyInsts.insert(BundleMember);
9178     }
9179     BundleMember = Next;
9180   }
9181 }
9182 
9183 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
9184   // Allocate a new ScheduleData for the instruction.
9185   if (ChunkPos >= ChunkSize) {
9186     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
9187     ChunkPos = 0;
9188   }
9189   return &(ScheduleDataChunks.back()[ChunkPos++]);
9190 }
9191 
9192 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
9193                                                       const InstructionsState &S) {
9194   if (getScheduleData(V, isOneOf(S, V)))
9195     return true;
9196   Instruction *I = dyn_cast<Instruction>(V);
9197   assert(I && "bundle member must be an instruction");
9198   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
9199          !doesNotNeedToBeScheduled(I) &&
9200          "phi nodes/insertelements/extractelements/extractvalues don't need to "
9201          "be scheduled");
9202   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
9203     ScheduleData *ISD = getScheduleData(I);
9204     if (!ISD)
9205       return false;
9206     assert(isInSchedulingRegion(ISD) &&
9207            "ScheduleData not in scheduling region");
9208     ScheduleData *SD = allocateScheduleDataChunks();
9209     SD->Inst = I;
9210     SD->init(SchedulingRegionID, S.OpValue);
9211     ExtraScheduleDataMap[I][S.OpValue] = SD;
9212     return true;
9213   };
9214   if (CheckScheduleForI(I))
9215     return true;
9216   if (!ScheduleStart) {
9217     // It's the first instruction in the new region.
9218     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
9219     ScheduleStart = I;
9220     ScheduleEnd = I->getNextNode();
9221     if (isOneOf(S, I) != I)
9222       CheckScheduleForI(I);
9223     assert(ScheduleEnd && "tried to vectorize a terminator?");
9224     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
9225     return true;
9226   }
9227   // Search up and down at the same time, because we don't know if the new
9228   // instruction is above or below the existing scheduling region.
9229   BasicBlock::reverse_iterator UpIter =
9230       ++ScheduleStart->getIterator().getReverse();
9231   BasicBlock::reverse_iterator UpperEnd = BB->rend();
9232   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
9233   BasicBlock::iterator LowerEnd = BB->end();
9234   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
9235          &*DownIter != I) {
9236     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
9237       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
9238       return false;
9239     }
9240 
9241     ++UpIter;
9242     ++DownIter;
9243   }
9244   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
9245     assert(I->getParent() == ScheduleStart->getParent() &&
9246            "Instruction is in wrong basic block.");
9247     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
9248     ScheduleStart = I;
9249     if (isOneOf(S, I) != I)
9250       CheckScheduleForI(I);
9251     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
9252                       << "\n");
9253     return true;
9254   }
9255   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
9256          "Expected to reach top of the basic block or instruction down the "
9257          "lower end.");
9258   assert(I->getParent() == ScheduleEnd->getParent() &&
9259          "Instruction is in wrong basic block.");
9260   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
9261                    nullptr);
9262   ScheduleEnd = I->getNextNode();
9263   if (isOneOf(S, I) != I)
9264     CheckScheduleForI(I);
9265   assert(ScheduleEnd && "tried to vectorize a terminator?");
9266   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
9267   return true;
9268 }
9269 
9270 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
9271                                                 Instruction *ToI,
9272                                                 ScheduleData *PrevLoadStore,
9273                                                 ScheduleData *NextLoadStore) {
9274   ScheduleData *CurrentLoadStore = PrevLoadStore;
9275   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
9276     // No need to allocate data for non-schedulable instructions.
9277     if (doesNotNeedToBeScheduled(I))
9278       continue;
9279     ScheduleData *SD = ScheduleDataMap.lookup(I);
9280     if (!SD) {
9281       SD = allocateScheduleDataChunks();
9282       ScheduleDataMap[I] = SD;
9283       SD->Inst = I;
9284     }
9285     assert(!isInSchedulingRegion(SD) &&
9286            "new ScheduleData already in scheduling region");
9287     SD->init(SchedulingRegionID, I);
9288 
9289     if (I->mayReadOrWriteMemory() &&
9290         (!isa<IntrinsicInst>(I) ||
9291          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
9292           cast<IntrinsicInst>(I)->getIntrinsicID() !=
9293               Intrinsic::pseudoprobe))) {
9294       // Update the linked list of memory accessing instructions.
9295       if (CurrentLoadStore) {
9296         CurrentLoadStore->NextLoadStore = SD;
9297       } else {
9298         FirstLoadStoreInRegion = SD;
9299       }
9300       CurrentLoadStore = SD;
9301     }
9302 
9303     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9304         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9305       RegionHasStackSave = true;
9306   }
9307   if (NextLoadStore) {
9308     if (CurrentLoadStore)
9309       CurrentLoadStore->NextLoadStore = NextLoadStore;
9310   } else {
9311     LastLoadStoreInRegion = CurrentLoadStore;
9312   }
9313 }
9314 
9315 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
9316                                                      bool InsertInReadyList,
9317                                                      BoUpSLP *SLP) {
9318   assert(SD->isSchedulingEntity());
9319 
9320   SmallVector<ScheduleData *, 10> WorkList;
9321   WorkList.push_back(SD);
9322 
9323   while (!WorkList.empty()) {
9324     ScheduleData *SD = WorkList.pop_back_val();
9325     for (ScheduleData *BundleMember = SD; BundleMember;
9326          BundleMember = BundleMember->NextInBundle) {
9327       assert(isInSchedulingRegion(BundleMember));
9328       if (BundleMember->hasValidDependencies())
9329         continue;
9330 
9331       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
9332                  << "\n");
9333       BundleMember->Dependencies = 0;
9334       BundleMember->resetUnscheduledDeps();
9335 
9336       // Handle def-use chain dependencies.
9337       if (BundleMember->OpValue != BundleMember->Inst) {
9338         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
9339           BundleMember->Dependencies++;
9340           ScheduleData *DestBundle = UseSD->FirstInBundle;
9341           if (!DestBundle->IsScheduled)
9342             BundleMember->incrementUnscheduledDeps(1);
9343           if (!DestBundle->hasValidDependencies())
9344             WorkList.push_back(DestBundle);
9345         }
9346       } else {
9347         for (User *U : BundleMember->Inst->users()) {
9348           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
9349             BundleMember->Dependencies++;
9350             ScheduleData *DestBundle = UseSD->FirstInBundle;
9351             if (!DestBundle->IsScheduled)
9352               BundleMember->incrementUnscheduledDeps(1);
9353             if (!DestBundle->hasValidDependencies())
9354               WorkList.push_back(DestBundle);
9355           }
9356         }
9357       }
9358 
9359       auto makeControlDependent = [&](Instruction *I) {
9360         auto *DepDest = getScheduleData(I);
9361         assert(DepDest && "must be in schedule window");
9362         DepDest->ControlDependencies.push_back(BundleMember);
9363         BundleMember->Dependencies++;
9364         ScheduleData *DestBundle = DepDest->FirstInBundle;
9365         if (!DestBundle->IsScheduled)
9366           BundleMember->incrementUnscheduledDeps(1);
9367         if (!DestBundle->hasValidDependencies())
9368           WorkList.push_back(DestBundle);
9369       };
9370 
9371       // Any instruction which isn't safe to speculate at the begining of the
9372       // block is control dependend on any early exit or non-willreturn call
9373       // which proceeds it.
9374       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
9375         for (Instruction *I = BundleMember->Inst->getNextNode();
9376              I != ScheduleEnd; I = I->getNextNode()) {
9377           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
9378             continue;
9379 
9380           // Add the dependency
9381           makeControlDependent(I);
9382 
9383           if (!isGuaranteedToTransferExecutionToSuccessor(I))
9384             // Everything past here must be control dependent on I.
9385             break;
9386         }
9387       }
9388 
9389       if (RegionHasStackSave) {
9390         // If we have an inalloc alloca instruction, it needs to be scheduled
9391         // after any preceeding stacksave.  We also need to prevent any alloca
9392         // from reordering above a preceeding stackrestore.
9393         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
9394             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
9395           for (Instruction *I = BundleMember->Inst->getNextNode();
9396                I != ScheduleEnd; I = I->getNextNode()) {
9397             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9398                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9399               // Any allocas past here must be control dependent on I, and I
9400               // must be memory dependend on BundleMember->Inst.
9401               break;
9402 
9403             if (!isa<AllocaInst>(I))
9404               continue;
9405 
9406             // Add the dependency
9407             makeControlDependent(I);
9408           }
9409         }
9410 
9411         // In addition to the cases handle just above, we need to prevent
9412         // allocas from moving below a stacksave.  The stackrestore case
9413         // is currently thought to be conservatism.
9414         if (isa<AllocaInst>(BundleMember->Inst)) {
9415           for (Instruction *I = BundleMember->Inst->getNextNode();
9416                I != ScheduleEnd; I = I->getNextNode()) {
9417             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
9418                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9419               continue;
9420 
9421             // Add the dependency
9422             makeControlDependent(I);
9423             break;
9424           }
9425         }
9426       }
9427 
9428       // Handle the memory dependencies (if any).
9429       ScheduleData *DepDest = BundleMember->NextLoadStore;
9430       if (!DepDest)
9431         continue;
9432       Instruction *SrcInst = BundleMember->Inst;
9433       assert(SrcInst->mayReadOrWriteMemory() &&
9434              "NextLoadStore list for non memory effecting bundle?");
9435       MemoryLocation SrcLoc = getLocation(SrcInst);
9436       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
9437       unsigned numAliased = 0;
9438       unsigned DistToSrc = 1;
9439 
9440       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
9441         assert(isInSchedulingRegion(DepDest));
9442 
9443         // We have two limits to reduce the complexity:
9444         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
9445         //    SLP->isAliased (which is the expensive part in this loop).
9446         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
9447         //    the whole loop (even if the loop is fast, it's quadratic).
9448         //    It's important for the loop break condition (see below) to
9449         //    check this limit even between two read-only instructions.
9450         if (DistToSrc >= MaxMemDepDistance ||
9451             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
9452              (numAliased >= AliasedCheckLimit ||
9453               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
9454 
9455           // We increment the counter only if the locations are aliased
9456           // (instead of counting all alias checks). This gives a better
9457           // balance between reduced runtime and accurate dependencies.
9458           numAliased++;
9459 
9460           DepDest->MemoryDependencies.push_back(BundleMember);
9461           BundleMember->Dependencies++;
9462           ScheduleData *DestBundle = DepDest->FirstInBundle;
9463           if (!DestBundle->IsScheduled) {
9464             BundleMember->incrementUnscheduledDeps(1);
9465           }
9466           if (!DestBundle->hasValidDependencies()) {
9467             WorkList.push_back(DestBundle);
9468           }
9469         }
9470 
9471         // Example, explaining the loop break condition: Let's assume our
9472         // starting instruction is i0 and MaxMemDepDistance = 3.
9473         //
9474         //                      +--------v--v--v
9475         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
9476         //             +--------^--^--^
9477         //
9478         // MaxMemDepDistance let us stop alias-checking at i3 and we add
9479         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
9480         // Previously we already added dependencies from i3 to i6,i7,i8
9481         // (because of MaxMemDepDistance). As we added a dependency from
9482         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
9483         // and we can abort this loop at i6.
9484         if (DistToSrc >= 2 * MaxMemDepDistance)
9485           break;
9486         DistToSrc++;
9487       }
9488     }
9489     if (InsertInReadyList && SD->isReady()) {
9490       ReadyInsts.insert(SD);
9491       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
9492                         << "\n");
9493     }
9494   }
9495 }
9496 
9497 void BoUpSLP::BlockScheduling::resetSchedule() {
9498   assert(ScheduleStart &&
9499          "tried to reset schedule on block which has not been scheduled");
9500   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
9501     doForAllOpcodes(I, [&](ScheduleData *SD) {
9502       assert(isInSchedulingRegion(SD) &&
9503              "ScheduleData not in scheduling region");
9504       SD->IsScheduled = false;
9505       SD->resetUnscheduledDeps();
9506     });
9507   }
9508   ReadyInsts.clear();
9509 }
9510 
9511 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
9512   if (!BS->ScheduleStart)
9513     return;
9514 
9515   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
9516 
9517   // A key point - if we got here, pre-scheduling was able to find a valid
9518   // scheduling of the sub-graph of the scheduling window which consists
9519   // of all vector bundles and their transitive users.  As such, we do not
9520   // need to reschedule anything *outside of* that subgraph.
9521 
9522   BS->resetSchedule();
9523 
9524   // For the real scheduling we use a more sophisticated ready-list: it is
9525   // sorted by the original instruction location. This lets the final schedule
9526   // be as  close as possible to the original instruction order.
9527   // WARNING: If changing this order causes a correctness issue, that means
9528   // there is some missing dependence edge in the schedule data graph.
9529   struct ScheduleDataCompare {
9530     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
9531       return SD2->SchedulingPriority < SD1->SchedulingPriority;
9532     }
9533   };
9534   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
9535 
9536   // Ensure that all dependency data is updated (for nodes in the sub-graph)
9537   // and fill the ready-list with initial instructions.
9538   int Idx = 0;
9539   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
9540        I = I->getNextNode()) {
9541     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
9542       TreeEntry *SDTE = getTreeEntry(SD->Inst);
9543       (void)SDTE;
9544       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
9545               SD->isPartOfBundle() ==
9546                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
9547              "scheduler and vectorizer bundle mismatch");
9548       SD->FirstInBundle->SchedulingPriority = Idx++;
9549 
9550       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
9551         BS->calculateDependencies(SD, false, this);
9552     });
9553   }
9554   BS->initialFillReadyList(ReadyInsts);
9555 
9556   Instruction *LastScheduledInst = BS->ScheduleEnd;
9557 
9558   // Do the "real" scheduling.
9559   while (!ReadyInsts.empty()) {
9560     ScheduleData *picked = *ReadyInsts.begin();
9561     ReadyInsts.erase(ReadyInsts.begin());
9562 
9563     // Move the scheduled instruction(s) to their dedicated places, if not
9564     // there yet.
9565     for (ScheduleData *BundleMember = picked; BundleMember;
9566          BundleMember = BundleMember->NextInBundle) {
9567       Instruction *pickedInst = BundleMember->Inst;
9568       if (pickedInst->getNextNode() != LastScheduledInst)
9569         pickedInst->moveBefore(LastScheduledInst);
9570       LastScheduledInst = pickedInst;
9571     }
9572 
9573     BS->schedule(picked, ReadyInsts);
9574   }
9575 
9576   // Check that we didn't break any of our invariants.
9577 #ifdef EXPENSIVE_CHECKS
9578   BS->verify();
9579 #endif
9580 
9581 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
9582   // Check that all schedulable entities got scheduled
9583   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
9584     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
9585       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
9586         assert(SD->IsScheduled && "must be scheduled at this point");
9587       }
9588     });
9589   }
9590 #endif
9591 
9592   // Avoid duplicate scheduling of the block.
9593   BS->ScheduleStart = nullptr;
9594 }
9595 
9596 unsigned BoUpSLP::getVectorElementSize(Value *V) {
9597   // If V is a store, just return the width of the stored value (or value
9598   // truncated just before storing) without traversing the expression tree.
9599   // This is the common case.
9600   if (auto *Store = dyn_cast<StoreInst>(V))
9601     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
9602 
9603   if (auto *IEI = dyn_cast<InsertElementInst>(V))
9604     return getVectorElementSize(IEI->getOperand(1));
9605 
9606   auto E = InstrElementSize.find(V);
9607   if (E != InstrElementSize.end())
9608     return E->second;
9609 
9610   // If V is not a store, we can traverse the expression tree to find loads
9611   // that feed it. The type of the loaded value may indicate a more suitable
9612   // width than V's type. We want to base the vector element size on the width
9613   // of memory operations where possible.
9614   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
9615   SmallPtrSet<Instruction *, 16> Visited;
9616   if (auto *I = dyn_cast<Instruction>(V)) {
9617     Worklist.emplace_back(I, I->getParent());
9618     Visited.insert(I);
9619   }
9620 
9621   // Traverse the expression tree in bottom-up order looking for loads. If we
9622   // encounter an instruction we don't yet handle, we give up.
9623   auto Width = 0u;
9624   while (!Worklist.empty()) {
9625     Instruction *I;
9626     BasicBlock *Parent;
9627     std::tie(I, Parent) = Worklist.pop_back_val();
9628 
9629     // We should only be looking at scalar instructions here. If the current
9630     // instruction has a vector type, skip.
9631     auto *Ty = I->getType();
9632     if (isa<VectorType>(Ty))
9633       continue;
9634 
9635     // If the current instruction is a load, update MaxWidth to reflect the
9636     // width of the loaded value.
9637     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
9638         isa<ExtractValueInst>(I))
9639       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
9640 
9641     // Otherwise, we need to visit the operands of the instruction. We only
9642     // handle the interesting cases from buildTree here. If an operand is an
9643     // instruction we haven't yet visited and from the same basic block as the
9644     // user or the use is a PHI node, we add it to the worklist.
9645     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9646              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
9647              isa<UnaryOperator>(I)) {
9648       for (Use &U : I->operands())
9649         if (auto *J = dyn_cast<Instruction>(U.get()))
9650           if (Visited.insert(J).second &&
9651               (isa<PHINode>(I) || J->getParent() == Parent))
9652             Worklist.emplace_back(J, J->getParent());
9653     } else {
9654       break;
9655     }
9656   }
9657 
9658   // If we didn't encounter a memory access in the expression tree, or if we
9659   // gave up for some reason, just return the width of V. Otherwise, return the
9660   // maximum width we found.
9661   if (!Width) {
9662     if (auto *CI = dyn_cast<CmpInst>(V))
9663       V = CI->getOperand(0);
9664     Width = DL->getTypeSizeInBits(V->getType());
9665   }
9666 
9667   for (Instruction *I : Visited)
9668     InstrElementSize[I] = Width;
9669 
9670   return Width;
9671 }
9672 
9673 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9674 // smaller type with a truncation. We collect the values that will be demoted
9675 // in ToDemote and additional roots that require investigating in Roots.
9676 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9677                                   SmallVectorImpl<Value *> &ToDemote,
9678                                   SmallVectorImpl<Value *> &Roots) {
9679   // We can always demote constants.
9680   if (isa<Constant>(V)) {
9681     ToDemote.push_back(V);
9682     return true;
9683   }
9684 
9685   // If the value is not an instruction in the expression with only one use, it
9686   // cannot be demoted.
9687   auto *I = dyn_cast<Instruction>(V);
9688   if (!I || !I->hasOneUse() || !Expr.count(I))
9689     return false;
9690 
9691   switch (I->getOpcode()) {
9692 
9693   // We can always demote truncations and extensions. Since truncations can
9694   // seed additional demotion, we save the truncated value.
9695   case Instruction::Trunc:
9696     Roots.push_back(I->getOperand(0));
9697     break;
9698   case Instruction::ZExt:
9699   case Instruction::SExt:
9700     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9701         isa<InsertElementInst>(I->getOperand(0)))
9702       return false;
9703     break;
9704 
9705   // We can demote certain binary operations if we can demote both of their
9706   // operands.
9707   case Instruction::Add:
9708   case Instruction::Sub:
9709   case Instruction::Mul:
9710   case Instruction::And:
9711   case Instruction::Or:
9712   case Instruction::Xor:
9713     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9714         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9715       return false;
9716     break;
9717 
9718   // We can demote selects if we can demote their true and false values.
9719   case Instruction::Select: {
9720     SelectInst *SI = cast<SelectInst>(I);
9721     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9722         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9723       return false;
9724     break;
9725   }
9726 
9727   // We can demote phis if we can demote all their incoming operands. Note that
9728   // we don't need to worry about cycles since we ensure single use above.
9729   case Instruction::PHI: {
9730     PHINode *PN = cast<PHINode>(I);
9731     for (Value *IncValue : PN->incoming_values())
9732       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9733         return false;
9734     break;
9735   }
9736 
9737   // Otherwise, conservatively give up.
9738   default:
9739     return false;
9740   }
9741 
9742   // Record the value that we can demote.
9743   ToDemote.push_back(V);
9744   return true;
9745 }
9746 
9747 void BoUpSLP::computeMinimumValueSizes() {
9748   // If there are no external uses, the expression tree must be rooted by a
9749   // store. We can't demote in-memory values, so there is nothing to do here.
9750   if (ExternalUses.empty())
9751     return;
9752 
9753   // We only attempt to truncate integer expressions.
9754   auto &TreeRoot = VectorizableTree[0]->Scalars;
9755   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9756   if (!TreeRootIT)
9757     return;
9758 
9759   // If the expression is not rooted by a store, these roots should have
9760   // external uses. We will rely on InstCombine to rewrite the expression in
9761   // the narrower type. However, InstCombine only rewrites single-use values.
9762   // This means that if a tree entry other than a root is used externally, it
9763   // must have multiple uses and InstCombine will not rewrite it. The code
9764   // below ensures that only the roots are used externally.
9765   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9766   for (auto &EU : ExternalUses)
9767     if (!Expr.erase(EU.Scalar))
9768       return;
9769   if (!Expr.empty())
9770     return;
9771 
9772   // Collect the scalar values of the vectorizable expression. We will use this
9773   // context to determine which values can be demoted. If we see a truncation,
9774   // we mark it as seeding another demotion.
9775   for (auto &EntryPtr : VectorizableTree)
9776     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9777 
9778   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9779   // have a single external user that is not in the vectorizable tree.
9780   for (auto *Root : TreeRoot)
9781     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9782       return;
9783 
9784   // Conservatively determine if we can actually truncate the roots of the
9785   // expression. Collect the values that can be demoted in ToDemote and
9786   // additional roots that require investigating in Roots.
9787   SmallVector<Value *, 32> ToDemote;
9788   SmallVector<Value *, 4> Roots;
9789   for (auto *Root : TreeRoot)
9790     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9791       return;
9792 
9793   // The maximum bit width required to represent all the values that can be
9794   // demoted without loss of precision. It would be safe to truncate the roots
9795   // of the expression to this width.
9796   auto MaxBitWidth = 8u;
9797 
9798   // We first check if all the bits of the roots are demanded. If they're not,
9799   // we can truncate the roots to this narrower type.
9800   for (auto *Root : TreeRoot) {
9801     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9802     MaxBitWidth = std::max<unsigned>(
9803         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9804   }
9805 
9806   // True if the roots can be zero-extended back to their original type, rather
9807   // than sign-extended. We know that if the leading bits are not demanded, we
9808   // can safely zero-extend. So we initialize IsKnownPositive to True.
9809   bool IsKnownPositive = true;
9810 
9811   // If all the bits of the roots are demanded, we can try a little harder to
9812   // compute a narrower type. This can happen, for example, if the roots are
9813   // getelementptr indices. InstCombine promotes these indices to the pointer
9814   // width. Thus, all their bits are technically demanded even though the
9815   // address computation might be vectorized in a smaller type.
9816   //
9817   // We start by looking at each entry that can be demoted. We compute the
9818   // maximum bit width required to store the scalar by using ValueTracking to
9819   // compute the number of high-order bits we can truncate.
9820   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9821       llvm::all_of(TreeRoot, [](Value *R) {
9822         assert(R->hasOneUse() && "Root should have only one use!");
9823         return isa<GetElementPtrInst>(R->user_back());
9824       })) {
9825     MaxBitWidth = 8u;
9826 
9827     // Determine if the sign bit of all the roots is known to be zero. If not,
9828     // IsKnownPositive is set to False.
9829     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9830       KnownBits Known = computeKnownBits(R, *DL);
9831       return Known.isNonNegative();
9832     });
9833 
9834     // Determine the maximum number of bits required to store the scalar
9835     // values.
9836     for (auto *Scalar : ToDemote) {
9837       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9838       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9839       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9840     }
9841 
9842     // If we can't prove that the sign bit is zero, we must add one to the
9843     // maximum bit width to account for the unknown sign bit. This preserves
9844     // the existing sign bit so we can safely sign-extend the root back to the
9845     // original type. Otherwise, if we know the sign bit is zero, we will
9846     // zero-extend the root instead.
9847     //
9848     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9849     //        one to the maximum bit width will yield a larger-than-necessary
9850     //        type. In general, we need to add an extra bit only if we can't
9851     //        prove that the upper bit of the original type is equal to the
9852     //        upper bit of the proposed smaller type. If these two bits are the
9853     //        same (either zero or one) we know that sign-extending from the
9854     //        smaller type will result in the same value. Here, since we can't
9855     //        yet prove this, we are just making the proposed smaller type
9856     //        larger to ensure correctness.
9857     if (!IsKnownPositive)
9858       ++MaxBitWidth;
9859   }
9860 
9861   // Round MaxBitWidth up to the next power-of-two.
9862   if (!isPowerOf2_64(MaxBitWidth))
9863     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9864 
9865   // If the maximum bit width we compute is less than the with of the roots'
9866   // type, we can proceed with the narrowing. Otherwise, do nothing.
9867   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9868     return;
9869 
9870   // If we can truncate the root, we must collect additional values that might
9871   // be demoted as a result. That is, those seeded by truncations we will
9872   // modify.
9873   while (!Roots.empty())
9874     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9875 
9876   // Finally, map the values we can demote to the maximum bit with we computed.
9877   for (auto *Scalar : ToDemote)
9878     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9879 }
9880 
9881 namespace {
9882 
9883 /// The SLPVectorizer Pass.
9884 struct SLPVectorizer : public FunctionPass {
9885   SLPVectorizerPass Impl;
9886 
9887   /// Pass identification, replacement for typeid
9888   static char ID;
9889 
9890   explicit SLPVectorizer() : FunctionPass(ID) {
9891     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9892   }
9893 
9894   bool doInitialization(Module &M) override { return false; }
9895 
9896   bool runOnFunction(Function &F) override {
9897     if (skipFunction(F))
9898       return false;
9899 
9900     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9901     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9902     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9903     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9904     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9905     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9906     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9907     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9908     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9909     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9910 
9911     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9912   }
9913 
9914   void getAnalysisUsage(AnalysisUsage &AU) const override {
9915     FunctionPass::getAnalysisUsage(AU);
9916     AU.addRequired<AssumptionCacheTracker>();
9917     AU.addRequired<ScalarEvolutionWrapperPass>();
9918     AU.addRequired<AAResultsWrapperPass>();
9919     AU.addRequired<TargetTransformInfoWrapperPass>();
9920     AU.addRequired<LoopInfoWrapperPass>();
9921     AU.addRequired<DominatorTreeWrapperPass>();
9922     AU.addRequired<DemandedBitsWrapperPass>();
9923     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9924     AU.addRequired<InjectTLIMappingsLegacy>();
9925     AU.addPreserved<LoopInfoWrapperPass>();
9926     AU.addPreserved<DominatorTreeWrapperPass>();
9927     AU.addPreserved<AAResultsWrapperPass>();
9928     AU.addPreserved<GlobalsAAWrapperPass>();
9929     AU.setPreservesCFG();
9930   }
9931 };
9932 
9933 } // end anonymous namespace
9934 
9935 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9936   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9937   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9938   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9939   auto *AA = &AM.getResult<AAManager>(F);
9940   auto *LI = &AM.getResult<LoopAnalysis>(F);
9941   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9942   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9943   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9944   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9945 
9946   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9947   if (!Changed)
9948     return PreservedAnalyses::all();
9949 
9950   PreservedAnalyses PA;
9951   PA.preserveSet<CFGAnalyses>();
9952   return PA;
9953 }
9954 
9955 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9956                                 TargetTransformInfo *TTI_,
9957                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9958                                 LoopInfo *LI_, DominatorTree *DT_,
9959                                 AssumptionCache *AC_, DemandedBits *DB_,
9960                                 OptimizationRemarkEmitter *ORE_) {
9961   if (!RunSLPVectorization)
9962     return false;
9963   SE = SE_;
9964   TTI = TTI_;
9965   TLI = TLI_;
9966   AA = AA_;
9967   LI = LI_;
9968   DT = DT_;
9969   AC = AC_;
9970   DB = DB_;
9971   DL = &F.getParent()->getDataLayout();
9972 
9973   Stores.clear();
9974   GEPs.clear();
9975   bool Changed = false;
9976 
9977   // If the target claims to have no vector registers don't attempt
9978   // vectorization.
9979   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9980     LLVM_DEBUG(
9981         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9982     return false;
9983   }
9984 
9985   // Don't vectorize when the attribute NoImplicitFloat is used.
9986   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9987     return false;
9988 
9989   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9990 
9991   // Use the bottom up slp vectorizer to construct chains that start with
9992   // store instructions.
9993   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9994 
9995   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9996   // delete instructions.
9997 
9998   // Update DFS numbers now so that we can use them for ordering.
9999   DT->updateDFSNumbers();
10000 
10001   // Scan the blocks in the function in post order.
10002   for (auto BB : post_order(&F.getEntryBlock())) {
10003     // Start new block - clear the list of reduction roots.
10004     R.clearReductionData();
10005     collectSeedInstructions(BB);
10006 
10007     // Vectorize trees that end at stores.
10008     if (!Stores.empty()) {
10009       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
10010                         << " underlying objects.\n");
10011       Changed |= vectorizeStoreChains(R);
10012     }
10013 
10014     // Vectorize trees that end at reductions.
10015     Changed |= vectorizeChainsInBlock(BB, R);
10016 
10017     // Vectorize the index computations of getelementptr instructions. This
10018     // is primarily intended to catch gather-like idioms ending at
10019     // non-consecutive loads.
10020     if (!GEPs.empty()) {
10021       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
10022                         << " underlying objects.\n");
10023       Changed |= vectorizeGEPIndices(BB, R);
10024     }
10025   }
10026 
10027   if (Changed) {
10028     R.optimizeGatherSequence();
10029     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
10030   }
10031   return Changed;
10032 }
10033 
10034 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
10035                                             unsigned Idx, unsigned MinVF) {
10036   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
10037                     << "\n");
10038   const unsigned Sz = R.getVectorElementSize(Chain[0]);
10039   unsigned VF = Chain.size();
10040 
10041   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
10042     return false;
10043 
10044   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
10045                     << "\n");
10046 
10047   R.buildTree(Chain);
10048   if (R.isTreeTinyAndNotFullyVectorizable())
10049     return false;
10050   if (R.isLoadCombineCandidate())
10051     return false;
10052   R.reorderTopToBottom();
10053   R.reorderBottomToTop();
10054   R.buildExternalUses();
10055 
10056   R.computeMinimumValueSizes();
10057 
10058   InstructionCost Cost = R.getTreeCost();
10059 
10060   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
10061   if (Cost < -SLPCostThreshold) {
10062     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
10063 
10064     using namespace ore;
10065 
10066     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
10067                                         cast<StoreInst>(Chain[0]))
10068                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
10069                      << " and with tree size "
10070                      << NV("TreeSize", R.getTreeSize()));
10071 
10072     R.vectorizeTree();
10073     return true;
10074   }
10075 
10076   return false;
10077 }
10078 
10079 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
10080                                         BoUpSLP &R) {
10081   // We may run into multiple chains that merge into a single chain. We mark the
10082   // stores that we vectorized so that we don't visit the same store twice.
10083   BoUpSLP::ValueSet VectorizedStores;
10084   bool Changed = false;
10085 
10086   int E = Stores.size();
10087   SmallBitVector Tails(E, false);
10088   int MaxIter = MaxStoreLookup.getValue();
10089   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
10090       E, std::make_pair(E, INT_MAX));
10091   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
10092   int IterCnt;
10093   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
10094                                   &CheckedPairs,
10095                                   &ConsecutiveChain](int K, int Idx) {
10096     if (IterCnt >= MaxIter)
10097       return true;
10098     if (CheckedPairs[Idx].test(K))
10099       return ConsecutiveChain[K].second == 1 &&
10100              ConsecutiveChain[K].first == Idx;
10101     ++IterCnt;
10102     CheckedPairs[Idx].set(K);
10103     CheckedPairs[K].set(Idx);
10104     Optional<int> Diff = getPointersDiff(
10105         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
10106         Stores[Idx]->getValueOperand()->getType(),
10107         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
10108     if (!Diff || *Diff == 0)
10109       return false;
10110     int Val = *Diff;
10111     if (Val < 0) {
10112       if (ConsecutiveChain[Idx].second > -Val) {
10113         Tails.set(K);
10114         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
10115       }
10116       return false;
10117     }
10118     if (ConsecutiveChain[K].second <= Val)
10119       return false;
10120 
10121     Tails.set(Idx);
10122     ConsecutiveChain[K] = std::make_pair(Idx, Val);
10123     return Val == 1;
10124   };
10125   // Do a quadratic search on all of the given stores in reverse order and find
10126   // all of the pairs of stores that follow each other.
10127   for (int Idx = E - 1; Idx >= 0; --Idx) {
10128     // If a store has multiple consecutive store candidates, search according
10129     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
10130     // This is because usually pairing with immediate succeeding or preceding
10131     // candidate create the best chance to find slp vectorization opportunity.
10132     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
10133     IterCnt = 0;
10134     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
10135       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
10136           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
10137         break;
10138   }
10139 
10140   // Tracks if we tried to vectorize stores starting from the given tail
10141   // already.
10142   SmallBitVector TriedTails(E, false);
10143   // For stores that start but don't end a link in the chain:
10144   for (int Cnt = E; Cnt > 0; --Cnt) {
10145     int I = Cnt - 1;
10146     if (ConsecutiveChain[I].first == E || Tails.test(I))
10147       continue;
10148     // We found a store instr that starts a chain. Now follow the chain and try
10149     // to vectorize it.
10150     BoUpSLP::ValueList Operands;
10151     // Collect the chain into a list.
10152     while (I != E && !VectorizedStores.count(Stores[I])) {
10153       Operands.push_back(Stores[I]);
10154       Tails.set(I);
10155       if (ConsecutiveChain[I].second != 1) {
10156         // Mark the new end in the chain and go back, if required. It might be
10157         // required if the original stores come in reversed order, for example.
10158         if (ConsecutiveChain[I].first != E &&
10159             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
10160             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
10161           TriedTails.set(I);
10162           Tails.reset(ConsecutiveChain[I].first);
10163           if (Cnt < ConsecutiveChain[I].first + 2)
10164             Cnt = ConsecutiveChain[I].first + 2;
10165         }
10166         break;
10167       }
10168       // Move to the next value in the chain.
10169       I = ConsecutiveChain[I].first;
10170     }
10171     assert(!Operands.empty() && "Expected non-empty list of stores.");
10172 
10173     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10174     unsigned EltSize = R.getVectorElementSize(Operands[0]);
10175     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
10176 
10177     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
10178                               MaxElts);
10179     auto *Store = cast<StoreInst>(Operands[0]);
10180     Type *StoreTy = Store->getValueOperand()->getType();
10181     Type *ValueTy = StoreTy;
10182     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
10183       ValueTy = Trunc->getSrcTy();
10184     unsigned MinVF = TTI->getStoreMinimumVF(
10185         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
10186 
10187     // FIXME: Is division-by-2 the correct step? Should we assert that the
10188     // register size is a power-of-2?
10189     unsigned StartIdx = 0;
10190     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
10191       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
10192         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
10193         if (!VectorizedStores.count(Slice.front()) &&
10194             !VectorizedStores.count(Slice.back()) &&
10195             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
10196           // Mark the vectorized stores so that we don't vectorize them again.
10197           VectorizedStores.insert(Slice.begin(), Slice.end());
10198           Changed = true;
10199           // If we vectorized initial block, no need to try to vectorize it
10200           // again.
10201           if (Cnt == StartIdx)
10202             StartIdx += Size;
10203           Cnt += Size;
10204           continue;
10205         }
10206         ++Cnt;
10207       }
10208       // Check if the whole array was vectorized already - exit.
10209       if (StartIdx >= Operands.size())
10210         break;
10211     }
10212   }
10213 
10214   return Changed;
10215 }
10216 
10217 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
10218   // Initialize the collections. We will make a single pass over the block.
10219   Stores.clear();
10220   GEPs.clear();
10221 
10222   // Visit the store and getelementptr instructions in BB and organize them in
10223   // Stores and GEPs according to the underlying objects of their pointer
10224   // operands.
10225   for (Instruction &I : *BB) {
10226     // Ignore store instructions that are volatile or have a pointer operand
10227     // that doesn't point to a scalar type.
10228     if (auto *SI = dyn_cast<StoreInst>(&I)) {
10229       if (!SI->isSimple())
10230         continue;
10231       if (!isValidElementType(SI->getValueOperand()->getType()))
10232         continue;
10233       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
10234     }
10235 
10236     // Ignore getelementptr instructions that have more than one index, a
10237     // constant index, or a pointer operand that doesn't point to a scalar
10238     // type.
10239     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
10240       auto Idx = GEP->idx_begin()->get();
10241       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
10242         continue;
10243       if (!isValidElementType(Idx->getType()))
10244         continue;
10245       if (GEP->getType()->isVectorTy())
10246         continue;
10247       GEPs[GEP->getPointerOperand()].push_back(GEP);
10248     }
10249   }
10250 }
10251 
10252 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
10253   if (!A || !B)
10254     return false;
10255   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
10256     return false;
10257   Value *VL[] = {A, B};
10258   return tryToVectorizeList(VL, R);
10259 }
10260 
10261 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
10262                                            bool LimitForRegisterSize) {
10263   if (VL.size() < 2)
10264     return false;
10265 
10266   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
10267                     << VL.size() << ".\n");
10268 
10269   // Check that all of the parts are instructions of the same type,
10270   // we permit an alternate opcode via InstructionsState.
10271   InstructionsState S = getSameOpcode(VL);
10272   if (!S.getOpcode())
10273     return false;
10274 
10275   Instruction *I0 = cast<Instruction>(S.OpValue);
10276   // Make sure invalid types (including vector type) are rejected before
10277   // determining vectorization factor for scalar instructions.
10278   for (Value *V : VL) {
10279     Type *Ty = V->getType();
10280     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
10281       // NOTE: the following will give user internal llvm type name, which may
10282       // not be useful.
10283       R.getORE()->emit([&]() {
10284         std::string type_str;
10285         llvm::raw_string_ostream rso(type_str);
10286         Ty->print(rso);
10287         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
10288                << "Cannot SLP vectorize list: type "
10289                << rso.str() + " is unsupported by vectorizer";
10290       });
10291       return false;
10292     }
10293   }
10294 
10295   unsigned Sz = R.getVectorElementSize(I0);
10296   unsigned MinVF = R.getMinVF(Sz);
10297   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
10298   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
10299   if (MaxVF < 2) {
10300     R.getORE()->emit([&]() {
10301       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
10302              << "Cannot SLP vectorize list: vectorization factor "
10303              << "less than 2 is not supported";
10304     });
10305     return false;
10306   }
10307 
10308   bool Changed = false;
10309   bool CandidateFound = false;
10310   InstructionCost MinCost = SLPCostThreshold.getValue();
10311   Type *ScalarTy = VL[0]->getType();
10312   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
10313     ScalarTy = IE->getOperand(1)->getType();
10314 
10315   unsigned NextInst = 0, MaxInst = VL.size();
10316   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
10317     // No actual vectorization should happen, if number of parts is the same as
10318     // provided vectorization factor (i.e. the scalar type is used for vector
10319     // code during codegen).
10320     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
10321     if (TTI->getNumberOfParts(VecTy) == VF)
10322       continue;
10323     for (unsigned I = NextInst; I < MaxInst; ++I) {
10324       unsigned OpsWidth = 0;
10325 
10326       if (I + VF > MaxInst)
10327         OpsWidth = MaxInst - I;
10328       else
10329         OpsWidth = VF;
10330 
10331       if (!isPowerOf2_32(OpsWidth))
10332         continue;
10333 
10334       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
10335           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
10336         break;
10337 
10338       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
10339       // Check that a previous iteration of this loop did not delete the Value.
10340       if (llvm::any_of(Ops, [&R](Value *V) {
10341             auto *I = dyn_cast<Instruction>(V);
10342             return I && R.isDeleted(I);
10343           }))
10344         continue;
10345 
10346       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
10347                         << "\n");
10348 
10349       R.buildTree(Ops);
10350       if (R.isTreeTinyAndNotFullyVectorizable())
10351         continue;
10352       R.reorderTopToBottom();
10353       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
10354       R.buildExternalUses();
10355 
10356       R.computeMinimumValueSizes();
10357       InstructionCost Cost = R.getTreeCost();
10358       CandidateFound = true;
10359       MinCost = std::min(MinCost, Cost);
10360 
10361       if (Cost < -SLPCostThreshold) {
10362         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
10363         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
10364                                                     cast<Instruction>(Ops[0]))
10365                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
10366                                  << " and with tree size "
10367                                  << ore::NV("TreeSize", R.getTreeSize()));
10368 
10369         R.vectorizeTree();
10370         // Move to the next bundle.
10371         I += VF - 1;
10372         NextInst = I + 1;
10373         Changed = true;
10374       }
10375     }
10376   }
10377 
10378   if (!Changed && CandidateFound) {
10379     R.getORE()->emit([&]() {
10380       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
10381              << "List vectorization was possible but not beneficial with cost "
10382              << ore::NV("Cost", MinCost) << " >= "
10383              << ore::NV("Treshold", -SLPCostThreshold);
10384     });
10385   } else if (!Changed) {
10386     R.getORE()->emit([&]() {
10387       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
10388              << "Cannot SLP vectorize list: vectorization was impossible"
10389              << " with available vectorization factors";
10390     });
10391   }
10392   return Changed;
10393 }
10394 
10395 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
10396   if (!I)
10397     return false;
10398 
10399   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
10400       isa<VectorType>(I->getType()))
10401     return false;
10402 
10403   Value *P = I->getParent();
10404 
10405   // Vectorize in current basic block only.
10406   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
10407   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
10408   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
10409     return false;
10410 
10411   // First collect all possible candidates
10412   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
10413   Candidates.emplace_back(Op0, Op1);
10414 
10415   auto *A = dyn_cast<BinaryOperator>(Op0);
10416   auto *B = dyn_cast<BinaryOperator>(Op1);
10417   // Try to skip B.
10418   if (A && B && B->hasOneUse()) {
10419     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
10420     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
10421     if (B0 && B0->getParent() == P)
10422       Candidates.emplace_back(A, B0);
10423     if (B1 && B1->getParent() == P)
10424       Candidates.emplace_back(A, B1);
10425   }
10426   // Try to skip A.
10427   if (B && A && A->hasOneUse()) {
10428     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
10429     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
10430     if (A0 && A0->getParent() == P)
10431       Candidates.emplace_back(A0, B);
10432     if (A1 && A1->getParent() == P)
10433       Candidates.emplace_back(A1, B);
10434   }
10435 
10436   if (Candidates.size() == 1)
10437     return tryToVectorizePair(Op0, Op1, R);
10438 
10439   // We have multiple options. Try to pick the single best.
10440   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
10441   if (!BestCandidate)
10442     return false;
10443   return tryToVectorizePair(Candidates[*BestCandidate].first,
10444                             Candidates[*BestCandidate].second, R);
10445 }
10446 
10447 namespace {
10448 
10449 /// Model horizontal reductions.
10450 ///
10451 /// A horizontal reduction is a tree of reduction instructions that has values
10452 /// that can be put into a vector as its leaves. For example:
10453 ///
10454 /// mul mul mul mul
10455 ///  \  /    \  /
10456 ///   +       +
10457 ///    \     /
10458 ///       +
10459 /// This tree has "mul" as its leaf values and "+" as its reduction
10460 /// instructions. A reduction can feed into a store or a binary operation
10461 /// feeding a phi.
10462 ///    ...
10463 ///    \  /
10464 ///     +
10465 ///     |
10466 ///  phi +=
10467 ///
10468 ///  Or:
10469 ///    ...
10470 ///    \  /
10471 ///     +
10472 ///     |
10473 ///   *p =
10474 ///
10475 class HorizontalReduction {
10476   using ReductionOpsType = SmallVector<Value *, 16>;
10477   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
10478   ReductionOpsListType ReductionOps;
10479   /// List of possibly reduced values.
10480   SmallVector<SmallVector<Value *>> ReducedVals;
10481   /// Maps reduced value to the corresponding reduction operation.
10482   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
10483   // Use map vector to make stable output.
10484   MapVector<Instruction *, Value *> ExtraArgs;
10485   WeakTrackingVH ReductionRoot;
10486   /// The type of reduction operation.
10487   RecurKind RdxKind;
10488 
10489   static bool isCmpSelMinMax(Instruction *I) {
10490     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
10491            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
10492   }
10493 
10494   // And/or are potentially poison-safe logical patterns like:
10495   // select x, y, false
10496   // select x, true, y
10497   static bool isBoolLogicOp(Instruction *I) {
10498     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
10499            match(I, m_LogicalOr(m_Value(), m_Value()));
10500   }
10501 
10502   /// Checks if instruction is associative and can be vectorized.
10503   static bool isVectorizable(RecurKind Kind, Instruction *I) {
10504     if (Kind == RecurKind::None)
10505       return false;
10506 
10507     // Integer ops that map to select instructions or intrinsics are fine.
10508     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
10509         isBoolLogicOp(I))
10510       return true;
10511 
10512     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
10513       // FP min/max are associative except for NaN and -0.0. We do not
10514       // have to rule out -0.0 here because the intrinsic semantics do not
10515       // specify a fixed result for it.
10516       return I->getFastMathFlags().noNaNs();
10517     }
10518 
10519     return I->isAssociative();
10520   }
10521 
10522   static Value *getRdxOperand(Instruction *I, unsigned Index) {
10523     // Poison-safe 'or' takes the form: select X, true, Y
10524     // To make that work with the normal operand processing, we skip the
10525     // true value operand.
10526     // TODO: Change the code and data structures to handle this without a hack.
10527     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
10528       return I->getOperand(2);
10529     return I->getOperand(Index);
10530   }
10531 
10532   /// Creates reduction operation with the current opcode.
10533   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
10534                          Value *RHS, const Twine &Name, bool UseSelect) {
10535     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
10536     switch (Kind) {
10537     case RecurKind::Or:
10538       if (UseSelect &&
10539           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10540         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
10541       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10542                                  Name);
10543     case RecurKind::And:
10544       if (UseSelect &&
10545           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10546         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
10547       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10548                                  Name);
10549     case RecurKind::Add:
10550     case RecurKind::Mul:
10551     case RecurKind::Xor:
10552     case RecurKind::FAdd:
10553     case RecurKind::FMul:
10554       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10555                                  Name);
10556     case RecurKind::FMax:
10557       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
10558     case RecurKind::FMin:
10559       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
10560     case RecurKind::SMax:
10561       if (UseSelect) {
10562         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
10563         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10564       }
10565       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
10566     case RecurKind::SMin:
10567       if (UseSelect) {
10568         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
10569         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10570       }
10571       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
10572     case RecurKind::UMax:
10573       if (UseSelect) {
10574         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
10575         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10576       }
10577       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
10578     case RecurKind::UMin:
10579       if (UseSelect) {
10580         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
10581         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10582       }
10583       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
10584     default:
10585       llvm_unreachable("Unknown reduction operation.");
10586     }
10587   }
10588 
10589   /// Creates reduction operation with the current opcode with the IR flags
10590   /// from \p ReductionOps, dropping nuw/nsw flags.
10591   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
10592                          Value *RHS, const Twine &Name,
10593                          const ReductionOpsListType &ReductionOps) {
10594     bool UseSelect = ReductionOps.size() == 2 ||
10595                      // Logical or/and.
10596                      (ReductionOps.size() == 1 &&
10597                       isa<SelectInst>(ReductionOps.front().front()));
10598     assert((!UseSelect || ReductionOps.size() != 2 ||
10599             isa<SelectInst>(ReductionOps[1][0])) &&
10600            "Expected cmp + select pairs for reduction");
10601     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
10602     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10603       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
10604         propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr,
10605                          /*IncludeWrapFlags=*/false);
10606         propagateIRFlags(Op, ReductionOps[1], nullptr,
10607                          /*IncludeWrapFlags=*/false);
10608         return Op;
10609       }
10610     }
10611     propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false);
10612     return Op;
10613   }
10614 
10615   static RecurKind getRdxKind(Value *V) {
10616     auto *I = dyn_cast<Instruction>(V);
10617     if (!I)
10618       return RecurKind::None;
10619     if (match(I, m_Add(m_Value(), m_Value())))
10620       return RecurKind::Add;
10621     if (match(I, m_Mul(m_Value(), m_Value())))
10622       return RecurKind::Mul;
10623     if (match(I, m_And(m_Value(), m_Value())) ||
10624         match(I, m_LogicalAnd(m_Value(), m_Value())))
10625       return RecurKind::And;
10626     if (match(I, m_Or(m_Value(), m_Value())) ||
10627         match(I, m_LogicalOr(m_Value(), m_Value())))
10628       return RecurKind::Or;
10629     if (match(I, m_Xor(m_Value(), m_Value())))
10630       return RecurKind::Xor;
10631     if (match(I, m_FAdd(m_Value(), m_Value())))
10632       return RecurKind::FAdd;
10633     if (match(I, m_FMul(m_Value(), m_Value())))
10634       return RecurKind::FMul;
10635 
10636     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
10637       return RecurKind::FMax;
10638     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
10639       return RecurKind::FMin;
10640 
10641     // This matches either cmp+select or intrinsics. SLP is expected to handle
10642     // either form.
10643     // TODO: If we are canonicalizing to intrinsics, we can remove several
10644     //       special-case paths that deal with selects.
10645     if (match(I, m_SMax(m_Value(), m_Value())))
10646       return RecurKind::SMax;
10647     if (match(I, m_SMin(m_Value(), m_Value())))
10648       return RecurKind::SMin;
10649     if (match(I, m_UMax(m_Value(), m_Value())))
10650       return RecurKind::UMax;
10651     if (match(I, m_UMin(m_Value(), m_Value())))
10652       return RecurKind::UMin;
10653 
10654     if (auto *Select = dyn_cast<SelectInst>(I)) {
10655       // Try harder: look for min/max pattern based on instructions producing
10656       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10657       // During the intermediate stages of SLP, it's very common to have
10658       // pattern like this (since optimizeGatherSequence is run only once
10659       // at the end):
10660       // %1 = extractelement <2 x i32> %a, i32 0
10661       // %2 = extractelement <2 x i32> %a, i32 1
10662       // %cond = icmp sgt i32 %1, %2
10663       // %3 = extractelement <2 x i32> %a, i32 0
10664       // %4 = extractelement <2 x i32> %a, i32 1
10665       // %select = select i1 %cond, i32 %3, i32 %4
10666       CmpInst::Predicate Pred;
10667       Instruction *L1;
10668       Instruction *L2;
10669 
10670       Value *LHS = Select->getTrueValue();
10671       Value *RHS = Select->getFalseValue();
10672       Value *Cond = Select->getCondition();
10673 
10674       // TODO: Support inverse predicates.
10675       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10676         if (!isa<ExtractElementInst>(RHS) ||
10677             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10678           return RecurKind::None;
10679       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10680         if (!isa<ExtractElementInst>(LHS) ||
10681             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10682           return RecurKind::None;
10683       } else {
10684         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10685           return RecurKind::None;
10686         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10687             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10688             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10689           return RecurKind::None;
10690       }
10691 
10692       switch (Pred) {
10693       default:
10694         return RecurKind::None;
10695       case CmpInst::ICMP_SGT:
10696       case CmpInst::ICMP_SGE:
10697         return RecurKind::SMax;
10698       case CmpInst::ICMP_SLT:
10699       case CmpInst::ICMP_SLE:
10700         return RecurKind::SMin;
10701       case CmpInst::ICMP_UGT:
10702       case CmpInst::ICMP_UGE:
10703         return RecurKind::UMax;
10704       case CmpInst::ICMP_ULT:
10705       case CmpInst::ICMP_ULE:
10706         return RecurKind::UMin;
10707       }
10708     }
10709     return RecurKind::None;
10710   }
10711 
10712   /// Get the index of the first operand.
10713   static unsigned getFirstOperandIndex(Instruction *I) {
10714     return isCmpSelMinMax(I) ? 1 : 0;
10715   }
10716 
10717   /// Total number of operands in the reduction operation.
10718   static unsigned getNumberOfOperands(Instruction *I) {
10719     return isCmpSelMinMax(I) ? 3 : 2;
10720   }
10721 
10722   /// Checks if the instruction is in basic block \p BB.
10723   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10724   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10725     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10726       auto *Sel = cast<SelectInst>(I);
10727       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10728       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10729     }
10730     return I->getParent() == BB;
10731   }
10732 
10733   /// Expected number of uses for reduction operations/reduced values.
10734   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10735     if (IsCmpSelMinMax) {
10736       // SelectInst must be used twice while the condition op must have single
10737       // use only.
10738       if (auto *Sel = dyn_cast<SelectInst>(I))
10739         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10740       return I->hasNUses(2);
10741     }
10742 
10743     // Arithmetic reduction operation must be used once only.
10744     return I->hasOneUse();
10745   }
10746 
10747   /// Initializes the list of reduction operations.
10748   void initReductionOps(Instruction *I) {
10749     if (isCmpSelMinMax(I))
10750       ReductionOps.assign(2, ReductionOpsType());
10751     else
10752       ReductionOps.assign(1, ReductionOpsType());
10753   }
10754 
10755   /// Add all reduction operations for the reduction instruction \p I.
10756   void addReductionOps(Instruction *I) {
10757     if (isCmpSelMinMax(I)) {
10758       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10759       ReductionOps[1].emplace_back(I);
10760     } else {
10761       ReductionOps[0].emplace_back(I);
10762     }
10763   }
10764 
10765   static Value *getLHS(RecurKind Kind, Instruction *I) {
10766     if (Kind == RecurKind::None)
10767       return nullptr;
10768     return I->getOperand(getFirstOperandIndex(I));
10769   }
10770   static Value *getRHS(RecurKind Kind, Instruction *I) {
10771     if (Kind == RecurKind::None)
10772       return nullptr;
10773     return I->getOperand(getFirstOperandIndex(I) + 1);
10774   }
10775 
10776 public:
10777   HorizontalReduction() = default;
10778 
10779   /// Try to find a reduction tree.
10780   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10781                                  ScalarEvolution &SE, const DataLayout &DL,
10782                                  const TargetLibraryInfo &TLI) {
10783     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10784            "Phi needs to use the binary operator");
10785     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10786             isa<IntrinsicInst>(Inst)) &&
10787            "Expected binop, select, or intrinsic for reduction matching");
10788     RdxKind = getRdxKind(Inst);
10789 
10790     // We could have a initial reductions that is not an add.
10791     //  r *= v1 + v2 + v3 + v4
10792     // In such a case start looking for a tree rooted in the first '+'.
10793     if (Phi) {
10794       if (getLHS(RdxKind, Inst) == Phi) {
10795         Phi = nullptr;
10796         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10797         if (!Inst)
10798           return false;
10799         RdxKind = getRdxKind(Inst);
10800       } else if (getRHS(RdxKind, Inst) == Phi) {
10801         Phi = nullptr;
10802         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10803         if (!Inst)
10804           return false;
10805         RdxKind = getRdxKind(Inst);
10806       }
10807     }
10808 
10809     if (!isVectorizable(RdxKind, Inst))
10810       return false;
10811 
10812     // Analyze "regular" integer/FP types for reductions - no target-specific
10813     // types or pointers.
10814     Type *Ty = Inst->getType();
10815     if (!isValidElementType(Ty) || Ty->isPointerTy())
10816       return false;
10817 
10818     // Though the ultimate reduction may have multiple uses, its condition must
10819     // have only single use.
10820     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10821       if (!Sel->getCondition()->hasOneUse())
10822         return false;
10823 
10824     ReductionRoot = Inst;
10825 
10826     // Iterate through all the operands of the possible reduction tree and
10827     // gather all the reduced values, sorting them by their value id.
10828     BasicBlock *BB = Inst->getParent();
10829     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10830     SmallVector<Instruction *> Worklist(1, Inst);
10831     // Checks if the operands of the \p TreeN instruction are also reduction
10832     // operations or should be treated as reduced values or an extra argument,
10833     // which is not part of the reduction.
10834     auto &&CheckOperands = [this, IsCmpSelMinMax,
10835                             BB](Instruction *TreeN,
10836                                 SmallVectorImpl<Value *> &ExtraArgs,
10837                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10838                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10839       for (int I = getFirstOperandIndex(TreeN),
10840                End = getNumberOfOperands(TreeN);
10841            I < End; ++I) {
10842         Value *EdgeVal = getRdxOperand(TreeN, I);
10843         ReducedValsToOps[EdgeVal].push_back(TreeN);
10844         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10845         // Edge has wrong parent - mark as an extra argument.
10846         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10847             !hasSameParent(EdgeInst, BB)) {
10848           ExtraArgs.push_back(EdgeVal);
10849           continue;
10850         }
10851         // If the edge is not an instruction, or it is different from the main
10852         // reduction opcode or has too many uses - possible reduced value.
10853         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10854             IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
10855             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10856             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10857           PossibleReducedVals.push_back(EdgeVal);
10858           continue;
10859         }
10860         ReductionOps.push_back(EdgeInst);
10861       }
10862     };
10863     // Try to regroup reduced values so that it gets more profitable to try to
10864     // reduce them. Values are grouped by their value ids, instructions - by
10865     // instruction op id and/or alternate op id, plus do extra analysis for
10866     // loads (grouping them by the distabce between pointers) and cmp
10867     // instructions (grouping them by the predicate).
10868     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10869         PossibleReducedVals;
10870     initReductionOps(Inst);
10871     while (!Worklist.empty()) {
10872       Instruction *TreeN = Worklist.pop_back_val();
10873       SmallVector<Value *> Args;
10874       SmallVector<Value *> PossibleRedVals;
10875       SmallVector<Instruction *> PossibleReductionOps;
10876       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10877       // If too many extra args - mark the instruction itself as a reduction
10878       // value, not a reduction operation.
10879       if (Args.size() < 2) {
10880         addReductionOps(TreeN);
10881         // Add extra args.
10882         if (!Args.empty()) {
10883           assert(Args.size() == 1 && "Expected only single argument.");
10884           ExtraArgs[TreeN] = Args.front();
10885         }
10886         // Add reduction values. The values are sorted for better vectorization
10887         // results.
10888         for (Value *V : PossibleRedVals) {
10889           size_t Key, Idx;
10890           std::tie(Key, Idx) = generateKeySubkey(
10891               V, &TLI,
10892               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10893                 auto It = PossibleReducedVals.find(Key);
10894                 if (It != PossibleReducedVals.end()) {
10895                   for (const auto &LoadData : It->second) {
10896                     auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10897                     if (getPointersDiff(RLI->getType(),
10898                                         RLI->getPointerOperand(), LI->getType(),
10899                                         LI->getPointerOperand(), DL, SE,
10900                                         /*StrictCheck=*/true))
10901                       return hash_value(RLI->getPointerOperand());
10902                   }
10903                 }
10904                 return hash_value(LI->getPointerOperand());
10905               },
10906               /*AllowAlternate=*/false);
10907           ++PossibleReducedVals[Key][Idx]
10908                 .insert(std::make_pair(V, 0))
10909                 .first->second;
10910         }
10911         Worklist.append(PossibleReductionOps.rbegin(),
10912                         PossibleReductionOps.rend());
10913       } else {
10914         size_t Key, Idx;
10915         std::tie(Key, Idx) = generateKeySubkey(
10916             TreeN, &TLI,
10917             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10918               auto It = PossibleReducedVals.find(Key);
10919               if (It != PossibleReducedVals.end()) {
10920                 for (const auto &LoadData : It->second) {
10921                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10922                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10923                                       LI->getType(), LI->getPointerOperand(),
10924                                       DL, SE, /*StrictCheck=*/true))
10925                     return hash_value(RLI->getPointerOperand());
10926                 }
10927               }
10928               return hash_value(LI->getPointerOperand());
10929             },
10930             /*AllowAlternate=*/false);
10931         ++PossibleReducedVals[Key][Idx]
10932               .insert(std::make_pair(TreeN, 0))
10933               .first->second;
10934       }
10935     }
10936     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10937     // Sort values by the total number of values kinds to start the reduction
10938     // from the longest possible reduced values sequences.
10939     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10940       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10941       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10942       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10943            It != E; ++It) {
10944         PossibleRedValsVect.emplace_back();
10945         auto RedValsVect = It->second.takeVector();
10946         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10947           return P1.second < P2.second;
10948         });
10949         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10950           PossibleRedValsVect.back().append(Data.second, Data.first);
10951       }
10952       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10953         return P1.size() > P2.size();
10954       });
10955       ReducedVals.emplace_back();
10956       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10957         ReducedVals.back().append(Data.rbegin(), Data.rend());
10958     }
10959     // Sort the reduced values by number of same/alternate opcode and/or pointer
10960     // operand.
10961     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10962       return P1.size() > P2.size();
10963     });
10964     return true;
10965   }
10966 
10967   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10968   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10969     constexpr int ReductionLimit = 4;
10970     constexpr unsigned RegMaxNumber = 4;
10971     constexpr unsigned RedValsMaxNumber = 128;
10972     // If there are a sufficient number of reduction values, reduce
10973     // to a nearby power-of-2. We can safely generate oversized
10974     // vectors and rely on the backend to split them to legal sizes.
10975     unsigned NumReducedVals = std::accumulate(
10976         ReducedVals.begin(), ReducedVals.end(), 0,
10977         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10978     if (NumReducedVals < ReductionLimit)
10979       return nullptr;
10980 
10981     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10982 
10983     // Track the reduced values in case if they are replaced by extractelement
10984     // because of the vectorization.
10985     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10986     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10987     // The same extra argument may be used several times, so log each attempt
10988     // to use it.
10989     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10990       assert(Pair.first && "DebugLoc must be set.");
10991       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10992       TrackedVals.try_emplace(Pair.second, Pair.second);
10993     }
10994 
10995     // The compare instruction of a min/max is the insertion point for new
10996     // instructions and may be replaced with a new compare instruction.
10997     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10998       assert(isa<SelectInst>(RdxRootInst) &&
10999              "Expected min/max reduction to have select root instruction");
11000       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
11001       assert(isa<Instruction>(ScalarCond) &&
11002              "Expected min/max reduction to have compare condition");
11003       return cast<Instruction>(ScalarCond);
11004     };
11005 
11006     // The reduction root is used as the insertion point for new instructions,
11007     // so set it as externally used to prevent it from being deleted.
11008     ExternallyUsedValues[ReductionRoot];
11009     SmallDenseSet<Value *> IgnoreList;
11010     for (ReductionOpsType &RdxOps : ReductionOps)
11011       for (Value *RdxOp : RdxOps) {
11012         if (!RdxOp)
11013           continue;
11014         IgnoreList.insert(RdxOp);
11015       }
11016     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
11017 
11018     // Need to track reduced vals, they may be changed during vectorization of
11019     // subvectors.
11020     for (ArrayRef<Value *> Candidates : ReducedVals)
11021       for (Value *V : Candidates)
11022         TrackedVals.try_emplace(V, V);
11023 
11024     DenseMap<Value *, unsigned> VectorizedVals;
11025     Value *VectorizedTree = nullptr;
11026     bool CheckForReusedReductionOps = false;
11027     // Try to vectorize elements based on their type.
11028     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
11029       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
11030       InstructionsState S = getSameOpcode(OrigReducedVals);
11031       SmallVector<Value *> Candidates;
11032       DenseMap<Value *, Value *> TrackedToOrig;
11033       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
11034         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
11035         // Check if the reduction value was not overriden by the extractelement
11036         // instruction because of the vectorization and exclude it, if it is not
11037         // compatible with other values.
11038         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
11039           if (isVectorLikeInstWithConstOps(Inst) &&
11040               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
11041             continue;
11042         Candidates.push_back(RdxVal);
11043         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
11044       }
11045       bool ShuffledExtracts = false;
11046       // Try to handle shuffled extractelements.
11047       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
11048           I + 1 < E) {
11049         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
11050         if (NextS.getOpcode() == Instruction::ExtractElement &&
11051             !NextS.isAltShuffle()) {
11052           SmallVector<Value *> CommonCandidates(Candidates);
11053           for (Value *RV : ReducedVals[I + 1]) {
11054             Value *RdxVal = TrackedVals.find(RV)->second;
11055             // Check if the reduction value was not overriden by the
11056             // extractelement instruction because of the vectorization and
11057             // exclude it, if it is not compatible with other values.
11058             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
11059               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
11060                 continue;
11061             CommonCandidates.push_back(RdxVal);
11062             TrackedToOrig.try_emplace(RdxVal, RV);
11063           }
11064           SmallVector<int> Mask;
11065           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
11066             ++I;
11067             Candidates.swap(CommonCandidates);
11068             ShuffledExtracts = true;
11069           }
11070         }
11071       }
11072       unsigned NumReducedVals = Candidates.size();
11073       if (NumReducedVals < ReductionLimit)
11074         continue;
11075 
11076       unsigned MaxVecRegSize = V.getMaxVecRegSize();
11077       unsigned EltSize = V.getVectorElementSize(Candidates[0]);
11078       unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize);
11079 
11080       unsigned ReduxWidth = std::min<unsigned>(
11081           PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts));
11082       unsigned Start = 0;
11083       unsigned Pos = Start;
11084       // Restarts vectorization attempt with lower vector factor.
11085       unsigned PrevReduxWidth = ReduxWidth;
11086       bool CheckForReusedReductionOpsLocal = false;
11087       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
11088                                   &CheckForReusedReductionOpsLocal,
11089                                   &PrevReduxWidth, &V,
11090                                   &IgnoreList](bool IgnoreVL = false) {
11091         bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList);
11092         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
11093           // Check if any of the reduction ops are gathered. If so, worth
11094           // trying again with less number of reduction ops.
11095           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
11096         }
11097         ++Pos;
11098         if (Pos < NumReducedVals - ReduxWidth + 1)
11099           return IsAnyRedOpGathered;
11100         Pos = Start;
11101         ReduxWidth /= 2;
11102         return IsAnyRedOpGathered;
11103       };
11104       while (Pos < NumReducedVals - ReduxWidth + 1 &&
11105              ReduxWidth >= ReductionLimit) {
11106         // Dependency in tree of the reduction ops - drop this attempt, try
11107         // later.
11108         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
11109             Start == 0) {
11110           CheckForReusedReductionOps = true;
11111           break;
11112         }
11113         PrevReduxWidth = ReduxWidth;
11114         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
11115         // Beeing analyzed already - skip.
11116         if (V.areAnalyzedReductionVals(VL)) {
11117           (void)AdjustReducedVals(/*IgnoreVL=*/true);
11118           continue;
11119         }
11120         // Early exit if any of the reduction values were deleted during
11121         // previous vectorization attempts.
11122         if (any_of(VL, [&V](Value *RedVal) {
11123               auto *RedValI = dyn_cast<Instruction>(RedVal);
11124               if (!RedValI)
11125                 return false;
11126               return V.isDeleted(RedValI);
11127             }))
11128           break;
11129         V.buildTree(VL, IgnoreList);
11130         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
11131           if (!AdjustReducedVals())
11132             V.analyzedReductionVals(VL);
11133           continue;
11134         }
11135         if (V.isLoadCombineReductionCandidate(RdxKind)) {
11136           if (!AdjustReducedVals())
11137             V.analyzedReductionVals(VL);
11138           continue;
11139         }
11140         V.reorderTopToBottom();
11141         // No need to reorder the root node at all.
11142         V.reorderBottomToTop(/*IgnoreReorder=*/true);
11143         // Keep extracted other reduction values, if they are used in the
11144         // vectorization trees.
11145         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
11146             ExternallyUsedValues);
11147         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
11148           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
11149             continue;
11150           for_each(ReducedVals[Cnt],
11151                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
11152                      if (isa<Instruction>(V))
11153                        LocalExternallyUsedValues[TrackedVals[V]];
11154                    });
11155         }
11156         // Number of uses of the candidates in the vector of values.
11157         SmallDenseMap<Value *, unsigned> NumUses;
11158         for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
11159           Value *V = Candidates[Cnt];
11160           if (NumUses.count(V) > 0)
11161             continue;
11162           NumUses[V] = std::count(VL.begin(), VL.end(), V);
11163         }
11164         for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
11165           Value *V = Candidates[Cnt];
11166           if (NumUses.count(V) > 0)
11167             continue;
11168           NumUses[V] = std::count(VL.begin(), VL.end(), V);
11169         }
11170         // Gather externally used values.
11171         SmallPtrSet<Value *, 4> Visited;
11172         for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
11173           Value *V = Candidates[Cnt];
11174           if (!Visited.insert(V).second)
11175             continue;
11176           unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V];
11177           if (NumOps != ReducedValsToOps.find(V)->second.size())
11178             LocalExternallyUsedValues[V];
11179         }
11180         for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
11181           Value *V = Candidates[Cnt];
11182           if (!Visited.insert(V).second)
11183             continue;
11184           unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V];
11185           if (NumOps != ReducedValsToOps.find(V)->second.size())
11186             LocalExternallyUsedValues[V];
11187         }
11188         V.buildExternalUses(LocalExternallyUsedValues);
11189 
11190         V.computeMinimumValueSizes();
11191 
11192         // Intersect the fast-math-flags from all reduction operations.
11193         FastMathFlags RdxFMF;
11194         RdxFMF.set();
11195         for (Value *U : IgnoreList)
11196           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
11197             RdxFMF &= FPMO->getFastMathFlags();
11198         // Estimate cost.
11199         InstructionCost TreeCost = V.getTreeCost(VL);
11200         InstructionCost ReductionCost =
11201             getReductionCost(TTI, VL, ReduxWidth, RdxFMF);
11202         InstructionCost Cost = TreeCost + ReductionCost;
11203         if (!Cost.isValid()) {
11204           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
11205           return nullptr;
11206         }
11207         if (Cost >= -SLPCostThreshold) {
11208           V.getORE()->emit([&]() {
11209             return OptimizationRemarkMissed(
11210                        SV_NAME, "HorSLPNotBeneficial",
11211                        ReducedValsToOps.find(VL[0])->second.front())
11212                    << "Vectorizing horizontal reduction is possible"
11213                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
11214                    << " and threshold "
11215                    << ore::NV("Threshold", -SLPCostThreshold);
11216           });
11217           if (!AdjustReducedVals())
11218             V.analyzedReductionVals(VL);
11219           continue;
11220         }
11221 
11222         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
11223                           << Cost << ". (HorRdx)\n");
11224         V.getORE()->emit([&]() {
11225           return OptimizationRemark(
11226                      SV_NAME, "VectorizedHorizontalReduction",
11227                      ReducedValsToOps.find(VL[0])->second.front())
11228                  << "Vectorized horizontal reduction with cost "
11229                  << ore::NV("Cost", Cost) << " and with tree size "
11230                  << ore::NV("TreeSize", V.getTreeSize());
11231         });
11232 
11233         Builder.setFastMathFlags(RdxFMF);
11234 
11235         // Vectorize a tree.
11236         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
11237 
11238         // Emit a reduction. If the root is a select (min/max idiom), the insert
11239         // point is the compare condition of that select.
11240         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
11241         if (IsCmpSelMinMax)
11242           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
11243         else
11244           Builder.SetInsertPoint(RdxRootInst);
11245 
11246         // To prevent poison from leaking across what used to be sequential,
11247         // safe, scalar boolean logic operations, the reduction operand must be
11248         // frozen.
11249         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
11250           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
11251 
11252         Value *ReducedSubTree =
11253             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
11254 
11255         if (!VectorizedTree) {
11256           // Initialize the final value in the reduction.
11257           VectorizedTree = ReducedSubTree;
11258         } else {
11259           // Update the final value in the reduction.
11260           Builder.SetCurrentDebugLocation(
11261               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
11262           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
11263                                     ReducedSubTree, "op.rdx", ReductionOps);
11264         }
11265         // Count vectorized reduced values to exclude them from final reduction.
11266         for (Value *V : VL)
11267           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
11268                 .first->getSecond();
11269         Pos += ReduxWidth;
11270         Start = Pos;
11271         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
11272       }
11273     }
11274     if (VectorizedTree) {
11275       // Finish the reduction.
11276       // Need to add extra arguments and not vectorized possible reduction
11277       // values.
11278       // Try to avoid dependencies between the scalar remainders after
11279       // reductions.
11280       auto &&FinalGen =
11281           [this, &Builder,
11282            &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
11283             unsigned Sz = InstVals.size();
11284             SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
11285                                                                      Sz % 2);
11286             for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
11287               Instruction *RedOp = InstVals[I + 1].first;
11288               Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
11289               Value *RdxVal1 = InstVals[I].second;
11290               Value *StableRdxVal1 = RdxVal1;
11291               auto It1 = TrackedVals.find(RdxVal1);
11292               if (It1 != TrackedVals.end())
11293                 StableRdxVal1 = It1->second;
11294               Value *RdxVal2 = InstVals[I + 1].second;
11295               Value *StableRdxVal2 = RdxVal2;
11296               auto It2 = TrackedVals.find(RdxVal2);
11297               if (It2 != TrackedVals.end())
11298                 StableRdxVal2 = It2->second;
11299               Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
11300                                          StableRdxVal2, "op.rdx", ReductionOps);
11301               ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
11302             }
11303             if (Sz % 2 == 1)
11304               ExtraReds[Sz / 2] = InstVals.back();
11305             return ExtraReds;
11306           };
11307       SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
11308       SmallPtrSet<Value *, 8> Visited;
11309       for (ArrayRef<Value *> Candidates : ReducedVals) {
11310         for (Value *RdxVal : Candidates) {
11311           if (!Visited.insert(RdxVal).second)
11312             continue;
11313           unsigned NumOps = VectorizedVals.lookup(RdxVal);
11314           for (Instruction *RedOp :
11315                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
11316                    .drop_back(NumOps))
11317             ExtraReductions.emplace_back(RedOp, RdxVal);
11318         }
11319       }
11320       for (auto &Pair : ExternallyUsedValues) {
11321         // Add each externally used value to the final reduction.
11322         for (auto *I : Pair.second)
11323           ExtraReductions.emplace_back(I, Pair.first);
11324       }
11325       // Iterate through all not-vectorized reduction values/extra arguments.
11326       while (ExtraReductions.size() > 1) {
11327         SmallVector<std::pair<Instruction *, Value *>> NewReds =
11328             FinalGen(ExtraReductions);
11329         ExtraReductions.swap(NewReds);
11330       }
11331       // Final reduction.
11332       if (ExtraReductions.size() == 1) {
11333         Instruction *RedOp = ExtraReductions.back().first;
11334         Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
11335         Value *RdxVal = ExtraReductions.back().second;
11336         Value *StableRdxVal = RdxVal;
11337         auto It = TrackedVals.find(RdxVal);
11338         if (It != TrackedVals.end())
11339           StableRdxVal = It->second;
11340         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
11341                                   StableRdxVal, "op.rdx", ReductionOps);
11342       }
11343 
11344       ReductionRoot->replaceAllUsesWith(VectorizedTree);
11345 
11346       // The original scalar reduction is expected to have no remaining
11347       // uses outside the reduction tree itself.  Assert that we got this
11348       // correct, replace internal uses with undef, and mark for eventual
11349       // deletion.
11350 #ifndef NDEBUG
11351       SmallSet<Value *, 4> IgnoreSet;
11352       for (ArrayRef<Value *> RdxOps : ReductionOps)
11353         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
11354 #endif
11355       for (ArrayRef<Value *> RdxOps : ReductionOps) {
11356         for (Value *Ignore : RdxOps) {
11357           if (!Ignore)
11358             continue;
11359 #ifndef NDEBUG
11360           for (auto *U : Ignore->users()) {
11361             assert(IgnoreSet.count(U) &&
11362                    "All users must be either in the reduction ops list.");
11363           }
11364 #endif
11365           if (!Ignore->use_empty()) {
11366             Value *Undef = UndefValue::get(Ignore->getType());
11367             Ignore->replaceAllUsesWith(Undef);
11368           }
11369           V.eraseInstruction(cast<Instruction>(Ignore));
11370         }
11371       }
11372     } else if (!CheckForReusedReductionOps) {
11373       for (ReductionOpsType &RdxOps : ReductionOps)
11374         for (Value *RdxOp : RdxOps)
11375           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
11376     }
11377     return VectorizedTree;
11378   }
11379 
11380 private:
11381   /// Calculate the cost of a reduction.
11382   InstructionCost getReductionCost(TargetTransformInfo *TTI,
11383                                    ArrayRef<Value *> ReducedVals,
11384                                    unsigned ReduxWidth, FastMathFlags FMF) {
11385     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
11386     Value *FirstReducedVal = ReducedVals.front();
11387     Type *ScalarTy = FirstReducedVal->getType();
11388     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
11389     InstructionCost VectorCost = 0, ScalarCost;
11390     // If all of the reduced values are constant, the vector cost is 0, since
11391     // the reduction value can be calculated at the compile time.
11392     bool AllConsts = all_of(ReducedVals, isConstant);
11393     switch (RdxKind) {
11394     case RecurKind::Add:
11395     case RecurKind::Mul:
11396     case RecurKind::Or:
11397     case RecurKind::And:
11398     case RecurKind::Xor:
11399     case RecurKind::FAdd:
11400     case RecurKind::FMul: {
11401       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
11402       if (!AllConsts)
11403         VectorCost =
11404             TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
11405       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
11406       break;
11407     }
11408     case RecurKind::FMax:
11409     case RecurKind::FMin: {
11410       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11411       if (!AllConsts) {
11412         auto *VecCondTy =
11413             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11414         VectorCost =
11415             TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11416                                         /*IsUnsigned=*/false, CostKind);
11417       }
11418       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11419       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
11420                                            SclCondTy, RdxPred, CostKind) +
11421                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11422                                            SclCondTy, RdxPred, CostKind);
11423       break;
11424     }
11425     case RecurKind::SMax:
11426     case RecurKind::SMin:
11427     case RecurKind::UMax:
11428     case RecurKind::UMin: {
11429       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11430       if (!AllConsts) {
11431         auto *VecCondTy =
11432             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11433         bool IsUnsigned =
11434             RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
11435         VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11436                                                  IsUnsigned, CostKind);
11437       }
11438       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11439       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
11440                                            SclCondTy, RdxPred, CostKind) +
11441                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11442                                            SclCondTy, RdxPred, CostKind);
11443       break;
11444     }
11445     default:
11446       llvm_unreachable("Expected arithmetic or min/max reduction operation");
11447     }
11448 
11449     // Scalar cost is repeated for N-1 elements.
11450     ScalarCost *= (ReduxWidth - 1);
11451     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
11452                       << " for reduction that starts with " << *FirstReducedVal
11453                       << " (It is a splitting reduction)\n");
11454     return VectorCost - ScalarCost;
11455   }
11456 
11457   /// Emit a horizontal reduction of the vectorized value.
11458   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
11459                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
11460     assert(VectorizedValue && "Need to have a vectorized tree node");
11461     assert(isPowerOf2_32(ReduxWidth) &&
11462            "We only handle power-of-two reductions for now");
11463     assert(RdxKind != RecurKind::FMulAdd &&
11464            "A call to the llvm.fmuladd intrinsic is not handled yet");
11465 
11466     ++NumVectorInstructions;
11467     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
11468   }
11469 };
11470 
11471 } // end anonymous namespace
11472 
11473 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
11474   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
11475     return cast<FixedVectorType>(IE->getType())->getNumElements();
11476 
11477   unsigned AggregateSize = 1;
11478   auto *IV = cast<InsertValueInst>(InsertInst);
11479   Type *CurrentType = IV->getType();
11480   do {
11481     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
11482       for (auto *Elt : ST->elements())
11483         if (Elt != ST->getElementType(0)) // check homogeneity
11484           return None;
11485       AggregateSize *= ST->getNumElements();
11486       CurrentType = ST->getElementType(0);
11487     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
11488       AggregateSize *= AT->getNumElements();
11489       CurrentType = AT->getElementType();
11490     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
11491       AggregateSize *= VT->getNumElements();
11492       return AggregateSize;
11493     } else if (CurrentType->isSingleValueType()) {
11494       return AggregateSize;
11495     } else {
11496       return None;
11497     }
11498   } while (true);
11499 }
11500 
11501 static void findBuildAggregate_rec(Instruction *LastInsertInst,
11502                                    TargetTransformInfo *TTI,
11503                                    SmallVectorImpl<Value *> &BuildVectorOpds,
11504                                    SmallVectorImpl<Value *> &InsertElts,
11505                                    unsigned OperandOffset) {
11506   do {
11507     Value *InsertedOperand = LastInsertInst->getOperand(1);
11508     Optional<unsigned> OperandIndex =
11509         getInsertIndex(LastInsertInst, OperandOffset);
11510     if (!OperandIndex)
11511       return;
11512     if (isa<InsertElementInst>(InsertedOperand) ||
11513         isa<InsertValueInst>(InsertedOperand)) {
11514       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
11515                              BuildVectorOpds, InsertElts, *OperandIndex);
11516 
11517     } else {
11518       BuildVectorOpds[*OperandIndex] = InsertedOperand;
11519       InsertElts[*OperandIndex] = LastInsertInst;
11520     }
11521     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
11522   } while (LastInsertInst != nullptr &&
11523            (isa<InsertValueInst>(LastInsertInst) ||
11524             isa<InsertElementInst>(LastInsertInst)) &&
11525            LastInsertInst->hasOneUse());
11526 }
11527 
11528 /// Recognize construction of vectors like
11529 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
11530 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
11531 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
11532 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
11533 ///  starting from the last insertelement or insertvalue instruction.
11534 ///
11535 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
11536 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
11537 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
11538 ///
11539 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
11540 ///
11541 /// \return true if it matches.
11542 static bool findBuildAggregate(Instruction *LastInsertInst,
11543                                TargetTransformInfo *TTI,
11544                                SmallVectorImpl<Value *> &BuildVectorOpds,
11545                                SmallVectorImpl<Value *> &InsertElts) {
11546 
11547   assert((isa<InsertElementInst>(LastInsertInst) ||
11548           isa<InsertValueInst>(LastInsertInst)) &&
11549          "Expected insertelement or insertvalue instruction!");
11550 
11551   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
11552          "Expected empty result vectors!");
11553 
11554   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
11555   if (!AggregateSize)
11556     return false;
11557   BuildVectorOpds.resize(*AggregateSize);
11558   InsertElts.resize(*AggregateSize);
11559 
11560   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
11561   llvm::erase_value(BuildVectorOpds, nullptr);
11562   llvm::erase_value(InsertElts, nullptr);
11563   if (BuildVectorOpds.size() >= 2)
11564     return true;
11565 
11566   return false;
11567 }
11568 
11569 /// Try and get a reduction value from a phi node.
11570 ///
11571 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
11572 /// if they come from either \p ParentBB or a containing loop latch.
11573 ///
11574 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
11575 /// if not possible.
11576 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
11577                                 BasicBlock *ParentBB, LoopInfo *LI) {
11578   // There are situations where the reduction value is not dominated by the
11579   // reduction phi. Vectorizing such cases has been reported to cause
11580   // miscompiles. See PR25787.
11581   auto DominatedReduxValue = [&](Value *R) {
11582     return isa<Instruction>(R) &&
11583            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
11584   };
11585 
11586   Value *Rdx = nullptr;
11587 
11588   // Return the incoming value if it comes from the same BB as the phi node.
11589   if (P->getIncomingBlock(0) == ParentBB) {
11590     Rdx = P->getIncomingValue(0);
11591   } else if (P->getIncomingBlock(1) == ParentBB) {
11592     Rdx = P->getIncomingValue(1);
11593   }
11594 
11595   if (Rdx && DominatedReduxValue(Rdx))
11596     return Rdx;
11597 
11598   // Otherwise, check whether we have a loop latch to look at.
11599   Loop *BBL = LI->getLoopFor(ParentBB);
11600   if (!BBL)
11601     return nullptr;
11602   BasicBlock *BBLatch = BBL->getLoopLatch();
11603   if (!BBLatch)
11604     return nullptr;
11605 
11606   // There is a loop latch, return the incoming value if it comes from
11607   // that. This reduction pattern occasionally turns up.
11608   if (P->getIncomingBlock(0) == BBLatch) {
11609     Rdx = P->getIncomingValue(0);
11610   } else if (P->getIncomingBlock(1) == BBLatch) {
11611     Rdx = P->getIncomingValue(1);
11612   }
11613 
11614   if (Rdx && DominatedReduxValue(Rdx))
11615     return Rdx;
11616 
11617   return nullptr;
11618 }
11619 
11620 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
11621   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
11622     return true;
11623   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
11624     return true;
11625   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
11626     return true;
11627   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
11628     return true;
11629   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
11630     return true;
11631   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
11632     return true;
11633   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
11634     return true;
11635   return false;
11636 }
11637 
11638 /// Attempt to reduce a horizontal reduction.
11639 /// If it is legal to match a horizontal reduction feeding the phi node \a P
11640 /// with reduction operators \a Root (or one of its operands) in a basic block
11641 /// \a BB, then check if it can be done. If horizontal reduction is not found
11642 /// and root instruction is a binary operation, vectorization of the operands is
11643 /// attempted.
11644 /// \returns true if a horizontal reduction was matched and reduced or operands
11645 /// of one of the binary instruction were vectorized.
11646 /// \returns false if a horizontal reduction was not matched (or not possible)
11647 /// or no vectorization of any binary operation feeding \a Root instruction was
11648 /// performed.
11649 static bool tryToVectorizeHorReductionOrInstOperands(
11650     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
11651     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
11652     const TargetLibraryInfo &TLI,
11653     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
11654   if (!ShouldVectorizeHor)
11655     return false;
11656 
11657   if (!Root)
11658     return false;
11659 
11660   if (Root->getParent() != BB || isa<PHINode>(Root))
11661     return false;
11662   // Start analysis starting from Root instruction. If horizontal reduction is
11663   // found, try to vectorize it. If it is not a horizontal reduction or
11664   // vectorization is not possible or not effective, and currently analyzed
11665   // instruction is a binary operation, try to vectorize the operands, using
11666   // pre-order DFS traversal order. If the operands were not vectorized, repeat
11667   // the same procedure considering each operand as a possible root of the
11668   // horizontal reduction.
11669   // Interrupt the process if the Root instruction itself was vectorized or all
11670   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
11671   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
11672   // CmpInsts so we can skip extra attempts in
11673   // tryToVectorizeHorReductionOrInstOperands and save compile time.
11674   std::queue<std::pair<Instruction *, unsigned>> Stack;
11675   Stack.emplace(Root, 0);
11676   SmallPtrSet<Value *, 8> VisitedInstrs;
11677   SmallVector<WeakTrackingVH> PostponedInsts;
11678   bool Res = false;
11679   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
11680                                                      Value *&B0,
11681                                                      Value *&B1) -> Value * {
11682     if (R.isAnalyzedReductionRoot(Inst))
11683       return nullptr;
11684     bool IsBinop = matchRdxBop(Inst, B0, B1);
11685     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
11686     if (IsBinop || IsSelect) {
11687       HorizontalReduction HorRdx;
11688       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
11689         return HorRdx.tryToReduce(R, TTI);
11690     }
11691     return nullptr;
11692   };
11693   while (!Stack.empty()) {
11694     Instruction *Inst;
11695     unsigned Level;
11696     std::tie(Inst, Level) = Stack.front();
11697     Stack.pop();
11698     // Do not try to analyze instruction that has already been vectorized.
11699     // This may happen when we vectorize instruction operands on a previous
11700     // iteration while stack was populated before that happened.
11701     if (R.isDeleted(Inst))
11702       continue;
11703     Value *B0 = nullptr, *B1 = nullptr;
11704     if (Value *V = TryToReduce(Inst, B0, B1)) {
11705       Res = true;
11706       // Set P to nullptr to avoid re-analysis of phi node in
11707       // matchAssociativeReduction function unless this is the root node.
11708       P = nullptr;
11709       if (auto *I = dyn_cast<Instruction>(V)) {
11710         // Try to find another reduction.
11711         Stack.emplace(I, Level);
11712         continue;
11713       }
11714     } else {
11715       bool IsBinop = B0 && B1;
11716       if (P && IsBinop) {
11717         Inst = dyn_cast<Instruction>(B0);
11718         if (Inst == P)
11719           Inst = dyn_cast<Instruction>(B1);
11720         if (!Inst) {
11721           // Set P to nullptr to avoid re-analysis of phi node in
11722           // matchAssociativeReduction function unless this is the root node.
11723           P = nullptr;
11724           continue;
11725         }
11726       }
11727       // Set P to nullptr to avoid re-analysis of phi node in
11728       // matchAssociativeReduction function unless this is the root node.
11729       P = nullptr;
11730       // Do not try to vectorize CmpInst operands, this is done separately.
11731       // Final attempt for binop args vectorization should happen after the loop
11732       // to try to find reductions.
11733       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11734         PostponedInsts.push_back(Inst);
11735     }
11736 
11737     // Try to vectorize operands.
11738     // Continue analysis for the instruction from the same basic block only to
11739     // save compile time.
11740     if (++Level < RecursionMaxDepth)
11741       for (auto *Op : Inst->operand_values())
11742         if (VisitedInstrs.insert(Op).second)
11743           if (auto *I = dyn_cast<Instruction>(Op))
11744             // Do not try to vectorize CmpInst operands,  this is done
11745             // separately.
11746             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11747                 !R.isDeleted(I) && I->getParent() == BB)
11748               Stack.emplace(I, Level);
11749   }
11750   // Try to vectorized binops where reductions were not found.
11751   for (Value *V : PostponedInsts)
11752     if (auto *Inst = dyn_cast<Instruction>(V))
11753       if (!R.isDeleted(Inst))
11754         Res |= Vectorize(Inst, R);
11755   return Res;
11756 }
11757 
11758 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11759                                                  BasicBlock *BB, BoUpSLP &R,
11760                                                  TargetTransformInfo *TTI) {
11761   auto *I = dyn_cast_or_null<Instruction>(V);
11762   if (!I)
11763     return false;
11764 
11765   if (!isa<BinaryOperator>(I))
11766     P = nullptr;
11767   // Try to match and vectorize a horizontal reduction.
11768   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11769     return tryToVectorize(I, R);
11770   };
11771   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11772                                                   *TLI, ExtraVectorization);
11773 }
11774 
11775 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11776                                                  BasicBlock *BB, BoUpSLP &R) {
11777   const DataLayout &DL = BB->getModule()->getDataLayout();
11778   if (!R.canMapToVector(IVI->getType(), DL))
11779     return false;
11780 
11781   SmallVector<Value *, 16> BuildVectorOpds;
11782   SmallVector<Value *, 16> BuildVectorInsts;
11783   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11784     return false;
11785 
11786   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11787   // Aggregate value is unlikely to be processed in vector register.
11788   return tryToVectorizeList(BuildVectorOpds, R);
11789 }
11790 
11791 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11792                                                    BasicBlock *BB, BoUpSLP &R) {
11793   SmallVector<Value *, 16> BuildVectorInsts;
11794   SmallVector<Value *, 16> BuildVectorOpds;
11795   SmallVector<int> Mask;
11796   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11797       (llvm::all_of(
11798            BuildVectorOpds,
11799            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11800        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11801     return false;
11802 
11803   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11804   return tryToVectorizeList(BuildVectorInsts, R);
11805 }
11806 
11807 template <typename T>
11808 static bool
11809 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11810                        function_ref<unsigned(T *)> Limit,
11811                        function_ref<bool(T *, T *)> Comparator,
11812                        function_ref<bool(T *, T *)> AreCompatible,
11813                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11814                        bool LimitForRegisterSize) {
11815   bool Changed = false;
11816   // Sort by type, parent, operands.
11817   stable_sort(Incoming, Comparator);
11818 
11819   // Try to vectorize elements base on their type.
11820   SmallVector<T *> Candidates;
11821   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11822     // Look for the next elements with the same type, parent and operand
11823     // kinds.
11824     auto *SameTypeIt = IncIt;
11825     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11826       ++SameTypeIt;
11827 
11828     // Try to vectorize them.
11829     unsigned NumElts = (SameTypeIt - IncIt);
11830     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11831                       << NumElts << ")\n");
11832     // The vectorization is a 3-state attempt:
11833     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11834     // size of maximal register at first.
11835     // 2. Try to vectorize remaining instructions with the same type, if
11836     // possible. This may result in the better vectorization results rather than
11837     // if we try just to vectorize instructions with the same/alternate opcodes.
11838     // 3. Final attempt to try to vectorize all instructions with the
11839     // same/alternate ops only, this may result in some extra final
11840     // vectorization.
11841     if (NumElts > 1 &&
11842         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11843       // Success start over because instructions might have been changed.
11844       Changed = true;
11845     } else if (NumElts < Limit(*IncIt) &&
11846                (Candidates.empty() ||
11847                 Candidates.front()->getType() == (*IncIt)->getType())) {
11848       Candidates.append(IncIt, std::next(IncIt, NumElts));
11849     }
11850     // Final attempt to vectorize instructions with the same types.
11851     if (Candidates.size() > 1 &&
11852         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11853       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11854         // Success start over because instructions might have been changed.
11855         Changed = true;
11856       } else if (LimitForRegisterSize) {
11857         // Try to vectorize using small vectors.
11858         for (auto *It = Candidates.begin(), *End = Candidates.end();
11859              It != End;) {
11860           auto *SameTypeIt = It;
11861           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11862             ++SameTypeIt;
11863           unsigned NumElts = (SameTypeIt - It);
11864           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11865                                             /*LimitForRegisterSize=*/false))
11866             Changed = true;
11867           It = SameTypeIt;
11868         }
11869       }
11870       Candidates.clear();
11871     }
11872 
11873     // Start over at the next instruction of a different type (or the end).
11874     IncIt = SameTypeIt;
11875   }
11876   return Changed;
11877 }
11878 
11879 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11880 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11881 /// operands. If IsCompatibility is false, function implements strict weak
11882 /// ordering relation between two cmp instructions, returning true if the first
11883 /// instruction is "less" than the second, i.e. its predicate is less than the
11884 /// predicate of the second or the operands IDs are less than the operands IDs
11885 /// of the second cmp instruction.
11886 template <bool IsCompatibility>
11887 static bool compareCmp(Value *V, Value *V2,
11888                        function_ref<bool(Instruction *)> IsDeleted) {
11889   auto *CI1 = cast<CmpInst>(V);
11890   auto *CI2 = cast<CmpInst>(V2);
11891   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11892     return false;
11893   if (CI1->getOperand(0)->getType()->getTypeID() <
11894       CI2->getOperand(0)->getType()->getTypeID())
11895     return !IsCompatibility;
11896   if (CI1->getOperand(0)->getType()->getTypeID() >
11897       CI2->getOperand(0)->getType()->getTypeID())
11898     return false;
11899   CmpInst::Predicate Pred1 = CI1->getPredicate();
11900   CmpInst::Predicate Pred2 = CI2->getPredicate();
11901   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11902   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11903   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11904   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11905   if (BasePred1 < BasePred2)
11906     return !IsCompatibility;
11907   if (BasePred1 > BasePred2)
11908     return false;
11909   // Compare operands.
11910   bool LEPreds = Pred1 <= Pred2;
11911   bool GEPreds = Pred1 >= Pred2;
11912   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11913     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11914     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11915     if (Op1->getValueID() < Op2->getValueID())
11916       return !IsCompatibility;
11917     if (Op1->getValueID() > Op2->getValueID())
11918       return false;
11919     if (auto *I1 = dyn_cast<Instruction>(Op1))
11920       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11921         if (I1->getParent() != I2->getParent())
11922           return false;
11923         InstructionsState S = getSameOpcode({I1, I2});
11924         if (S.getOpcode())
11925           continue;
11926         return false;
11927       }
11928   }
11929   return IsCompatibility;
11930 }
11931 
11932 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11933     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11934     bool AtTerminator) {
11935   bool OpsChanged = false;
11936   SmallVector<Instruction *, 4> PostponedCmps;
11937   for (auto *I : reverse(Instructions)) {
11938     if (R.isDeleted(I))
11939       continue;
11940     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11941       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11942     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11943       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11944     } else if (isa<CmpInst>(I)) {
11945       PostponedCmps.push_back(I);
11946       continue;
11947     }
11948     // Try to find reductions in buildvector sequnces.
11949     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11950   }
11951   if (AtTerminator) {
11952     // Try to find reductions first.
11953     for (Instruction *I : PostponedCmps) {
11954       if (R.isDeleted(I))
11955         continue;
11956       for (Value *Op : I->operands())
11957         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11958     }
11959     // Try to vectorize operands as vector bundles.
11960     for (Instruction *I : PostponedCmps) {
11961       if (R.isDeleted(I))
11962         continue;
11963       OpsChanged |= tryToVectorize(I, R);
11964     }
11965     // Try to vectorize list of compares.
11966     // Sort by type, compare predicate, etc.
11967     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11968       return compareCmp<false>(V, V2,
11969                                [&R](Instruction *I) { return R.isDeleted(I); });
11970     };
11971 
11972     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11973       if (V1 == V2)
11974         return true;
11975       return compareCmp<true>(V1, V2,
11976                               [&R](Instruction *I) { return R.isDeleted(I); });
11977     };
11978     auto Limit = [&R](Value *V) {
11979       unsigned EltSize = R.getVectorElementSize(V);
11980       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11981     };
11982 
11983     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11984     OpsChanged |= tryToVectorizeSequence<Value>(
11985         Vals, Limit, CompareSorter, AreCompatibleCompares,
11986         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11987           // Exclude possible reductions from other blocks.
11988           bool ArePossiblyReducedInOtherBlock =
11989               any_of(Candidates, [](Value *V) {
11990                 return any_of(V->users(), [V](User *U) {
11991                   return isa<SelectInst>(U) &&
11992                          cast<SelectInst>(U)->getParent() !=
11993                              cast<Instruction>(V)->getParent();
11994                 });
11995               });
11996           if (ArePossiblyReducedInOtherBlock)
11997             return false;
11998           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11999         },
12000         /*LimitForRegisterSize=*/true);
12001     Instructions.clear();
12002   } else {
12003     // Insert in reverse order since the PostponedCmps vector was filled in
12004     // reverse order.
12005     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
12006   }
12007   return OpsChanged;
12008 }
12009 
12010 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
12011   bool Changed = false;
12012   SmallVector<Value *, 4> Incoming;
12013   SmallPtrSet<Value *, 16> VisitedInstrs;
12014   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
12015   // node. Allows better to identify the chains that can be vectorized in the
12016   // better way.
12017   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
12018   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
12019     assert(isValidElementType(V1->getType()) &&
12020            isValidElementType(V2->getType()) &&
12021            "Expected vectorizable types only.");
12022     // It is fine to compare type IDs here, since we expect only vectorizable
12023     // types, like ints, floats and pointers, we don't care about other type.
12024     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
12025       return true;
12026     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
12027       return false;
12028     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
12029     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
12030     if (Opcodes1.size() < Opcodes2.size())
12031       return true;
12032     if (Opcodes1.size() > Opcodes2.size())
12033       return false;
12034     Optional<bool> ConstOrder;
12035     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
12036       // Undefs are compatible with any other value.
12037       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
12038         if (!ConstOrder)
12039           ConstOrder =
12040               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
12041         continue;
12042       }
12043       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
12044         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
12045           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
12046           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
12047           if (!NodeI1)
12048             return NodeI2 != nullptr;
12049           if (!NodeI2)
12050             return false;
12051           assert((NodeI1 == NodeI2) ==
12052                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
12053                  "Different nodes should have different DFS numbers");
12054           if (NodeI1 != NodeI2)
12055             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
12056           InstructionsState S = getSameOpcode({I1, I2});
12057           if (S.getOpcode())
12058             continue;
12059           return I1->getOpcode() < I2->getOpcode();
12060         }
12061       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
12062         if (!ConstOrder)
12063           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
12064         continue;
12065       }
12066       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
12067         return true;
12068       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
12069         return false;
12070     }
12071     return ConstOrder && *ConstOrder;
12072   };
12073   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
12074     if (V1 == V2)
12075       return true;
12076     if (V1->getType() != V2->getType())
12077       return false;
12078     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
12079     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
12080     if (Opcodes1.size() != Opcodes2.size())
12081       return false;
12082     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
12083       // Undefs are compatible with any other value.
12084       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
12085         continue;
12086       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
12087         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
12088           if (I1->getParent() != I2->getParent())
12089             return false;
12090           InstructionsState S = getSameOpcode({I1, I2});
12091           if (S.getOpcode())
12092             continue;
12093           return false;
12094         }
12095       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
12096         continue;
12097       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
12098         return false;
12099     }
12100     return true;
12101   };
12102   auto Limit = [&R](Value *V) {
12103     unsigned EltSize = R.getVectorElementSize(V);
12104     return std::max(2U, R.getMaxVecRegSize() / EltSize);
12105   };
12106 
12107   bool HaveVectorizedPhiNodes = false;
12108   do {
12109     // Collect the incoming values from the PHIs.
12110     Incoming.clear();
12111     for (Instruction &I : *BB) {
12112       PHINode *P = dyn_cast<PHINode>(&I);
12113       if (!P)
12114         break;
12115 
12116       // No need to analyze deleted, vectorized and non-vectorizable
12117       // instructions.
12118       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
12119           isValidElementType(P->getType()))
12120         Incoming.push_back(P);
12121     }
12122 
12123     // Find the corresponding non-phi nodes for better matching when trying to
12124     // build the tree.
12125     for (Value *V : Incoming) {
12126       SmallVectorImpl<Value *> &Opcodes =
12127           PHIToOpcodes.try_emplace(V).first->getSecond();
12128       if (!Opcodes.empty())
12129         continue;
12130       SmallVector<Value *, 4> Nodes(1, V);
12131       SmallPtrSet<Value *, 4> Visited;
12132       while (!Nodes.empty()) {
12133         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
12134         if (!Visited.insert(PHI).second)
12135           continue;
12136         for (Value *V : PHI->incoming_values()) {
12137           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
12138             Nodes.push_back(PHI1);
12139             continue;
12140           }
12141           Opcodes.emplace_back(V);
12142         }
12143       }
12144     }
12145 
12146     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
12147         Incoming, Limit, PHICompare, AreCompatiblePHIs,
12148         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
12149           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
12150         },
12151         /*LimitForRegisterSize=*/true);
12152     Changed |= HaveVectorizedPhiNodes;
12153     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
12154   } while (HaveVectorizedPhiNodes);
12155 
12156   VisitedInstrs.clear();
12157 
12158   SmallVector<Instruction *, 8> PostProcessInstructions;
12159   SmallDenseSet<Instruction *, 4> KeyNodes;
12160   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
12161     // Skip instructions with scalable type. The num of elements is unknown at
12162     // compile-time for scalable type.
12163     if (isa<ScalableVectorType>(it->getType()))
12164       continue;
12165 
12166     // Skip instructions marked for the deletion.
12167     if (R.isDeleted(&*it))
12168       continue;
12169     // We may go through BB multiple times so skip the one we have checked.
12170     if (!VisitedInstrs.insert(&*it).second) {
12171       if (it->use_empty() && KeyNodes.contains(&*it) &&
12172           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
12173                                       it->isTerminator())) {
12174         // We would like to start over since some instructions are deleted
12175         // and the iterator may become invalid value.
12176         Changed = true;
12177         it = BB->begin();
12178         e = BB->end();
12179       }
12180       continue;
12181     }
12182 
12183     if (isa<DbgInfoIntrinsic>(it))
12184       continue;
12185 
12186     // Try to vectorize reductions that use PHINodes.
12187     if (PHINode *P = dyn_cast<PHINode>(it)) {
12188       // Check that the PHI is a reduction PHI.
12189       if (P->getNumIncomingValues() == 2) {
12190         // Try to match and vectorize a horizontal reduction.
12191         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
12192                                      TTI)) {
12193           Changed = true;
12194           it = BB->begin();
12195           e = BB->end();
12196           continue;
12197         }
12198       }
12199       // Try to vectorize the incoming values of the PHI, to catch reductions
12200       // that feed into PHIs.
12201       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
12202         // Skip if the incoming block is the current BB for now. Also, bypass
12203         // unreachable IR for efficiency and to avoid crashing.
12204         // TODO: Collect the skipped incoming values and try to vectorize them
12205         // after processing BB.
12206         if (BB == P->getIncomingBlock(I) ||
12207             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
12208           continue;
12209 
12210         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
12211                                             P->getIncomingBlock(I), R, TTI);
12212       }
12213       continue;
12214     }
12215 
12216     // Ran into an instruction without users, like terminator, or function call
12217     // with ignored return value, store. Ignore unused instructions (basing on
12218     // instruction type, except for CallInst and InvokeInst).
12219     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
12220                             isa<InvokeInst>(it))) {
12221       KeyNodes.insert(&*it);
12222       bool OpsChanged = false;
12223       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
12224         for (auto *V : it->operand_values()) {
12225           // Try to match and vectorize a horizontal reduction.
12226           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
12227         }
12228       }
12229       // Start vectorization of post-process list of instructions from the
12230       // top-tree instructions to try to vectorize as many instructions as
12231       // possible.
12232       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
12233                                                 it->isTerminator());
12234       if (OpsChanged) {
12235         // We would like to start over since some instructions are deleted
12236         // and the iterator may become invalid value.
12237         Changed = true;
12238         it = BB->begin();
12239         e = BB->end();
12240         continue;
12241       }
12242     }
12243 
12244     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
12245         isa<InsertValueInst>(it))
12246       PostProcessInstructions.push_back(&*it);
12247   }
12248 
12249   return Changed;
12250 }
12251 
12252 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
12253   auto Changed = false;
12254   for (auto &Entry : GEPs) {
12255     // If the getelementptr list has fewer than two elements, there's nothing
12256     // to do.
12257     if (Entry.second.size() < 2)
12258       continue;
12259 
12260     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
12261                       << Entry.second.size() << ".\n");
12262 
12263     // Process the GEP list in chunks suitable for the target's supported
12264     // vector size. If a vector register can't hold 1 element, we are done. We
12265     // are trying to vectorize the index computations, so the maximum number of
12266     // elements is based on the size of the index expression, rather than the
12267     // size of the GEP itself (the target's pointer size).
12268     unsigned MaxVecRegSize = R.getMaxVecRegSize();
12269     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
12270     if (MaxVecRegSize < EltSize)
12271       continue;
12272 
12273     unsigned MaxElts = MaxVecRegSize / EltSize;
12274     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
12275       auto Len = std::min<unsigned>(BE - BI, MaxElts);
12276       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
12277 
12278       // Initialize a set a candidate getelementptrs. Note that we use a
12279       // SetVector here to preserve program order. If the index computations
12280       // are vectorizable and begin with loads, we want to minimize the chance
12281       // of having to reorder them later.
12282       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
12283 
12284       // Some of the candidates may have already been vectorized after we
12285       // initially collected them. If so, they are marked as deleted, so remove
12286       // them from the set of candidates.
12287       Candidates.remove_if(
12288           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
12289 
12290       // Remove from the set of candidates all pairs of getelementptrs with
12291       // constant differences. Such getelementptrs are likely not good
12292       // candidates for vectorization in a bottom-up phase since one can be
12293       // computed from the other. We also ensure all candidate getelementptr
12294       // indices are unique.
12295       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
12296         auto *GEPI = GEPList[I];
12297         if (!Candidates.count(GEPI))
12298           continue;
12299         auto *SCEVI = SE->getSCEV(GEPList[I]);
12300         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
12301           auto *GEPJ = GEPList[J];
12302           auto *SCEVJ = SE->getSCEV(GEPList[J]);
12303           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
12304             Candidates.remove(GEPI);
12305             Candidates.remove(GEPJ);
12306           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
12307             Candidates.remove(GEPJ);
12308           }
12309         }
12310       }
12311 
12312       // We break out of the above computation as soon as we know there are
12313       // fewer than two candidates remaining.
12314       if (Candidates.size() < 2)
12315         continue;
12316 
12317       // Add the single, non-constant index of each candidate to the bundle. We
12318       // ensured the indices met these constraints when we originally collected
12319       // the getelementptrs.
12320       SmallVector<Value *, 16> Bundle(Candidates.size());
12321       auto BundleIndex = 0u;
12322       for (auto *V : Candidates) {
12323         auto *GEP = cast<GetElementPtrInst>(V);
12324         auto *GEPIdx = GEP->idx_begin()->get();
12325         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
12326         Bundle[BundleIndex++] = GEPIdx;
12327       }
12328 
12329       // Try and vectorize the indices. We are currently only interested in
12330       // gather-like cases of the form:
12331       //
12332       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
12333       //
12334       // where the loads of "a", the loads of "b", and the subtractions can be
12335       // performed in parallel. It's likely that detecting this pattern in a
12336       // bottom-up phase will be simpler and less costly than building a
12337       // full-blown top-down phase beginning at the consecutive loads.
12338       Changed |= tryToVectorizeList(Bundle, R);
12339     }
12340   }
12341   return Changed;
12342 }
12343 
12344 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
12345   bool Changed = false;
12346   // Sort by type, base pointers and values operand. Value operands must be
12347   // compatible (have the same opcode, same parent), otherwise it is
12348   // definitely not profitable to try to vectorize them.
12349   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
12350     if (V->getPointerOperandType()->getTypeID() <
12351         V2->getPointerOperandType()->getTypeID())
12352       return true;
12353     if (V->getPointerOperandType()->getTypeID() >
12354         V2->getPointerOperandType()->getTypeID())
12355       return false;
12356     // UndefValues are compatible with all other values.
12357     if (isa<UndefValue>(V->getValueOperand()) ||
12358         isa<UndefValue>(V2->getValueOperand()))
12359       return false;
12360     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
12361       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12362         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
12363             DT->getNode(I1->getParent());
12364         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
12365             DT->getNode(I2->getParent());
12366         assert(NodeI1 && "Should only process reachable instructions");
12367         assert(NodeI2 && "Should only process reachable instructions");
12368         assert((NodeI1 == NodeI2) ==
12369                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
12370                "Different nodes should have different DFS numbers");
12371         if (NodeI1 != NodeI2)
12372           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
12373         InstructionsState S = getSameOpcode({I1, I2});
12374         if (S.getOpcode())
12375           return false;
12376         return I1->getOpcode() < I2->getOpcode();
12377       }
12378     if (isa<Constant>(V->getValueOperand()) &&
12379         isa<Constant>(V2->getValueOperand()))
12380       return false;
12381     return V->getValueOperand()->getValueID() <
12382            V2->getValueOperand()->getValueID();
12383   };
12384 
12385   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
12386     if (V1 == V2)
12387       return true;
12388     if (V1->getPointerOperandType() != V2->getPointerOperandType())
12389       return false;
12390     // Undefs are compatible with any other value.
12391     if (isa<UndefValue>(V1->getValueOperand()) ||
12392         isa<UndefValue>(V2->getValueOperand()))
12393       return true;
12394     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
12395       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12396         if (I1->getParent() != I2->getParent())
12397           return false;
12398         InstructionsState S = getSameOpcode({I1, I2});
12399         return S.getOpcode() > 0;
12400       }
12401     if (isa<Constant>(V1->getValueOperand()) &&
12402         isa<Constant>(V2->getValueOperand()))
12403       return true;
12404     return V1->getValueOperand()->getValueID() ==
12405            V2->getValueOperand()->getValueID();
12406   };
12407   auto Limit = [&R, this](StoreInst *SI) {
12408     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
12409     return R.getMinVF(EltSize);
12410   };
12411 
12412   // Attempt to sort and vectorize each of the store-groups.
12413   for (auto &Pair : Stores) {
12414     if (Pair.second.size() < 2)
12415       continue;
12416 
12417     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
12418                       << Pair.second.size() << ".\n");
12419 
12420     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
12421       continue;
12422 
12423     Changed |= tryToVectorizeSequence<StoreInst>(
12424         Pair.second, Limit, StoreSorter, AreCompatibleStores,
12425         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
12426           return vectorizeStores(Candidates, R);
12427         },
12428         /*LimitForRegisterSize=*/false);
12429   }
12430   return Changed;
12431 }
12432 
12433 char SLPVectorizer::ID = 0;
12434 
12435 static const char lv_name[] = "SLP Vectorizer";
12436 
12437 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
12438 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
12439 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
12440 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12441 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
12442 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
12443 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
12444 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
12445 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
12446 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
12447 
12448 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
12449